@zvada/agent-server 0.3.26 → 0.3.27

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 (124) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +1 -1
  3. package/dist/client/client.js +27 -11
  4. package/dist/client/connection.js +35 -3
  5. package/dist/core/agents/claude-code/approvals.js +1 -1
  6. package/dist/core/agents/codex-app-server/plan-approval.js +1 -1
  7. package/dist/core/agents/scripted/scripted-agent.js +30 -3
  8. package/dist/core/presets.js +4 -1
  9. package/dist/core/runtime/agent-runtime.js +15 -5
  10. package/dist/core/runtime/event-processor.js +13 -8
  11. package/dist/core/runtime/origin-line.js +42 -0
  12. package/dist/core/runtime/request-broker.js +2 -1
  13. package/dist/core/runtime/steering.js +4 -3
  14. package/dist/core/runtime/turn.js +6 -4
  15. package/dist/operator/errors.js +97 -0
  16. package/dist/operator/index.js +10 -5
  17. package/dist/operator/mcp.js +7 -12
  18. package/dist/operator/operator.js +1336 -380
  19. package/dist/operator/refs.js +59 -0
  20. package/dist/operator/render.js +171 -74
  21. package/dist/operator/session-tools.js +87 -0
  22. package/dist/operator/types.js +30 -0
  23. package/dist/operator/view.js +82 -27
  24. package/dist/protocol/config.js +12 -5
  25. package/dist/protocol/conversation.js +3 -0
  26. package/dist/protocol/history.js +2 -1
  27. package/dist/protocol/index.js +1 -0
  28. package/dist/protocol/lifecycle.js +19 -0
  29. package/dist/protocol/origin.js +39 -0
  30. package/dist/protocol/reduce.js +2 -0
  31. package/dist/protocol/wire.js +17 -0
  32. package/dist/server/routes.js +15 -5
  33. package/dist/types/client/client.d.ts.map +1 -1
  34. package/dist/types/client/connection.d.ts +14 -2
  35. package/dist/types/client/connection.d.ts.map +1 -1
  36. package/dist/types/client/turns.d.ts +2 -2
  37. package/dist/types/client/turns.d.ts.map +1 -1
  38. package/dist/types/core/agents/base.d.ts +2 -0
  39. package/dist/types/core/agents/base.d.ts.map +1 -1
  40. package/dist/types/core/agents/scripted/scripted-agent.d.ts +14 -1
  41. package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -1
  42. package/dist/types/core/presets.d.ts.map +1 -1
  43. package/dist/types/core/runtime/agent-runtime.d.ts +4 -2
  44. package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
  45. package/dist/types/core/runtime/event-processor.d.ts +2 -2
  46. package/dist/types/core/runtime/event-processor.d.ts.map +1 -1
  47. package/dist/types/core/runtime/origin-line.d.ts +15 -0
  48. package/dist/types/core/runtime/origin-line.d.ts.map +1 -0
  49. package/dist/types/core/runtime/request-broker.d.ts +1 -1
  50. package/dist/types/core/runtime/request-broker.d.ts.map +1 -1
  51. package/dist/types/core/runtime/steering.d.ts +7 -4
  52. package/dist/types/core/runtime/steering.d.ts.map +1 -1
  53. package/dist/types/core/runtime/turn.d.ts.map +1 -1
  54. package/dist/types/operator/errors.d.ts +83 -0
  55. package/dist/types/operator/errors.d.ts.map +1 -0
  56. package/dist/types/operator/index.d.ts +10 -5
  57. package/dist/types/operator/index.d.ts.map +1 -1
  58. package/dist/types/operator/mcp.d.ts +1 -1
  59. package/dist/types/operator/mcp.d.ts.map +1 -1
  60. package/dist/types/operator/operator.d.ts +15 -197
  61. package/dist/types/operator/operator.d.ts.map +1 -1
  62. package/dist/types/operator/refs.d.ts +25 -0
  63. package/dist/types/operator/refs.d.ts.map +1 -0
  64. package/dist/types/operator/render.d.ts +59 -19
  65. package/dist/types/operator/render.d.ts.map +1 -1
  66. package/dist/types/operator/session-tools.d.ts +61 -0
  67. package/dist/types/operator/session-tools.d.ts.map +1 -0
  68. package/dist/types/operator/types.d.ts +441 -0
  69. package/dist/types/operator/types.d.ts.map +1 -0
  70. package/dist/types/operator/view.d.ts +19 -29
  71. package/dist/types/operator/view.d.ts.map +1 -1
  72. package/dist/types/protocol/config.d.ts +20 -5
  73. package/dist/types/protocol/config.d.ts.map +1 -1
  74. package/dist/types/protocol/conversation.d.ts +44 -3
  75. package/dist/types/protocol/conversation.d.ts.map +1 -1
  76. package/dist/types/protocol/history.d.ts +1 -1
  77. package/dist/types/protocol/history.d.ts.map +1 -1
  78. package/dist/types/protocol/index.d.ts +1 -0
  79. package/dist/types/protocol/index.d.ts.map +1 -1
  80. package/dist/types/protocol/lifecycle.d.ts +40 -2
  81. package/dist/types/protocol/lifecycle.d.ts.map +1 -1
  82. package/dist/types/protocol/origin.d.ts +49 -0
  83. package/dist/types/protocol/origin.d.ts.map +1 -0
  84. package/dist/types/protocol/reduce.d.ts.map +1 -1
  85. package/dist/types/protocol/wire-api.d.ts +39 -1
  86. package/dist/types/protocol/wire-api.d.ts.map +1 -1
  87. package/dist/types/protocol/wire.d.ts +65 -2
  88. package/dist/types/protocol/wire.d.ts.map +1 -1
  89. package/dist/types/server/routes.d.ts.map +1 -1
  90. package/docs/consuming.md +56 -121
  91. package/docs/sync-history.md +2 -1
  92. package/package.json +1 -1
  93. package/src/client/client.ts +36 -9
  94. package/src/client/connection.ts +31 -1
  95. package/src/client/turns.ts +2 -1
  96. package/src/core/agents/base.ts +2 -0
  97. package/src/core/agents/claude-code/approvals.ts +2 -2
  98. package/src/core/agents/codex-app-server/plan-approval.ts +1 -1
  99. package/src/core/agents/scripted/scripted-agent.ts +42 -3
  100. package/src/core/presets.ts +4 -1
  101. package/src/core/runtime/agent-runtime.ts +31 -7
  102. package/src/core/runtime/event-processor.ts +13 -6
  103. package/src/core/runtime/origin-line.ts +43 -0
  104. package/src/core/runtime/request-broker.ts +2 -0
  105. package/src/core/runtime/steering.ts +8 -4
  106. package/src/core/runtime/turn.ts +11 -4
  107. package/src/operator/errors.ts +218 -0
  108. package/src/operator/index.ts +18 -23
  109. package/src/operator/mcp.ts +7 -16
  110. package/src/operator/operator.ts +1583 -613
  111. package/src/operator/refs.ts +75 -0
  112. package/src/operator/render.ts +208 -98
  113. package/src/operator/session-tools.ts +126 -0
  114. package/src/operator/types.ts +505 -0
  115. package/src/operator/view.ts +93 -42
  116. package/src/protocol/config.ts +14 -6
  117. package/src/protocol/conversation.ts +3 -0
  118. package/src/protocol/history.ts +2 -1
  119. package/src/protocol/index.ts +1 -0
  120. package/src/protocol/lifecycle.ts +21 -0
  121. package/src/protocol/origin.ts +47 -0
  122. package/src/protocol/reduce.ts +4 -0
  123. package/src/protocol/wire.ts +18 -0
  124. package/src/server/routes.ts +16 -5
