@zvada/agent-server 0.3.23 → 0.3.25

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 (280) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +14 -5
  3. package/dist/accounts/chatgpt.js +144 -0
  4. package/dist/accounts/check.js +71 -0
  5. package/dist/accounts/claude.js +80 -0
  6. package/dist/accounts/endpoint.js +104 -0
  7. package/dist/accounts/http.js +58 -0
  8. package/dist/accounts/index.js +9 -0
  9. package/dist/client/client.js +745 -0
  10. package/dist/client/connection.js +338 -0
  11. package/dist/client/history.js +49 -0
  12. package/dist/client/index.js +6 -0
  13. package/dist/client/listeners.js +19 -0
  14. package/dist/client/logins.js +92 -0
  15. package/dist/client/rpc.js +105 -0
  16. package/dist/client/streams.js +432 -0
  17. package/dist/client/transports.js +118 -0
  18. package/dist/client/turns.js +122 -0
  19. package/dist/core/agents/acp/acp-agent.js +425 -0
  20. package/dist/core/agents/acp/adapter.js +231 -0
  21. package/dist/core/agents/acp/client.js +222 -0
  22. package/dist/core/agents/acp/known-agents.js +57 -0
  23. package/dist/core/agents/acp/mappings.js +164 -0
  24. package/dist/core/agents/acp/requests.js +79 -0
  25. package/dist/core/agents/attachments.js +14 -0
  26. package/dist/core/agents/base.js +64 -0
  27. package/dist/core/agents/claude-code/adapter.js +474 -0
  28. package/dist/core/agents/claude-code/approvals.js +245 -0
  29. package/dist/core/agents/claude-code/claude-agent.js +319 -0
  30. package/dist/core/agents/claude-code/credentials.js +142 -0
  31. package/dist/core/agents/claude-code/events.js +11 -0
  32. package/dist/core/agents/claude-code/login.js +217 -0
  33. package/dist/core/agents/claude-code/mcp.js +181 -0
  34. package/dist/core/agents/claude-code/models.js +74 -0
  35. package/dist/core/agents/claude-code/options.js +240 -0
  36. package/dist/core/agents/claude-code/outcome.js +204 -0
  37. package/dist/core/agents/claude-code/results.js +58 -0
  38. package/dist/core/agents/claude-code/sdk-pair.js +59 -0
  39. package/dist/core/agents/claude-code/session.js +593 -0
  40. package/dist/core/agents/claude-code/spawn.js +125 -0
  41. package/dist/core/agents/claude-code/spend.js +118 -0
  42. package/dist/core/agents/claude-code/tools.js +131 -0
  43. package/dist/core/agents/claude-code/turn-usage.js +121 -0
  44. package/dist/core/agents/claude-code/turn.js +199 -0
  45. package/dist/core/agents/codex-app-server/adapter.js +463 -0
  46. package/dist/core/agents/codex-app-server/client.js +338 -0
  47. package/dist/core/agents/codex-app-server/codex-agent.js +294 -0
  48. package/dist/core/agents/codex-app-server/commands.js +184 -0
  49. package/dist/core/agents/codex-app-server/credentials.js +92 -0
  50. package/dist/core/agents/codex-app-server/effort.js +13 -0
  51. package/dist/core/agents/codex-app-server/events.js +18 -0
  52. package/dist/core/agents/codex-app-server/homes.js +118 -0
  53. package/dist/core/agents/codex-app-server/input.js +52 -0
  54. package/dist/core/agents/codex-app-server/items.js +307 -0
  55. package/dist/core/agents/codex-app-server/login.js +183 -0
  56. package/dist/core/agents/codex-app-server/mcp.js +323 -0
  57. package/dist/core/agents/codex-app-server/models.js +160 -0
  58. package/dist/core/agents/codex-app-server/options.js +155 -0
  59. package/dist/core/agents/codex-app-server/plan-approval.js +124 -0
  60. package/dist/core/agents/codex-app-server/protocol.js +38 -0
  61. package/dist/core/agents/codex-app-server/requests.js +250 -0
  62. package/dist/core/agents/codex-app-server/session.js +278 -0
  63. package/dist/core/agents/codex-app-server/subagents.js +260 -0
  64. package/dist/core/agents/codex-app-server/thread-settings.js +214 -0
  65. package/dist/core/agents/codex-app-server/turn-items.js +69 -0
  66. package/dist/core/agents/codex-app-server/turn.js +448 -0
  67. package/dist/core/agents/codex-app-server/user-login.js +78 -0
  68. package/dist/core/agents/config-fingerprint.js +10 -0
  69. package/dist/core/agents/credentials.js +71 -0
  70. package/dist/core/agents/diffs.js +27 -0
  71. package/dist/core/agents/elicitation.js +42 -0
  72. package/dist/core/agents/inherit-config.js +5 -0
  73. package/dist/core/agents/login.js +56 -0
  74. package/dist/core/agents/mcp-config.js +109 -0
  75. package/dist/core/agents/plan.js +6 -0
  76. package/dist/core/agents/process-pool.js +307 -0
  77. package/dist/core/agents/registry.js +49 -0
  78. package/dist/core/agents/scripted/adapter.js +86 -0
  79. package/dist/core/agents/scripted/mcp-call.js +74 -0
  80. package/dist/core/agents/scripted/scripted-agent.js +331 -0
  81. package/dist/core/agents/scripted/scripts.js +154 -0
  82. package/dist/core/agents/scripted/steps.js +87 -0
  83. package/dist/core/agents/session-agent.js +209 -0
  84. package/dist/core/agents/stderr-tail.js +71 -0
  85. package/dist/core/agents/thinking-levels.js +9 -0
  86. package/dist/core/agents/types.js +1 -0
  87. package/dist/core/diagnostics.js +23 -0
  88. package/dist/core/index.js +31 -0
  89. package/dist/core/presets.js +114 -0
  90. package/dist/core/processes/identity.js +92 -0
  91. package/dist/core/processes/lifeline.js +218 -0
  92. package/dist/core/processes/native-processes.js +299 -0
  93. package/dist/core/processes/process-table.js +164 -0
  94. package/dist/core/provision/cache-trust.js +121 -0
  95. package/dist/core/provision/cache-usage.js +61 -0
  96. package/dist/core/provision/checksums.js +22 -0
  97. package/dist/core/provision/extract.js +29 -0
  98. package/dist/core/provision/index.js +4 -0
  99. package/dist/core/provision/install-build.js +99 -0
  100. package/dist/core/provision/npm.js +316 -0
  101. package/dist/core/provision/pins.js +35 -0
  102. package/dist/core/provision/platform.js +65 -0
  103. package/dist/core/provision/provisioner.js +372 -0
  104. package/dist/core/provision/releases.js +68 -0
  105. package/dist/core/provision/tools.js +279 -0
  106. package/dist/core/proxy/anthropic-proxy.js +163 -0
  107. package/dist/core/proxy/api-key-store.js +30 -0
  108. package/dist/core/proxy/index.js +3 -0
  109. package/dist/core/proxy/loopback.js +86 -0
  110. package/dist/core/runtime/agent-runtime.js +437 -0
  111. package/dist/core/runtime/event-processor.js +379 -0
  112. package/dist/core/runtime/event-sink.js +65 -0
  113. package/dist/core/runtime/harness-clis.js +83 -0
  114. package/dist/core/runtime/harness-logins.js +313 -0
  115. package/dist/core/runtime/login-reads.js +71 -0
  116. package/dist/core/runtime/model-lists.js +160 -0
  117. package/dist/core/runtime/permission-policy.js +84 -0
  118. package/dist/core/runtime/request-broker.js +139 -0
  119. package/dist/core/runtime/steering.js +79 -0
  120. package/dist/core/runtime/turn-outcome.js +16 -0
  121. package/dist/core/runtime/turn.js +339 -0
  122. package/dist/core/utils/bounded.js +13 -0
  123. package/dist/core/utils/deadline.js +57 -0
  124. package/dist/core/utils/errors.js +176 -0
  125. package/dist/core/utils/is-record.js +4 -0
  126. package/dist/core/utils/loopback.js +11 -0
  127. package/dist/index.js +4 -0
  128. package/dist/operator/index.js +10 -0
  129. package/dist/operator/mcp.js +139 -0
  130. package/dist/operator/operator.js +499 -0
  131. package/dist/operator/render.js +408 -0
  132. package/dist/operator/view.js +35 -0
  133. package/dist/protocol/account.js +96 -0
  134. package/dist/protocol/async-queue.js +65 -0
  135. package/dist/protocol/auth.js +169 -0
  136. package/dist/protocol/canonical.js +18 -0
  137. package/dist/protocol/clis.js +63 -0
  138. package/dist/protocol/config.js +137 -0
  139. package/dist/protocol/conversation.js +231 -0
  140. package/dist/protocol/credentials.js +142 -0
  141. package/dist/protocol/errors.js +190 -0
  142. package/dist/protocol/execution.js +28 -0
  143. package/dist/protocol/factories.js +231 -0
  144. package/dist/protocol/guards.js +71 -0
  145. package/dist/protocol/harness.js +93 -0
  146. package/dist/protocol/history.js +201 -0
  147. package/dist/protocol/ids.js +37 -0
  148. package/dist/protocol/index.js +36 -0
  149. package/dist/protocol/lifecycle.js +562 -0
  150. package/dist/protocol/meta-keys.js +17 -0
  151. package/dist/protocol/meta.js +13 -0
  152. package/dist/protocol/model-catalog.js +223 -0
  153. package/dist/protocol/models.js +84 -0
  154. package/dist/protocol/part-input.js +94 -0
  155. package/dist/protocol/parts.js +166 -0
  156. package/dist/protocol/plan.js +31 -0
  157. package/dist/protocol/reduce.js +484 -0
  158. package/dist/protocol/selectors.js +136 -0
  159. package/dist/protocol/seq-cursor.js +37 -0
  160. package/dist/protocol/stop-reasons.js +41 -0
  161. package/dist/protocol/thinking.js +31 -0
  162. package/dist/protocol/time.js +21 -0
  163. package/dist/protocol/tokens.js +57 -0
  164. package/dist/protocol/tool-closure.js +70 -0
  165. package/dist/protocol/tool-state.js +153 -0
  166. package/dist/protocol/verify.js +467 -0
  167. package/dist/protocol/vocabulary.js +27 -0
  168. package/dist/protocol/wire-api.js +94 -0
  169. package/dist/protocol/wire.js +669 -0
  170. package/dist/server/acp/binding.js +251 -0
  171. package/dist/server/acp/session-records.js +53 -0
  172. package/dist/server/acp/translate.js +401 -0
  173. package/dist/server/agent-server.js +338 -0
  174. package/dist/server/bin.js +492 -0
  175. package/dist/server/feedback.js +216 -0
  176. package/dist/server/history.js +123 -0
  177. package/dist/server/index.js +8 -0
  178. package/dist/server/install.js +171 -0
  179. package/dist/server/open-parts.js +87 -0
  180. package/dist/server/routes.js +292 -0
  181. package/dist/server/secrets.js +19 -0
  182. package/dist/server/session-gate.js +54 -0
  183. package/dist/server/session-log.js +66 -0
  184. package/dist/server/session-store.js +243 -0
  185. package/dist/server/subscriptions.js +189 -0
  186. package/dist/server/transports.js +214 -0
  187. package/dist/server/wire-error.js +26 -0
  188. package/dist/sync/event-log.js +89 -0
  189. package/dist/sync/fit.js +202 -0
  190. package/dist/sync/history-reader.js +33 -0
  191. package/dist/sync/history-sqlite.js +281 -0
  192. package/dist/sync/history.js +163 -0
  193. package/dist/sync/index.js +5 -0
  194. package/dist/sync/journal-sqlite.js +316 -0
  195. package/dist/sync/journal.js +10 -0
  196. package/dist/sync/live-tails.js +85 -0
  197. package/dist/sync/node-sqlite.js +27 -0
  198. package/dist/sync/projection.js +32 -0
  199. package/dist/sync/recovery.js +117 -0
  200. package/dist/sync/retry.js +45 -0
  201. package/dist/sync/schema.js +73 -0
  202. package/dist/sync/sql.js +94 -0
  203. package/dist/sync/sqlite-file.js +31 -0
  204. package/dist/sync/sqlite.js +18 -0
  205. package/dist/sync/worker.js +212 -0
  206. package/dist/types/client/client.d.ts +6 -1
  207. package/dist/types/client/client.d.ts.map +1 -1
  208. package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
  209. package/dist/types/core/agents/claude-code/claude-agent.d.ts +4 -1
  210. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  211. package/dist/types/core/agents/claude-code/options.d.ts +28 -11
  212. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  213. package/dist/types/core/agents/claude-code/session.d.ts +8 -0
  214. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  215. package/dist/types/core/agents/codex-app-server/homes.d.ts +6 -0
  216. package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -1
  217. package/dist/types/core/agents/codex-app-server/login.d.ts +12 -0
  218. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
  219. package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
  220. package/dist/types/core/agents/codex-app-server/session.d.ts +4 -1
  221. package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
  222. package/dist/types/core/agents/process-pool.d.ts +8 -0
  223. package/dist/types/core/agents/process-pool.d.ts.map +1 -1
  224. package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -1
  225. package/dist/types/core/agents/scripted/steps.d.ts +1 -1
  226. package/dist/types/core/presets.d.ts +2 -2
  227. package/dist/types/core/presets.d.ts.map +1 -1
  228. package/dist/types/core/processes/identity.d.ts.map +1 -1
  229. package/dist/types/core/processes/lifeline.d.ts.map +1 -1
  230. package/dist/types/core/processes/process-table.d.ts.map +1 -1
  231. package/dist/types/core/provision/extract.d.ts.map +1 -1
  232. package/dist/types/core/runtime/agent-runtime.d.ts +4 -1
  233. package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
  234. package/dist/types/core/runtime/turn.d.ts +12 -7
  235. package/dist/types/core/runtime/turn.d.ts.map +1 -1
  236. package/dist/types/protocol/clis.d.ts +3 -3
  237. package/dist/types/protocol/conversation.d.ts +6 -6
  238. package/dist/types/protocol/credentials.d.ts +13 -1
  239. package/dist/types/protocol/credentials.d.ts.map +1 -1
  240. package/dist/types/protocol/errors.d.ts +6 -4
  241. package/dist/types/protocol/errors.d.ts.map +1 -1
  242. package/dist/types/protocol/lifecycle.d.ts +4 -4
  243. package/dist/types/protocol/wire-api.d.ts +12 -12
  244. package/dist/types/protocol/wire.d.ts +8 -8
  245. package/dist/types/server/bin.d.ts +3 -0
  246. package/dist/types/server/bin.d.ts.map +1 -0
  247. package/dist/types/server/routes.d.ts.map +1 -1
  248. package/dist/types/server/transports.d.ts +2 -1
  249. package/dist/types/server/transports.d.ts.map +1 -1
  250. package/dist/types/sync/node-sqlite.d.ts +4 -1
  251. package/dist/types/sync/node-sqlite.d.ts.map +1 -1
  252. package/docs/consuming.md +56 -7
  253. package/docs/deploy.md +35 -0
  254. package/docs/harnesses.md +30 -5
  255. package/package.json +43 -18
  256. package/src/client/client.ts +114 -44
  257. package/src/core/agents/claude-code/approvals.ts +5 -1
  258. package/src/core/agents/claude-code/claude-agent.ts +32 -5
  259. package/src/core/agents/claude-code/options.ts +28 -11
  260. package/src/core/agents/claude-code/session.ts +13 -0
  261. package/src/core/agents/codex-app-server/homes.ts +11 -2
  262. package/src/core/agents/codex-app-server/login.ts +30 -0
  263. package/src/core/agents/codex-app-server/requests.ts +7 -6
  264. package/src/core/agents/codex-app-server/session.ts +11 -2
  265. package/src/core/agents/process-pool.ts +30 -4
  266. package/src/core/agents/scripted/scripted-agent.ts +2 -1
  267. package/src/core/agents/scripted/steps.ts +1 -1
  268. package/src/core/presets.ts +3 -2
  269. package/src/core/processes/identity.ts +1 -0
  270. package/src/core/processes/lifeline.ts +10 -1
  271. package/src/core/processes/process-table.ts +1 -0
  272. package/src/core/provision/extract.ts +1 -0
  273. package/src/core/runtime/agent-runtime.ts +6 -3
  274. package/src/core/runtime/turn.ts +21 -9
  275. package/src/protocol/credentials.ts +19 -5
  276. package/src/protocol/errors.ts +12 -3
  277. package/src/server/bin.ts +25 -10
  278. package/src/server/routes.ts +3 -2
  279. package/src/server/transports.ts +6 -1
  280. package/src/sync/node-sqlite.ts +19 -3
