@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/CHANGELOG.md CHANGED
@@ -7,6 +7,39 @@ and the measurements. Evidence lives in the LLP, not here. A release groups
7
7
  its bullets under Breaking, Added, Changed and Fixed, breaking first. The
8
8
  released sections below that predate this convention are kept as written.
9
9
 
10
+ ## 0.3.27
11
+
12
+ ### Breaking
13
+
14
+ - `./operator` is v2 and replaces v1: callers are `SessionCaller` or `ExternalCaller`,
15
+ the host is the new `OperatorHost` (`list`, `view`, `send` and capabilities), and the
16
+ tools are `whoami`, `list_sessions`, `read_session`, `wait_for_sessions`, `list_models`,
17
+ `start_session`, `send_message`, `answer_request`, `stop_sessions`, `archive` (LLP 0019).
18
+ - The operator holds nothing between calls: a message is sent only while its call is
19
+ open. A host refuses at its own commit by throwing `Refused` (code, sessions, state);
20
+ caps across starters are the host's, and `start` delivers the first task as the turn
21
+ `StartInput.turnId` (LLP 0019).
22
+
23
+ ### Added
24
+
25
+ - `origin` on `turn/start`, `turn/steer` and `RunRequest` (`OriginSchema`: `person`,
26
+ `session`, `assistant`): the agent reads one line saying an agent sent it, the user
27
+ message's `message.started` carries `origin`, and a retry from another sender is
28
+ `turnConflict`. `initialize` answers `features: ["origin"]`; the client refuses a
29
+ non-person origin to a server without it, re-sends after a redial included. An
30
+ origin's ids and names are at most 255 characters (`ORIGIN_FIELD_MAX`); a
31
+ `TurnHandle`'s `steer` takes one. Conversation checkpoints are format `v2` (LLP 0019).
32
+ - `permission.requested` says what it decides: `purpose` is `plan` for a plan's
33
+ approval and `tool` otherwise (`PERMISSION_PURPOSES`, open; none reads as `tool`).
34
+ `./operator` reads a plan from it, not from its option ids (LLP 0002, Permissions).
35
+ - `operatorSessionTools` and `OPERATOR_GUIDANCE`: the operator as a session's own
36
+ tools, through the engine's delivery of host tools (LLP 0019, LLP 0018).
37
+ - A host's own tool is given its call's deadline and signal (`CallScope`), and a
38
+ refusal's archive hint names a workspace's only chat as its workspace (`Archivable`;
39
+ `refuse.hasChildren` and `refuse.limitSessions` take one) (LLP 0019).
40
+ - `OperatorOptions.onError(error, tool, caller)`: the host sees each unexpected failure a
41
+ call answers without, once; never a refusal, and it cannot change the answer (LLP 0019).
42
+
10
43
  ## 0.3.26
11
44
 
12
45
  ### Breaking
package/README.md CHANGED
@@ -14,7 +14,7 @@ One package, seven seats — pick the subpath for how you consume it:
14
14
  | `@zvada/agent-server/server` | **The standard wire** — serve the engine over JSON-RPC 2.0 NDJSON (stdio / WebSocket listen / dial-out) with quick-ack turns, per-session `seq`, bounded replay, and an ACP v1 binding (`--acp`). Ships the `agent-server` bin. |
15
15
  | `@zvada/agent-server/client` | **The typed consumer client** — spawn/connect/attach, `runTurn` as an async iterable, permission responses, reconnect with sequenced replay healing (a turn start whose ack a dropped connection lost is re-sent and joins the running turn), `subscribe` / `joinTurn` to follow a session or a turn another client started, the harnesses' logins (`authStatus`, `login`). Depends only on the contract + node builtins. |
16
16
  | `@zvada/agent-server/accounts` | **A login the product holds** — sign a subscription in for a credential the product stores (ChatGPT, Claude), renew it, and answer each turn's credential request (`createCredentialHandler`, `credentialsFrom`). `fetch` and Web Crypto only: it runs in a Worker. |