package/docs/consuming.md CHANGED
@@ -977,140 +977,75 @@ event later: its `events/replay` answers `unknownSession`, and that answer *is*
977
977
  the terminal signal (the session is gone; nothing more will be appended to it).
978
978
  Treat `unknownSession` on replay as "session over", not as an error to retry.
979
979
 
980
- ## Let an outside agent operate your sessions
980
+ ## Let agents operate your sessions
981
981
 
982
- In this section the operator is that outside agent; elsewhere in this guide
982
+ In this section the operator is the agent doing it; elsewhere in this guide
983
983
  it is whoever runs the engine (an operator option).
984
- `@zvada/agent-server/operator` gives a hosted assistant (ChatGPT, Claude, a
985
- CLI agent) the tools to operate your product's coding agents:
986
- `list_sessions`, `read_session`, `start_session`, `send_message`,
987
- `wait_for_session`, `watch_sessions`, `answer_request`, `stop_session`. They
988
- answer in short text that names the next call and never report a session
989
- waiting on a person as done. Each tool that waits takes one argument, `wait`
990
- (seconds, default 60, 0 looks once and returns), and no call is held past
991
- `maxWaitSeconds` (90, or a function of the caller, such as the seconds its
992
- sign-in has left; below one second a call looks once and answers). What an
993
- agent, a person or a repository wrote is quoted, each line after ` | `, so
994
- it never reads as a hint (` -> tool(args)`); a plan or permission is
995
- approved only by an answer that is a yes and nothing more; a form, a page to
996
- visit or a secret is shown as waiting on the person, where the session runs,
997
- and the tools refuse to answer it (LLP 0014).
998
-
999
- You implement `OperatorHost`: which sessions the caller sees, how to read one,
1000
- how to send, cancel and answer a turn. Who may call, what a session is called
1001
- and where it is stored stay yours. A host over the engine alone, folding
1002
- events in memory:
984
+ `@zvada/agent-server/operator` gives an outside assistant (ChatGPT, Claude, a
985
+ CLI agent), your own window, and your own sessions' agents one set of tools
986
+ over your product's sessions: `whoami`, `list_sessions`, `read_session`,
987
+ `wait_for_sessions`, `list_models`, `start_session`, `send_message`,
988
+ `answer_request`, `stop_sessions`, `archive` (LLP 0019, LLP 0014). A tool your
989
+ host cannot serve is not listed. They answer in short text that names the
990
+ next call (only calls that exist), quote what agents and repositories wrote
991
+ after ` | `, and refuse with a closed set of codes:
992
+ `refused (<code>): <sentence>`.
993
+
994
+ The package owns, for every host, and keeps nothing between calls: a
995
+ message is sent only while the call carrying it is open (to a busy session
996
+ after its turn ends on its own, within the call's wait; otherwise the
997
+ answer says nothing was sent); an identical request in flight runs nothing
998
+ new;
999
+ a session may not act on itself, reads only in plan mode, answers only in
1000
+ sessions it started, and a permission only with full access; depth, starts
1001
+ per session, agent setups and starts per minute are limited (`limits`);
1002
+ waits are capped by caller (a session 120 s by default, at most 240; an
1003
+ outside caller 60, at most 90 and never past `endsAt`). Each message carries
1004
+ its sender to the engine (`origin`), which tells the receiving agent when it
1005
+ is not the person.
1006
+
1007
+ You implement `OperatorHost`: `list`, `view` (with the turn facts
1008
+ `running` and `lastEnded`, whatever page it shows), `turn` (one turn by
1009
+ id), `send` and `onChange` are required; the rest are capabilities (`entry`, `projects`, `start`,
1010
+ `cancel`, `respond`, `archive`, `models`, `authorize`, `policy`, `admit`,
1011
+ `outcome`, `describe`). A session is an engine session, its id minted by
1012
+ your `start` before it returns, even while its new workspace is set up
1013
+ (`status: setting_up`), and delivering the first message once it is set
1014
+ up is your `start`'s, as the turn `input.turnId` (a `cancel` with no turn
1015
+ id drops it); a workspace is your container for sessions. The package's
1016
+ checks are preflight: enforce archive eligibility, a start into an archived
1017
+ workspace or by an archived starter, and any cap across starters (agent
1018
+ setups, disk) atomically at your own commit, by throwing `Refused` with the
1019
+ code and the sessions concerned; the package words it. `viewOf` makes a session's
1020
+ `SessionView` from the engine's folded state; a host with rows of its own
1021
+ builds the same shape. `send` gets a turn id the package minted, to pass to
1022
+ `turn/start` as is, so a repeat converges. Keep your own access check at
1023
+ each write as well: the package asks `authorize` before each tool and each
1024
+ write it makes, not inside yours. A host that serves session callers gives
1025
+ `policy`, the facts the rules and limits rest on, from its own store.
1026
+ `test/operator/engine-host.ts` is a complete host over the engine in about
1027
+ 200 lines.
1003
1028
 
