@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,437 @@
1
+ import { RunRequestSchema, canonicalJson, turnIdentity } from "../../protocol/index.js";
2
+ import { withTimeout } from "../utils/deadline.js";
3
+ import { InvalidRequestError, TurnConflictError, TurnForgottenError } from "../utils/errors.js";
4
+ import { EventSinkError } from "./event-sink.js";
5
+ import { awaitingInstall, harnessCliProgress, harnessClis } from "./harness-clis.js";
6
+ import { HarnessLogins } from "./harness-logins.js";
7
+ import { ModelLists, catalogModelList } from "./model-lists.js";
8
+ import { StandingRules } from "./permission-policy.js";
9
+ import { Turn, wellFormedInput, } from "./turn.js";
10
+ // Caller-supplied IDs need not be UUIDs; encode the tuple without delimiter collisions.
11
+ const turnKeyOf = (sessionId, turnId) => JSON.stringify([sessionId, turnId]);
12
+ // @ref LLP 0003#commit-before-acknowledging — a turn sent again converges when it is the same turn
13
+ const inputKeyOf = (request) => canonicalJson(turnIdentity(request));
14
+ /**
15
+ * Per-session convergence window. An older turn keeps only its id: a retry
16
+ * of it is refused (`TurnForgottenError`), since a turn id names one turn in
17
+ * the session's stream (LLP 0002) and a turn that ran never runs again.
18
+ */
19
+ const SETTLED_TURNS = 16;
20
+ /** Give up on stragglers after this long; the process is exiting anyway. */
21
+ const DEFAULT_DRAIN_TIMEOUT_MS = 10_000;
22
+ /**
23
+ * The engine. Owns no transport and no harness specifics: it admits each
24
+ * RunRequest once as a `Turn`, which runs it on its harness and streams
25
+ * normalized LifecycleEvents to a sink, and routes cancels, answers and
26
+ * steers to the turns they are for.
27
+ */
28
+ export class AgentRuntime {
29
+ registry;
30
+ /**
31
+ * Admitted turns by turn key, until they settle: what a retried run
32
+ * converges on, and what cancels, answers and steers reach.
33
+ */
34
+ turns = new Map();
35
+ /** What each logical session remembers across its turns, until it closes. */
36
+ sessions = new Map();
37
+ shutdownPromise;
38
+ /** Aborted as shutdown begins, and part of every run's signal: a run still
39
+ * setting up then, which its harness has not yet tracked, stops too. */
40
+ stopping = new AbortController();
41
+ modelLists = new ModelLists();
42
+ logins;
43
+ host;
44
+ constructor(registry, options = {}) {
45
+ this.registry = registry;
46
+ this.logins = new HarnessLogins((harness) => registry.getAgent(harness), (harness, store) => {
47
+ registry.getAgent(harness).loginChanged?.(store);
48
+ this.modelLists.forget(harness);
49
+ });
50
+ this.host = {
51
+ registry,
52
+ modelLists: this.modelLists,
53
+ onDiagnostic: options.onDiagnostic,
54
+ memory: (sessionId) => this.memoryOf(sessionId),
55
+ cancel: (harness, sessionId) => this.cancel(harness, sessionId),
56
+ };
57
+ }
58
+ get harnesses() {
59
+ return this.registry.list();
60
+ }
61
+ capabilities(harness) {
62
+ // A custom agent that declares none says it ignores nothing.
63
+ return { ignoredSettings: [], ...this.registry.getAgent(harness).capabilities };
64
+ }
65
+ /**
66
+ * The models a harness offers, read from its CLI for the login and folder a
67
+ * turn with the same `cwd`, `env` and `apiKey` would use, and cached. Never
68
+ * rejects for a registered harness: without a live list it returns the
69
+ * catalog, with `error` saying why. Turns then fit their thinking level to
70
+ * the listed levels of the model they run. A read installs nothing: while
71
+ * the harness's CLI is not installed yet, being installed or failed to,
72
+ * the answer is the catalog with that `error`, kept by no cache, so the
73
+ * first read after the install is live.
74
+ */
75
+ async models(query) {
76
+ const agent = this.registry.getAgent(query.harness);
77
+ // @ref LLP 0010#a-read-installs-nothing — a model picker opened downloads no CLI
78
+ const awaiting = await awaitingInstall(this.registry.provisioner, query.harness);
79
+ if (awaiting)
80
+ return { ...catalogModelList(query.harness, Date.now()), error: awaiting };
81
+ return await this.modelLists.get(agent, query);
82
+ }
83
+ /**
84
+ * Where each harness's CLI is (every registered harness when `harnesses`
85
+ * is absent), found without installing anything: `ready`, `missing` (what
86
+ * its first turn would install), `installing`, `failed` (why), or
87
+ * `unmanaged` (ACP's agent is the operator's command).
88
+ */
89
+ async listClis(harnesses = this.harnesses) {
90
+ for (const harness of harnesses)
91
+ this.registry.getAgent(harness);
92
+ return harnessClis(this.registry.provisioner, harnesses, false);
93
+ }
94
+ // @ref LLP 0010#p3--ready-before-the-first-turn-and-visible — a product installs at setup, not in a turn
95
+ /**
96
+ * Install each harness's CLI now rather than at its first turn, joining an
97
+ * install already running, and answer where each one is after: a failed
98
+ * install is reported with its error, not thrown. Progress goes to
99
+ * `onCliProgress`.
100
+ */
101
+ async prepareClis(harnesses = this.harnesses) {
102
+ for (const harness of harnesses)
103
+ this.registry.getAgent(harness);
104
+ return harnessClis(this.registry.provisioner, harnesses, true);
105
+ }
106
+ /**
107
+ * Every install of a harness's CLI, whoever caused it (a turn,
108
+ * `prepareClis`, a login or logout; a read installs nothing): at most four
109
+ * a second, and always its last phase. Returns the unsubscribe.
110
+ */
111
+ onCliProgress(observer) {
112
+ const provisioner = this.registry.provisioner;
113
+ if (!provisioner)
114
+ return () => { };
115
+ return provisioner.observe((progress) => {
116
+ for (const event of harnessCliProgress(progress, this.harnesses))
117
+ observer(event);
118
+ });
119
+ }
120
+ /**
121
+ * Each harness's login, as its CLI says it for the store and environment a
122
+ * turn with `env` would use (every registered harness when `harnesses` is
123
+ * absent): signed in, with what and as whom, signed out, or unknown and
124
+ * why; and the logins it offers. A login made elsewhere (a terminal) that
125
+ * a read notices counts as a change, as `login` and `logout` do: each
126
+ * session's next turn starts a new CLI, and `onAuthUpdated` hears it. A
127
+ * login under way to the store is `loginUnderWay`. A read installs
128
+ * nothing: a harness whose CLI is not installed yet, being installed or
129
+ * failed to is `unknown`, with no methods and `error` saying which, and
130
+ * its CLI is not run.
131
+ */
132
+ async authStatus(harnesses = this.harnesses, env) {
133
+ for (const harness of harnesses)
134
+ this.registry.getAgent(harness);
135
+ return Promise.all(harnesses.map(async (harness) => {
136
+ // @ref LLP 0010#a-read-installs-nothing — a settings page opened downloads no CLI
137
+ const error = await awaitingInstall(this.registry.provisioner, harness);
138
+ if (error === undefined)
139
+ return this.logins.statusOf(harness, env);
140
+ return { harness, state: "unknown", methods: [], error };
141
+ }));
142
+ }
143
+ /**
144
+ * Start one of a harness's logins through its CLI's own flow, answered as
145
+ * soon as the CLI says where the user signs in; `onAuthUpdated` says how
146
+ * it ended. A login under way to the same harness and store is cancelled.
147
+ */
148
+ login(params) {
149
+ return this.logins.login(params);
150
+ }
151
+ /** Finish a login with the code its `codeUrl` page showed: how it ended. */
152
+ completeLogin(loginId, code) {
153
+ return this.logins.complete(loginId, code);
154
+ }
155
+ /** Stop a login under way. */
156
+ cancelLogin(loginId) {
157
+ return this.logins.cancel(loginId);
158
+ }
159
+ /** Remove a harness's CLI login; answers its login after. */
160
+ logout(harness, env) {
161
+ return this.logins.logout(harness, env);
162
+ }
163
+ /** Every change of a harness's login and every login's end. Returns the unsubscribe. */
164
+ onAuthUpdated(listener) {
165
+ return this.logins.onUpdated(listener);
166
+ }
167
+ /**
168
+ * Answer a pending `permission.requested` event. Returns false when the
169
+ * request is unknown (already resolved, cancelled, or a sessionId mismatch).
170
+ */
171
+ respondPermission(sessionId, requestId, outcome) {
172
+ return this.respond("permission", sessionId, requestId, outcome);
173
+ }
174
+ /**
175
+ * Answer a pending `elicitation.requested` event. Returns false when the
176
+ * request is unknown (already resolved, cancelled, or a sessionId mismatch).
177
+ */
178
+ respondElicitation(sessionId, requestId, outcome) {
179
+ return this.respond("elicitation", sessionId, requestId, outcome);
180
+ }
181
+ respond(kind, sessionId, requestId, answer) {
182
+ return this.turnsOf(sessionId).some((turn) => turn.requests.respond(kind, requestId, answer));
183
+ }
184
+ /**
185
+ * Probe how `run()` would admit this request WITHOUT executing anything:
186
+ * `new` (would run), `inflight`/`completed` (an identical request was
187
+ * already admitted — a retry must converge, not re-execute). Throws
188
+ * `TurnConflictError` when this turnId was admitted with DIFFERENT input,
189
+ * or ran too long ago to converge on (`TurnForgottenError`), and the turn's
190
+ * `EventSinkError` when its durable sink stopped it.
191
+ * Wire seats use this to quick-ack a duplicate instead of starting it.
192
+ */
193
+ admission(request) {
194
+ const known = this.known(request);
195
+ if (!known)
196
+ return { status: "new" };
197
+ return known instanceof Turn
198
+ ? { status: "inflight" }
199
+ : { status: "completed", summary: known.summary };
200
+ }
201
+ /** The admitted turn a request names, in flight or settled; throws as `admission` says. */
202
+ known(request) {
203
+ const { sessionId, turnId } = request;
204
+ const memory = this.sessions.get(sessionId);
205
+ const known = this.turns.get(turnKeyOf(sessionId, turnId)) ?? memory?.settled.get(turnId);
206
+ if (!known) {
207
+ if (memory?.forgotten.has(turnId))
208
+ throw new TurnForgottenError(sessionId, turnId);
209
+ return undefined;
210
+ }
211
+ if (known.inputKey !== inputKeyOf(request))
212
+ throw new TurnConflictError(sessionId, turnId);
213
+ if (known instanceof Turn)
214
+ return known;
215
+ // It may have run tools before its sink failed: never run it again.
216
+ if ("failure" in known)
217
+ throw known.failure;
218
+ return known;
219
+ }
220
+ run(request, sink, opts = {}) {
221
+ if (this.shutdownPromise)
222
+ return Promise.reject(new Error("agent runtime is shutting down"));
223
+ // Checked once, here: the wire refuses an invalid request before it
224
+ // reaches the engine, and an embedder's is refused the same way.
225
+ const parsed = RunRequestSchema.safeParse(request);
226
+ if (!parsed.success) {
227
+ const issues = parsed.error.issues.map((issue) => ({
228
+ path: issue.path.join("."),
229
+ message: issue.message,
230
+ }));
231
+ return Promise.reject(new InvalidRequestError(issues));
232
+ }
233
+ // Idempotent admission (the embed-tier guard a retried DO RPC needs): a
234
+ // duplicate {sessionId, turnId} with identical input converges on the
235
+ // original run — the in-flight promise or the memoized summary — and is
236
+ // never executed twice. The retry's sink receives no events; the first
237
+ // delivery (or a wire-tier replay) owns those. Same ids with different
238
+ // input is a caller bug, surfaced loudly instead of silently re-running.
239
+ let known;
240
+ try {
241
+ known = this.known(parsed.data);
242
+ }
243
+ catch (error) {
244
+ return Promise.reject(error);
245
+ }
246
+ if (known instanceof Turn)
247
+ return known.running;
248
+ if (known)
249
+ return Promise.resolve(known.summary);
250
+ const signal = opts.signal
251
+ ? AbortSignal.any([opts.signal, this.stopping.signal])
252
+ : this.stopping.signal;
253
+ const turn = new Turn(parsed.data, inputKeyOf(parsed.data), sink, signal, this.host);
254
+ const key = turnKeyOf(turn.sessionId, turn.turnId);
255
+ this.turns.set(key, turn);
256
+ // One handler, not a .finally chain: the inflight→settled transition
257
+ // must be atomic within a single microtask, or a concurrent admission
258
+ // probe could observe the settled turn as still inflight. Remembered in
259
+ // the same step it leaves `turns`: a retried steer always finds the
260
+ // turn's answers.
261
+ turn.running.then((summary) => this.settle(key, turn, { summary }),
262
+ // A rejected run is NOT memoized: it died before executing the turn
263
+ // loop (registry/setup), so a retry is allowed to try again. Unless its
264
+ // durable sink stopped it, possibly after it had run tools.
265
+ (error) => this.settle(key, turn, error instanceof EventSinkError ? { failure: error } : undefined));
266
+ return turn.running;
267
+ }
268
+ settle(key, turn, settled) {
269
+ if (this.turns.get(key) === turn)
270
+ this.turns.delete(key);
271
+ if (!settled)
272
+ return;
273
+ const { settled: window, forgotten } = this.memoryOf(turn.sessionId);
274
+ window.set(turn.turnId, { inputKey: turn.inputKey, steers: turn.steers.answers(), ...settled });
275
+ for (const oldest of window.keys()) {
276
+ if (window.size <= SETTLED_TURNS)
277
+ break;
278
+ window.delete(oldest);
279
+ forgotten.add(oldest);
280
+ }
281
+ }
282
+ /**
283
+ * Cancel the session's in-flight turn. An idle session is a clean no-op ack
284
+ * (`{confirmed: true, hadTurn: false}`); `confirmed: false` means a turn
285
+ * existed but the harness did not acknowledge the interrupt — the agent may
286
+ * still be running; `turn.ended` remains the source of truth. A turn
287
+ * admitted but not yet on its harness answers `hadTurn: false` too (the
288
+ * harness had nothing to interrupt), and still ends `cancelled`: the turn
289
+ * keeps the cancel, and its harness begins it stopped.
290
+ */
291
+ async cancel(harness, sessionId) {
292
+ // The turn keeps the cancel (its signal), and any harness parked on an
293
+ // approval is unblocked, before (and regardless of) the agent-level abort.
294
+ for (const turn of this.turnsOf(sessionId))
295
+ void turn.requestCancel();
296
+ return await this.registry.getAgent(harness).cancel(sessionId);
297
+ }
298
+ /**
299
+ * Add input to a running turn (`turn/steer`). The agent reads it at its
300
+ * next step, where the stream shows it as a user message; a turn that ends
301
+ * first lists it in `turn.ended.undeliveredSteers`. A retry (same
302
+ * `steerId`, same input) converges on the first answer, also after the turn
303
+ * ended; the same id with other input throws `TurnConflictError`. Input the
304
+ * harness cannot take throws, as it would fail a turn.
305
+ */
306
+ async steer(sessionId, request) {
307
+ const { turnId, steerId, input } = request;
308
+ if (typeof input === "string" ? input.trim() === "" : input.length === 0) {
309
+ throw new Error("a steer carries input");
310
+ }
311
+ const inputKey = canonicalJson(input);
312
+ const turn = this.turns.get(turnKeyOf(sessionId, turnId));
313
+ const known = turn
314
+ ? turn.steers.find(steerId)
315
+ : this.sessions.get(sessionId)?.settled.get(turnId)?.steers.get(steerId);
316
+ if (known) {
317
+ if (known.inputKey !== inputKey)
318
+ throw new TurnConflictError(sessionId, turnId, steerId);
319
+ const first = await known.result;
320
+ return first.outcome === "steered" ? { ...first, deduplicated: true } : first;
321
+ }
322
+ // A steer id names a message in the session, as a turn id does.
323
+ if (this.steerIdTaken(sessionId, steerId))
324
+ throw new TurnConflictError(sessionId, turnId, steerId);
325
+ if (!turn?.steers.open) {
326
+ const active = this.turnsOf(sessionId).find((t) => t.steers.open);
327
+ return { outcome: "no_active_turn", ...(active && { activeTurnId: active.turnId }) };
328
+ }
329
+ const agent = this.registry.getAgent(turn.harness);
330
+ const deliver = agent.capabilities.steering ? agent.steer?.bind(agent) : undefined;
331
+ if (!deliver)
332
+ 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) }));
335
+ }
336
+ /** Whether another turn of the session, live or remembered, took this steer id. */
337
+ steerIdTaken(sessionId, steerId) {
338
+ const settled = [...(this.sessions.get(sessionId)?.settled.values() ?? [])];
339
+ return (this.turnsOf(sessionId).some((turn) => turn.steers.find(steerId)) ||
340
+ settled.some((turn) => turn.steers.has(steerId)));
341
+ }
342
+ /**
343
+ * Call after the host resumes from suspension, before admitting new turns.
344
+ * Retains conversations and admission receipts, and ends no process: Claude,
345
+ * Codex app-server and ACP replace each retained subprocess before its
346
+ * session's next prompt and strictly resume saved history. Their MCP
347
+ * reset/reload controls can retain dead connections.
348
+ */
349
+ invalidateMcpConnections() {
350
+ for (const harness of this.registry.list()) {
351
+ this.registry.getAgent(harness).invalidateMcpConnections?.();
352
+ }
353
+ }
354
+ /**
355
+ * Watch the native processes this runtime's harnesses start for sessions,
356
+ * and see each gone: what a host keeps (a journal does) so that its next
357
+ * start can call `stopOrphans`. Returns the unsubscribe. Throwing at
358
+ * `started` fails that spawn.
359
+ */
360
+ onNativeProcess(observer) {
361
+ return this.registry.processes.observe(observer);
362
+ }
363
+ /**
364
+ * The harnesses whose agents start their native processes through this
365
+ * runtime's, which records them: a restart can vouch for their sessions.
366
+ * A session of any other harness stays fenced when a restart cuts it off.
367
+ */
368
+ recordedHarnesses() {
369
+ return new Set(this.registry
370
+ .list()
371
+ .filter((harness) => this.registry.getAgent(harness).processes === this.registry.processes));
372
+ }
373
+ // @ref LLP 0007#records-and-the-restart-sweep — verify, then stop what is still ours
374
+ /**
375
+ * The restart sweep, for records a previous owner of the host's store left:
376
+ * each that still names its running process (same boot, start time and
377
+ * executable) is stopped with its tool sessions; one whose pid now names
378
+ * another process is left alone. Says what became of each.
379
+ */
380
+ stopOrphans(records) {
381
+ return this.registry.processes.stopOrphans(records);
382
+ }
383
+ /** Dispose one idle logical session and its harness-native resources. */
384
+ async closeSession(harness, sessionId) {
385
+ this.sessions.delete(sessionId);
386
+ await Promise.all(this.turnsOf(sessionId).map((turn) => turn.requestCancel()));
387
+ // A harness this runtime does not run (a session restored from a journal
388
+ // written with another registry) holds nothing here to release.
389
+ if (!this.registry.has(harness))
390
+ return;
391
+ const agent = this.registry.getAgent(harness);
392
+ if (agent.release)
393
+ await agent.release(sessionId);
394
+ else
395
+ await agent.cancel(sessionId);
396
+ }
397
+ shutdown(opts = {}) {
398
+ // Memoized: the first caller's timeout wins.
399
+ this.shutdownPromise ??= this.performShutdown(opts.drainTimeoutMs ?? DEFAULT_DRAIN_TIMEOUT_MS);
400
+ return this.shutdownPromise;
401
+ }
402
+ async performShutdown(drainTimeoutMs) {
403
+ this.stopping.abort();
404
+ this.logins.shutdown();
405
+ const turns = [...this.turns.values()];
406
+ await Promise.all(turns.map((turn) => turn.requests.cancelAll()));
407
+ let terminationError;
408
+ try {
409
+ await this.registry.terminateAll();
410
+ }
411
+ catch (error) {
412
+ terminationError = error;
413
+ }
414
+ // Drain active runs, but don't let a harness that ignores its abort
415
+ // signal hang the process's shutdown forever.
416
+ await withTimeout(Promise.allSettled(turns.map((turn) => turn.running)), drainTimeoutMs);
417
+ this.sessions.clear();
418
+ // No CLI outlives the runtime that started it, nor a tool it ran: a
419
+ // host that shuts one runtime down and keeps running relies on no lifeline.
420
+ await this.registry.processes.stopAll();
421
+ if (terminationError !== undefined)
422
+ throw terminationError;
423
+ }
424
+ /** The session's admitted turns that have not settled. */
425
+ turnsOf(sessionId) {
426
+ return [...this.turns.values()].filter((turn) => turn.sessionId === sessionId);
427
+ }
428
+ /** The session's memory, made on first use, and again after `closeSession` forgot it. */
429
+ memoryOf(sessionId) {
430
+ let memory = this.sessions.get(sessionId);
431
+ if (!memory) {
432
+ memory = { standingRules: new StandingRules(), settled: new Map(), forgotten: new Set() };
433
+ this.sessions.set(sessionId, memory);
434
+ }
435
+ return memory;
436
+ }
437
+ }