Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 123 additions & 0 deletions docs/context-execution.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
# AGH context execution

Use [the execution SDK](execution-pkg.md) and set `Request.Context` to
`ContextExecution` to dispatch an AGH context envelope. Existing callers can
keep using their current `Client.Run` requests. The managed path owns the local
execution journal. AGH owns authorization, knowledge assembly, checkpoint
acceptance, credential policy and the broker.

## Dispatch and receipt

1. Open a private, canonical local journal directory (mode `0700`) with
`OpenContextStore`. Use the same directory for all processes handling the
task. Keep the journal's dispatch keys for the whole supported retry window.
2. Resolve the authorized project, resource roots, native executable and Skill
sources to absolute paths. Populate the envelope with the current AGH scope,
versions and capability requirements. Hash task and instruction bytes with
`ContextContentDigest`. Preset descriptors use the uppercase preset name,
source ID, classification, original byte count and digest. Pass the actual
bytes in the SDK request. Ordinary MCP server descriptors pin the digest of
their resolved `MCPServer` configuration.
3. Seal with `envelope.Digest()` and place the result in `EnvelopeDigest`.
Seal each binding with `binding.Digest()` before sealing the envelope. The
version is `1.0`. Top-level optional extensions survive JSON forwarding
within major version 1. Digests use compact Go JSON with ordered object
keys and preserved number tokens. Credential values travel outside the
envelope.
4. Supply an `Authorize` callback that checks current grants. Offload invokes
it before claiming the dispatch and again immediately before opening the
native process. When authorizing a handoff, check each checkpoint reference
against the receiving Agent, scope, audience and current policy. Use the
run's context to cancel a dispatched turn if AGH revokes its access.
5. Read `Result.ContextReceipt` on success and error. The injection evidence is
produced after native launch for Claude and after an acknowledged Codex
turn start. It includes the actual cwd, configured roots, pinned Skill
snapshots, tool versions, compiled instruction digest and byte count, and
per-document digests and byte counts. Resource-root digests are authorized
metadata for caller-managed directories. AGH validates any corresponding
snapshot or revision. The receipt contains no instruction or document text,
broker configuration or credential values.

A terminal receipt distinguishes `completed` execution, pre-dispatch
`rejected` execution and an `unknown` outcome after launch. Completion is
execution evidence. AGH separately confirms the task and its side effects.
The journal persists only receipts and reference metadata. Private native
session files live beside the journal and have the provider's retention and
format. AGH owns journal and runtime retention.

A replay of the same still-authorized envelope returns
`dispatch_already_recorded` with the prior receipt and executes no native turn.
Key reuse with changed input yields `idempotency_conflict`. A claimed dispatch
without a terminal receipt yields `dispatch_unknown`, including an interrupted
process or an in-flight concurrent request. Reconcile side effects before
assigning a new dispatch key. Separate machines must share the same dispatch
owner or use AGH's own durable claim system.

## Runtime capabilities

| Capability | Claude stream-json | Codex app-server |
| --- | --- | --- |
| Clean home, config, cwd and explicit instructions | Yes | Yes |
| Explicit ambient runtime | Yes, fresh invocation | Pre-dispatch rejection |
| Additional workspace roots | Native `--add-dir` | Thread and turn workspace roots |
| Exact Skill snapshots | Pre-dispatch rejection | Verified staged copies |
| Tool-scoped credential broker | MCP | MCP |
| Managed native resume | Same clean runtime and compatible fingerprint | Same clean runtime and compatible fingerprint |
| Explicit task checkpoint handoff | Yes | Yes |

`RequiredCapabilities` accepts `clean`, `ambient`, `preset_documents`,
`resource_roots`, `native_resume`, `exact_skills`, `mcp`, `credential_broker`
and `checkpoint`. Unknown or unavailable requirements fail before launch.

Clean is the default. Offload creates a private native home and empty cwd with
the primary project as the first workspace root. Only selected roots go into
the native protocol. The boot environment keeps PATH and locale and sets fresh
home/config/cache/data locations. Claude clean mode uses an explicit gateway
token in the selected profile. Codex clean mode uses a caller-supplied
`ContextExecution.CodexAPIKey` and an empty native authentication directory at
first launch. The selected profile and executable are explicit in both cases.
Set `Runtime.AuthVersion` to the provider credential version and change it on
rotation.