17
- | `@zvada/agent-server/operator` | **Operator tools** — the session tools an outside agent (a hosted assistant, a CLI agent) operates your product's coding agents with, over an `OperatorHost` you implement, and a dependency-free MCP binding (`createMcpHandler`). Protocol and zod only. See [consuming](docs/consuming.md#let-an-outside-agent-operate-your-sessions) and LLP 0014. |
17
+ | `@zvada/agent-server/operator` | **Operator tools** — the session tools an outside assistant, your window or your own sessions' agents operate your product's coding agents with, over an `OperatorHost` you implement, and a dependency-free MCP binding (`createMcpHandler`). Protocol and zod only. See [consuming](docs/consuming.md#let-agents-operate-your-sessions), LLP 0014 and LLP 0019. |
18
18
  | `@zvada/agent-server/sync` | **Experimental.** Optional durable journal port and history helpers: transfer, open, follow, managed sync. |
19
19
  | `@zvada/agent-server/sync/sqlite` | **Experimental.** Bun SQLite journal with its history and checkpoint store. |
20
20
  | `@zvada/agent-server/sync/node-sqlite` | **Experimental.** Same storage under Node >=22.16 using built-in SQLite (itself experimental in Node 22). |
@@ -1,4 +1,4 @@
1
- import { AuthUpdatedSchema, HarnessCliProgressSchema, SessionOverflowParamsSchema, WIRE_ERROR_CODES, WIRE_METHODS, decodeWireEventEnvelope, decodeWireMessage, generateUUIDv7, } from "../protocol/index.js";
1
+ import { AuthUpdatedSchema, HarnessCliProgressSchema, SessionOverflowParamsSchema, WIRE_ERROR_CODES, WIRE_FEATURES, WIRE_METHODS, agentOrigin, decodeWireEventEnvelope, decodeWireMessage, generateUUIDv7, } from "../protocol/index.js";
2
2
  import { Connection, ConnectionClosedError, ConnectionRefusedError, ProtocolVersionMismatchError, } from "./connection.js";
3
3
  import { createHistoryClient } from "./history.js";
4
4
  import { Listeners } from "./listeners.js";
@@ -163,7 +163,7 @@ export class AgentServerClient {
163
163
  // Before the first `await`: a cancel sent right behind this call goes out after the start.
164
164
  const release = this.starts.begin(sessionId, turnId);
165
165
  try {
166
- await this.initialize();
166
+ carriesOrigin(await this.initialize(), params.origin);
167
167
  if (this.turns.running(sessionId))
168
168
  throw new Error(`session ${sessionId} already has an active turn`);
169
169
  const handle = this.turns.open(sessionId, turnId, true);
@@ -175,7 +175,7 @@ export class AgentServerClient {
175
175
  (ack) => {
176
176
  if (!ack.terminal)
177
177
  this.joinAt(handle, ack.headSeq, { turnId });
178
- });
178
+ }, (server) => carriesOrigin(server, params.origin));
179
179
  release();
180
180
  const accepted = await sending;
181
181
  const { terminal } = accepted;
@@ -211,12 +211,12 @@ export class AgentServerClient {
211
211
  // As in `runTurn`: a cancel sent right behind this call goes out after the start.
212
212
  const release = this.starts.begin(sessionId, turnId);
213
213
  try {
214
- await this.initialize();
214
+ carriesOrigin(await this.initialize(), params.origin);
215
215
  // `request` sends (or fails for no connection) in this call.
216
216
  const answer = this.connection.request(WIRE_METHODS.turnStart, { ...params, sessionId, turnId }, (ack) => {
217
217
  if (params.subscribe !== false && !ack.terminal)
218
218
  this.streams.joined(sessionId, ack.headSeq, { turnId });
219
- });
219
+ }, (server) => carriesOrigin(server, params.origin));
220
220
  release();
221
221
  return await answer;
222
222
  }
@@ -263,7 +263,7 @@ export class AgentServerClient {
263
263
  * steer's user message, its receipt, reaches it.
264
264
  */
265
265
  async steerTurn(params) {
266
- await this.initialize();
266
+ carriesOrigin(await this.initialize(), params.origin);
267
267
  const { sessionId, turnId } = params;
268
268
  // One it cannot subscribe to still takes the steer; only its receipt is lost.
269
269
  if (!this.streams.follows(sessionId))
@@ -272,10 +272,7 @@ export class AgentServerClient {
272
272
  if (ack.activeTurn?.turnId === turnId)
273
273
  this.streams.joined(sessionId, ack.headSeq, { turnId });
274
274
  }).catch(() => undefined);
275
- return this.connection.resend(WIRE_METHODS.turnSteer, {
276
- ...params,
277
- steerId: params.steerId ?? generateUUIDv7(),
278
- });
275
+ return this.connection.resend(WIRE_METHODS.turnSteer, { ...params, steerId: params.steerId ?? generateUUIDv7() }, undefined, (server) => carriesOrigin(server, params.origin));
279
276
  }
