@zvada/agent-server 0.3.20 → 0.3.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/README.md +2 -1
  3. package/dist/types/client/connection.d.ts +2 -0
  4. package/dist/types/client/connection.d.ts.map +1 -1
  5. package/dist/types/client/logins.d.ts +2 -2
  6. package/dist/types/client/logins.d.ts.map +1 -1
  7. package/dist/types/core/agents/claude-code/approvals.d.ts +16 -5
  8. package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
  9. package/dist/types/core/agents/claude-code/options.d.ts +5 -3
  10. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  11. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  12. package/dist/types/core/agents/codex-app-server/client.d.ts +9 -0
  13. package/dist/types/core/agents/codex-app-server/client.d.ts.map +1 -1
  14. package/dist/types/core/agents/codex-app-server/codex-agent.d.ts +3 -1
  15. package/dist/types/core/agents/codex-app-server/codex-agent.d.ts.map +1 -1
  16. package/dist/types/core/agents/codex-app-server/homes.d.ts +7 -5
  17. package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -1
  18. package/dist/types/core/agents/codex-app-server/mcp.d.ts +48 -8
  19. package/dist/types/core/agents/codex-app-server/mcp.d.ts.map +1 -1
  20. package/dist/types/core/agents/codex-app-server/options.d.ts +6 -2
  21. package/dist/types/core/agents/codex-app-server/options.d.ts.map +1 -1
  22. package/dist/types/core/agents/codex-app-server/session.d.ts +10 -1
  23. package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
  24. package/dist/types/core/agents/codex-app-server/turn.d.ts +6 -0
  25. package/dist/types/core/agents/codex-app-server/turn.d.ts.map +1 -1
  26. package/dist/types/core/agents/plan.d.ts +2 -13
  27. package/dist/types/core/agents/plan.d.ts.map +1 -1
  28. package/dist/types/core/index.d.ts +1 -1
  29. package/dist/types/core/index.d.ts.map +1 -1
  30. package/dist/types/core/runtime/agent-runtime.d.ts +2 -1
  31. package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
  32. package/dist/types/core/runtime/turn.d.ts +2 -0
  33. package/dist/types/core/runtime/turn.d.ts.map +1 -1
  34. package/dist/types/core/utils/errors.d.ts +8 -0
  35. package/dist/types/core/utils/errors.d.ts.map +1 -1
  36. package/dist/types/operator/index.d.ts +11 -0
  37. package/dist/types/operator/index.d.ts.map +1 -0
  38. package/dist/types/operator/mcp.d.ts +33 -0
  39. package/dist/types/operator/mcp.d.ts.map +1 -0
  40. package/dist/types/operator/operator.d.ts +206 -0
  41. package/dist/types/operator/operator.d.ts.map +1 -0
  42. package/dist/types/operator/render.d.ts +87 -0
  43. package/dist/types/operator/render.d.ts.map +1 -0
  44. package/dist/types/operator/view.d.ts +44 -0
  45. package/dist/types/operator/view.d.ts.map +1 -0
  46. package/dist/types/protocol/plan.d.ts +20 -0
  47. package/dist/types/protocol/plan.d.ts.map +1 -0
  48. package/dist/types/server/acp/binding.d.ts.map +1 -1
  49. package/dist/types/sync/worker.d.ts.map +1 -1
  50. package/docs/consuming.md +188 -14
  51. package/docs/harnesses.md +13 -8
  52. package/package.json +6 -1
  53. package/src/client/connection.ts +10 -0
  54. package/src/client/logins.ts +23 -14
  55. package/src/core/agents/claude-code/approvals.ts +33 -6
  56. package/src/core/agents/claude-code/options.ts +5 -3
  57. package/src/core/agents/claude-code/session.ts +4 -2
  58. package/src/core/agents/codex-app-server/client.ts +32 -2
  59. package/src/core/agents/codex-app-server/codex-agent.ts +26 -5
  60. package/src/core/agents/codex-app-server/homes.ts +16 -9
  61. package/src/core/agents/codex-app-server/mcp.ts +122 -21
  62. package/src/core/agents/codex-app-server/options.ts +10 -1
  63. package/src/core/agents/codex-app-server/session.ts +46 -9
  64. package/src/core/agents/codex-app-server/turn.ts +26 -12
  65. package/src/core/agents/plan.ts +3 -19
  66. package/src/core/index.ts +1 -0
  67. package/src/core/runtime/agent-runtime.ts +22 -16
  68. package/src/core/runtime/turn.ts +2 -0
  69. package/src/core/utils/errors.ts +13 -0
  70. package/src/operator/index.ts +40 -0
  71. package/src/operator/mcp.ts +171 -0
  72. package/src/operator/operator.ts +778 -0
  73. package/src/operator/render.ts +435 -0
  74. package/src/operator/view.ts +82 -0
  75. package/src/protocol/plan.ts +35 -0
  76. package/src/server/acp/binding.ts +3 -2
  77. package/src/sync/worker.ts +4 -0