Claude ambient mode additionally requires explicit authorization in the
envelope and in `Authorize`. Its cwd is the primary project. The receipt
identifies the inherited HOME, Claude configuration, Skill/plugin roots and
environment classes. A clean setup failure ends the dispatch.

Workspace roots constrain native context selection. Filesystem access still
depends on the caller's OS permissions. Requests that require an enforced
per-root mode, such as read-only, fail before dispatch.
The declared tools select MCP servers. Native built-in tool behavior follows
the adapter's permission policy. Claude supports explicit tool-free execution
through `Runtime.ToolsDisabled`.

Resume requires the `NativeSessionRef` from the latest successful receipt and
the same subject, task, scope, authorization, runtime and injected context
fingerprint. The next turn may supply a new task message. One successor can
claim a receipt. Use reference-based handoff after uncertain native execution,
when native state is absent, or when the receiving configuration changes.
Credential-bound turns start fresh and have no reusable managed session.

## Checkpoints and tool leases

Call `ContextStore.SaveCheckpoint` with the source run and the explicitly
confirmed steps, independent evidence references, pending/unknown step IDs and
artifact references. Repeating an identical save returns the same reference.
The receiving Agent supplies that reference in a new envelope. AGH selects and
assembles the authorized facts or artifacts into that request. It can allow a
different audience, scope or backend after independently authorizing the
references. Offload never reads the producer's native transcript to assemble
the receiver's context.

Version 1 supports `broker` and `mcp` credential delivery. Offload validates an
opaque, time-limited binding against its Run and declared MCP tool. The broker
installs a dedicated endpoint with non-secret configuration. It authenticates
the tool process, enforces allowed operations, redemption counts, expiry and
revocation, and scrubs results before returning them to the native harness.
Secret values are never passed to Offload by this interface.

Offload bounds the run by the earliest envelope, checkpoint or lease expiry.
It calls broker release on success, error and cancellation, including partial
activation. A release failure is visible in the receipt. The broker owns expiry
and revocation after process death. Unsupported delivery methods such as direct
environment values or temporary secret files fail before native launch.
3 changes: 3 additions & 0 deletions docs/execution-pkg.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ a normalized or complete UI transcript.

[API, compatibility and validation details](execution-pkg-detail.md).

For authorization-bound runtime setup, injection receipts and reference-based
handoff, see [AGH context execution](context-execution.md).

## Embedding a full Host

Optional `Request.Native` controls let an embedding Host preserve Claude session
Expand Down
47 changes: 33 additions & 14 deletions internal/worker/codex_app_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,21 @@ type jsonRPCMessage struct {
}

type appServerParser struct {
mu sync.Mutex
w io.WriteCloser
nextID int
pending map[string]chan jsonRPCMessage
done chan struct{}
doneOnce sync.Once
err error
s streamSummary
threadID string
turnID string
report strings.Builder
completedReport string
skillConfig []appServerSkillConfig
o Opts
mu sync.Mutex
w io.WriteCloser
nextID int
turnStartRequest string
pending map[string]chan jsonRPCMessage
done chan struct{}
doneOnce sync.Once
err error
s streamSummary
threadID string
turnID string
report strings.Builder
completedReport string
skillConfig []appServerSkillConfig
o Opts
}

