Skip to content

Commit 5542c92

Browse files
authored
🚀 Hand a prepared agent session to its native UI (#518)
* 🚀 Hand a prepared agent session to its native UI `<Session.Launch>` prepares one durable coding-agent session from its rendered body and gives the provider's own interactive UI the terminal for that exact session, then continues the document after it exits. Backed by `Agent.launch(instructions, options)`, whose base handler fails: answering `prompt()` does not make a provider launch-capable. The body renders completely first, and only what it rendered crosses as the instruction layer — the prose around the element stays documentation. The launch performs no model turn. Phases are retained as `agent_session_launch` records under one expansion identity: `prepared` before ACP ownership is released, then `detached`, then `exited`. Separate records because a launch interrupted between detach and spawn has to resume the session it already prepared rather than create a replacement. Authority for those phases is delivered, never published. The public `launch` route carries one frozen, one-use request describing the ask and answers nothing; middleware may inspect it, narrow it through `with()`, refuse it, or delegate it, and what it returns is discarded. Core hands the provider factory it installs a separate authority as a closure argument — no context holds one, no request member carries one, and there is no reader for one. That authority runs each absent phase once, cross-checks the record against the request that was routed, retains it before the next live effect, and derives the result. A rebuilt look-alike, a superseded parent, a foreign request, a repeated delegation, and a fabricated completion each author nothing. Which request is live is recorded by the invocation that issued it, never on the request. Nothing a handler holds points back: the value carries its facts and `with()`, and `Reflect.ownKeys()` over it finds nothing else. That distinction is the whole boundary — a symbol-keyed property would have been readable, copyable, and therefore retargetable by the handler it was meant to be hidden from. The partition handle keeps its state the same way, in a private field, so reflection over one finds no state and no launch to reach. The ACPX provider installs the layer at session creation, refuses an agent whose native launcher is not advertised or that asserts no provider-native identity, releases ACP ownership before the spawn, and marks its handle stale so a later `<Prompt>` reattaches. A changed instruction layer is refused outright: ACPX fixes the layer when the ACP session is created, and its cached transcript stays empty across native turns, so nothing here can show that discarding a session would be safe. No launch path discards persistent provider state — not even for a session an enclosing `<Session>` established and nothing has used. Every operation that can act on an advertised provider-returned session — establishing it, subscribing a prompt, launching, resuming an incomplete launch — takes exclusive ownership of it first, under the natural key `(acpx, agent command, session key)`. The coordinator answering that is built by the host and passed straight into the provider, because a decision document middleware could replace is not one. Acquisition never waits: contention retains `session-busy` before any ACP work. An owner acknowledges quiescence only once it holds no usable handle, so a handoff that could not release leaves the record active — and the next owner is told to recover it rather than inferring safety from a released lock, a pid, or an empty transcript. Deno and the compiled binary combine a process-local occupancy table, one non-blocking advisory lock, and an ownership record atomically replaced and durably flushed under `~/.acpx/xmd-native-sessions/v1`. Node and Bun build none and fail closed: neither exposes a cross-process advisory lock, and a pid or heartbeat emulation calls a paused process dead and admits two owners. `<TestAgent>` installs one ACP provider, lexically, in its own invocation, and selects a complete per-test partition on every dispatch. Installing is what makes the provider reachable from the content it serves and what makes that one closure the only holder of launch authority; partitioning is what keeps one test's sessions, queues, records and coordinator out of the next. A partition handle is launch-free and resolves only by live module-private identity, so a foreign, fabricated, or dismantled one reaches no state at all. It also installs a controlled launcher for its body, because a scripted agent's native UI does not exist and the terminal belongs to whoever is running the tests. The native launcher is its own seam, not `exec`: it takes the run's one foreground-terminal lease before an agent is resolved, flushes what the document has produced, inherits the terminal to the child, and reaps a child that ignores the interrupt by pid — Deno's `ChildProcess.kill()` delivers only its first signal, so escalation through the handle silently does nothing. The authored half of the evidence is one executable Markdown document, `packages/test-agent/src/NativeSessionLaunch.test.md`, run whole: the launch, the prompt that proves no turn was spent, and the eager-`<Session>` refusal are written as Markdown rather than assembled from a TypeScript string. No real adapter is advertised. `claude` and `codex` have command shapes and contract tests; the opt-in Claude proof shows the ACP adapter creates no resumable native state and asserts no native identity, so it fails closed. Refs #517 Claude-Session: https://claude.ai/code/session_01MNztk1fikXUnD2FW4yS6Kr * 🔒 Keep a session owned when its ACP handle would not close `releaseHandle()` reported a failed `close()` and then marked the managed entry stale anyway. Stale is what `holding()` reads, so both callers of the ordinary release path — `session()` and the prompt ownership finalizer — then saw this scope holding nothing and acknowledged quiescence. The durable record went idle for a session ACP had not let go of, and the next owner was handed it. A close that failed released nothing, so the entry stays live: quiescence is not acknowledged, the record stays active, and the next owner is refused with `session-recovery-required`. A successful close is unchanged — stale handle, idle record, and the session is free. The native-launch detach path already had this shape, which is why it was not affected. `NO11` drives both supported call sites with a failing `close()` and proves the refusal arrives before any ACP work, while the provider scope still reports the close it could not complete. Its observations are collected inside the scope and asserted outside it: that scope's teardown raises the cleanup failure, which replaces anything the body raised, so an assertion written in there passes whatever happens. Also repairs two typechecks the frozen focused matrix did not cover and CI found: `packages/test-agent/tests/provider.test.ts` still built the provider with the replaced `resolveRoute` seam, and `AG1`/`AG2` still asserted `AgentProviders.resolve(name)`, which the request-only installation protocol removed. Both now exercise the surviving contract. Refs #517 Claude-Session: https://claude.ai/code/session_01MNztk1fikXUnD2FW4yS6Kr * 🧪 Keep the Deno session-coordinator proof out of the Node and Bun corpus `packages/runtime/tests/agent-session-coordinator.test.ts` is the Deno adapter's own proof: it takes a non-blocking advisory lock through `Deno.FsFile.tryLock` and races it against real Deno children that are killed mid-ownership so a tombstone survives them. Both the lock primitive and the children are Deno's, so the file reached for `Deno` directly — which `tsc` cannot resolve and Bun cannot run. `test-node` failed its typecheck on four `Deno` references plus two `unknown` chunks; `test-bun` ran the file and failed all seven Tier CO cases. The runtime-exclusion mechanism is where a deliberate absence from one runtime is recorded and reviewed, and this is the shape it already carries for `workflow-lifecycle-authority.test.ts`, which races the same primitive. The provider-neutral half of the contract stays on every runtime: owner kinds, contention, quiescence, the tombstone and the record shape are proven through `packages/acp/tests/native-launch.test.ts`, and the host difference itself through `packages/cli/tests/agent-session-coordinator.test.ts`, which runs under all three. Delivery only. No source behavior changes, and no file under `packages/` differs from the reviewed head. Refs #517 Claude-Session: https://claude.ai/code/session_01MNztk1fikXUnD2FW4yS6Kr * 📝 Bind the post-launch answer with component capture `main` retired the reserved `<Capture>` directive in favour of `<Let>` and component-level capture, leaving `Capture` resolvable only as an ordinary component name. The authored journey still wrapped its post-launch prompt in the retired directive, so after the rebase the direct-launch scenario stopped at that line with `Cannot resolve component: Capture` — before it could prove the launch spent no turn. The prompt binds its own rendered answer now. The observation is unchanged: the scenario holds one scripted stage, the launch does not consume it, and the prompt that follows still receives `nothing yet`. Authored acceptance only. No scenario, assertion, authority, coordinator, provider-partition, reconciliation, specification, or architecture change. Refs #517 Claude-Session: https://claude.ai/code/session_01MNztk1fikXUnD2FW4yS6Kr --------- Co-authored-by: Taras Mankovski <[email protected]>
1 parent dda464c commit 5542c92

59 files changed

Lines changed: 9066 additions & 257 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎architecture.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,17 @@ Existing documents and code get aligned to this section retroactively.
7878
| host profile | a named production assembly a trusted host offers a testing harness — `run` today — reused after argument parsing rather than restated; a host that cannot offer one refuses rather than approximating it |
7979
| execution outcome | what one nested document execution ended as, as the harness publishes it: a settlement carrying the exact completion `Result`, or, for a workflow attempt, a durable suspension carrying the run and suspension identities. A suspension is neither success nor failure |
8080
| trusted host | the code that decides what an execution is for — a CLI entrypoint or a workflow runner — as distinct from the document, the components it expands, and the middleware packages composed around it |
81+
| native session launch | preparing one durable coding-agent session from a document and then handing its provider's own interactive UI the terminal for that exact session. It is session construction followed by an ownership handoff, not a chat frontend: XMD performs no model turn, proxies no native turn, and journals no native conversation |
82+
| provider-native session identity | the identity an agent asserts for its own durable session state, distinct from the logical XMD session key and from the ACP/ACPX record identity. Only an asserted one crosses a handoff; XMD never infers that a string a native CLI would accept is one |
83+
| instruction layer | the provider-native session, system or developer instructions a launch installs before the native UI accepts its first user turn. It is not a user message, and it is not conversation history |
84+
| foreground-terminal lease | the one exclusive claim on the run's terminal a native launch holds. A host with no terminal refuses it, and two launches cannot hold it at once even when they name different sessions |
85+
| native launcher | the host-owned seam that reserves that lease, flushes what the document has produced, spawns one native UI with the terminal inherited, and reports its terminal status and nothing else. It is not `exec`, whose children are piped, captured and journaled |
86+
| launch request | the frozen, one-use value public launch middleware routes. It carries the facts of one launch and `with()`, and nothing that can settle one. Identity is object identity: a rebuilt look-alike describes the same ask and authorizes none of it |
87+
| provider authority | what core delivers to the provider factory it installs, as an argument that factory closes over. It validates the routed request, runs each absent phase once, cross-checks and retains what comes back, and derives the result. There is no reader for one, no context holding one, and no request member carrying one |
88+
| session coordinator | the host-built capability that answers who owns one logical agent session right now, across processes. It is passed directly into the provider that needs it and is deliberately not contextual: a decision document middleware could replace is not one. Acquisition never waits |
89+
| quiescence | the one-use acknowledgement an ownership body gives. It does not mean "I finished" — it means nothing this owner started can still act on the session, which is why a handoff that could not release its handle never gives it |
90+
| recovery tombstone | an ownership record left active because its owner never proved it stopped. A crash releases the kernel lock and not this, and no pid, elapsed time, released lock or empty transcript clears it |
91+
| provider partition | one complete, independently owned agent-provider state — runtime, store, managed sessions, queues, coordinator, teardown — selected by the one installed factory at each dispatch. Production is the single-partition case of the same path; holding a partition grants work, never permission |
8192
| `JournalProvenance` | a non-operational, equality-only witness that a live publication stream descends from the exact journal backend a provider selected for one workflow run; it grants no append, read, execution, publication or reconciliation capability, and is meaningful only because the provider retains the witness it established and later requires exact equality |
8293

8394
## Three axes
@@ -2626,6 +2637,17 @@ module-local identity, and private sentinels remain valid when no second loaded
26262637
copy needs to read the value. String names and metadata keys that cross loaded
26272638
copies are compatibility contracts; changing one is a breaking change.
26282639

2640+
Unreachable to another loaded copy and unreachable to a holder of the object are
2641+
different properties, and only the first is what a module-local symbol gives.
2642+
A symbol-keyed property is an ordinary property: `Reflect.ownKeys()` returns it,
2643+
a descriptor read returns its value, and `Object.getOwnPropertyDescriptors()`
2644+
copies it onto a look-alike — non-enumerable and frozen change none of that. So
2645+
a symbol names state safely and hides none. State a value must carry but its
2646+
holder must not reach belongs in a private field, or in membership of a set the
2647+
owner keeps; both are absent from every key list, descriptor, and copy. A
2648+
capability boundary that a handler holding the object could read across is not
2649+
one, whichever of the two properties it was reasoned from.
2650+
26292651
## Construct inventory
26302652

26312653
Status is measured against main.
@@ -2658,6 +2680,7 @@ Status is measured against main.
26582680
| `exec as="name"` | binds one command's settled outcome — exit status, stdout and stderr — as an ordinary mutable binding; the block displays neither channel, renders nothing, and a nonzero status raises nothing. Only the built-in exec terminal and the built-in `timeout` may compose one, authorized by factory identity rather than by registered name, and asked for through a capability-backed request public middleware composes around but cannot issue, claim twice or answer | built on the #447 stack |
26592681
| testing harness (`<Execution>`) | runs another document as a real root under a production host profile, authorized by canonical `<Test>` alone: declarations installed before the root import, child output displayed progressively and collected only when asked, journal retention selected independently of observation, and the outcome published by the invocation's own terminal through a request public middleware composes around but cannot answer | built on the #454 stack for `host="run"`; the workflow profile and `<WorkflowRun>` are unbuilt, and a host that offers no workflow profile refuses them |
26602682
| `Config` run deadline / exec default / Fetch default | three independently owned contextual timeouts, absent unless configured, each read by exactly one consumer | built on main |
2683+
| native session launch (`<Session.Launch>` / `Agent.launch()`) | prepares one durable coding-agent session from the rendered body of `<Session.Launch>` and hands the provider's native UI the terminal for that exact session, then continues the document after it exits. The body renders completely first and only what it rendered crosses as the instruction layer; the launch performs no model turn; the run's one foreground-terminal lease is taken before an agent is resolved, so a host with no terminal refuses without probing for an installed CLI; the ACPX provider installs the layer at session creation, refuses an agent whose native launcher is not advertised or that asserts no provider-native identity, releases ACP ownership before the spawn, and marks its handle stale so a later `<Prompt>` reattaches. Phases are retained as `agent_session_launch` records under one expansion identity — `prepared` before ownership is released, then `detached`, then `exited` — so a completed replay launches nothing and an interrupted one resumes the retained identity instead of creating a replacement session. The public route carries an opaque one-use launch request and answers nothing; authority to run and retain a phase is delivered to the installed provider directly, so neither a returned completion nor a rebuilt request authors a launch. Every operation that can act on an advertised provider-returned session takes exclusive ownership under one natural key first, through a coordinator the host built and passed in; contention refuses instead of queueing, an owner that never proved it stopped leaves a recovery tombstone, and a host that can build none refuses before contacting an agent. No launch path discards persistent provider state | built on the #517 stack; no real adapter is advertised, `Agent.AddDir` is unbuilt, and both fail closed |
26612684
| `<Fetch>` | performs one XMD-mediated HTTP read through contextual `API.Fetch`, admitting the whole request before transport, and retains the normalized request and the detached response as one `fetch` durable observation; capture decides whether a status is data or a failure, and the trusted host's destination ceiling sits below the component | built on the #456 stack; a generated fragment may name the pinned identity only for a request the trusted host stated exactly, on the #369 stack |
26622685
| `API.Files` | routes every document filesystem operation to the installed provider, with no host default and structural failure data | built on the #227 stack |
26632686
| host Files provider / `useHostFiles()` | resolves document paths in the caller's filesystem, containing them while the host namespace is stable; installed by all four CLI entrypoints | built on the #227 stack |

‎packages/acp/mod.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,5 +19,21 @@ export type { AcpxProviderDependencies, SessionRouteContext } from "./src/provid
1919
/** The agent ACPX selects when nothing else is configured. */
2020
export { DEFAULT_AGENT_NAME } from "acpx/runtime";
2121

22-
export { useAcpxProvider } from "./src/provider.ts";
22+
/**
23+
* Native session launch: the adapters whose resume command shape this package
24+
* knows, and the (empty by default) set it is willing to hand a session to.
25+
*/
26+
export {
27+
ADVERTISED_NATIVE_LAUNCH,
28+
knownNativeAdapters,
29+
nativeAdapterFor,
30+
} from "./src/native-launch.ts";
31+
export type { NativeAdapter } from "./src/native-launch.ts";
32+
33+
export {
34+
AcpxPartitionError,
35+
createPartitionedAcpxProvider,
36+
useAcpxProvider,
37+
} from "./src/provider.ts";
38+
export type { AcpxPartitionSelector } from "./src/provider.ts";
2339
export type { AcpxProvider, ProbeCapableRuntime } from "./src/provider.ts";

‎packages/acp/src/native-launch.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* Native launcher adapters (specs/native-agent-session-launch-spec.md
3+
* §Provider-native identity).
4+
*
5+
* An adapter knows one thing a document must never state: the argv that makes
6+
* a particular coding-agent CLI resume one exact provider-native session.
7+
* `claude --resume <id>` and `codex resume <id>` are adapter implementation
8+
* details, not authored values, and neither an executable path nor a session
9+
* id ever appears in a document.
10+
*
11+
* Knowing the command shape is not the same as being launch-capable.
12+
* Advertisement is separate and deliberately empty by default: an adapter is
13+
* advertised only once an integration test has proven, against the installed
14+
* CLI, that the session ACP created is the session the native UI resumes and
15+
* that the prepared instruction layer is in force on its first user turn.
16+
* Until then `<Session.Launch>` refuses that agent before releasing its ACP
17+
* session, which is the failure the contract asks for rather than a hopeful
18+
* spawn.
19+
*/
20+
21+
export interface NativeAdapter {
22+
/** Stable adapter identity — `claude`, `codex`. Never an executable path. */
23+
launcher: string;
24+
/** The argv that resumes this exact provider-native session. */
25+
resume(nativeSessionId: string): string[];
26+
}
27+
28+
const ADAPTERS: Readonly<Record<string, NativeAdapter>> = {
29+
claude: {
30+
launcher: "claude",
31+
resume: (nativeSessionId) => ["claude", "--resume", nativeSessionId],
32+
},
33+
codex: {
34+
launcher: "codex",
35+
resume: (nativeSessionId) => ["codex", "resume", nativeSessionId],
36+
},
37+
};
38+
39+
/**
40+
* The adapters whose native resume and instruction contracts have been proven
41+
* against the installed CLI.
42+
*
43+
* Empty on `main`. A host that has run the opt-in integration proof for an
44+
* adapter passes its name through `AcpxProviderDependencies.advertiseNativeLaunch`.
45+
*/
46+
export const ADVERTISED_NATIVE_LAUNCH: readonly string[] = [];
47+
48+
export function nativeAdapterFor(agentName: string): NativeAdapter | undefined {
49+
return Object.hasOwn(ADAPTERS, agentName) ? ADAPTERS[agentName] : undefined;
50+
}
51+
52+
/** Every adapter whose command shape this package knows, for diagnostics. */
53+
export function knownNativeAdapters(): string[] {
54+
return Object.keys(ADAPTERS).sort();
55+
}

0 commit comments

Comments
 (0)