@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
@@ -0,0 +1,435 @@
1
+ /**
2
+ * A session, in words a model can act on: short, with the next step named as
3
+ * the call that takes it. Pure functions over a `SessionView`.
4
+ *
5
+ * `ref` is how the hints name the session: its name, or `group/name` where the
6
+ * name alone is ambiguous.
7
+ */
8
+
9
+ import type { ElicitationOutcome, PermissionOutcome } from "../protocol/lifecycle.ts";
10
+ import type { Part, UnknownPart } from "../protocol/parts.ts";
11
+ import { PLAN_OPTION_IDS } from "../protocol/plan.ts";
12
+ import { type SessionView, type ViewMessage, type Waiting, isPlan, phaseOf } from "./view.ts";
13
+
14
+ const clip = (text: string, limit: number) =>
15
+ text.length > limit ? `${text.slice(0, limit - 1)}…` : text;
16
+
17
+ // @ref LLP 0014#untrusted-text — text an agent wrote or a repository holds never starts a line
18
+ // Untrusted text (what an agent or a person wrote, a question, an option, an
19
+ // error, a permission's title) is either a block of `QUOTE` lines or one
20
+ // JSON-encoded line after a label. The tool's own hints are ` -> tool(...)`,
21
+ // which no quoted line can produce: each of its lines begins with the marker.
22
+ /** The marker every line of untrusted text begins with. */
23
+ export const QUOTE = " | ";
24
+
25
+ /** Line breaks a reader may honour, the C0/C1 controls and bidirectional overrides. */
26
+ const BREAKS = /\r\n|[\n\r\v\f\u0085\u2028\u2029]/g;
27
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: the controls are what it drops
28
+ const CONTROLS = /[\u0000-\u0008\u000e-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;
29
+
30
+ /** What a JSON string still carries raw that may break a line or reorder it: escaped in a hint. */
31
+ const UNSAFE_IN_JSON = new RegExp(`${BREAKS.source}|${CONTROLS.source}`, "g");
32
+
33
+ /** The most messages `read_session` reads. */
34
+ export const MAX_LAST = 100;
35
+
36
+ /** Untrusted text as one line: no line breaks or controls, runs of space collapsed. */
37
+ export function oneLine(text: string): string {
38
+ return text.replace(BREAKS, " ").replace(CONTROLS, "").replace(/\s+/g, " ").trim();
39
+ }
40
+
41
+ /** Untrusted text as a block: each of its lines carried after `QUOTE`. */
42
+ export function quote(text: string): string {
43
+ return text
44
+ .replace(CONTROLS, "")
45
+ .split(BREAKS)
46
+ .map((line) => `${QUOTE}${line}`.trimEnd())
47
+ .join("\n");
48
+ }
49
+
50
+ /** Untrusted text named in prose (a session, a project, an option): one JSON-quoted line. */
51
+ export const quoted = (text: string) => JSON.stringify(oneLine(text));
52
+
53
+ /** A label, then the untrusted text as a quoted block under it. */
54
+ const block = (label: string, text: string) => `${label}\n${quote(text)}`;
55
+
56
+ const textOf = (parts: readonly (Part | UnknownPart)[]) =>
57
+ parts
58
+ .flatMap((part) => (part.type === "text" && "text" in part ? [String(part.text)] : []))
59
+ .join("")
60
+ .trim();
61
+
62
+ /**
63
+ * The next step, as the tool call that takes it:
64
+ * `-> answer_request(session: "voyager", answer: "<your answer>")`.
65
+ */
66
+ export function callHint(
67
+ tool: string,
68
+ args: Record<string, string | number | boolean> = {},
69
+ ): string {
70
+ // `\uXXXX` for what JSON leaves raw (U+2028, C1, bidi controls): the value reads back the same.
71
+ const json = (value: string | number | boolean) =>
72
+ JSON.stringify(value).replace(UNSAFE_IN_JSON, (found) =>
73
+ [...found].map((c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`).join(""),
74
+ );
75
+ const named = Object.entries(args).map(([key, value]) => `${key}: ${json(value)}`);
76
+ return `-> ${tool}(${named.join(", ")})`;
77
+ }
78
+
79
+ /** A choice's labels on one line: `options: "USD", "EUR"`. */
80
+ const optionsLine = (labels: readonly string[]) => `options: ${labels.map(quoted).join(", ")}`;
81
+
82
+ /** What ends a path in a command: a space, a quote, or the shell's punctuation. */
83
+ const PATH_END = "\\s\"'`;&|()<>";
84
+ /** Not inside a longer path: what comes before the folder is no part of a name. */
85
+ const PATH_START = "(?<![\\w.~\\\\/-])";
86
+ /** What a shell escapes with a backslash in a path (`Live\ Mac`). */
87
+ const SHELL_ESCAPED = /[\s'"\\$`!&*()[\]{};|<>?]/g;
88
+ const REGEXP_SPECIAL = /[.*+?^${}()|[\]\\]/g;
89
+
90
+ /**
91
+ * `text` with the folder `root` read relative wherever it appears: a path
92
+ * under it as the rest of the path, the folder itself as `.`. Its form with
93
+ * spaces escaped, as a shell command writes it, too. A folder whose name
94
+ * merely starts with it (`root-old`) is left alone.
95
+ */
96
+ function relativeTo(root: string, text: string): string {
97
+ const folder = root.replace(/\/+$/, "");
98
+ // "" or "/": there is nothing to read relative to.
99
+ if (folder.length < 2 || !text) return text;
100
+ const forms = [...new Set([folder, folder.replace(SHELL_ESCAPED, "\\$&")])].map((form) =>
101
+ form.replace(REGEXP_SPECIAL, "\\$&"),
102
+ );
103
+ const pattern = new RegExp(
104
+ `${PATH_START}(?:${forms.join("|")})(?:(/)(?=[^${PATH_END}])|/?(?=[${PATH_END}]|$))`,
105
+ "g",
106
+ );
107
+ return text.replace(pattern, (_match, slash?: string) => (slash ? "" : "."));
108
+ }
109
+
110
+ /** One question a tool call put to the person, as its input carries it. */
111
+ interface AskedQuestion {
112
+ question: string;
113
+ options: string[];
114
+ }
115
+
116
+ /**
117
+ * What a tool call put to the person, keyed by what its input carries, not
118
+ * by a tool's name: questions (`questions`, each with a `question`, its
119
+ * options labels or `{ label }`s), or a plan (a `switch_mode` call's `plan`).
120
+ */
121
+ function askedIn(
122
+ part: Part | UnknownPart,
123
+ ): { questions: AskedQuestion[] } | { plan: string } | undefined {
124
+ if (part.type !== "tool" || !("toolName" in part)) return undefined;
125
+ const input = (part.state as { input?: unknown }).input;
126
+ if (!input || typeof input !== "object") return undefined;
127
+ const { questions, plan } = input as { questions?: unknown; plan?: unknown };
128
+ if (Array.isArray(questions)) {
129
+ const asked = questions.flatMap((entry): AskedQuestion[] => {
130
+ const { question, options } = (entry ?? {}) as { question?: unknown; options?: unknown };
131
+ if (typeof question !== "string" || !question.trim()) return [];
132
+ const labels = (Array.isArray(options) ? options : []).flatMap((option) => {
133
+ const label = typeof option === "string" ? option : (option as { label?: unknown })?.label;
134
+ return typeof label === "string" ? [label] : [];
135
+ });
136
+ return [{ question, options: labels }];
137
+ });
138
+ if (asked.length) return { questions: asked };
139
+ }
140
+ if (part.kind === "switch_mode" && typeof plan === "string" && plan.trim()) return { plan };
141
+ return undefined;
142
+ }
143
+
144
+ /**
145
+ * What a tool call put to the person, for the lines under its own: each
146
+ * question with its options and, once the call has settled, what the agent
147
+ * was told (the answers, or a dismissal), or the plan. All of it is
148
+ * untrusted text.
149
+ */
150
+ function askedLines(part: Part | UnknownPart, root = ""): string[] {
151
+ const asked = askedIn(part);
152
+ if (!asked) return [];
153
+ const state = (part as { state: { status: string; output?: unknown; error?: unknown } }).state;
154
+ const told = String(state.output ?? state.error ?? "");
155
+ const toldLines = told.trim()
156
+ ? [block("agent was told:", clip(relativeTo(root, told), 600))]
157
+ : [];
158
+ if ("plan" in asked) {
159
+ // Sent back, the agent was told what to change. An approval's words are the
160
+ // harness's, and Claude's hold the plan file's path: the call's line says it.
161
+ return [block("plan:", clip(asked.plan, 800)), ...(state.status === "failed" ? toldLines : [])];
162
+ }
163
+ const settled = state.status === "completed" || state.status === "failed";
164
+ const lines = asked.questions.flatMap((question) => [
165
+ block("question:", clip(question.question, 800)),
166
+ ...(question.options.length ? [optionsLine(question.options)] : []),
167
+ ]);
168
+ return settled ? [...lines, ...toldLines] : lines;
169
+ }
170
+
171
+ /**
172
+ * One tool call on one line: its name, what it acted on, and whether it failed.
173
+ * `working: false` (its session runs no turn) shows a tool left open as
174
+ * interrupted, not running: its turn ended without it. Paths under `root` read
175
+ * relative to it, wherever they appear. A call that put a question to the
176
+ * person says whether it was answered, one that put a plan whether it was
177
+ * approved (`askedIn`).
178
+ */
179
+ export function toolLine(part: Part | UnknownPart, root = "", working = true): string | null {
180
+ if (part.type !== "tool" || !("toolName" in part)) return null;
181
+ const state = part.state as { status: string; input?: Record<string, unknown>; output?: unknown };
182
+ const input = state.input ?? {};
183
+ const raw = String(
184
+ input.file_path ??
185
+ input.path ??
186
+ input.command ??
187
+ input.pattern ??
188
+ input.url ??
189
+ input.description ??
190
+ "",
191
+ );
192
+ const target = oneLine(relativeTo(root, raw));
193
+ const mark = markOf(part, state, working);
194
+ return clip(`${oneLine(String(part.toolName))}${target ? ` ${target}` : ""}${mark}`, 140);
195
+ }
196
+
197
+ /** How a call stands, in the words for what it is: a tool failed, a question answered, a plan approved. */
198
+ function markOf(
199
+ part: Part | UnknownPart,
200
+ state: { status: string; output?: unknown },
201
+ working: boolean,
202
+ ): string {
203
+ const open = state.status === "in_progress" || state.status === "pending";
204
+ const asked = askedIn(part);
205
+ if (!asked) {
206
+ if (state.status === "failed") return " (failed)";
207
+ return open ? (working ? " (running)" : " (interrupted)") : "";
208
+ }
209
+ const plan = "plan" in asked;
210
+ if (open) {
211
+ if (!working) return " (interrupted)";
212
+ return plan ? " (waiting for approval)" : " (waiting for an answer)";
213
+ }
214
+ const ended = state.status === "failed" || state.status === "cancelled";
215
+ if (!plan) return ended ? " (not answered)" : "";
216
+ if (ended) return " (not approved)";
217
+ // A plan presented with nobody to ask completes with no words: no verdict.
218
+ return state.output ? " (approved)" : "";
219
+ }
220
+
221
+ /**
222
+ * Why only the person can answer what the agent waits on, where the session
223
+ * runs: a form to fill in, a page to visit, a secret to type, or a kind of
224
+ * request these tools do not know. Undefined for one a model may answer.
225
+ */
226
+ export function personOnly(waiting: Waiting): string | undefined {
227
+ if (waiting.kind !== "question") return undefined;
228
+ const { mode, questions = [] } = waiting.request;
229
+ if (mode === "form") return "a form to fill in";
230
+ if (mode === "url") return "a page to visit";
231
+ if (mode !== "question") return "a request these tools cannot answer";
232
+ return questions.some((question) => question.secret) ? "a secret to type" : undefined;
233
+ }
234
+
235
+ /**
236
+ * What the agent waits on, and the exact call that answers it. What only the
237
+ * person can answer (`personOnly`) is one line, with no call.
238
+ */
239
+ export function describeWaiting(waiting: Waiting, ref: string): string {
240
+ const only = waiting.kind === "question" && personOnly(waiting);
241
+ if (only) {
242
+ return `only the person can answer this, where the session runs (${only}): ${quoted(clip(waiting.request.message, 300))}`;
243
+ }
244
+ const answer = (text: string) => callHint("answer_request", { session: ref, answer: text });
245
+ const options = (labels: readonly string[], ownWords = false) =>
246
+ labels.length ? `\n${optionsLine(labels)}${ownWords ? " (or your own words)" : ""}` : "";
247
+ if (waiting.kind === "question") {
248
+ const questions = waiting.request.questions ?? [];
249
+ const asked = questions.length
250
+ ? questions
251
+ .map(
252
+ (q) =>
253
+ `${block("question:", q.question)}${options(
254
+ (q.options ?? []).map((o) => o.label),
255
+ true,
256
+ )}`,
257
+ )
258
+ .join("\n")
259
+ : block("question:", waiting.request.message);
260
+ const form =
261
+ questions.length > 1 ? "<one answer per question, separated by ; >" : "<your answer>";
262
+ return `${asked}\n ${answer(form)}`;
263
+ }
264
+ if (isPlan(waiting.request)) {
265
+ const approve = ` ${answer("approve")} (or answer: "<what to change>")`;
266
+ // Never approved unseen: the plan itself, or the call that shows it.
267
+ const plan = waiting.request.toolCall?.rawInput?.plan;
268
+ return typeof plan === "string" && plan.trim()
269
+ ? `plan waiting for approval:\n${quote(clip(plan, 800))}\n${approve}`
270
+ : `plan waiting for approval; read it before answering\n ${callHint("read_session", { session: ref })}\n${approve}`;
271
+ }
272
+ const named = waiting.request.options.map((option) => option.name);
273
+ return `${block("permission:", waiting.request.title)}${options(named)}\n ${answer("allow")} (or answer: "deny")`;
274
+ }
275
+
276
+ /** The agent's words since the person last spoke. */
277
+ export function lastReply(messages: readonly ViewMessage[]): string {
278
+ // A loop, not `findLastIndex`: consumers compile this source with their own `lib`.
279
+ let lastUser = messages.length - 1;
280
+ while (lastUser >= 0 && messages[lastUser]?.role !== "user") lastUser--;
281
+ return messages
282
+ .slice(lastUser + 1)
283
+ .filter((message) => message.role === "assistant" && !message.nested)
284
+ .map((message) => textOf(message.parts))
285
+ .filter(Boolean)
286
+ .join("\n");
287
+ }
288
+
289
+ /**
290
+ * How a turn stands: finished, waiting on the person, failed, or still going.
291
+ * `waitedSeconds` is how long this call waited; `note` is the host's line of
292
+ * facts for a turn that is not working any more.
293
+ */
294
+ export function renderOutcome(
295
+ view: SessionView,
296
+ ref: string,
297
+ waitedSeconds?: number,
298
+ note?: string,
299
+ ): string {
300
+ const phase = phaseOf(view);
301
+ if (phase === "working") {
302
+ // No messages at all: it is being set up, or its first turn has not shown yet.
303
+ const detail = [
304
+ view.messages.length ? "" : "starting up, no messages yet",
305
+ waitedSeconds ? `still running after ${waitedSeconds}s` : "",
306
+ ].filter(Boolean);
307
+ return `status: working${detail.length ? ` (${detail.join("; ")})` : ""}\n ${callHint("wait_for_session", { session: ref })}`;
308
+ }
309
+ const fresh = phase === "idle" && !view.messages.length;
310
+ const lines = [`status: ${fresh ? "idle (no messages yet)" : phase === "idle" ? "done" : phase}`];
311
+ const reply = lastReply(view.messages);
312
+ if (reply) lines.push(block("agent said:", clip(reply, 1500)));
313
+ for (const waiting of view.waiting) lines.push(describeWaiting(waiting, ref));
314
+ if (phase === "error") lines.push(block("error:", view.error ?? "the turn failed"));
315
+ if (note) lines.push(oneLine(note));
316
+ if (phase === "error" || reply.length > 1500) {
317
+ lines.push(` ${callHint("read_session", { session: ref })}`);
318
+ }
319
+ return lines.join("\n");
320
+ }
321
+
322
+ export interface RenderOptions {
323
+ /** How many recent messages (default 10). */
324
+ last?: number;
325
+ /** Paths in tool lines are shown relative to this folder. */
326
+ root?: string;
327
+ }
328
+
329
+ /**
330
+ * The conversation, condensed: what was asked, what the agent said, which
331
+ * tools it ran, and under a call that asked the person its questions and
332
+ * what the agent was told (or its plan).
333
+ */
334
+ export function renderConversation(
335
+ view: SessionView,
336
+ ref: string,
337
+ options: RenderOptions = {},
338
+ ): string {
339
+ const lines: string[] = [];
340
+ // The host was asked for `last`; a host that gives more is cut here.
341
+ const shown = view.messages.slice(-Math.max(1, options.last ?? 10));
342
+ // A tool awaiting approval is open in a working turn; one an ended turn left open was interrupted.
343
+ const working = view.status === "working";
344
+ for (const message of shown) {
345
+ const text = textOf(message.parts);
346
+ if (message.role === "user") {
347
+ lines.push(block("[you]", clip(text, 800)));
348
+ continue;
349
+ }
350
+ for (const part of message.parts) {
351
+ const line = toolLine(part, options.root, working);
352
+ if (!line) continue;
353
+ lines.push(` · ${line}`);
354
+ // Under the call's line, aligned with its name.
355
+ for (const asked of askedLines(part, options.root)) {
356
+ lines.push(asked.replace(/^/gm, " "));
357
+ }
358
+ }
359
+ if (text) lines.push(block("[agent]", clip(text, 1200)));
360
+ }
361
+ if (!shown.length) lines.push("(no messages yet)");
362
+ const cut = view.older || shown.length < view.messages.length;
363
+ lines.push(`(status: ${phaseOf(view)})`);
364
+ if (view.error && phaseOf(view) === "error") lines.push(block("error:", view.error));
365
+ for (const waiting of view.waiting) lines.push(describeWaiting(waiting, ref));
366
+ if (cut) {
367
+ lines.push(
368
+ shown.length >= MAX_LAST
369
+ ? `older messages exist; read_session shows at most the last ${MAX_LAST}.`
370
+ : `older messages exist: ${callHint("read_session", { session: ref, last: Math.min(shown.length + 10, MAX_LAST) })}`,
371
+ );
372
+ }
373
+ return lines.join("\n");
374
+ }
375
+
376
+ /** A person's words as the engine takes them, for the request the agent waits on. */
377
+ export type Answer =
378
+ | { kind: "question"; requestId: string; outcome: ElicitationOutcome }
379
+ | { kind: "decision"; requestId: string; outcome: PermissionOutcome };
380
+
381
+ /** A yes is the whole answer: "yes, but drop step 3" is not one. */
382
+ const YES =
383
+ /^(approve|approved|yes|yes please|yep|ok|okay|allow|accept|go|go ahead|do it|proceed|sure|lgtm)[\s.!]*$/i;
384
+ /** A no may carry its reason: "deny, it deletes the cache". */
385
+ const NO = /^(no|deny|denied|reject|stop|cancel)\b/i;
386
+
387
+ /**
388
+ * What a person said, as the outcome of the request the agent waits on (one
389
+ * a model may answer: not `personOnly`).
390
+ * A question takes the words (one per question, split on new lines or `;`,
391
+ * matched to an option's label where one fits). A plan is approved only by
392
+ * an answer that is a yes and nothing more ("approve", "ok", "go ahead"), and
393
+ * otherwise sent back with the words as what to change. A permission takes an
394
+ * option's name, a whole yes (allow once) or a no (reject once, the words as
395
+ * the reason); anything else cancels it.
396
+ */
397
+ export function answerFor(waiting: Waiting, text: string): Answer {
398
+ const said = text.trim();
399
+ if (waiting.kind === "question") {
400
+ const questions = waiting.request.questions ?? [];
401
+ // One answer per question, in order; a single question takes the whole text.
402
+ const each = questions.length > 1 ? said.split(/\s*\n\s*|\s*;\s*/) : [said];
403
+ const content: Record<string, string> = {};
404
+ questions.forEach((question, index) => {
405
+ const given = each[index];
406
+ if (!given) return;
407
+ const option = question.options?.find((o) => o.label.toLowerCase() === given.toLowerCase());
408
+ content[question.id] = option?.label ?? given;
409
+ });
410
+ if (questions.length === 0) content.answer = said;
411
+ return {
412
+ kind: "question",
413
+ requestId: waiting.request.requestId,
414
+ outcome: { action: "accept", content },
415
+ };
416
+ }
417
+ const { requestId, options } = waiting.request;
418
+ const pick = (optionId: string, message?: string): Answer => ({
419
+ kind: "decision",
420
+ requestId,
421
+ outcome: { outcome: "selected", optionId, ...(message ? { message } : {}) },
422
+ });
423
+ if (isPlan(waiting.request)) {
424
+ // Approving starts the work with edits still asked for; anything else is what to change.
425
+ return YES.test(said)
426
+ ? pick(PLAN_OPTION_IDS.approve)
427
+ : pick(PLAN_OPTION_IDS.keepPlanning, said);
428
+ }
429
+ const named = options.find((option) => option.name.toLowerCase() === said.toLowerCase());
430
+ if (named) return pick(named.optionId);
431
+ const kind = YES.test(said) ? "allow_once" : NO.test(said) ? "reject_once" : undefined;
432
+ const chosen = kind && options.find((option) => option.kind === kind);
433
+ if (chosen) return pick(chosen.optionId, kind === "reject_once" ? said : undefined);
434
+ return { kind: "decision", requestId, outcome: { outcome: "cancelled" } };
435
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * What an operator needs to know about one session, however its host keeps it.
3
+ *
4
+ * A host that holds a folded `ConversationState` gets this with `viewOf`. A host
5
+ * that keeps its own rows (messages with their parts, a status column) builds
6
+ * the same shape directly. Nothing here knows about projects, workspaces,
7
+ * accounts or storage: those are the host's.
8
+ */
9
+
10
+ import {
11
+ type ConversationElicitation,
12
+ type ConversationPermission,
13
+ type ConversationState,
14
+ conversationMessages,
15
+ pendingElicitations,
16
+ pendingPermissions,
17
+ } from "../protocol/conversation.ts";
18
+ import type { Part, UnknownPart } from "../protocol/parts.ts";
19
+ import { PLAN_OPTION_IDS } from "../protocol/plan.ts";
20
+
21
+ export interface ViewMessage {
22
+ role: "user" | "assistant";
23
+ parts: readonly (Part | UnknownPart)[];
24
+ /** A sub-agent's output: shown nested, never as the agent's reply. */
25
+ nested?: boolean;
26
+ }
27
+
28
+ /** A question the agent asked, as the engine's `elicitation.requested` carries it. */
29
+ export type QuestionRequest = Pick<
30
+ ConversationElicitation,
31
+ "requestId" | "mode" | "message" | "questions" | "url"
32
+ >;
33
+ /** A decision the agent waits on (a tool's approval, or a plan), as `permission.requested` carries it. */
34
+ export type DecisionRequest = Pick<
35
+ ConversationPermission,
36
+ "requestId" | "title" | "toolCall" | "options"
37
+ >;
38
+
39
+ export type Waiting =
40
+ | { kind: "question"; request: QuestionRequest }
41
+ | { kind: "decision"; request: DecisionRequest };
42
+
43
+ export interface SessionView {
44
+ /** Whether a turn is running. "Waiting on a person" is `waiting`, not a status. */
45
+ status: "idle" | "working" | "error";
46
+ messages: readonly ViewMessage[];
47
+ waiting: readonly Waiting[];
48
+ error?: string;
49
+ /** The host holds earlier messages than the ones given here. */
50
+ older?: boolean;
51
+ }
52
+
53
+ /** What a person would call the session's state. Waiting on them is not "finished". */
54
+ export type Phase = "idle" | "working" | "needs_input" | "error";
55
+
56
+ export function phaseOf(view: Pick<SessionView, "status" | "waiting">): Phase {
57
+ return view.waiting.length > 0 ? "needs_input" : view.status;
58
+ }
59
+
60
+ /** A plan's approval is a decision whose options include "keep planning" (`PLAN_OPTIONS`). */
61
+ export function isPlan(request: DecisionRequest): boolean {
62
+ return request.options.some((option) => option.optionId === PLAN_OPTION_IDS.keepPlanning);
63
+ }
64
+
65
+ /** The view of a session whose events were folded with the engine's reducer. */
66
+ export function viewOf(state: ConversationState): SessionView {
67
+ const last = state.turns.at(-1);
68
+ const failed = last?.status === "ended" ? last.error : undefined;
69
+ return {
70
+ status: last?.status === "active" ? "working" : failed ? "error" : "idle",
71
+ messages: conversationMessages(state).map((message) => ({
72
+ role: message.role,
73
+ parts: message.parts,
74
+ ...(message.parentToolCallId ? { nested: true } : {}),
75
+ })),
76
+ waiting: [
77
+ ...pendingElicitations(state).map((request) => ({ kind: "question" as const, request })),
78
+ ...pendingPermissions(state).map((request) => ({ kind: "decision" as const, request })),
79
+ ],
80
+ ...(failed ? { error: failed.message } : {}),
81
+ };
82
+ }
@@ -0,0 +1,35 @@
1
+ import type { PermissionOption } from "./lifecycle.ts";
2
+
3
+ /** The ids of a plan's options: each is the permission mode the session goes on in. */
4
+ export const PLAN_OPTION_IDS = {
5
+ acceptEdits: "accept_edits",
6
+ approve: "default",
7
+ keepPlanning: "plan",
8
+ } as const;
9
+
10
+ // @ref LLP 0001#d4--permission-requests-are-first-class-protocol — a plan's approval picks the mode
11
+ /**
12
+ * How a user answers an agent's plan: go on in a mode, or keep planning. Each
13
+ * option's id is the permission mode the session goes on in. These are Claude
14
+ * Code's own choices; Codex's TUI asks the same ("implement this plan" / "stay
15
+ * in Plan mode"). Auto-accepting edits is a standing choice for the edits to
16
+ * come (`allow_always`, as claude-agent-acp marks it), so an approver that
17
+ * takes the one-time approval implements asking for each edit. No standing
18
+ * rule answers a later plan: the broker keeps none for a harness's options.
19
+ */
20
+ export const PLAN_OPTIONS: PermissionOption[] = [
21
+ {
22
+ optionId: PLAN_OPTION_IDS.acceptEdits,
23
+ name: "Yes, and auto-accept edits",
24
+ kind: "allow_always",
25
+ },
26
+ {
27
+ optionId: PLAN_OPTION_IDS.approve,
28
+ name: "Yes, and manually approve edits",
29
+ kind: "allow_once",
30
+ },
31
+ { optionId: PLAN_OPTION_IDS.keepPlanning, name: "No, keep planning", kind: "reject_once" },
32
+ ];
33
+
34
+ /** What a plan's approval asks. */
35
+ export const PLAN_TITLE = "Implement this plan?";
@@ -71,8 +71,9 @@ export async function createAcpAgentApp(options: AcpBindingOptions): Promise<Age
71
71
  const sessions = new Map<string, BoundSession>();
72
72
  const checkMcpSupport = (servers: readonly unknown[] | undefined): void => {
73
73
  if (harness === "codex-app-server" && servers?.length) {
74
- // ACP supplies MCP entries, but has no session-specific CODEX_HOME
75
- // field. Never write those credentials into the operator's user home.
74
+ // ACP supplies MCP entries, and this binding does not pass them on to
75
+ // Codex: it names no CODEX_HOME for the session, and whether a session
76
+ // may run in the operator's own home is not ACP's to say (LLP 0001, D21).
76
77
  throw acp.RequestError.invalidParams(
77
78
  undefined,
78
79
  "Codex MCP is not supported by this ACP binding; use the engine or JSON-RPC API with a session-specific env.CODEX_HOME",
@@ -139,6 +139,10 @@ class HistorySync {
139
139
  : (await this.source.head(this.ref)).version;
140
140
  if (acknowledged && sameVersion(local, acknowledged)) {
141
141
  budget.progressed();
142
+ // The destination holds the source's head: synced, also after a
143
+ // failed wait, whose error no longer describes anything.
144
+ if (this.current.state !== "synced")
145
+ this.set({ state: "synced", localVersion: local, failures: 0, error: undefined });
142
146
  await idleAfter(waited, signal);
143
147
  continue;
144
148
  }