package/docs/consuming.md CHANGED
@@ -484,7 +484,9 @@ identical request converges on the original execution — the wire acks it with
484
484
  `deduplicated: true` and `events/replay` fills anything you missed. The same
485
485
  `turnId` with different input fails loudly (`turnConflict` /
486
486
  `TurnConflictError`). This is what makes at-least-once RPC layers (Durable
487
- Object retries, queue redelivery) safe over the engine.
487
+ Object retries, queue redelivery) safe over the engine. Without a journal the
488
+ engine keeps the answers of a session's last 16 turns: a retry of an older
489
+ one fails the same way (`TurnForgottenError`) rather than running it again.
488
490
 
489
491
  Built-in harnesses allow one active turn per logical session, including setup
490
492
  and cancellation cleanup. Different sessions can run in parallel. Wait for the
@@ -544,7 +546,7 @@ CLI's `--inherit-config`, choose how much (LLP 0001, D17):
544
546
 
545
547
  | Level | Claude Code | Codex app-server |
546
548
  | --- | --- | --- |
547
- | `all` (default) | every settings source (user, project, local) and the auto-memory Claude keeps for the repository, as the CLI itself does | the turn's `env.CODEX_HOME`, else the process's: the user's `~/.codex` |
549
+ | `all` (default) | every settings source (user, project, local) and the auto-memory Claude keeps for the repository, as the CLI itself does | the turn's `env.CODEX_HOME`, else the process's: the user's `~/.codex`, which the engine never writes |
548
550
  | `project` | the repository's settings, hooks, `.mcp.json` servers and instruction files; nothing of the user's, no auto-memory, no claude.ai connectors | the repository's `AGENTS.md` and skills, in a home of the session's own |
549
551
  | `none` | only the servers the host and the turn name | as `project`, without the repository's `AGENTS.md` |
550
552
 
@@ -569,7 +571,7 @@ At `project` and `none` every Codex turn needs `config.env.CODEX_HOME`, an
569
571
  existing absolute folder of the session's own: never the user's `~/.codex`,
570
572
  never another session's. A turn without one fails `invalid_request` before
571
573
  Codex starts. The engine owns that home's `mcp_servers` table, as for