@@ -0,0 +1,408 @@
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
+ import { PLAN_OPTION_IDS } from "../protocol/plan.js";
9
+ import { isPlan, phaseOf, } from "./view.js";
10
+ const clip = (text, limit) => text.length > limit ? `${text.slice(0, limit - 1)}…` : text;
11
+ // @ref LLP 0014#untrusted-text — text an agent wrote or a repository holds never starts a line
12
+ // Untrusted text (what an agent or a person wrote, a question, an option, an
13
+ // error, a permission's title) is either a block of `QUOTE` lines or one
14
+ // JSON-encoded line after a label. The tool's own hints are ` -> tool(...)`,
15
+ // which no quoted line can produce: each of its lines begins with the marker.
16
+ /** The marker every line of untrusted text begins with. */
17
+ export const QUOTE = " | ";
18
+ /** Line breaks a reader may honour, the C0/C1 controls and bidirectional overrides. */
19
+ const BREAKS = /\r\n|[\n\r\v\f\u0085\u2028\u2029]/g;
20
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: the controls are what it drops
21
+ const CONTROLS = /[\u0000-\u0008\u000e-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;
22
+ /** What a JSON string still carries raw that may break a line or reorder it: escaped in a hint. */
23
+ const UNSAFE_IN_JSON = new RegExp(`${BREAKS.source}|${CONTROLS.source}`, "g");
24
+ /** The most messages `read_session` reads. */
25
+ export const MAX_LAST = 100;
26
+ /** Untrusted text as one line: no line breaks or controls, runs of space collapsed. */
27
+ export function oneLine(text) {
28
+ return text.replace(BREAKS, " ").replace(CONTROLS, "").replace(/\s+/g, " ").trim();
29
+ }
30
+ /** Untrusted text as a block: each of its lines carried after `QUOTE`. */
31
+ export function quote(text) {
32
+ return text
33
+ .replace(CONTROLS, "")
34
+ .split(BREAKS)
35
+ .map((line) => `${QUOTE}${line}`.trimEnd())
36
+ .join("\n");
37
+ }
38
+ /** Untrusted text named in prose (a session, a project, an option): one JSON-quoted line. */
39
+ export const quoted = (text) => JSON.stringify(oneLine(text));
40
+ /** A label, then the untrusted text as a quoted block under it. */
41
+ const block = (label, text) => `${label}\n${quote(text)}`;
42
+ const textOf = (parts) => parts
43
+ .flatMap((part) => (part.type === "text" && "text" in part ? [String(part.text)] : []))
44
+ .join("")
45
+ .trim();
46
+ /**
47
+ * The next step, as the tool call that takes it:
48
+ * `-> answer_request(session: "voyager", answer: "<your answer>")`.
49
+ */
50
+ export function callHint(tool, args = {}) {
51
+ // `\uXXXX` for what JSON leaves raw (U+2028, C1, bidi controls): the value reads back the same.
52
+ const json = (value) => JSON.stringify(value).replace(UNSAFE_IN_JSON, (found) => [...found].map((c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`).join(""));
53
+ const named = Object.entries(args).map(([key, value]) => `${key}: ${json(value)}`);
54
+ return `-> ${tool}(${named.join(", ")})`;
55
+ }
56
+ /** A choice's labels on one line: `options: "USD", "EUR"`. */
57
+ const optionsLine = (labels) => `options: ${labels.map(quoted).join(", ")}`;
58
+ /** What ends a path in a command: a space, a quote, or the shell's punctuation. */
59
+ const PATH_END = "\\s\"'`;&|()<>";
60
+ /** Not inside a longer path: what comes before the folder is no part of a name. */
61
+ const PATH_START = "(?<![\\w.~\\\\/-])";
62
+ /** What a shell escapes with a backslash in a path (`Live\ Mac`). */
63
+ const SHELL_ESCAPED = /[\s'"\\$`!&*()[\]{};|<>?]/g;
64
+ const REGEXP_SPECIAL = /[.*+?^${}()|[\]\\]/g;
65
+ /**
66
+ * `text` with the folder `root` read relative wherever it appears: a path
67
+ * under it as the rest of the path, the folder itself as `.`. Its form with
68
+ * spaces escaped, as a shell command writes it, too. A folder whose name
69
+ * merely starts with it (`root-old`) is left alone.
70
+ */
71
+ function relativeTo(root, text) {
72
+ const folder = root.replace(/\/+$/, "");
73
+ // "" or "/": there is nothing to read relative to.
74
+ if (folder.length < 2 || !text)
75
+ return text;
76
+ const forms = [...new Set([folder, folder.replace(SHELL_ESCAPED, "\\$&")])].map((form) => form.replace(REGEXP_SPECIAL, "\\$&"));
77
+ const pattern = new RegExp(`${PATH_START}(?:${forms.join("|")})(?:(/)(?=[^${PATH_END}])|/?(?=[${PATH_END}]|$))`, "g");
78
+ return text.replace(pattern, (_match, slash) => (slash ? "" : "."));
79
+ }
80
+ /**
81
+ * What a tool call put to the person, keyed by what its input carries, not
82
+ * by a tool's name: questions (`questions`, each with a `question`, its
83
+ * options labels or `{ label }`s), or a plan (a `switch_mode` call's `plan`).
84
+ */
85
+ function askedIn(part) {
86
+ if (part.type !== "tool" || !("toolName" in part))
87
+ return undefined;
88
+ const input = part.state.input;
89
+ if (!input || typeof input !== "object")
90
+ return undefined;
91
+ const { questions, plan } = input;
92
+ if (Array.isArray(questions)) {
93
+ const asked = questions.flatMap((entry) => {
94
+ const { question, options } = (entry ?? {});
95
+ if (typeof question !== "string" || !question.trim())
96
+ return [];
97
+ const labels = (Array.isArray(options) ? options : []).flatMap((option) => {
98
+ const label = typeof option === "string" ? option : option?.label;
99
+ return typeof label === "string" ? [label] : [];
100
+ });
101
+ return [{ question, options: labels }];
102
+ });
103
+ if (asked.length)
104
+ return { questions: asked };
105
+ }
106
+ if (part.kind === "switch_mode" && typeof plan === "string" && plan.trim())
107
+ return { plan };
108
+ return undefined;
109
+ }
110
+ /**
111
+ * What a tool call put to the person, for the lines under its own: each
112
+ * question with its options and, once the call has settled, what the agent
113
+ * was told (the answers, or a dismissal), or the plan. All of it is
114
+ * untrusted text.
115
+ */
116
+ function askedLines(part, root = "") {
117
+ const asked = askedIn(part);
118
+ if (!asked)
119
+ return [];
120
+ const state = part.state;
121
+ const told = String(state.output ?? state.error ?? "");
122
+ const toldLines = told.trim()
123
+ ? [block("agent was told:", clip(relativeTo(root, told), 600))]
124
+ : [];
125
+ if ("plan" in asked) {
126
+ // Sent back, the agent was told what to change. An approval's words are the
127
+ // harness's, and Claude's hold the plan file's path: the call's line says it.
128
+ return [block("plan:", clip(asked.plan, 800)), ...(state.status === "failed" ? toldLines : [])];
129
+ }
130
+ const settled = state.status === "completed" || state.status === "failed";
131
+ const lines = asked.questions.flatMap((question) => [
132
+ block("question:", clip(question.question, 800)),
133
+ ...(question.options.length ? [optionsLine(question.options)] : []),
134
+ ]);
135
+ return settled ? [...lines, ...toldLines] : lines;
136
+ }
137
+ /**
138
+ * One tool call on one line: its name, what it acted on, and whether it failed.
139
+ * `working: false` (its session runs no turn) shows a tool left open as
140
+ * interrupted, not running: its turn ended without it. Paths under `root` read
141
+ * relative to it, wherever they appear. A call that put a question to the
142
+ * person says whether it was answered, one that put a plan whether it was
143
+ * approved (`askedIn`).
144
+ */
145
+ export function toolLine(part, root = "", working = true) {
146
+ if (part.type !== "tool" || !("toolName" in part))
147
+ return null;
148
+ const state = part.state;
149
+ const input = state.input ?? {};
150
+ // @ref LLP 0002#a-tool-call-says-what-it-acts-on — the command the model wrote, not a harness's shell around it
151
+ const { command, url } = part;
152
+ const raw = String(command ??
153
+ url ??
154
+ input.file_path ??
155
+ input.path ??
156
+ input.command ??
157
+ input.pattern ??
158
+ input.url ??
159
+ input.description ??
160
+ "");
161
+ const target = oneLine(relativeTo(root, raw));
162
+ const mark = markOf(part, state, working);
163
+ return clip(`${oneLine(String(part.toolName))}${target ? ` ${target}` : ""}${mark}`, 140);
164
+ }
165
+ /** How a call stands, in the words for what it is: a tool failed, a question answered, a plan approved. */
166
+ function markOf(part, state, working) {
167
+ const open = state.status === "in_progress" || state.status === "pending";
168
+ const asked = askedIn(part);
169
+ if (!asked) {
170
+ if (state.status === "failed")
171
+ return " (failed)";
172
+ return open ? (working ? " (running)" : " (interrupted)") : "";
173
+ }
174
+ const plan = "plan" in asked;
175
+ if (open) {
176
+ if (!working)
177
+ return " (interrupted)";
178
+ return plan ? " (waiting for approval)" : " (waiting for an answer)";
179
+ }
180
+ const ended = state.status === "failed" || state.status === "cancelled";
181
+ if (!plan)
182
+ return ended ? " (not answered)" : "";
183
+ if (ended)
184
+ return " (not approved)";
185
+ // A plan presented with nobody to ask completes with no words: no verdict.
186
+ return state.output ? " (approved)" : "";
187
+ }
188
+ /**
189
+ * Why only the person can answer what the agent waits on, where the session
190
+ * runs: a form to fill in, a page to visit, a secret to type, or a kind of
191
+ * request these tools do not know. Undefined for one a model may answer.
192
+ */
193
+ export function personOnly(waiting) {
194
+ if (waiting.kind !== "question")
195
+ return undefined;
196
+ const { mode, questions = [] } = waiting.request;
197
+ if (mode === "form")
198
+ return "a form to fill in";
199
+ if (mode === "url")
200
+ return "a page to visit";
201
+ if (mode !== "question")
202
+ return "a request these tools cannot answer";
203
+ return questions.some((question) => question.secret) ? "a secret to type" : undefined;
204
+ }
205
+ /**
206
+ * What a permission is about, a line each, quoted: its command, else its
207
+ * address, else its files (under `root` relative to it), then why the agent
208
+ * asks, when it says. Empty when the request carries none of them.
209
+ */
210
+ function aboutLines(toolCall, root) {
211
+ if (!toolCall)
212
+ return "";
213
+ const files = (toolCall.locations ?? []).map((location) => relativeTo(root, location.path));
214
+ const more = files.length > 10 ? ` (and ${files.length - 10} more)` : "";
215
+ const what = toolCall.command?.trim()
216
+ ? `command: ${quoted(clip(relativeTo(root, toolCall.command), 500))}`
217
+ : toolCall.url?.trim()
218
+ ? `url: ${quoted(clip(toolCall.url, 500))}`
219
+ : files.length
220
+ ? `files: ${files.slice(0, 10).map(quoted).join(", ")}${more}`
221
+ : "";
222
+ const why = toolCall.reason?.trim() ? `reason: ${quoted(clip(toolCall.reason, 300))}` : "";
223
+ return [what, why]
224
+ .filter(Boolean)
225
+ .map((line) => `\n${line}`)
226
+ .join("");
227
+ }
228
+ /**
229
+ * What the agent waits on, and the exact call that answers it. What only the
230
+ * person can answer (`personOnly`) is one line, with no call. Paths under
231
+ * `root` read relative to it.
232
+ */
233
+ export function describeWaiting(waiting, ref, root = "") {
234
+ const only = waiting.kind === "question" && personOnly(waiting);
235
+ if (only) {
236
+ return `only the person can answer this, where the session runs (${only}): ${quoted(clip(waiting.request.message, 300))}`;
237
+ }
238
+ const answer = (text) => callHint("answer_request", { session: ref, answer: text });
239
+ const options = (labels, ownWords = false) => labels.length ? `\n${optionsLine(labels)}${ownWords ? " (or your own words)" : ""}` : "";
240
+ if (waiting.kind === "question") {
241
+ const questions = waiting.request.questions ?? [];
242
+ const asked = questions.length
243
+ ? questions
244
+ .map((q) => `${block("question:", q.question)}${options((q.options ?? []).map((o) => o.label), true)}`)
245
+ .join("\n")
246
+ : block("question:", waiting.request.message);
247
+ const form = questions.length > 1 ? "<one answer per question, separated by ; >" : "<your answer>";
248
+ return `${asked}\n ${answer(form)}`;
249
+ }
250
+ if (isPlan(waiting.request)) {
251
+ const approve = ` ${answer("approve")} (or answer: "<what to change>")`;
252
+ // Never approved unseen: the plan itself, or the call that shows it.
253
+ const plan = waiting.request.toolCall?.rawInput?.plan;
254
+ return typeof plan === "string" && plan.trim()
255
+ ? `plan waiting for approval:\n${quote(clip(plan, 800))}\n${approve}`
256
+ : `plan waiting for approval; read it before answering\n ${callHint("read_session", { session: ref })}\n${approve}`;
257
+ }
258
+ const named = waiting.request.options.map((option) => option.name);
259
+ const about = aboutLines(waiting.request.toolCall, root);
260
+ return `${block("permission:", waiting.request.title)}${about}${options(named)}\n ${answer("allow")} (or answer: "deny")`;
261
+ }
262
+ /** The agent's words since the person last spoke. */
263
+ export function lastReply(messages) {
264
+ // A loop, not `findLastIndex`: consumers compile this source with their own `lib`.
265
+ let lastUser = messages.length - 1;
266
+ while (lastUser >= 0 && messages[lastUser]?.role !== "user")
267
+ lastUser--;
268
+ return messages
269
+ .slice(lastUser + 1)
270
+ .filter((message) => message.role === "assistant" && !message.nested)
271
+ .map((message) => textOf(message.parts))
272
+ .filter(Boolean)
273
+ .join("\n");
274
+ }
275
+ /**
276
+ * How a turn stands: finished, waiting on the person, failed, or still going.
277
+ * `waitedSeconds` is how long this call waited; `note` is the host's line of
278
+ * facts for a turn that is not working any more; paths under `root` in what it
279
+ * waits on read relative to it.
280
+ */
281
+ export function renderOutcome(view, ref, waitedSeconds, note, root) {
282
+ const phase = phaseOf(view);
283
+ if (phase === "working") {
284
+ // No messages at all: it is being set up, or its first turn has not shown yet.
285
+ const detail = [
286
+ view.messages.length ? "" : "starting up, no messages yet",
287
+ waitedSeconds ? `still running after ${waitedSeconds}s` : "",
288
+ ].filter(Boolean);
289
+ return `status: working${detail.length ? ` (${detail.join("; ")})` : ""}\n ${callHint("wait_for_session", { session: ref })}`;
290
+ }
291
+ const fresh = phase === "idle" && !view.messages.length;
292
+ const lines = [`status: ${fresh ? "idle (no messages yet)" : phase === "idle" ? "done" : phase}`];
293
+ const reply = lastReply(view.messages);
294
+ if (reply)
295
+ lines.push(block("agent said:", clip(reply, 1500)));
296
+ for (const waiting of view.waiting)
297
+ lines.push(describeWaiting(waiting, ref, root));
298
+ if (phase === "error")
299
+ lines.push(block("error:", view.error ?? "the turn failed"));
300
+ if (note)
301
+ lines.push(oneLine(note));
302
+ if (phase === "error" || reply.length > 1500) {
303
+ lines.push(` ${callHint("read_session", { session: ref })}`);
304
+ }
305
+ return lines.join("\n");
306
+ }
307
+ /**
308
+ * The conversation, condensed: what was asked, what the agent said, which
309
+ * tools it ran, and under a call that asked the person its questions and
310
+ * what the agent was told (or its plan).
311
+ */
312
+ export function renderConversation(view, ref, options = {}) {
313
+ const lines = [];
314
+ // The host was asked for `last`; a host that gives more is cut here.
315
+ const shown = view.messages.slice(-Math.max(1, options.last ?? 10));
316
+ // A tool awaiting approval is open in a working turn; one an ended turn left open was interrupted.
317
+ const working = view.status === "working";
318
+ for (const message of shown) {
319
+ const text = textOf(message.parts);
320
+ if (message.role === "user") {
321
+ lines.push(block("[you]", clip(text, 800)));
322
+ continue;
323
+ }
324
+ for (const part of message.parts) {
325
+ const line = toolLine(part, options.root, working);
326
+ if (!line)
327
+ continue;
328
+ lines.push(` · ${line}`);
329
+ // Under the call's line, aligned with its name.
330
+ for (const asked of askedLines(part, options.root)) {
331
+ lines.push(asked.replace(/^/gm, " "));
332
+ }
333
+ }
334
+ if (text)
335
+ lines.push(block("[agent]", clip(text, 1200)));
336
+ }
337
+ if (!shown.length)
338
+ lines.push("(no messages yet)");
339
+ const cut = view.older || shown.length < view.messages.length;
340
+ lines.push(`(status: ${phaseOf(view)})`);
341
+ if (view.error && phaseOf(view) === "error")
342
+ lines.push(block("error:", view.error));
343
+ for (const waiting of view.waiting)
344
+ lines.push(describeWaiting(waiting, ref, options.root));
345
+ if (cut) {
346
+ lines.push(shown.length >= MAX_LAST
347
+ ? `older messages exist; read_session shows at most the last ${MAX_LAST}.`
348
+ : `older messages exist: ${callHint("read_session", { session: ref, last: Math.min(shown.length + 10, MAX_LAST) })}`);
349
+ }
350
+ return lines.join("\n");
351
+ }
352
+ /** A yes is the whole answer: "yes, but drop step 3" is not one. */
353
+ const YES = /^(approve|approved|yes|yes please|yep|ok|okay|allow|accept|go|go ahead|do it|proceed|sure|lgtm)[\s.!]*$/i;
354
+ /** A no may carry its reason: "deny, it deletes the cache". */
355
+ const NO = /^(no|deny|denied|reject|stop|cancel)\b/i;
356
+ /**
357
+ * What a person said, as the outcome of the request the agent waits on (one
358
+ * a model may answer: not `personOnly`).
359
+ * A question takes the words (one per question, split on new lines or `;`,
360
+ * matched to an option's label where one fits). A plan is approved only by
361
+ * an answer that is a yes and nothing more ("approve", "ok", "go ahead"), and
362
+ * otherwise sent back with the words as what to change. A permission takes an
363
+ * option's name, a whole yes (allow once) or a no (reject once, the words as
364
+ * the reason); anything else cancels it.
365
+ */
366
+ export function answerFor(waiting, text) {
367
+ const said = text.trim();
368
+ if (waiting.kind === "question") {
369
+ const questions = waiting.request.questions ?? [];
370
+ // One answer per question, in order; a single question takes the whole text.
371
+ const each = questions.length > 1 ? said.split(/\s*\n\s*|\s*;\s*/) : [said];
372
+ const content = {};
373
+ questions.forEach((question, index) => {
374
+ const given = each[index];
375
+ if (!given)
376
+ return;
377
+ const option = question.options?.find((o) => o.label.toLowerCase() === given.toLowerCase());
378
+ content[question.id] = option?.label ?? given;
379
+ });
380
+ if (questions.length === 0)
381
+ content.answer = said;
382
+ return {
383
+ kind: "question",
384
+ requestId: waiting.request.requestId,
385
+ outcome: { action: "accept", content },
386
+ };
387
+ }
388
+ const { requestId, options } = waiting.request;
389
+ const pick = (optionId, message) => ({
390
+ kind: "decision",
391
+ requestId,
392
+ outcome: { outcome: "selected", optionId, ...(message ? { message } : {}) },
393
+ });
394
+ if (isPlan(waiting.request)) {
395
+ // Approving starts the work with edits still asked for; anything else is what to change.
396
+ return YES.test(said)
397
+ ? pick(PLAN_OPTION_IDS.approve)
398
+ : pick(PLAN_OPTION_IDS.keepPlanning, said);
399
+ }
400
+ const named = options.find((option) => option.name.toLowerCase() === said.toLowerCase());
401
+ if (named)
402
+ return pick(named.optionId);
403
+ const kind = YES.test(said) ? "allow_once" : NO.test(said) ? "reject_once" : undefined;
404
+ const chosen = kind && options.find((option) => option.kind === kind);
405
+ if (chosen)
406
+ return pick(chosen.optionId, kind === "reject_once" ? said : undefined);
407
+ return { kind: "decision", requestId, outcome: { outcome: "cancelled" } };
408
+ }
@@ -0,0 +1,35 @@
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
+ import { conversationMessages, pendingElicitations, pendingPermissions, } from "../protocol/conversation.js";
10
+ import { PLAN_OPTION_IDS } from "../protocol/plan.js";
11
+ export function phaseOf(view) {
12
+ return view.waiting.length > 0 ? "needs_input" : view.status;
13
+ }
14
+ /** A plan's approval is a decision whose options include "keep planning" (`PLAN_OPTIONS`). */
15
+ export function isPlan(request) {
16
+ return request.options.some((option) => option.optionId === PLAN_OPTION_IDS.keepPlanning);
17
+ }
18
+ /** The view of a session whose events were folded with the engine's reducer. */
19
+ export function viewOf(state) {
20
+ const last = state.turns.at(-1);
21
+ const failed = last?.status === "ended" ? last.error : undefined;
22
+ return {
23
+ status: last?.status === "active" ? "working" : failed ? "error" : "idle",
24
+ messages: conversationMessages(state).map((message) => ({
25
+ role: message.role,
26
+ parts: message.parts,
27
+ ...(message.parentToolCallId ? { nested: true } : {}),
28
+ })),
29
+ waiting: [
30
+ ...pendingElicitations(state).map((request) => ({ kind: "question", request })),
31
+ ...pendingPermissions(state).map((request) => ({ kind: "decision", request })),
32
+ ],
33
+ ...(failed ? { error: failed.message } : {}),
34
+ };
35
+ }
@@ -0,0 +1,96 @@
1
+ // Who a login is, wherever it lives: the CLI's own (`auth.ts`, LLP 0011) or
2
+ // one a product holds (`credentials.ts`, LLP 0012). Never secret.
3
+ import { z } from "zod";
4
+ /**
5
+ * Who a harness runs as, wherever its login lives: the CLI's own
6
+ * (`auth/status`) or one a product holds (`CredentialGrant`). Never secret.
7
+ */
8
+ export const AccountInfoSchema = z.object({
9
+ /** Who serves the model: `anthropic`, `openai`, `bedrock`, `vertex`, `foundry`, …. */
10
+ provider: z.string().optional(),
11
+ /** The account, where the provider says it. */
12
+ email: z.string().optional(),
13
+ organization: z.string().optional(),
14
+ /** The plan a subscription is on, as the provider names it (`max`, `pro`, `plus`, …). */
15
+ plan: z.string().optional(),
16
+ });
17
+ /** What each harness's subscriptions are called, by the plan its provider names. */
18
+ const PLANS = {
19
+ "claude-code": {
20
+ product: "Claude",
21
+ plans: { free: "Free", pro: "Pro", max: "Max", team: "Team", enterprise: "Enterprise" },
22
+ },
23
+ "codex-app-server": {
24
+ product: "ChatGPT",
25
+ plans: {
26
+ free: "Free",
27
+ go: "Go",
28
+ plus: "Plus",
29
+ pro: "Pro",
30
+ team: "Team",
31
+ business: "Business",
32
+ enterprise: "Enterprise",
33
+ edu: "Edu",
34
+ },
35
+ },
36
+ };
37
+ const KEYS = {
38
+ "claude-code": "Anthropic API key",
39
+ "codex-app-server": "OpenAI API key",
40
+ };
41
+ const CLOUDS = {
42
+ bedrock: "Amazon Bedrock",
43
+ vertex: "Google Vertex AI",
44
+ foundry: "Microsoft Foundry",
45
+ };
46
+ /**
47
+ * What to call a login, the same wherever it lives: `Claude Max`, `ChatGPT
48
+ * Pro`, `Claude subscription` (plan unknown), `OpenAI API key`, `Amazon
49
+ * Bedrock`. A plan this table does not know shows as the provider names it.
50
+ */
51
+ export function accountLabel(harness, login) {
52
+ if (login.credential === "api_key")
53
+ return KEYS[harness] ?? "API key";
54
+ if (login.credential === "cloud")
55
+ return login.provider && (CLOUDS[login.provider] ?? login.provider);
56
+ if (login.credential !== "subscription")
57
+ return undefined;
58
+ const names = PLANS[harness];
59
+ if (!names)
60
+ return login.plan;
61
+ const plan = login.plan && (names.plans[login.plan] ?? login.plan);
62
+ return plan ? `${names.product} ${plan}` : `${names.product} subscription`;
63
+ }
64
+ /** Who serves each harness's models, where a grant does not say. */
65
+ const PROVIDERS = {
66
+ "claude-code": "anthropic",
67
+ "codex-app-server": "openai",
68
+ };
69
+ /**
70
+ * A login the product holds, as `auth/status` says one, without its secret:
71
+ * a product shows both kinds with one view.
72
+ */
73
+ export function grantAuth(grant) {
74
+ const { harness, credential } = grant;
75
+ const gateway = credential.type === "api_key" && credential.baseUrl !== undefined;
76
+ const provider = grant.provider ?? (gateway ? undefined : PROVIDERS[harness]);
77
+ const plan = grant.plan ?? (credential.type === "chatgpt" ? credential.plan : undefined);
78
+ const login = {
79
+ credential: credential.type === "api_key" ? "api_key" : "subscription",
80
+ ...(provider && { provider }),
81
+ ...(plan && { plan }),
82
+ };
83
+ const label = accountLabel(harness, login);
84
+ return {
85
+ harness,
86
+ state: "signed_in",
87
+ source: "product",
88
+ ...login,
89
+ ...(grant.email && { email: grant.email }),
90
+ ...(grant.organization && { organization: grant.organization }),
91
+ ...(label && { label }),
92
+ ...(credential.type !== "api_key" &&
93
+ credential.expiresAt !== undefined && { expiresAt: credential.expiresAt }),
94
+ methods: [],
95
+ };
96
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Single-consumer async channel. Producers `push()` values and then `end()`
3
+ * (graceful) or `fail(error)` (consumers reject once buffered values drain);
4
+ * a single consumer iterates with `for await`. `push` after end/fail is a
5
+ * no-op; `return()` lets a consumer `break` out and end the stream. Shared by
6
+ * core (prompt feeding, per-turn event buffering) and client (turn streams).
7
+ */
8
+ export class AsyncQueue {
9
+ queue = [];
10
+ waiting = [];
11
+ done = false;
12
+ failure;
13
+ push(value) {
14
+ if (this.done)
15
+ return;
16
+ const w = this.waiting.shift();
17
+ if (w)
18
+ w.resolve({ value, done: false });
19
+ else
20
+ this.queue.push(value);
21
+ }
22
+ end() {
23
+ if (this.done)
24
+ return;
25
+ this.done = true;
26
+ for (const w of this.waiting)
27
+ w.resolve({ value: undefined, done: true });
28
+ this.waiting = [];
29
+ }
30
+ fail(error) {
31
+ if (this.done)
32
+ return;
33
+ this.done = true;
34
+ this.failure = error;
35
+ for (const w of this.waiting)
36
+ w.reject(error);
37
+ this.waiting = [];
38
+ }
39
+ get size() {
40
+ return this.queue.length;
41
+ }
42
+ next() {
43
+ // Check length, not the shifted value: a queued `undefined`/falsy item is
44
+ // a real value and must not be mistaken for an empty queue.
45
+ if (this.queue.length > 0) {
46
+ return Promise.resolve({ value: this.queue.shift(), done: false });
47
+ }
48
+ if (this.done) {
49
+ return this.failure !== undefined
50
+ ? Promise.reject(this.failure)
51
+ : Promise.resolve({ value: undefined, done: true });
52
+ }
53
+ return new Promise((resolve, reject) => this.waiting.push({ resolve, reject }));
54
+ }
55
+ return() {
56
+ // IteratorClose is terminal: a consumer that breaks has discarded every
57
+ // buffered value, even when return() is called directly.
58
+ this.queue = [];
59
+ this.end();
60
+ return Promise.resolve({ value: undefined, done: true });
61
+ }
62
+ [Symbol.asyncIterator]() {
63
+ return this;
64
+ }
65
+ }