1004
1029
  ```ts
1005
- import { OperatorError, createOperator, phaseOf, viewOf, type OperatorHost } from "@zvada/agent-server/operator";
1030
+ import { createMcpHandler, createOperator, tool } from "@zvada/agent-server/operator";
1006
1031
 
1007
- server.onEvent(({ sessionId, event }) => {
1008
- const held = sessions.get(sessionId);
1009
- if (held) held.state = reduceConversation(held.state, event);
1010
- for (const wake of waiters) wake(); // `changed` below
1032
+ const operator = createOperator(host, {
1033
+ extra: [tool({ name: "read_changes", title: "Read changes", description: "…", input: {…}, effect: "read", run })],
1011
1034
  });
1012
- const host: OperatorHost<Caller> = {
1013
- list: async () => [...sessions].map(([id, s]) =>
1014
- ({ id, name: s.name, group: s.project, phase: phaseOf(viewOf(s.state)), root: s.cwd })),
1015
- view: async (_caller, id) => viewOf(sessions.get(id)!.state),
1016
- async send(_caller, id, message, { delivery }) {
1017
- if (delivery === "interrupt") await client.cancelTurn(id);
1018
- try {
1019
- await client.startTurn({ sessionId: id, turnId: crypto.randomUUID(), input: message, config: configFor(id) });
1020
- } catch (error) {
1021
- if (/turnActive/.test(String(error))) throw new OperatorError("It is still working. Nothing was sent.");
1022
- throw error;
1023
- }
1024
- },
1025
- cancel: async (_caller, id) => void (await client.cancelTurn(id)),
1026
- async respond(_caller, id, answer) {
1027
- if (answer.kind === "question") await client.respondElicitation(id, answer.requestId, answer.outcome);
1028
- else await client.respondPermission(id, answer.requestId, answer.outcome);
1029
- },
1030
- start: async (_caller, { group, message }) => newSession(group, message), // optional
1031
- groups: async () => projects.map((p) => p.name), // optional
1032
- outcome: async (_caller, entry) => `changes: ${await diffStat(entry.root)}`, // optional
1033
- changed: (signal) => new Promise((resolve) => { // optional
1034
- const wake = () => { waiters.delete(wake); resolve(); };
1035
- waiters.add(wake);
1036
- signal.addEventListener("abort", wake, { once: true });
1037
- }),
1038
- };
1039
- const operator = createOperator(host);
1040
- ```
1041
-
1042
- `viewOf` makes a session's view from the engine's folded state; a host that
1043
- keeps rows of its own builds the same `SessionView` (its messages, what it
1044
- waits on in the engine's request shapes). This host makes its own turn ids
1045
- and does not detect repeats, so a model that sends the same message twice is
1046
- told the session is busy. A host that wants to join a repeat instead (the
1047
- same caller, session and message while the turn that message started has not
1048
- ended) sends nothing and resolves `send` to `{ duplicate: true }`; `start`
1049
- returns its `SessionEntry` with `duplicate: true` for the same caller's same
1050
- task in the same project while that session sets up or its first turn runs
1051
- (`StartResult`). Only then does `wait: 0` look at the session, answering how
1052
- that turn stands, and a wait settle from the current view at once; a fresh
1053
- send or start answers "the agent is working", since your view may not show
1054
- its turn yet. `start` may return as soon as the session exists: until its
1055
- first turn begins, its view is `working` with no messages, and the wait
1056
- covers setup and the turn alike. When a send or a stop did something your
1057
- view cannot show (a message you held and replaced, or dropped before it was
1058
- sent), say it in one line: `send` resolves to `{ note }`, which
1059
- `send_message` says before the outcome, and `cancel` resolves to `{ note }`,
1060
- which `stop_session` answers with instead of waiting for the view to change.
1061
- `start` is optional, and without it there is no `start_session`.
1062
- `entry(caller, id)` is optional too: a host whose `list` holds only its
1063
- newest sessions gives the others by id there. It gets any reference that
1064
- names nothing listed, and may throw an `OperatorError` to refuse one in your
1065
- words (a session archived). `groups(caller)` is optional: every project a
1066
- session could start in, so `list_sessions` shows the ones with no session
1067
- yet. `extra: [tool({...})]` adds your own tools (a diff, an archive) beside
1068
- these; mark one that reaches past your host `openWorld` and one that may
1069
- lose work `destructive`. `changed` must remove what it registered when its
1070
- signal aborts; the operator aborts it after every look. A plan request you
1071
- build yourself uses the engine's `PLAN_OPTIONS` and `PLAN_TITLE`, exported
1072
- here, so `answer_request` reads it as a plan.
1073
-
1074
- Access is yours too. `tools()` is the same for every caller (an assistant
1075
- keeps the list it got when it connected), so refuse a call around `call`, in
1076
- your words:
1077
-
1078
- ```ts
1079
- import { OperatorError, type ToolSource } from "@zvada/agent-server/operator";
1080
-
1081
- const tools: ToolSource<Caller> = {
1082
- tools: (caller) => operator.tools(caller),
1083
- async call(name, args, caller) {
1084
- const found = operator.tools(caller).find((tool) => tool.name === name);
1085
- if (found && !found.readOnly && !caller.canOperate) {
1086
- throw new OperatorError(`${name} needs operate access here. Nothing was done.`);
1087
- }
1088
- return operator.call(name, args, caller);
1089
- },
1090
- };
1091
- ```
1092
-
1093
- Serve them over MCP (stateless Streamable HTTP) with `createMcpHandler`. It
1094
- has no dependency and is not a server: your route authenticates and names the
1095
- caller.
1096
-
1097
- ```ts
1098
- import { createMcpHandler } from "@zvada/agent-server/operator";
1099
-
1100
- const mcp = createMcpHandler(tools, { name: "my-product", version: "1.0.0" });
1035
+ const mcp = createMcpHandler(operator, { name: "my-product", version: "1.0.0" });
1101
1036
  app.post("/mcp", async (c) => {
1102
1037
  const caller = await authenticate(c.req.header("authorization")); // yours: 401 if not
1103
- const answer = await mcp(await c.req.json(), caller);
1038
+ const answer = await mcp(await c.req.json(), caller); // an ExternalCaller
1104
1039
  return answer === null ? c.body(null, 202) : c.json(answer);
1105
1040
  });
1106
1041
  app.get("/mcp", (c) => c.body(null, 405));
1107
1042
  ```
1108
1043
 
1109
- A failed call reaches the model as an `isError` tool result, not a JSON-RPC
1110
- error, so it reads the reason. Throw an `OperatorError` for words you mean
1111
- the model to act on: its message goes through as it is. Any other error may
1112
- carry an agent's or a repository's text, so it is answered as one quoted
1113
- line (`The tool failed: "…"`); turn your own refusals into `OperatorError`s.
1044
+ A host's own tool declares its `effect` honestly (anything that changes
1045
+ something or posts outside is `write`); plan mode and `authorize` apply to
1046
+ it, and it may not change sessions. A failed call reaches the model as an
1047
+ `isError` tool result: an `OperatorError`'s words as they are, any other
1048
+ failure as `refused (failed)` with none of its text.
1114
1049
 