572
- per-turn MCP below. A fresh home has no login: hand one over with
574
+ per-turn MCP in a home below. A fresh home has no login: hand one over with
573
575
  [`credentials`](harnesses.md#host-managed-codex-authentication) or the turn's
574
576
  `apiKey`. Codex loads the repository's skills and
575
577
  `~/.agents/skills` at every level; turn one off by name in the home you
@@ -588,7 +590,8 @@ says.
588
590
  For Claude and Codex app-server, `RunConfig.mcpServers` is the complete set of wire-configured
589
591
  servers for that turn, not an incremental patch. Repeating an unchanged set
590
592
  reuses the running process and its MCP connections. Changed entries are
591
- applied through the harness's native configuration API before the prompt;
593
+ applied through the harness's native configuration API before the prompt
594
+ (a Codex turn that names no home starts a new process for them, below);
592
595
  finishing a turn does not restart the agent or its servers. Omitting the map
593
596
  on a later turn removes the previous wire-configured set, just like `{}`.
594
597
  Claude's host `sdkMcpServers` remain attached. The native CLI may also load MCP servers
@@ -615,10 +618,46 @@ turns and supply the current complete map on each turn. The explicit live
615
618
  next turn's map takes precedence. External MCP servers enforce credential
616
619
  expiry; ending a turn does not itself revoke an attached credential.
617
620
 
618
- Codex supports stdio and Streamable HTTP servers; legacy SSE is rejected. Its
619
- per-turn MCP configuration requires an existing, absolute, session-specific
620
- `config.env.CODEX_HOME` directory (below `inheritConfig: "all"` every Codex
621
- turn does). Create it with mode `0700`, retain it while
621
+ Codex supports stdio and Streamable HTTP servers; legacy SSE is rejected,
622
+ and Codex's `codex_apps` name is reserved. Where a turn's servers go depends
623
+ on whether it names a home (LLP 0001, D21).
624
+
625
+ **No home named** (`inheritConfig: "all"` only). The turn runs in the
626
+ process's Codex home, the user's own `~/.codex`, with the user's servers,
627
+ threads and login, and its servers ride the thread's own config
628
+ (`thread/start` and `thread/resume`): the engine writes no file. What Codex
629
+ does with a thread's config is Codex's: with 0.160.0 no file of the home held
630
+ the servers' headers or environment (observed, LLP 0001 D21), and no test
631
+ holds that, so look again when the Codex pin moves. A thread's config is
632
+ fixed once it is open, so:
633
+
634
+ - An unchanged set keeps the warm process and its connections.
635
+ - A changed set (a server added, removed or changed, a rotated header)
636
+ replaces the session's process before the turn and resumes the thread with
637
+ the new set, as a login change does. It costs about a tenth of a second,
638
+ and ends the terminals earlier turns left running. `required` is the
639
+ engine's and is no change.
640
+ - A server that could not connect is tried again by a reload, in the same
641
+ process, on the schedule above.
642
+ - A server whose name Codex's own configuration also has (the user's
643
+ `config.toml`, a trusted repository's `.codex/config.toml`) is merged with
644
+ it by Codex, setting by setting: the turn's values win, and the other's
645
+ remaining headers, environment and tool filter would apply to the turn's
646
+ server. The engine reads Codex's configuration before the thread opens and
647
+ before each turn, and refuses such a turn as `invalid_request`, naming
648
+ `mcpServers.<name>`; rename one of them. A same-named server that sets
649
+ nothing more than the turn does goes on as the turn's. The refusal is the
650
+ whole turn's, `required: false` or not, so a product whose servers have
651
+ common names (`github`, `linear`) gives them names of its own before it
652
+ runs Codex without a home.
653
+ - A session whose first turn failed before the model ran (a required server
654
+ down) has no conversation yet, and reported no native id: its next turn
655
+ starts one.
656
+
657
+ **A home named** (`config.env.CODEX_HOME`; below `inheritConfig: "all"`
658
+ every Codex turn names one). An existing, absolute, session-specific
659
+ directory, where the engine writes the turn's servers. Create it with mode
660
+ `0700`, retain it while
622
661
  the conversation may resume, and delete it when that logical session is
623
662
  released. It contains conversation history and MCP credentials. Never share
624
663
  it between sessions or use the operator's normal Codex home.
@@ -631,12 +670,14 @@ while retaining login and token renewal in its own account manager.
631
670
  The repository's interactive CLI accepts `--codex-home=/absolute/private/path`
632
671
  and remembers the path for `--continue`; the operator supplies the existing home.
633
672
  Standalone CLI use relies on native authentication in that home. `--connect`
634
- can use an embedded server's external authentication instead.
673
+ can use an embedded server's external authentication instead. Without
674
+ `--codex-home`, at `--inherit-config=all`, the CLI's Codex turns run in the
675
+ user's own home with their `--mcp` servers in the thread's config.
635
676
  The ACP **server binding** (`createAcpAgentApp` /
636
677
  `agent-server --acp --harness codex-app-server`) has no per-session environment
637
678
  resource seam in this release. It rejects supplied Codex MCP servers explicitly
638
679
  at `session/new` or `session/resume`. Use the engine or standard JSON-RPC API
639
- with `config.env.CODEX_HOME` for that combination. This limitation is separate
680
+ for that combination. This limitation is separate
640
681
  from the engine's ACP **harness**, which forwards MCP to other ACP agents.
641
682
 
642
683
  An explicitly supplied `CODEX_HOME` gives the engine ownership of that home's
@@ -644,11 +685,11 @@ user-layer `mcp_servers` table: each turn replaces that table, including
644
685
  clearing it when the map is omitted. Without an explicit home or a per-turn
645
686
  map, native Codex configuration continues to work normally. Repository and
646
687
  plugin servers remain separate, but a higher-priority setting that changes a
647
- requested server fails preparation before reload. Codex's `codex_apps` name
648
- is reserved.
688
+ requested server fails preparation before reload.
649
689
 
650
- Codex writes changed configuration without reloading, verifies its effective
651
- settings, then reloads MCP and checks readiness before submitting the prompt.
690
+ In a home, Codex writes changed configuration without reloading, verifies its
691
+ effective settings, then reloads MCP and checks readiness before submitting
692
+ the prompt; without one, the servers start with the thread.
652
693
  Servers still starting are awaited through native startup notifications, with
653
694
  a bounded deadline (30 seconds); a required server that failed fails
654
695
  preparation at once, with the cause Codex gave.
@@ -709,6 +750,139 @@ event later: its `events/replay` answers `unknownSession`, and that answer *is*
709
750
  the terminal signal (the session is gone; nothing more will be appended to it).
710
751
  Treat `unknownSession` on replay as "session over", not as an error to retry.
711
752
 
753
+ ## Let an outside agent operate your sessions
754
+
755
+ `@zvada/agent-server/operator` gives a hosted assistant (ChatGPT, Claude, a
756
+ CLI agent) the tools to operate your product's coding agents:
757
+ `list_sessions`, `read_session`, `start_session`, `send_message`,
758
+ `wait_for_session`, `watch_sessions`, `answer_request`, `stop_session`. They
759
+ answer in short text that names the next call and never report a session
760
+ waiting on a person as done. Each tool that waits takes one argument, `wait`
761
+ (seconds, default 60, 0 looks once and returns), and no call is held past
762
+ `maxWaitSeconds` (90, or a function of the caller, such as the seconds its
763
+ sign-in has left; below one second a call looks once and answers). What an
764
+ agent, a person or a repository wrote is quoted, each line after ` | `, so
765
+ it never reads as a hint (` -> tool(args)`); a plan or permission is
766
+ approved only by an answer that is a yes and nothing more; a form, a page to
767
+ visit or a secret is shown as waiting on the person, where the session runs,
768
+ and the tools refuse to answer it (LLP 0014).
769
+
770
+ You implement `OperatorHost`: which sessions the caller sees, how to read one,
771
+ how to send, cancel and answer a turn. Who may call, what a session is called
772
+ and where it is stored stay yours. A host over the engine alone, folding
773
+ events in memory:
774
+
775
+ ```ts
776
+ import { OperatorError, createOperator, phaseOf, viewOf, type OperatorHost } from "@zvada/agent-server/operator";
777
+
778
+ server.onEvent(({ sessionId, event }) => {
779
+ const held = sessions.get(sessionId);
780
+ if (held) held.state = reduceConversation(held.state, event);
781
+ for (const wake of waiters) wake(); // `changed` below
782
+ });
783
+ const host: OperatorHost<Caller> = {
784
+ list: async () => [...sessions].map(([id, s]) =>
785
+ ({ id, name: s.name, group: s.project, phase: phaseOf(viewOf(s.state)), root: s.cwd })),
786
+ view: async (_caller, id) => viewOf(sessions.get(id)!.state),
787
+ async send(_caller, id, message, { delivery }) {
788
+ if (delivery === "interrupt") await client.cancelTurn(id);
789
+ try {
790
+ await client.startTurn({ sessionId: id, turnId: crypto.randomUUID(), input: message, config: configFor(id) });
791
+ } catch (error) {
792
+ if (/turnActive/.test(String(error))) throw new OperatorError("It is still working. Nothing was sent.");
793
+ throw error;
794
+ }
795
+ },
796
+ cancel: async (_caller, id) => void (await client.cancelTurn(id)),
797
+ async respond(_caller, id, answer) {
798
+ if (answer.kind === "question") await client.respondElicitation(id, answer.requestId, answer.outcome);
799
+ else await client.respondPermission(id, answer.requestId, answer.outcome);
800
+ },
801
+ start: async (_caller, { group, message }) => newSession(group, message), // optional
802
+ groups: async () => projects.map((p) => p.name), // optional
803
+ outcome: async (_caller, entry) => `changes: ${await diffStat(entry.root)}`, // optional
804
+ changed: (signal) => new Promise((resolve) => { // optional
805
+ const wake = () => { waiters.delete(wake); resolve(); };
806
+ waiters.add(wake);
807
+ signal.addEventListener("abort", wake, { once: true });
808
+ }),
809
+ };
810
+ const operator = createOperator(host);
811
+ ```
812
+
813
+ `viewOf` makes a session's view from the engine's folded state; a host that
814
+ keeps rows of its own builds the same `SessionView` (its messages, what it
815
+ waits on in the engine's request shapes). This host makes its own turn ids
816
+ and does not detect repeats, so a model that sends the same message twice is
817
+ told the session is busy. A host that wants to join a repeat instead (the
818
+ same caller, session and message while the turn that message started has not
819
+ ended) sends nothing and resolves `send` to `{ duplicate: true }`; `start`
820
+ returns its `SessionEntry` with `duplicate: true` for the same caller's same
821
+ task in the same project while that session sets up or its first turn runs
822
+ (`StartResult`). Only then does `wait: 0` look at the session, answering how
823
+ that turn stands, and a wait settle from the current view at once; a fresh
824
+ send or start answers "the agent is working", since your view may not show
825
+ its turn yet. `start` may return as soon as the session exists: until its
826
+ first turn begins, its view is `working` with no messages, and the wait
827
+ covers setup and the turn alike. When a send or a stop did something your
828
+ view cannot show (a message you held and replaced, or dropped before it was
829
+ sent), say it in one line: `send` resolves to `{ note }`, which
830
+ `send_message` says before the outcome, and `cancel` resolves to `{ note }`,
831
+ which `stop_session` answers with instead of waiting for the view to change.
832
+ `start` is optional, and without it there is no `start_session`.
833
+ `entry(caller, id)` is optional too: a host whose `list` holds only its
834
+ newest sessions gives the others by id there. It gets any reference that
835
+ names nothing listed, and may throw an `OperatorError` to refuse one in your
836
+ words (a session archived). `groups(caller)` is optional: every project a
837
+ session could start in, so `list_sessions` shows the ones with no session
838
+ yet. `extra: [tool({...})]` adds your own tools (a diff, an archive) beside
839
+ these; mark one that reaches past your host `openWorld` and one that may
840
+ lose work `destructive`. `changed` must remove what it registered when its
841
+ signal aborts; the operator aborts it after every look. A plan request you
842
+ build yourself uses the engine's `PLAN_OPTIONS` and `PLAN_TITLE`, exported
843
+ here, so `answer_request` reads it as a plan.
844
+
845
+ Access is yours too. `tools()` is the same for every caller (an assistant
846
+ keeps the list it got when it connected), so refuse a call around `call`, in
847
+ your words:
848
+
849
+ ```ts
850
+ import { OperatorError, type ToolSource } from "@zvada/agent-server/operator";
851
+
852
+ const tools: ToolSource<Caller> = {
853
+ tools: (caller) => operator.tools(caller),
854
+ async call(name, args, caller) {
855
+ const found = operator.tools(caller).find((tool) => tool.name === name);
856
+ if (found && !found.readOnly && !caller.canOperate) {
857
+ throw new OperatorError(`${name} needs operate access here. Nothing was done.`);
858
+ }
859
+ return operator.call(name, args, caller);
860
+ },
861
+ };
862
+ ```
863
+
864
+ Serve them over MCP (stateless Streamable HTTP) with `createMcpHandler`. It
865
+ has no dependency and is not a server: your route authenticates and names the
866
+ caller.
867
+
868
+ ```ts
869
+ import { createMcpHandler } from "@zvada/agent-server/operator";
870
+
871
+ const mcp = createMcpHandler(tools, { name: "my-product", version: "1.0.0" });
872
+ app.post("/mcp", async (c) => {
873
+ const caller = await authenticate(c.req.header("authorization")); // yours: 401 if not
874
+ const answer = await mcp(await c.req.json(), caller);
875
+ return answer === null ? c.body(null, 202) : c.json(answer);
876
+ });
877
+ app.get("/mcp", (c) => c.body(null, 405));
878
+ ```
879
+
880
+ A failed call reaches the model as an `isError` tool result, not a JSON-RPC
881
+ error, so it reads the reason. Throw an `OperatorError` for words you mean
882
+ the model to act on: its message goes through as it is. Any other error may
883
+ carry an agent's or a repository's text, so it is answered as one quoted
884
+ line (`The tool failed: "…"`); turn your own refusals into `OperatorError`s.
885
+
712
886
  ## Listen to the engine's diagnostics
713
887
 
714
888
  Pass `onDiagnostic` (registry/runtime/proxy options) and log what arrives:
package/docs/harnesses.md CHANGED
@@ -54,7 +54,7 @@ warm multi-turn reuse, a unified `ThinkingLevel`, and normalized token usage.
54
54
  | `systemPromptAppend` | ✅ | ✅ (`developerInstructions`) |
55
55
  | `additionalDirectories` | ✅ | ✅ (writable roots of the workspace-write sandbox; a change starts a new process) |
56
56
  | `maxTurns` | ✅ | ❌ |
57
- | `mcpServers` | ✅ | ✅ (stdio / Streamable HTTP; isolated `CODEX_HOME`) |
57
+ | `mcpServers` | ✅ | ✅ (stdio / Streamable HTTP; in the thread's config, or written to the `CODEX_HOME` the turn names) |
58
58
  | `apiKey` / `env` | ✅ | ✅ (the key logs in that session's process, in memory only; a credential the product holds wins) |
59
59
  | `disableTools` | ✅ | ❌ refused as `invalid_request`: Codex gives the model its tools however it is configured (use `plan` or `default`) |
60
60
  | permission requests (capability `permissionRequests`) | ✅ (`canUseTool`) | ✅ (`on-request` approvals in `default`, `accept_edits` and `plan`, MCP tool consent included; a plan turn's edits are declined) |
@@ -115,11 +115,15 @@ confirmed fails with its outcome unknown, and the cancel answers
115
115
  `unconfirmed`. A cancel that arrives after Codex's turn ended stops nothing.
116
116
 
117
117
  Codex per-turn MCP is supported through the engine and JSON-RPC API, and the
118
- repository CLI with an explicit `--codex-home`. The ACP server binding cannot
119
- provide isolated homes and rejects this combination at session admission.
120
- Below `inheritConfig: "all"` every Codex turn needs such a home, so the bin
121
- refuses `--acp --harness codex-app-server` with `--inherit-config project` or
122
- `none`.
118
+ repository CLI: in the user's own Codex home at `inheritConfig: "all"`, where
119
+ the servers ride the thread's config and nothing is written, or in a home of
120
+ the session's own (`config.env.CODEX_HOME`, the CLI's `--codex-home`), where
121
+ the engine writes them (LLP 0001, D21; see
122
+ [MCP configuration](consuming.md#configure-mcp-between-turns)). The ACP
123
+ server binding rejects Codex MCP at session admission.
124
+ Below `inheritConfig: "all"` every Codex turn needs a home of its session's
125
+ own, so the bin refuses `--acp --harness codex-app-server` with
126
+ `--inherit-config project` or `none`.
123
127
 
124
128
  The ACP server binding (`agent-server --acp`) records each session's native
125
129
  id under `$AGENT_SERVER_ACP_SESSION_DIR` (default
@@ -256,8 +260,9 @@ or none, which runs the turn as without it (its own `apiKey`, else the
256
260
  `CODEX_HOME`'s own login). Throw when the selected account is unavailable:
257
261
  the turn fails before Codex starts.
258
262
 
259
- Authentication and session storage are independent. Per-turn MCP still needs an
260
- isolated `CODEX_HOME` for writable configuration and conversation history, but
263
+ Authentication and session storage are independent. A session in a home of
264
+ its own (every one below `inheritConfig: "all"`, and one whose MCP servers
265
+ the engine writes) keeps its configuration and conversation history there, and
261
266
  a held credential lets the host authenticate that session without a separate
262
267
  native login or copying `auth.json` into each home. The engine keeps no token
263
268
  store: its logins (`auth/login`) are the CLI's own, stored in a home's own
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zvada/agent-server",
3
- "version": "0.3.20",
3
+ "version": "0.3.22",
4
4
  "description": "Harness-agnostic agent execution engine: run Claude Code, Codex (app-server), and any ACP agent behind one interface with a normalized event stream, multi-turn sessions, and resume. Root export is the wire contract; /core, /server, /client are the seats.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -96,6 +96,11 @@
96
96
  "types": "./dist/types/accounts/index.d.ts",
97
97
  "default": "./src/accounts/index.ts"
98
98
  },
99
+ "./operator": {
100
+ "agent-server-source": "./src/operator/index.ts",
101
+ "types": "./dist/types/operator/index.d.ts",
102
+ "default": "./src/operator/index.ts"
103
+ },
99
104
  "./package.json": "./package.json",
100
105
  "./sync": {
101
106
  "agent-server-source": "./src/sync/index.ts",
@@ -346,6 +346,9 @@ export class Connection {
346
346
  // A refusal is the server's answer, not an outage: every redial would get it.
347
347
  if (failure instanceof ConnectionRefusedError) return this.refused(failure);
348
348
  error = failure instanceof Error ? failure.message : String(failure);
349
+ // The attempt's own transport, when its handshake failed: the next
350
+ // attempt opens another, and nothing else would close this one.
351
+ this.discard();
349
352
  }
350
353
  }
351
354
  if (!this.closed) {
@@ -359,6 +362,13 @@ export class Connection {
359
362
  }
360
363
  }
361
364
 
365
+ /** Let the current transport go without reporting it as a drop: it was never handed over. */
366
+ private discard(): void {
367
+ const transport = this.transport;
368
+ this.transport = null;
369
+ transport?.close();
370
+ }
371
+
362
372
  /** Closed for good by the server's refusal, which what waits on the connection fails with. */
363
373
  private refused(refusal: ConnectionRefusedError): void {
364
374
  if (this.closed) return;
@@ -38,8 +38,8 @@ export interface LoginsPort {
38
38
  }
39
39
 
40
40
  /**
41
- * Start a login and follow it to its end. Its end is watched for from before
42
- * the request: `auth/updated` may come before the answer.
41
+ * Start a login and follow it to its end. Its end, and the connection's, are
42
+ * watched for from before the request: either may come before the answer.
43
43
  */
44
44
  export async function startLogin(
45
45
  port: LoginsPort,
@@ -47,20 +47,31 @@ export async function startLogin(
47
47
  ): Promise<LoginHandle> {
48
48
  // Every login's end from before the request: this one's may come before its answer.
49
49
  const early = new Map<string, AuthUpdated>();
50
- const follow: { told?: (update: AuthUpdated) => void } = {};
50
+ const follow: { told?: (update: AuthUpdated) => void; lost?: () => void } = {};
51
+ /** The connection was lost before the answer was read: no end can be told now. */
52
+ let lostEarly = false;
51
53
  const offUpdates = port.updates.add((update) => {
52
54
  if (!update.login) return;
53
55
  if (follow.told) follow.told(update);
54
56
  else early.set(update.login.loginId, update);
55
57
  });
58
+ const offConnection = port.connection.add((event) => {
59
+ // Its end may be told while the connection is down: a product reads the login again.
60
+ if (follow.lost) {
61
+ if (event.state === "reconnected" || event.state === "closed") follow.lost();
62
+ }
63
+ // Before its answer is read, a drop is what loses it: a request sent
64
+ // during a redial's handshake is followed by that redial's `reconnected`.
65
+ else if (event.state === "disconnected" || event.state === "closed") lostEarly = true;
66
+ });
56
67
  let login: AuthLogin;
57
68
  try {
58
69
  login = await request();
59
70
  } catch (error) {
60
71
  offUpdates();
72
+ offConnection();
61
73
  throw error;
62
74
  }
63
- let offConnection = () => {};
64
75
  let resolveDone!: (auth: HarnessAuth) => void;
65
76
  let rejectDone!: (error: LoginError) => void;
66
77
  const done = new Promise<HarnessAuth>((resolve, reject) => {
@@ -80,17 +91,15 @@ export async function startLogin(
80
91
  if (update?.login?.loginId === login.loginId) settle(update.login, update.auth);
81
92
  };
82
93
  follow.told = told;
83
- // Its end may be told while the connection is down: a product reads the login again.
84
- offConnection = port.connection.add((event) => {
85
- if (event.state === "reconnected" || event.state === "closed") {
86
- settle({
87
- loginId: login.loginId,
88
- outcome: "disconnected",
89
- error: "The connection to the server was lost: read the login's status again.",
90
- });
91
- }
92
- });
94
+ follow.lost = () =>
95
+ settle({
96
+ loginId: login.loginId,
97
+ outcome: "disconnected",
98
+ error: "The connection to the server was lost: read the login's status again.",
99
+ });
100
+ // An end told early wins: it says how the login ended, a lost connection only that it is unknown.
93
101
  told(early.get(login.loginId));
102
+ if (lostEarly) follow.lost();
94
103
  return {
95
104
  ...login,
96
105
  done,
@@ -27,13 +27,40 @@ export type ClaudeTurnRequests = Pick<
27
27
  /** What Claude is told when it asks while no turn runs. */
28
28
  const NO_TURN = "No turn is running, so nobody can answer this.";
29
29
 
30
+ /** The SDK's warning, at `query()`, that its spawn options shadow `canUseTool`. */
31
+ const CALLBACK_SHADOWED = "CLAUDE_SDK_CAN_USE_TOOL_SHADOWED";
32
+
33
+ /**
34
+ * Start a session's query. Under `bypassPermissions` the SDK warns that
35
+ * `canUseTool` is never asked, but Claude still asks it about what needs a
36
+ * person (AskUserQuestion, ExitPlanMode), which is what the callback is for:
37
+ * that warning is left off the host's stderr, where it would print a stack at
38
+ * every spawn. Any other warning, and this one in any other mode, passes.
39
+ */
40
+ export function startQuery<Q>(permissionMode: string | undefined, start: () => Q): Q {
41
+ if (permissionMode !== "bypassPermissions") return start();
42
+ const emit = process.emitWarning;
43
+ process.emitWarning = ((warning: string | Error, ...rest: unknown[]) => {
44
+ if ((rest[0] as { code?: unknown } | undefined)?.code === CALLBACK_SHADOWED) return;
45
+ (emit as (...args: unknown[]) => void).call(process, warning, ...rest);
46
+ }) as typeof process.emitWarning;
47
+ try {
48
+ return start();
49
+ } finally {
50
+ process.emitWarning = emit;
51
+ }
52
+ }
53
+
30
54
  /**
31
55
  * The SDK approval callback, fixed at spawn: it asks the turn running when it
32
- * is called. Questions and plans go to the user first: they are not
33
- * approvals, so no host policy answers them. Then the host `toolPolicy` (full
34
- * native PermissionResult power), then the turn's interactive broker. The SDK
35
- * passes a REAL `toolUseID` (>=0.2.138), so brokered requests correlate to
36
- * their tool parts exactly.
56
+ * is called, which Claude does for a call its mode and rules do not approve
57
+ * by themselves (under `bypass_permissions`, only questions and plans). The
58
+ * host `toolPolicy` sees each such call first (full native PermissionResult
59
+ * power), questions and plans included; a call it leaves
60
+ * (`undefined`) goes to the turn: a question to its elicitation, a plan or a
61
+ * tool's approval to its interactive broker. The SDK passes a REAL
62
+ * `toolUseID` (>=0.2.138), so brokered requests correlate to their tool parts
63
+ * exactly.
37
64
  */
38
65
  export function createCanUseTool(deps: {
39
66
  sessionId: string;
@@ -44,7 +71,7 @@ export function createCanUseTool(deps: {
44
71
  return async (toolName, input, options) => {
45
72
  const { signal, toolUseID, agentID, suggestions, blockedPath, decisionReason } = options;
46
73
  // The host's policy sees every call first, questions and plans too: a
47
- // host answers a plan through its own channel (Deus does). A policy
74
+ // host answers a plan through its own channel (AGNT does). A policy
48
75
  // that wants the user to answer them returns undefined.
49
76
  const verdict = await deps.policy?.(toolName, input, {
50
77
  sessionId: deps.sessionId,
@@ -48,9 +48,11 @@ export type ClaudeSdkOptionOverrides = Partial<
48
48
  >;
49
49
 
50
50
  /**
51
- * Pre-broker tool policy: the host's programmatic say on every tool call,
52
- * questions (AskUserQuestion) and plan approvals (ExitPlanMode) included,
53
- * BEFORE the interactive permission broker and elicitation. Returns the SDK's own
51
+ * Pre-broker tool policy: the host's programmatic say on every call Claude
52
+ * asks about, questions (AskUserQuestion) and plan approvals (ExitPlanMode)
53
+ * included, BEFORE the interactive permission broker and elicitation. Claude
54
+ * asks about a call its mode and rules do not approve by themselves: under
55
+ * `bypass_permissions`, only questions and plans. Returns the SDK's own
54
56
  * `PermissionResult` (so hosts keep full native power: `updatedInput`,
55
57
  * `updatedPermissions`) or undefined to fall through to the broker.
56
58
  * Operator embed-tier only — never wire-sourced.
@@ -14,7 +14,7 @@ import type { NativeProcess } from "../../processes/native-processes.ts";
14
14
  import { withTimeout } from "../../utils/deadline.ts";
15
15
  import { SessionResumeError } from "../../utils/errors.ts";
16
16
  import { IDLE_TIMEOUT_MS } from "../session-pool.ts";
17
- import { createCanUseTool, createOnElicitation } from "./approvals.ts";
17
+ import { createCanUseTool, createOnElicitation, startQuery } from "./approvals.ts";
18
18
  import { commandStarted } from "./events.ts";
19
19
  import { ClaudeMcpConnections } from "./mcp.ts";
20
20
  import {
@@ -188,7 +188,9 @@ export class ClaudeSession {
188
188
  // Release/shutdown may finish while an async options/tool factory is
189
189
  // pending. Never create a query after its owner has already terminated.
190
190
  if (this.currentState === "terminated") throw new Error("Session terminated during startup");
191
- this.query = sdk.query({ prompt: this.promptQueue, options });
191
+ this.query = startQuery(options.permissionMode, () =>
192
+ sdk.query({ prompt: this.promptQueue, options }),
193
+ );
192
194
  const events = this.consumeEvents();
193
195
  if (!this.config.disableTools && Object.keys(this.mcp.servers).length) {
194
196
  try {
@@ -48,6 +48,12 @@ export interface CodexConnection {
48
48
  close(): void;
49
49
  /** End the app-server by its own shutdown: whether that confirmed its threads and tools stopped. */
50
50
  closeAndWait(timeoutMs?: number): Promise<boolean>;
51
+ /**
52
+ * Settles once an app-server that was ended has exited, or could not be
53
+ * made to: Codex lets one process write a thread, so another resumes it
54
+ * after this. A connection without it has nothing to wait for.
55
+ */
56
+ gone?(): Promise<void>;
51
57
  }
52
58
 
53
59
  /** How far `pages` reads a list. */
@@ -156,6 +162,8 @@ export class CodexAppServerClient implements CodexConnection {
156
162
  private exited = false;
157
163
  private lastExit?: Error;
158
164
  private nativeShutdownFailed = false;
165
+ /** The app-server's exit, or the end of a stop that could not end it. */
166
+ private leaving?: Promise<unknown>;
159
167
 
160
168
  constructor(private readonly opts: CodexAppServerClientOptions) {}
161
169
 
@@ -225,10 +233,17 @@ export class CodexAppServerClient implements CodexConnection {
225
233
  this.rejectPending((method) => new Error(`codex app-server closed before '${method}'`));
226
234
  // SIGTERM stops its command at once (0.07 s, measured); the walk and the
227
235
  // SIGKILL after the grace cover an app-server that cannot act on it.
228
- void native?.stop();
236
+ if (native) this.leaving = Promise.race([native.exited, native.stop()]);
229
237
  if (wasOpen) this.notifyClosed();
230
238
  }
231
239
 
240
+ gone(): Promise<void> {
241
+ return Promise.resolve(this.leaving).then(
242
+ () => {},
243
+ () => {},
244
+ );
245
+ }
246
+
232
247
  /** EOF invokes native thread/tool cleanup. Killing the server alone proves nothing about workers. */
233
248
  closeAndWait(timeoutMs = 2_000): Promise<boolean> {
234
249
  if (this.shutdown) return this.shutdown;
@@ -240,6 +255,15 @@ export class CodexAppServerClient implements CodexConnection {
240
255
  return this.shutdown;
241
256
  }
242
257
  this.exited = true;
258
+ // Gone when it exited, or when the stop a slow shutdown falls back to is
259
+ // done: that can outlast the answer this returns.
260
+ let stopped = () => {};
261
+ this.leaving = Promise.race([
262
+ native.exited,
263
+ new Promise<void>((resolve) => {
264
+ stopped = resolve;
265
+ }),
266
+ ]);
243
267
  this.shutdown = new Promise<boolean>((resolve) => {
244
268
  let forced = false;
245
269
  const finish = (confirmed: boolean) => {
@@ -254,7 +278,7 @@ export class CodexAppServerClient implements CodexConnection {
254
278
  // @ref LLP 0007#what-each-harness-does — a SIGKILLed app-server leaves its commands running
255
279
  const killTimer = setTimeout(() => {
256
280
  forced = true;
257
- void native.stop();
281
+ void native.stop().then(stopped, stopped);
258
282
  }, timeoutMs);
259
283
  const deadline = setTimeout(() => finish(false), timeoutMs * 2);
260
284
  // In stdio mode SIGTERM bypasses Codex's async shutdown. EOF drains
@@ -297,6 +321,7 @@ export class CodexAppServerClient implements CodexConnection {
297
321
  ...(this.opts.sessionId !== undefined && { sessionId: this.opts.sessionId }),
298
322
  });
299
323
  this.native = native;
324
+ this.leaving = native.exited;
300
325
  const proc = native.child;
301
326
  proc.stdout?.on("data", (chunk: Buffer) => this.onStdout(chunk));
302
327
  // A broken pipe usually means the process died: its exit, which says
@@ -394,6 +419,11 @@ export class CodexAppServerClient implements CodexConnection {
394
419
  if (this.exited) return;
395
420
  this.exited = true;
396
421
  this.lastExit = error;
422
+ // A broken pipe closes it while the app-server may still run (wedged,
423
+ // its stdin gone). It is stopped, so the process that takes its thread
424
+ // waits the stop's grace at most, not for an exit that never comes.
425
+ const native = this.native;
426
+ if (native) this.leaving = Promise.race([native.exited, native.stop()]);
397
427
  this.rejectPending(() => error);
398
428
  this.notifyClosed(error);
399
429
  }