280
277
  /**
281
278
  * Cancel the session's active turn; resolves once cancellation propagated.
@@ -669,7 +666,13 @@ export class AgentServerClient {
669
666
  get catchUp() {
670
667
  return handle.catchUp;
671
668
  },
672
- steer: (input, steerId) => this.steerTurn({ sessionId, turnId, input, ...(steerId !== undefined && { steerId }) }),
669
+ steer: (input, steerId, origin) => this.steerTurn({
670
+ sessionId,
671
+ turnId,
672
+ input,
673
+ ...(steerId !== undefined && { steerId }),
674
+ ...(origin && { origin }),
675
+ }),
673
676
  };
674
677
  }
675
678
  /**
@@ -743,3 +746,16 @@ export class AgentServerClient {
743
746
  return this.connection.request(WIRE_METHODS.sessionSubscribe, params, onAnswer);
744
747
  }
745
748
  }
749
+ // @ref LLP 0019#origin-on-the-wire-and-to-the-model — fail closed: an origin a server would strip reads as the person's
750
+ /**
751
+ * Refuse to send another sender's input to a server that does not carry
752
+ * `origin`: its schema would drop the field, and the agent would read the
753
+ * message as the person's. The person's input goes anywhere.
754
+ */
755
+ function carriesOrigin(server, origin) {
756
+ if (!agentOrigin(origin))
757
+ return;
758
+ if (server.features?.includes(WIRE_FEATURES.origin))
759
+ return;
760
+ throw new Error("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.");
761
+ }
@@ -73,6 +73,10 @@ export class Connection {
73
73
  /** The server process (or, durable, the journal) whose logs the client follows. */
74
74
  serverIdentity;
75
75
  initializing = null;
76
+ /** The current transport's handshake, once answered; cleared when it is asked again. */
77
+ negotiated;
78
+ /** The transport `negotiated` was answered on: a feature check holds only for it. */
79
+ negotiatedOn = null;
76
80
  reconnecting = false;
77
81
  /** Ends the redial backoff early: `close()` must not wait it out. */
78
82
  stopBackoff = null;
@@ -110,6 +114,10 @@ export class Connection {
110
114
  if (transport.closed)
111
115
  throw new ConnectionClosedError("transport opened already closed");
112
116
  this.transport = transport;
117
+ // A new transport's server is not the old one's until its own handshake says so.
118
+ this.initializing = null;
119
+ this.negotiated = undefined;
120
+ this.negotiatedOn = null;
113
121
  this.host.opened(this.reconnecting);
114
122
  transport.onLine((line) => {
115
123
  if (this.transport === transport)
@@ -122,6 +130,9 @@ export class Connection {
122
130
  * client for good: it rejects with `ProtocolVersionMismatchError`.
123
131
  */
124
132
  initialize() {
133
+ if (!this.initializing)
134
+ this.negotiated = undefined;
135
+ const on = this.transport;
125
136
  this.initializing ??= this.request(WIRE_METHODS.initialize, {
126
137
  protocolVersion: WIRE_PROTOCOL_VERSION,
127
138
  client: this.options.clientInfo,
@@ -137,6 +148,8 @@ export class Connection {
137
148
  if (this.serverIdentity !== undefined && this.serverIdentity !== identity)
138
149
  this.host.serverChanged();
139
150
  this.serverIdentity = identity;
151
+ this.negotiated = result;
152
+ this.negotiatedOn = on;
140
153
  return result;
141
154
  })
142
155
  .catch((error) => {
@@ -156,12 +169,25 @@ export class Connection {
156
169
  return this.refusal ?? refusal;
157
170
  }
158
171
  /** A request, its answer read as `WIRE_API` reads the method's. */
159
- request(method, params, onAnswer) {
172
+ request(method, params, onAnswer,
173
+ /** Asked with the handshake of the very transport the request goes on; throw to send nothing. */
174
+ admit) {
160
175
  if (this.closed)
161
176
  return Promise.reject(this.refusal ?? new ConnectionClosedError("client closed"));
162
177
  const transport = this.transport;
163
178
  if (!transport)
164
179
  return Promise.reject(new ConnectionClosedError("not connected"));
180
+ if (admit) {
181
+ // This transport's handshake not answered yet: wait for it, then ask again.
182
+ if (this.negotiatedOn !== transport || !this.negotiated)
183
+ return this.initialize().then(() => this.request(method, params, onAnswer, admit));
184
+ try {
185
+ admit(this.negotiated);
186
+ }
187
+ catch (error) {
188
+ return Promise.reject(error);
189
+ }
190
+ }
165
191
  return this.rpc.request(transport, method, params, WIRE_API[method].decode, onAnswer);
166
192
  }
167
193
  /**
@@ -173,11 +199,17 @@ export class Connection {
173
199
  * re-sends at most: a server that accepts connections but never answers
174
200
  * would otherwise be retried forever.
175
201
  */
176
- async resend(method, params, onAnswer) {
202
+ async resend(method, params, onAnswer,
203
+ /**
204
+ * Asked with the server this attempt goes to, before each send, re-sends
205
+ * included: a redial may reach another build of the server. Throw to send
206
+ * nothing (LLP 0019: an origin that server would strip).
207
+ */
208
+ admit) {
177
209
  for (let resends = 0;; resends++) {
178
210
  const identity = this.serverIdentity;
179
211
  try {
180
- return await this.request(method, params, onAnswer);
212
+ return await this.request(method, params, onAnswer, admit);
181
213
  }
182
214
  catch (error) {
183
215
  if (!(error instanceof ConnectionClosedError) || !this.redials || resends >= MAX_RESENDS)
@@ -94,7 +94,7 @@ export function createCanUseTool(deps) {
94
94
  return decision;
95
95
  };
96
96
  if (toolName === "ExitPlanMode") {
97
- return planVerdict(await ask(PLAN_TITLE, { options: PLAN_OPTIONS }), input);
97
+ return planVerdict(await ask(PLAN_TITLE, { options: PLAN_OPTIONS, purpose: "plan" }), input);
98
98
  }
99
99
  // @ref LLP 0001#d4--permission-requests-are-first-class-protocol — "always" is Claude's own rule
100
100
  // "Always" is the rule Claude suggests (`Bash(npm test *)`, accept-edits
@@ -60,7 +60,7 @@ export async function* askPlan(turn, native) {
60
60
  kind: CODEX_TOOL_KINDS.plan,
61
61
  title: PLAN_TITLE,
62
62
  rawInput: { plan: offered.text },
63
- }, { signal: asking.signal, options: PLAN_OPTIONS });
63
+ }, { signal: asking.signal, options: PLAN_OPTIONS, purpose: "plan" });
64
64
  }
65
65
  finally {
66
66
  offAbort();
@@ -21,6 +21,7 @@ import { inputToText, } from "../../../protocol/index.js";
21
21
  import { onAbort, untilAborted } from "../../utils/deadline.js";
22
22
  import { AgentServerError, InvalidRequestError } from "../../utils/errors.js";
23
23
  import { NO_ANSWERS, questionRequest } from "../elicitation.js";
24
+ import { hostToolSessions, refuseHostName, } from "../host-tools.js";
24
25
  import { SessionAgent } from "../session-agent.js";
25
26
  import { callMcpTool, callableServer } from "./mcp-call.js";
26
27
  import { readStep } from "./steps.js";
@@ -111,23 +112,32 @@ export class ScriptedAgent extends SessionAgent {
111
112
  /** Turns each session has run in this engine. */
112
113
  turns = new Map();
113
114
  processes;
115
+ host;
116
+ /** Each session's running turn and its mode, as its host tools' calls read them. */
117
+ live = new Map();
114
118
  constructor(options) {
115
119
  super();
116
120
  this.options = options;
117
121
  this.processes = options.processes;
122
+ // A script decides itself whether to ask before a call (`ask`): its writes are not held to full access.
123
+ this.host = hostToolSessions(options.hostTools, this.harness, {
124
+ live: (sessionId) => this.live.get(sessionId),
125
+ });
118
126
  }
119
127
  async listModels() {
120
128
  return [MODEL];
121
129
  }
122
- async *executeTurn(input, options, controller) {
130
+ async *executeTurn(input, given, controller) {
123
131
  const { signal } = controller;
124
132
  // A turn cancelled before it began is still a turn of its script: it
125
133
  // opens it and stops at its first step (or at its end, when it has no
126
134
  // step), so a queue skips the turn's steps through its `end` and the
127
135
  // next turn plays its own.
128
136
  // A script runs nothing of its own: the abort stops it, so a cancel is confirmed at once.
129
- this.cancelWith(options, async () => true);
130
- const { sessionId, turnId } = options;
137
+ this.cancelWith(given, async () => true);
138
+ const { sessionId, turnId } = given;
139
+ const options = await this.withHostTools(given);
140
+ this.live.set(sessionId, { turnId, permissionMode: options.permissionMode ?? "default" });
131
141
  // A later turn of the session resumes the id its first one reported.
132
142
  options.onNativeSession?.(options.resumeSessionId ?? `scripted-${sessionId}`, {
133
143
  resumed: options.resumeSessionId !== undefined,
@@ -157,6 +167,8 @@ export class ScriptedAgent extends SessionAgent {
157
167
  }
158
168
  }
159
169
  finally {
170
+ if (this.live.get(sessionId)?.turnId === turnId)
171
+ this.live.delete(sessionId);
160
172
  // Not awaited: a cancelled turn may have left a `next()` the test never releases.
161
173
  void Promise.resolve(iterator.return?.()).catch(() => { });
162
174
  }
@@ -316,10 +328,25 @@ export class ScriptedAgent extends SessionAgent {
316
328
  }
317
329
  return { input: decision.updatedInput ?? input };
318
330
  }
331
+ /** The turn's MCP servers with the host's, by the name its source gives, when it has one. */
332
+ async withHostTools(options) {
333
+ const lease = await this.host?.lease(options.sessionId, options.cwd);
334
+ if (!lease)
335
+ return options;
336
+ const { source } = lease;
337
+ refuseHostName(options.mcpServers, source.name);
338
+ const server = await lease.http();
339
+ return { ...options, mcpServers: { ...options.mcpServers, [source.name]: server } };
340
+ }
319
341
  async release(sessionId) {
320
342
  this.turns.delete(sessionId);
343
+ this.host?.release(sessionId);
321
344
  await super.release(sessionId);
322
345
  }
346
+ async terminateAll() {
347
+ await super.terminateAll();
348
+ await this.host?.close();
349
+ }
323
350
  }
324
351
  /** The turn's config, as `echo: "config"` says it: MCP servers by name, `env` by its keys alone. */
325
352
  function echoConfig(options) {
@@ -67,7 +67,10 @@ const HARNESSES = {
67
67
  throw new Error("the scripted harness requires CreateRegistryOptions.scripted (turn)");
68
68
  }
69
69
  // @ref LLP 0007#what-each-harness-does — it starts none, so a restart vouches for it
70
- return [new ScriptedAgent({ ...opts.scripted, processes }), createScriptedTransformer];
70
+ return [
71
+ new ScriptedAgent({ ...opts.scripted, hostTools: opts.hostTools, processes }),
72
+ createScriptedTransformer,
73
+ ];
71
74
  },
72
75
  };
73
76
  const atTheTop = (option) => `set ${option} at the top level of the registry's options`;
@@ -1,10 +1,11 @@
1
- import { RunRequestSchema, canonicalJson, turnIdentity } from "../../protocol/index.js";
1
+ import { RunRequestSchema, agentOrigin, canonicalJson, turnIdentity, } from "../../protocol/index.js";
2
2
  import { withTimeout } from "../utils/deadline.js";
3
3
  import { InvalidRequestError, TurnConflictError, TurnForgottenError } from "../utils/errors.js";
4
4
  import { EventSinkError } from "./event-sink.js";
5
5
  import { awaitingInstall, harnessCliProgress, harnessClis } from "./harness-clis.js";
6
6
  import { HarnessLogins } from "./harness-logins.js";
7
7
  import { ModelLists, catalogModelList } from "./model-lists.js";
8
+ import { withOriginLine } from "./origin-line.js";
8
9
  import { StandingRules } from "./permission-policy.js";
9
10
  import { Turn, wellFormedInput, } from "./turn.js";
10
11
  // Caller-supplied IDs need not be UUIDs; encode the tuple without delimiter collisions.
@@ -304,11 +305,15 @@ export class AgentRuntime {
304
305
  * harness cannot take throws, as it would fail a turn.
305
306
  */
306
307
  async steer(sessionId, request) {
307
- const { turnId, steerId, input } = request;
308
+ const { turnId, steerId, input, origin: sent } = request;
308
309
  if (typeof input === "string" ? input.trim() === "" : input.length === 0) {
309
310
  throw new Error("a steer carries input");
310
311
  }
311
- const inputKey = canonicalJson(input);
312
+ // Another sender is another steer; the person's origin, said or not, adds nothing.
313
+ // Its own copy, taken at admission: the caller's object may change after.
314
+ const given = agentOrigin(sent);
315
+ const origin = given && { ...given };
316
+ const inputKey = canonicalJson(origin ? { input, origin } : input);
312
317
  const turn = this.turns.get(turnKeyOf(sessionId, turnId));
313
318
  const known = turn
314
319
  ? turn.steers.find(steerId)
@@ -330,8 +335,13 @@ export class AgentRuntime {
330
335
  const deliver = agent.capabilities.steering ? agent.steer?.bind(agent) : undefined;
331
336
  if (!deliver)
332
337
  return { outcome: "unsupported" };
333
- // Its echo is the caller's input; the agent is given it well-formed.
334
- return await turn.steers.accept(steerId, inputKey, input, () => deliver(sessionId, { ...request, input: wellFormedInput(input) }));
338
+ // Its echo is the caller's input; the agent is given it well-formed, after
339
+ // the sender's line when it is not the person.
340
+ return await turn.steers.accept(steerId, inputKey, input, () => deliver(sessionId, {
341
+ turnId,
342
+ steerId,
343
+ input: wellFormedInput(withOriginLine(input, origin)),
344
+ }), origin);
335
345
  }
336
346
  /** Whether another turn of the session, live or remembered, took this steer id. */
337
347
  steerIdTaken(sessionId, steerId) {
@@ -1,4 +1,4 @@
1
- import { createSteerEchoParts, createUserEchoParts, echoMessageId, extendPart, generateUUIDv7, steerMessageId, } from "../../protocol/index.js";
1
+ import { agentOrigin, createSteerEchoParts, createUserEchoParts, echoMessageId, extendPart, generateUUIDv7, steerMessageId, } from "../../protocol/index.js";
2
2
  /**
3
3
  * The execution `turn.ended` carries: the request, plus what the harness said
4
4
  * it ran. Models the stream reported (Claude's API model, a Codex reroute) say
@@ -81,8 +81,8 @@ export class EventProcessor {
81
81
  * id (`echoMessageId`), so a consumer that minted the turnId can predict the
82
82
  * whole echo instead of reconciling a look-alike against it.
83
83
  */
84
- *echoUserMessage(input) {
85
- yield* this.openMessage("user", undefined, echoMessageId(this.turnId));
84
+ *echoUserMessage(input, origin) {
85
+ yield* this.openMessage("user", undefined, echoMessageId(this.turnId), undefined, origin);
86
86
  for (const part of createUserEchoParts(input, this.turnId)) {
87
87
  yield* this.emitPart(part);
88
88
  }
@@ -96,11 +96,11 @@ export class EventProcessor {
96
96
  * already echoed, is ignored.
97
97
  */
98
98
  *echoSteer(steerId) {
99
- const input = this.steers.read(steerId);
100
- if (input === undefined)
99
+ const steer = this.steers.read(steerId);
100
+ if (steer === undefined)
101
101
  return;
102
- yield* this.openMessage("user", undefined, steerMessageId(steerId));
103
- for (const part of createSteerEchoParts(input, steerId)) {
102
+ yield* this.openMessage("user", undefined, steerMessageId(steerId), undefined, steer.origin);
103
+ for (const part of createSteerEchoParts(steer.input, steerId)) {
104
104
  yield* this.emitPart(part);
105
105
  }
106
106
  yield* this.closeMessage();
@@ -258,7 +258,9 @@ export class EventProcessor {
258
258
  /** Derived id for the user echo; harness messages get a fresh UUIDv7. */
259
259
  id,
260
260
  /** The model the harness said produced it. */
261
- model) {
261
+ model,
262
+ /** A user message's sender, when not the person. */
263
+ origin) {
262
264
  if (this.openMessageId)
263
265
  yield* this.closeMessage();
264
266
  if (role === "assistant")
@@ -267,6 +269,7 @@ export class EventProcessor {
267
269
  // with one that dates it by this event.
268
270
  const startedAt = Date.now();
269
271
  const messageId = id ?? generateUUIDv7(startedAt);
272
+ const sender = agentOrigin(origin);
270
273
  this.openMessageId = messageId;
271
274
  this.openMessageParent = parentToolCallId;
272
275
  const named = role === "assistant" ? this.messageModel(model, parentToolCallId) : {};
@@ -288,6 +291,8 @@ export class EventProcessor {
288
291
  // the model the harness said wrote it (Claude's API model), else the
289
292
  // one it runs the turn on (Codex's thread model), else the request's.
290
293
  ...named,
294
+ // A copy: what a sink does to the event never reaches the request or the model's line.
295
+ ...(role === "user" && sender && { origin: { ...sender } }),
291
296
  timestamp: startedAt,
292
297
  };
293
298
  return messageId;
@@ -0,0 +1,42 @@
1
+ import { agentOrigin } from "../../protocol/index.js";
2
+ // @ref LLP 0019#origin-on-the-wire-and-to-the-model — the line is the engine's, first, and only for an agent
3
+ /**
4
+ * The one line an agent is given before a message that is not the person's,
5
+ * saying who sent it. Undefined for the person, whose messages carry none.
6
+ * The names and ids are the host's and untrusted: each is one JSON-quoted
7
+ * line, so none can end the line, the bracket or the quote.
8
+ */
9
+ export function originLine(origin) {
10
+ const sender = agentOrigin(origin);
11
+ if (!sender)
12
+ return undefined;
13
+ const tail = "the person's own messages never carry this line.";
14
+ if (sender.kind === "session") {
15
+ const named = sender.name ? `session ${quoted(sender.name)}, id` : "session id";
16
+ return `[From another agent, not from the person: ${named} ${quoted(sender.sessionId)}. Weigh it as a colleague's request; ${tail}]`;
17
+ }
18
+ return `[From an outside assistant the person connected, not typed by the person: ${quoted(sender.name)}, id ${quoted(sender.id)}. It acts for the person but is not the person; ${tail}]`;
19
+ }
20
+ /** Line breaks a reader may honour, the C0/C1 controls and bidirectional overrides. */
21
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: the controls are what it drops
22
+ const UNSAFE = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u200e\u200f\u202a-\u202e\u2066-\u2069]+/g;
23
+ /** The longest name or id the line carries. */
24
+ const LONGEST = 200;
25
+ /** One line, JSON-quoted: breaks and controls become a space, then it is clipped. */
26
+ function quoted(text) {
27
+ const line = text.replace(UNSAFE, " ").replace(/\s+/g, " ").trim();
28
+ return JSON.stringify(line.length > LONGEST ? `${line.slice(0, LONGEST - 1)}…` : line);
29
+ }
30
+ /**
31
+ * The input as its agent is given it: the sender's line first when it is not
32
+ * the person (to text after a blank line; before a list as a text part of its
33
+ * own). The echo, and every store, keep the caller's input as it was sent.
34
+ */
35
+ export function withOriginLine(input, origin) {
36
+ const line = originLine(origin);
37
+ if (!line)
38
+ return input;
39
+ if (typeof input === "string")
40
+ return `${line}\n\n${input}`;
41
+ return [{ type: "text", text: line }, ...input];
42
+ }
@@ -44,13 +44,14 @@ export class RequestBroker {
44
44
  return !this.closed;
45
45
  }
46
46
  /** Ask whether a tool may run; resolves with the answer, or a cancel. */
47
- askPermission(toolCall, options, signal) {
47
+ askPermission(toolCall, options, signal, purpose = "tool") {
48
48
  const { sessionId, turnId } = this.turn;
49
49
  return this.park("permission", signal, (requestId) => ({
50
50
  type: "permission.requested",
51
51
  sessionId,
52
52
  turnId,
53
53
  requestId,
54
+ purpose,
54
55
  title: toolCall.title ?? `Allow tool: ${toolCall.toolName}`,
55
56
  toolCall,
56
57
  options,
@@ -19,11 +19,12 @@ export class TurnSteers {
19
19
  return this.steers.get(steerId);
20
20
  }
21
21
  /** Take a steer, and hand it to the harness with `deliver`. */
22
- accept(steerId, inputKey, input, deliver) {
22
+ accept(steerId, inputKey, input, deliver, origin) {
23
23
  let answered;
24
24
  const steer = {
25
25
  inputKey,
26
26
  input,
27
+ ...(origin && { origin }),
27
28
  state: "held",
28
29
  result: new Promise((resolve) => {
29
30
  answered = resolve;
@@ -52,13 +53,13 @@ export class TurnSteers {
52
53
  steer.state = "refused";
53
54
  return { outcome: "no_active_turn" };
54
55
  }
55
- /** The agent read a steer: its input, once, for its echo. */
56
+ /** The agent read a steer: its input and sender, once, for its echo. */
56
57
  read(steerId) {
57
58
  const steer = this.steers.get(steerId);
58
59
  if (steer?.state !== "held")
59
60
  return undefined;
60
61
  steer.state = "read";
61
- return steer.input;
62
+ return { input: steer.input, ...(steer.origin && { origin: steer.origin }) };
62
63
  }
63
64
  /** The steers it took that the agent has not read (all of them, once the turn is over). */
64
65
  undelivered() {
@@ -2,6 +2,7 @@ import { DEFAULT_TOKEN_USAGE, errorInfo } from "../../protocol/index.js";
2
2
  import { emitDiagnostic } from "../diagnostics.js";
3
3
  import { EventProcessor } from "./event-processor.js";
4
4
  import { EventSinkError } from "./event-sink.js";
5
+ import { withOriginLine } from "./origin-line.js";
5
6
  import { decisionFor, optionsFor, permissionAsk } from "./permission-policy.js";
6
7
  import { RequestBroker } from "./request-broker.js";
7
8
  import { TurnSteers } from "./steering.js";
@@ -126,7 +127,7 @@ export class Turn {
126
127
  return answered;
127
128
  }
128
129
  async execute() {
129
- const { sessionId, turnId, input, config } = this.request;
130
+ const { sessionId, turnId, input, config, origin } = this.request;
130
131
  // Looked up as the turn executes: a harness the registry lacks rejects
131
132
  // the run, which is not remembered, so a retry may run.
132
133
  const agent = this.host.registry.getAgent(config.harness);
@@ -156,11 +157,12 @@ export class Turn {
156
157
  // the stream is a complete transcript and multi-client attach works. It is
157
158
  // the caller's input as sent, which the caller can predict; the agent is
158
159
  // given it well-formed (`wellFormedInput`).
159
- for (const event of this.processor.echoUserMessage(input))
160
+ for (const event of this.processor.echoUserMessage(input, origin))
160
161
  await this.emit(event);
161
162
  let threw;
162
163
  try {
163
- const given = wellFormedInput(input);
164
+ // @ref LLP 0019#origin-on-the-wire-and-to-the-model — told who sent it, when not the person
165
+ const given = wellFormedInput(withOriginLine(input, origin));
164
166
  for await (const raw of agent.execute(given, this.agentOptions(modelThinking))) {
165
167
  await this.announceNativeSession();
166
168
  if (config.includeRaw) {
@@ -274,7 +276,7 @@ export class Turn {
274
276
  if (standing)
275
277
  return standing;
276
278
  const options = optionsFor(ask);
277
- const outcome = await this.requests.askPermission(toolCall, options, opts?.signal);
279
+ const outcome = await this.requests.askPermission(toolCall, options, opts?.signal, opts?.purpose ?? "tool");
278
280
  if (outcome.outcome === "cancelled")
279
281
  return CANCEL;
280
282
  const { decision, selected } = decisionFor(outcome, options);