func newAppServerParser(w io.WriteCloser, o Opts) *appServerParser {
Expand Down Expand Up @@ -76,6 +77,15 @@ func (p *appServerParser) feed(line []byte) {
p.mu.Lock()
ch := p.pending[key]
delete(p.pending, key)
if ch != nil && p.o.Context != nil && key == p.turnStartRequest && len(m.Error) == 0 {
var response struct {
Turn struct{ ID string } `json:"turn"`
}
if json.Unmarshal(m.Result, &response) == nil && response.Turn.ID != "" {
p.turnID = response.Turn.ID
p.o.Context.Injected()
}
}
p.mu.Unlock()
if ch == nil {
p.fail(errors.New("Codex app-server returned an unknown JSON-RPC id"))
Expand Down Expand Up @@ -247,6 +257,9 @@ func (p *appServerParser) request(method string, params any) (json.RawMessage, e
ch := make(chan jsonRPCMessage, 1)
p.pending[id] = ch
requestID := p.nextID
if p.o.Context != nil && method == "turn/start" {
p.turnStartRequest = id
}
p.mu.Unlock()
if err := p.write(map[string]any{"jsonrpc": "2.0", "id": requestID, "method": method, "params": params}); err != nil {
return nil, err
Expand Down Expand Up @@ -303,6 +316,9 @@ func (p *appServerParser) initialize() error {
if json.Unmarshal(threadRaw, &thread) != nil || thread.Thread.ID == "" {
return errors.New("Codex app-server returned an invalid thread")
}
if p.o.Context != nil && p.o.Resume != "" && thread.Thread.ID != p.o.Resume {
return errors.New("Codex app-server acknowledged a different native thread")
}
p.mu.Lock()
p.threadID, p.s.Session = thread.Thread.ID, thread.Thread.ID
p.s.ObservedModel = firstNonEmpty(thread.Model, thread.Thread.Model)
Expand All @@ -313,6 +329,9 @@ func (p *appServerParser) initialize() error {
_ = json.Unmarshal([]byte(p.o.Native.JSONSchema), &schema)
turn["outputSchema"] = schema
}
if p.o.Context != nil {
p.o.Context.Dispatched()
}
turnRaw, err := p.request("turn/start", turn)
if err != nil {
return err
Expand Down
13 changes: 12 additions & 1 deletion internal/worker/environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,12 @@ func (o *Opts) prepareEnvironment(sourceHome string) (func() error, error) {
return nil, err
}
o.environment = []string{"HOME=" + filepath.Join(root, "home"), "XDG_CONFIG_HOME=" + filepath.Join(root, "config"), "XDG_CACHE_HOME=" + filepath.Join(root, "cache"), "XDG_DATA_HOME=" + filepath.Join(root, "data"), "XDG_STATE_HOME=" + filepath.Join(root, "data"), "CLAUDE_CONFIG_DIR=" + filepath.Join(root, "claude")}
for _, key := range []string{"PATH", "TMPDIR", "LANG", "LC_ALL", "SSL_CERT_FILE", "SSL_CERT_DIR"} {
keys := []string{"PATH", "TMPDIR", "LANG", "LC_ALL", "SSL_CERT_FILE", "SSL_CERT_DIR"}
if o.Context != nil && o.Context.Clean {
keys = []string{"PATH", "LANG", "LC_ALL"}
o.environment = append(o.environment, "TMPDIR="+filepath.Join(root, "cache"))
}
for _, key := range keys {
if value, ok := os.LookupEnv(key); ok {
o.environment = append(o.environment, key+"="+value)
}
Expand All @@ -193,6 +198,12 @@ func (o *Opts) prepareEnvironment(sourceHome string) (func() error, error) {
return nil, errors.New("native session is not recorded in this isolated environment")
}
}
if o.Context != nil && o.Context.Clean {
if _, err := os.Lstat(filepath.Join(destination, "auth.json")); !errors.Is(err, os.ErrNotExist) {
return nil, errors.New("clean Codex context requires an absent native auth.json")
}
return func() error { return nil }, nil
}
target := filepath.Join(destination, "auth.json")
source := filepath.Join(sourceHome, "auth.json")
if st, err := os.Lstat(source); err == nil && st.Mode()&os.ModeSymlink != 0 {
Expand Down
49 changes: 44 additions & 5 deletions internal/worker/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ var errIdle = errors.New("worker idle")
// Opts is one worker run.
type Opts struct {
EnvironmentDirectory string
Context *ContextDispatch
environment []string
// EnvSet and EnvUnset are per-run caller changes to the child environment,
// applied before Offload's own credential and account variables.
Expand Down Expand Up @@ -102,6 +103,15 @@ type Opts struct {
Limits config.Limits
}

// ContextDispatch carries the managed launch policy and evidence hooks.
type ContextDispatch struct {
Clean bool
Executable string
BeforeStart func(context.Context) error
Dispatched func()
Injected func()
}

// Capture is structurally shared with the public execution package, keeping
// recorder ownership outside the native worker without creating an import cycle.
type Capture interface {
Expand Down Expand Up @@ -279,7 +289,7 @@ func childEnv(base []string, o Opts, token string) []string {
env = append(env, "CLAUDE_CONFIG_DIR="+o.Native.ProfileDirectory)
}
env = append(env, "CLAUDE_CODE_DISABLE_AUTO_MEMORY=1")
if !o.Native.Extraction && !o.Native.RestrictedReadOnly && len(o.AddDirs) > 0 {
if o.Context == nil && !o.Native.Extraction && !o.Native.RestrictedReadOnly && len(o.AddDirs) > 0 {
env = append(env, "CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1")
}
for k, v := range o.Native.StreamEnvironment {
Expand Down Expand Up @@ -364,11 +374,11 @@ func Run(ctx context.Context, o Opts) (rec history.Record, err error) {
return rec, fmt.Errorf("session managed account home changed")
}
o.CodexHome = accountHome
} else if o.Profile.BackendName() == "codex" && o.CodexHome == "" {
} else if o.Profile.BackendName() == "codex" && o.CodexHome == "" && o.Context == nil {
o.CodexHome = codexHome()
}
sourceHome := o.CodexHome
if o.EnvironmentDirectory != "" && o.Profile.BackendName() == "codex" && o.Profile.CodexAccount == "" {
if o.EnvironmentDirectory != "" && o.Profile.BackendName() == "codex" && o.Profile.CodexAccount == "" && o.Context == nil {
sourceHome = codexHome()
if o.CodexHome != "" && o.CodexHome != sourceHome && o.CodexHome != filepath.Join(o.EnvironmentDirectory, "codex") {
return rec, errors.New("isolated Codex account home changed")
Expand Down Expand Up @@ -491,7 +501,11 @@ func Run(ctx context.Context, o Opts) (rec history.Record, err error) {
switch rec.Backend {
case "codex":
rec.ErrorKind = "launch"
bin, err = codexBin()
if o.Context != nil {
bin = o.Context.Executable
} else {
bin, err = codexBin()
}
if err != nil {
return rec, fmt.Errorf("codex CLI not found: %w", err)
}
Expand All @@ -515,7 +529,9 @@ func Run(ctx context.Context, o Opts) (rec history.Record, err error) {
}
}
rec.ErrorKind = "launch"
if o.Native != nil && o.Native.Executable != "" {
if o.Context != nil {
bin = o.Context.Executable
} else if o.Native != nil && o.Native.Executable != "" {
bin = o.Native.Executable
} else {
bin, err = claudeBin()
Expand Down Expand Up @@ -551,6 +567,10 @@ func Run(ctx context.Context, o Opts) (rec history.Record, err error) {
hooks := hooks{starting: slot.Starting, startFailed: slot.StartFailed, started: func(g proc.Group) { slot.Track(g); pub.group(g) }, cleaning: func() { pub.phase(live.Cleaning) }, cleaned: slot.Clear}

a := runAttempt(ctx, bin, o, promptPath, token, o.Timeout, pub.update, hooks)
if a.contextErr != nil {
rec.ErrorKind = "context_denied"
return rec, a.contextErr
}
if a.gateErr != nil {
rec.ErrorKind = ErrorKind(a.gateErr)
return rec, a.gateErr
Expand All @@ -565,6 +585,13 @@ func Run(ctx context.Context, o Opts) (rec history.Record, err error) {
leftover = a.leftover
}
s := a.s
if o.Context != nil && o.Resume != "" && s.Result != nil {
observed := firstNonEmpty(s.Result.SessionID, s.Session)
if observed != o.Resume || s.Session != "" && s.Session != o.Resume {
rec.ErrorKind = "session_incompatible"
return rec, errors.New("native harness did not confirm the requested continuation")
}
}
if rec.Backend == "agy" {
rec.ObservedModel = s.ObservedModel
rec.Model = firstNonEmpty(s.ObservedModel, o.Model)
Expand Down Expand Up @@ -734,6 +761,7 @@ func Run(ctx context.Context, o Opts) (rec history.Record, err error) {

// attempt is the outcome of one worker process.
type attempt struct {
contextErr error
gateErr error // admission failure before any backend process starts
baseline *history.TokenUsage
baselineError string
Expand Down Expand Up @@ -911,6 +939,14 @@ func runAttempt(ctx context.Context, bin string, o Opts, promptPath, token strin
if err := config.CheckEnabled(); err != nil {
return attempt{runErr: err, gateErr: err}
}
if o.Context != nil {
if err := o.Context.BeforeStart(ctx); err != nil {
return attempt{contextErr: err}
}
if err := ctx.Err(); err != nil {
return attempt{contextErr: err}
}
}
kind := transcript.AttemptKindRun
if o.Salvage {
kind = transcript.AttemptKindReport
Expand All @@ -929,6 +965,9 @@ func runAttempt(ctx context.Context, bin string, o Opts, promptPath, token strin
}
if appServer != nil {
appServer.start()
} else if o.Context != nil {
o.Context.Dispatched()
o.Context.Injected()
}
if acp != nil {
acp.start(o, acpPrompt)
Expand Down
Loading
Loading