1115
1050
  ## Listen to the engine's diagnostics
1116
1051
 
@@ -161,7 +161,8 @@ each increment. `openHistory` applies a checkpoint only at or before each
161
161
  segment's pinned cut, after verifying that prefix, then folds the tail; a newer
162
162
  checkpoint never substitutes for an older fork cut. A checkpoint in an unknown
163
163
  format is skipped and the events replayed, and `{checkpoints: false}` forces it.
164
- The format `agent-server.conversation.v1` changes whenever reducer semantics do.
164
+ The format (`agent-server.conversation.v2` since user messages carry `origin`)
165
+ changes whenever reducer semantics do.
165
166
  No method accepts an uploaded projection: stores build them from their own
166
167
  events, which stay authoritative.
167
168
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zvada/agent-server",
3
- "version": "0.3.26",
3
+ "version": "0.3.27",
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",
@@ -15,6 +15,7 @@ import {
15
15
  type InitializeResult,
16
16
  type ModelList,
17
17
  type ModelsListParams,
18
+ type Origin,
18
19
  type PermissionOutcome,
19
20
  type RunningTurn,
20
21
  type SessionConfirmStoppedParams,
@@ -27,8 +28,10 @@ import {
27
28
  type TurnSteerParams,
28
29
  type TurnSteerResult,
29
30
  WIRE_ERROR_CODES,
31
+ WIRE_FEATURES,
30
32
  WIRE_METHODS,
31
33
  type WireTransport,
34
+ agentOrigin,
32
35
  decodeWireEventEnvelope,
33
36
  decodeWireMessage,
34
37
  generateUUIDv7,
@@ -321,7 +324,7 @@ export class AgentServerClient {
321
324
  // Before the first `await`: a cancel sent right behind this call goes out after the start.
322
325
  const release = this.starts.begin(sessionId, turnId);
323
326
  try {
324
- await this.initialize();
327
+ carriesOrigin(await this.initialize(), params.origin);
325
328
  if (this.turns.running(sessionId))
326
329
  throw new Error(`session ${sessionId} already has an active turn`);
327
330
  const handle = this.turns.open(sessionId, turnId, true);
@@ -335,6 +338,7 @@ export class AgentServerClient {
335
338
  (ack) => {
336
339
  if (!ack.terminal) this.joinAt(handle, ack.headSeq, { turnId });
337
340
  },
341
+ (server) => carriesOrigin(server, params.origin),
338
342
  );
339
343
  release();
340
344
  const accepted = await sending;
@@ -373,7 +377,7 @@ export class AgentServerClient {
373
377
  // As in `runTurn`: a cancel sent right behind this call goes out after the start.
374
378
  const release = this.starts.begin(sessionId, turnId);
375
379
  try {
376
- await this.initialize();
380
+ carriesOrigin(await this.initialize(), params.origin);
377
381
  // `request` sends (or fails for no connection) in this call.
378
382
  const answer = this.connection.request(
379
383
  WIRE_METHODS.turnStart,
@@ -382,6 +386,7 @@ export class AgentServerClient {
382
386
  if (params.subscribe !== false && !ack.terminal)
383
387
  this.streams.joined(sessionId, ack.headSeq, { turnId });
384
388
  },
389
+ (server) => carriesOrigin(server, params.origin),
385
390
  );
386
391
  release();
387
392
  return await answer;
@@ -431,7 +436,7 @@ export class AgentServerClient {
431
436
  * steer's user message, its receipt, reaches it.
432
437
  */
433
438
  async steerTurn(params: TurnSteerParams): Promise<TurnSteerResult> {
434
- await this.initialize();
439
+ carriesOrigin(await this.initialize(), params.origin);
435
440
  const { sessionId, turnId } = params;
436
441
  // One it cannot subscribe to still takes the steer; only its receipt is lost.
437
442
  if (!this.streams.follows(sessionId))
@@ -440,10 +445,12 @@ export class AgentServerClient {
440
445
  if (ack.activeTurn?.turnId === turnId)
441
446
  this.streams.joined(sessionId, ack.headSeq, { turnId });
442
447
  }).catch(() => undefined);
443
- return this.connection.resend(WIRE_METHODS.turnSteer, {
444
- ...params,
445
- steerId: params.steerId ?? generateUUIDv7(),
446
- });
448
+ return this.connection.resend(
449
+ WIRE_METHODS.turnSteer,
450
+ { ...params, steerId: params.steerId ?? generateUUIDv7() },
451
+ undefined,
452
+ (server) => carriesOrigin(server, params.origin),
453
+ );
447
454
  }
448
455
 
449
456
  /**
@@ -895,8 +902,14 @@ export class AgentServerClient {
895
902
  get catchUp() {
896
903
  return handle.catchUp;
897
904
  },
898
- steer: (input: AgentInput, steerId?: string) =>
899
- this.steerTurn({ sessionId, turnId, input, ...(steerId !== undefined && { steerId }) }),
905
+ steer: (input: AgentInput, steerId?: string, origin?: Origin) =>
906
+ this.steerTurn({
907
+ sessionId,
908
+ turnId,
909
+ input,
910
+ ...(steerId !== undefined && { steerId }),
911
+ ...(origin && { origin }),
912
+ }),
900
913
  };
901
914
  }
902
915
 
@@ -971,3 +984,17 @@ export class AgentServerClient {
971
984
  return this.connection.request(WIRE_METHODS.sessionSubscribe, params, onAnswer);
972
985
  }
973
986
  }
987
+
988
+ // @ref LLP 0019#origin-on-the-wire-and-to-the-model — fail closed: an origin a server would strip reads as the person's
989
+ /**
990
+ * Refuse to send another sender's input to a server that does not carry
991
+ * `origin`: its schema would drop the field, and the agent would read the
992
+ * message as the person's. The person's input goes anywhere.
993
+ */
994
+ function carriesOrigin(server: InitializeResult, origin: Origin | undefined): void {
995
+ if (!agentOrigin(origin)) return;
996
+ if (server.features?.includes(WIRE_FEATURES.origin)) return;
997
+ throw new Error(
998
+ "This server does not carry a message's origin (no `origin` in its features); nothing was sent. Upgrade the server, or send the input as the person's.",
999
+ );
1000
+ }
@@ -180,6 +180,10 @@ export class Connection {
180
180
  /** The server process (or, durable, the journal) whose logs the client follows. */
181
181
  private serverIdentity: string | undefined;
182
182
  private initializing: Promise<InitializeResult> | null = null;
183
+ /** The current transport's handshake, once answered; cleared when it is asked again. */
184
+ private negotiated: InitializeResult | undefined;
185
+ /** The transport `negotiated` was answered on: a feature check holds only for it. */
186
+ private negotiatedOn: WireTransport | null = null;
183
187
  private reconnecting = false;
184
188
  /** Ends the redial backoff early: `close()` must not wait it out. */
185
189
  private stopBackoff: (() => void) | null = null;
@@ -218,6 +222,10 @@ export class Connection {
218
222
  }
219
223
  if (transport.closed) throw new ConnectionClosedError("transport opened already closed");
220
224
  this.transport = transport;
225
+ // A new transport's server is not the old one's until its own handshake says so.
226
+ this.initializing = null;
227
+ this.negotiated = undefined;
228
+ this.negotiatedOn = null;
221
229
  this.host.opened(this.reconnecting);
222
230
  transport.onLine((line) => {
223
231
  if (this.transport === transport) this.host.line(line, transport);
@@ -230,6 +238,8 @@ export class Connection {
230
238
  * client for good: it rejects with `ProtocolVersionMismatchError`.
231
239
  */
232
240
  initialize(): Promise<InitializeResult> {
241
+ if (!this.initializing) this.negotiated = undefined;
242
+ const on = this.transport;
233
243
  this.initializing ??= this.request(WIRE_METHODS.initialize, {
234
244
  protocolVersion: WIRE_PROTOCOL_VERSION,
235
245
  client: this.options.clientInfo,
@@ -245,6 +255,8 @@ export class Connection {
245
255
  if (this.serverIdentity !== undefined && this.serverIdentity !== identity)
246
256
  this.host.serverChanged();
247
257
  this.serverIdentity = identity;
258
+ this.negotiated = result;
259
+ this.negotiatedOn = on;
248
260
  return result;
249
261
  })
250
262
  .catch((error: unknown) => {
@@ -280,11 +292,23 @@ export class Connection {
280
292
  method: M,
281
293
  params: WireParams<M>,
282
294
  onAnswer?: OnAnswer<WireDecodedResult<M>>,
295
+ /** Asked with the handshake of the very transport the request goes on; throw to send nothing. */
296
+ admit?: (server: InitializeResult) => void,
283
297
  ): Promise<WireDecodedResult<M>> {
284
298
  if (this.closed)
285
299
  return Promise.reject(this.refusal ?? new ConnectionClosedError("client closed"));
286
300
  const transport = this.transport;
287
301
  if (!transport) return Promise.reject(new ConnectionClosedError("not connected"));
302
+ if (admit) {
303
+ // This transport's handshake not answered yet: wait for it, then ask again.
304
+ if (this.negotiatedOn !== transport || !this.negotiated)
305
+ return this.initialize().then(() => this.request(method, params, onAnswer, admit));
306
+ try {
307
+ admit(this.negotiated);
308
+ } catch (error) {
309
+ return Promise.reject(error);
310
+ }
311
+ }
288
312
  return this.rpc.request(transport, method, params, WIRE_API[method].decode, onAnswer);
289
313
  }
290
314
 
@@ -301,11 +325,17 @@ export class Connection {
301
325
  method: M,
302
326
  params: WireParams<M>,
303
327
  onAnswer?: OnAnswer<WireDecodedResult<M>>,
328
+ /**
329
+ * Asked with the server this attempt goes to, before each send, re-sends
330
+ * included: a redial may reach another build of the server. Throw to send
331
+ * nothing (LLP 0019: an origin that server would strip).
332
+ */
333
+ admit?: (server: InitializeResult) => void,
304
334
  ): Promise<WireDecodedResult<M>> {
305
335
  for (let resends = 0; ; resends++) {
306
336
  const identity = this.serverIdentity;
307
337
  try {
308
- return await this.request(method, params, onAnswer);
338
+ return await this.request(method, params, onAnswer, admit);
309
339
  } catch (error) {
310
340
  if (!(error instanceof ConnectionClosedError) || !this.redials || resends >= MAX_RESENDS)
311
341
  throw error;
@@ -3,6 +3,7 @@ import {
3
3
  AsyncQueue,
4
4
  type DecodedLifecycleEvent,
5
5
  type DecodedWireEventEnvelope,
6
+ type Origin,
6
7
  type TurnEndedEvent,
7
8
  type TurnSteerResult,
8
9
  type UnknownEvent,
@@ -35,7 +36,7 @@ export interface TurnHandle {
35
36
  */
36
37
  readonly catchUp: number;
37
38
  /** Add input to this turn while it runs (see `AgentServerClient.steerTurn`). */
38
- steer(input: AgentInput, steerId?: string): Promise<TurnSteerResult>;
39
+ steer(input: AgentInput, steerId?: string, origin?: Origin): Promise<TurnSteerResult>;
39
40
  }
40
41
 
41
42
  /**
@@ -58,6 +58,8 @@ export type PermissionRequestHandler = (
58
58
  * comes from them; the decision says which was picked.
59
59
  */
60
60
  options?: PermissionOption[];
61
+ /** A plan's approval says so (`permission.requested`'s `purpose`); anything else is a tool's. */
62
+ purpose?: "plan";
61
63
  /**
62
64
  * How an "always" answer works for this request. `{ rule }`: the harness
63
65
  * keeps it itself, scoped as `rule` says (Claude's own session rule,
@@ -101,7 +101,7 @@ export function createCanUseTool(deps: {
101
101
  */
102
102
  const ask = async (
103
103
  title: string | undefined,
104
- opts: { options?: PermissionOption[]; always?: { rule: string } | null },
104
+ opts: { options?: PermissionOption[]; always?: { rule: string } | null; purpose?: "plan" },
105
105
  ): Promise<PermissionDecision | undefined> => {
106
106
  if (!turn.permissions) return undefined;
107
107
  // @ref LLP 0002#a-tool-call-says-what-it-acts-on — why Claude asks is `reason`, in the CLI's words
@@ -119,7 +119,7 @@ export function createCanUseTool(deps: {
119
119
  return decision;
120
120
  };
121
121
  if (toolName === "ExitPlanMode") {
122
- return planVerdict(await ask(PLAN_TITLE, { options: PLAN_OPTIONS }), input);
122
+ return planVerdict(await ask(PLAN_TITLE, { options: PLAN_OPTIONS, purpose: "plan" }), input);
123
123
  }
124
124
  // @ref LLP 0001#d4--permission-requests-are-first-class-protocol — "always" is Claude's own rule
125
125
  // "Always" is the rule Claude suggests (`Bash(npm test *)`, accept-edits
@@ -77,7 +77,7 @@ export async function* askPlan(
77
77
  title: PLAN_TITLE,
78
78
  rawInput: { plan: offered.text },
79
79
  },
80
- { signal: asking.signal, options: PLAN_OPTIONS },
80
+ { signal: asking.signal, options: PLAN_OPTIONS, purpose: "plan" },
81
81
  );
82
82
  } finally {
83
83
  offAbort();
@@ -21,6 +21,7 @@ import {
21
21
  type AgentCapabilities,
22
22
  type AgentInput,
23
23
  type ModelDescriptor,
24
+ type PermissionMode,
24
25
  type PermissionToolCall,
25
26
  type RunConfig,
26
27
  inputToText,
@@ -30,6 +31,12 @@ import { onAbort, untilAborted } from "../../utils/deadline.ts";
30
31
  import { AgentServerError, InvalidRequestError } from "../../utils/errors.ts";
31
32
  import type { AgentExecuteOptions, RawAgentEvent } from "../base.ts";
32
33
  import { NO_ANSWERS, questionRequest } from "../elicitation.ts";
34
+ import {
35
+ type HostToolSessions,
36
+ type HostTools,
37
+ hostToolSessions,
38
+ refuseHostName,
39
+ } from "../host-tools.ts";
33
40
  import type { CliLogin } from "../login.ts";
34
41
  import { SessionAgent } from "../session-agent.ts";
35
42
  import type { ScriptedEvent } from "./adapter.ts";
@@ -123,6 +130,12 @@ export interface ScriptedAgentOptions {
123
130
  * restart fences its cut-off sessions.
124
131
  */
125
132
  processes?: NativeProcesses;
133
+ /**
134
+ * The host's tools (`hostTools`): a session's source is a turn's `http`
135
+ * MCP server at the engine's loopback, so a `call` step calls it as an
136
+ * agent would, each call naming the turn running then (LLP 0018).
137
+ */
138
+ hostTools?: HostTools;
126
139
  }
127
140
 
128
141
  /** The one model it lists: it runs none. */
@@ -185,10 +198,17 @@ export class ScriptedAgent extends SessionAgent {
185
198
  private readonly turns = new Map<string, number>();
186
199
 
187
200
  readonly processes?: NativeProcesses;
201
+ private readonly host?: HostToolSessions;
202
+ /** Each session's running turn and its mode, as its host tools' calls read them. */
203
+ private readonly live = new Map<string, { turnId: string; permissionMode: PermissionMode }>();
188
204
 
189
205
  constructor(private readonly options: ScriptedAgentOptions) {
190
206
  super();
191
207
  this.processes = options.processes;
208
+ // A script decides itself whether to ask before a call (`ask`): its writes are not held to full access.
209
+ this.host = hostToolSessions(options.hostTools, this.harness, {
210
+ live: (sessionId) => this.live.get(sessionId),
211
+ });
192
212
  }
193
213
 
194
214
  async listModels(): Promise<ModelDescriptor[]> {
@@ -197,7 +217,7 @@ export class ScriptedAgent extends SessionAgent {
197
217
 
198
218
  protected override async *executeTurn(
199
219
  input: AgentInput,
200
- options: AgentExecuteOptions,
220
+ given: AgentExecuteOptions,
201
221
  controller: AbortController,
202
222
  ): AsyncIterableIterator<RawAgentEvent> {
203
223
  const { signal } = controller;
@@ -206,8 +226,10 @@ export class ScriptedAgent extends SessionAgent {
206
226
  // step), so a queue skips the turn's steps through its `end` and the
207
227
  // next turn plays its own.
208
228
  // A script runs nothing of its own: the abort stops it, so a cancel is confirmed at once.
209
- this.cancelWith(options, async () => true);
210
- const { sessionId, turnId } = options;
229
+ this.cancelWith(given, async () => true);
230
+ const { sessionId, turnId } = given;
231
+ const options = await this.withHostTools(given);
232
+ this.live.set(sessionId, { turnId, permissionMode: options.permissionMode ?? "default" });
211
233
  // A later turn of the session resumes the id its first one reported.
212
234
  options.onNativeSession?.(options.resumeSessionId ?? `scripted-${sessionId}`, {
213
235
  resumed: options.resumeSessionId !== undefined,
@@ -246,6 +268,7 @@ export class ScriptedAgent extends SessionAgent {
246
268
  outcome = played.outcome;
247
269
  }
248
270
  } finally {
271
+ if (this.live.get(sessionId)?.turnId === turnId) this.live.delete(sessionId);
249
272
  // Not awaited: a cancelled turn may have left a `next()` the test never releases.
250
273
  void Promise.resolve(iterator.return?.()).catch(() => {});
251
274
  }
@@ -403,10 +426,26 @@ export class ScriptedAgent extends SessionAgent {
403
426
  return { input: decision.updatedInput ?? input };
404
427
  }
405
428
 
429
+ /** The turn's MCP servers with the host's, by the name its source gives, when it has one. */
430
+ private async withHostTools(options: AgentExecuteOptions): Promise<AgentExecuteOptions> {
431
+ const lease = await this.host?.lease(options.sessionId, options.cwd);
432
+ if (!lease) return options;
433
+ const { source } = lease;
434
+ refuseHostName(options.mcpServers, source.name);
435
+ const server = await lease.http();
436
+ return { ...options, mcpServers: { ...options.mcpServers, [source.name]: server } };
437
+ }
438
+
406
439
  override async release(sessionId: string): Promise<void> {
407
440
  this.turns.delete(sessionId);
441
+ this.host?.release(sessionId);
408
442
  await super.release(sessionId);
409
443
  }
444
+
445
+ override async terminateAll(): Promise<void> {
446
+ await super.terminateAll();
447
+ await this.host?.close();
448
+ }
410
449
  }
411
450
 
412
451
  /** The turn's config, as `echo: "config"` says it: MCP servers by name, `env` by its keys alone. */
@@ -197,7 +197,10 @@ const HARNESSES: Record<
197
197
  throw new Error("the scripted harness requires CreateRegistryOptions.scripted (turn)");
198
198
  }
199
199
  // @ref LLP 0007#what-each-harness-does — it starts none, so a restart vouches for it
200
- return [new ScriptedAgent({ ...opts.scripted, processes }), createScriptedTransformer];
200
+ return [
201
+ new ScriptedAgent({ ...opts.scripted, hostTools: opts.hostTools, processes }),
202
+ createScriptedTransformer,
203
+ ];
201
204
  },
202
205
  };
203
206