@zvada/agent-server 0.3.23 → 0.3.24

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 (246) hide show
  1. package/CHANGELOG.md +34 -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 +686 -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 +330 -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 +91 -0
  91. package/dist/core/processes/lifeline.js +210 -0
  92. package/dist/core/processes/native-processes.js +299 -0
  93. package/dist/core/processes/process-table.js +163 -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 +28 -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 +434 -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 +329 -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 +141 -0
  141. package/dist/protocol/errors.js +181 -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 +291 -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/core/agents/claude-code/approvals.d.ts.map +1 -1
  207. package/dist/types/core/agents/claude-code/claude-agent.d.ts +4 -1
  208. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  209. package/dist/types/core/agents/claude-code/options.d.ts +24 -11
  210. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  211. package/dist/types/core/agents/claude-code/session.d.ts +8 -0
  212. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  213. package/dist/types/core/agents/codex-app-server/homes.d.ts +6 -0
  214. package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -1
  215. package/dist/types/core/agents/codex-app-server/login.d.ts +12 -0
  216. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
  217. package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
  218. package/dist/types/core/agents/codex-app-server/session.d.ts +4 -1
  219. package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
  220. package/dist/types/core/agents/process-pool.d.ts +8 -0
  221. package/dist/types/core/agents/process-pool.d.ts.map +1 -1
  222. package/dist/types/core/presets.d.ts +2 -2
  223. package/dist/types/core/presets.d.ts.map +1 -1
  224. package/dist/types/server/bin.d.ts +3 -0
  225. package/dist/types/server/bin.d.ts.map +1 -0
  226. package/dist/types/server/transports.d.ts +2 -1
  227. package/dist/types/server/transports.d.ts.map +1 -1
  228. package/dist/types/sync/node-sqlite.d.ts +4 -1
  229. package/dist/types/sync/node-sqlite.d.ts.map +1 -1
  230. package/docs/consuming.md +30 -4
  231. package/docs/deploy.md +28 -0
  232. package/docs/harnesses.md +13 -1
  233. package/package.json +43 -18
  234. package/src/core/agents/claude-code/approvals.ts +5 -1
  235. package/src/core/agents/claude-code/claude-agent.ts +32 -5
  236. package/src/core/agents/claude-code/options.ts +24 -11
  237. package/src/core/agents/claude-code/session.ts +13 -0
  238. package/src/core/agents/codex-app-server/homes.ts +11 -2
  239. package/src/core/agents/codex-app-server/login.ts +30 -0
  240. package/src/core/agents/codex-app-server/requests.ts +7 -6
  241. package/src/core/agents/codex-app-server/session.ts +11 -2
  242. package/src/core/agents/process-pool.ts +30 -4
  243. package/src/core/presets.ts +3 -2
  244. package/src/server/bin.ts +25 -10
  245. package/src/server/transports.ts +6 -1
  246. package/src/sync/node-sqlite.ts +19 -3
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The stop reasons that mean "the turn finished the way it was supposed to".
3
+ * A subset of `STOP_REASONS` — everything except `error`.
4
+ *
5
+ * `cancelled` is CLEAN: the user asked for the turn to stop and it stopped.
6
+ * Products that treat it as a failure paint an error banner over the user's
7
+ * own action (all three copies of this set in the wild got this right, and
8
+ * two of them then drifted on `refusal` and `max_turn_requests`).
9
+ *
10
+ * Zod-free and dependency-free on purpose: this is a membership test, and a
11
+ * consumer branching on a stop reason should not have to load the schemas.
12
+ */
13
+ export const CLEAN_STOP_REASONS = [
14
+ "end_turn",
15
+ "max_tokens",
16
+ "max_turn_requests",
17
+ "refusal",
18
+ "cancelled",
19
+ ];
20
+ /**
21
+ * True when the turn stopped for a reason this build knows to be clean.
22
+ *
23
+ * `StopReason` is an OPEN vocabulary: a newer engine's value, or an
24
+ * adapter's `_`-prefixed extension, reaches an older consumer unchanged. Such
25
+ * a value is classified as NOT clean — the conservative direction. Showing a
26
+ * failure affordance for an outcome we cannot interpret is recoverable (the
27
+ * user retries); silently rendering an unknown outcome as success is not (the
28
+ * turn looks complete, the work is gone, nothing points at the cause).
29
+ */
30
+ export function isCleanStop(reason) {
31
+ return CLEAN_STOP_REASONS.includes(reason);
32
+ }
33
+ /**
34
+ * The complement of `isCleanStop`: `error`, plus every stop reason this build
35
+ * does not know (see the conservative-classification note above). `undefined`
36
+ * — a turn with no stop reason at all — is a failure too: a turn that ended
37
+ * without saying why did not end well.
38
+ */
39
+ export function isFailureStopReason(reason) {
40
+ return !isCleanStop(reason);
41
+ }
@@ -0,0 +1,31 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * A single, harness-agnostic reasoning dial. Each harness maps it to its own
4
+ * native control: Claude -> adaptive `thinking` + `effort`; Codex ->
5
+ * `ReasoningEffort`. What runs depends on the model: Claude's ceiling is `max`
6
+ * (it runs `ultra` as `max`), and Codex runs the nearest level the model
7
+ * accepts.
8
+ */
9
+ export const THINKING_LEVELS = ["off", "low", "medium", "high", "xhigh", "max", "ultra"];
10
+ export const ThinkingLevelSchema = z.enum(THINKING_LEVELS);
11
+ export function isThinkingLevel(v) {
12
+ return THINKING_LEVELS.includes(v);
13
+ }
14
+ const rank = (level) => THINKING_LEVELS.indexOf(level);
15
+ /**
16
+ * The level a model runs when it offers only `supported`: the highest one at
17
+ * or below `level`, else its lowest. Use it when switching models, so `ultra`
18
+ * on a model topping out at `max` becomes `max`, not a fixed fallback.
19
+ * `undefined` when the model offers none.
20
+ */
21
+ export function clampThinkingLevel(level, supported) {
22
+ let below;
23
+ let lowest;
24
+ for (const candidate of supported) {
25
+ if (lowest === undefined || rank(candidate) < rank(lowest))
26
+ lowest = candidate;
27
+ if (rank(candidate) <= rank(level) && (below === undefined || rank(candidate) > rank(below)))
28
+ below = candidate;
29
+ }
30
+ return below ?? lowest;
31
+ }
@@ -0,0 +1,21 @@
1
+ import { z } from "zod";
2
+ // @ref LLP 0002#epoch-milliseconds — validated at the boundary, not only documented
3
+ /**
4
+ * Every instant on this wire is epoch MILLISECONDS, as an integer.
5
+ * One schema, used by every `timestamp` and every nested `time.start`/
6
+ * `time.end`, so the boundary validation is real rather than prose: a bare
7
+ * `z.number()` accepts `-5`, `1.5` and `-0`, all of which round-trip silently
8
+ * and then sort, subtract and render wrong (a seconds-based stamp lands in
9
+ * 1970; `-0` breaks `Object.is` keyed caches).
10
+ */
11
+ export const EpochMsSchema = z
12
+ .number()
13
+ .int()
14
+ .nonnegative()
15
+ // -0 passes `>= 0`; it is not a legal instant, and it survives JSON as `0`
16
+ // only by accident of the serializer.
17
+ .refine((value) => !Object.is(value, -0), { message: "epoch-ms must not be -0" });
18
+ /** A start/end span in epoch ms (tool executions, thinking blocks). */
19
+ export const TimeSpanSchema = z.object({ start: EpochMsSchema, end: EpochMsSchema });
20
+ /** A span whose end is unknown while the thing is still running. */
21
+ export const OpenTimeSpanSchema = z.object({ start: EpochMsSchema, end: EpochMsSchema.optional() });
@@ -0,0 +1,57 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Normalized token accounting. Every harness reports usage differently
4
+ * (Claude: input/output/cache_creation/cache_read; Codex: input/output/
5
+ * reasoning/cached). Adapters fold those into this single shape.
6
+ *
7
+ * INVARIANTS (normative — so consumers never subtract):
8
+ * - `input` is NON-CACHED input tokens ONLY; billed input =
9
+ * `input + cache.read + cache.write` (the three are disjoint).
10
+ * - `reasoning` is a subset of `output` (output already includes it).
11
+ * - `writeEphemeral5m`/`writeEphemeral1h` are subsets of `cache.write`.
12
+ * Providers that fold cache hits into a total prompt count are unfolded once,
13
+ * at the adapter — never downstream.
14
+ */
15
+ export const TokenUsageSchema = z.object({
16
+ input: z.number().default(0),
17
+ output: z.number().default(0),
18
+ reasoning: z.number().optional(),
19
+ cache: z
20
+ .object({
21
+ read: z.number().default(0),
22
+ write: z.number().default(0),
23
+ /** Anthropic 5m-TTL cache-creation bucket, when reported. */
24
+ writeEphemeral5m: z.number().optional(),
25
+ /** Anthropic 1h-TTL cache-creation bucket, when reported. */
26
+ writeEphemeral1h: z.number().optional(),
27
+ })
28
+ .optional(),
29
+ });
30
+ export const DEFAULT_TOKEN_USAGE = {
31
+ input: 0,
32
+ output: 0,
33
+ reasoning: 0,
34
+ cache: { read: 0, write: 0 },
35
+ };
36
+ function addOptional(a, b) {
37
+ if (a === undefined && b === undefined)
38
+ return undefined;
39
+ return (a ?? 0) + (b ?? 0);
40
+ }
41
+ export function addTokenUsage(a, b) {
42
+ return {
43
+ input: a.input + b.input,
44
+ output: a.output + b.output,
45
+ reasoning: (a.reasoning ?? 0) + (b.reasoning ?? 0),
46
+ cache: {
47
+ read: (a.cache?.read ?? 0) + (b.cache?.read ?? 0),
48
+ write: (a.cache?.write ?? 0) + (b.cache?.write ?? 0),
49
+ ...(addOptional(a.cache?.writeEphemeral5m, b.cache?.writeEphemeral5m) !== undefined
50
+ ? { writeEphemeral5m: addOptional(a.cache?.writeEphemeral5m, b.cache?.writeEphemeral5m) }
51
+ : {}),
52
+ ...(addOptional(a.cache?.writeEphemeral1h, b.cache?.writeEphemeral1h) !== undefined
53
+ ? { writeEphemeral1h: addOptional(a.cache?.writeEphemeral1h, b.cache?.writeEphemeral1h) }
54
+ : {}),
55
+ },
56
+ };
57
+ }
@@ -0,0 +1,70 @@
1
+ import { STANDARD_PERMISSION_OPTIONS, isRejectKind } from "./guards.js";
2
+ import { META_KEYS } from "./meta-keys.js";
3
+ /** Why a tool its turn left running failed: it may have done what it was for. */
4
+ export const TOOL_OUTCOME_UNKNOWN = "The turn ended before this tool finished. Its outcome is unknown and its effects were not undone.";
5
+ /** Why a tool call its turn left half-written, or never approved, failed: it never ran. */
6
+ export const TOOL_NEVER_RAN = "The turn ended before this tool call was complete, so it never ran.";
7
+ /** Why a tool that was running when agent-server stopped failed: as with an ended turn, it may have run. */
8
+ export const TOOL_INTERRUPTED = "Tool execution was interrupted when agent-server stopped. Its outcome is unknown and its effects were not undone. Check the current state before continuing or retrying.";
9
+ /** The words of each closure: the model and the user read them, machines read `closure`. */
10
+ const CLOSURE_ERRORS = {
11
+ never_ran: TOOL_NEVER_RAN,
12
+ outcome_unknown: TOOL_OUTCOME_UNKNOWN,
13
+ interrupted: TOOL_INTERRUPTED,
14
+ };
15
+ // @ref LLP 0002#tools-a-turn-leaves-open — cancelled for a cancel, else failed and why
16
+ /**
17
+ * How a tool its turn left open ends; undefined for one that is not open. A
18
+ * cancelled turn cancels it. Otherwise a call whose input never finished
19
+ * streaming, or whose approval was asked for and refused, never ran; one that
20
+ * was running may have done what it was for, so its outcome is unknown, as
21
+ * `outcomeUnknown` says: its turn ended, or agent-server stopped under it. A
22
+ * pending call keeps what it streamed in `_meta`, and `tail`, what streamed
23
+ * after its last kept snapshot. The reducer closes tools at their turn's end
24
+ * with it, and crash recovery the turns a dead server left running.
25
+ */
26
+ export function closeToolLeftOpen(state, turnId, part, opts) {
27
+ const open = part.state;
28
+ if (open.status !== "pending" && open.status !== "in_progress")
29
+ return undefined;
30
+ // What a pending call streamed: the snapshot's `partialInput` when the
31
+ // adapter re-stated one, else the fold's own delta accumulator (shipped
32
+ // adapters stream tool input as deltas without re-snapshotting the pending
33
+ // tool), then what streamed after its last kept snapshot.
34
+ const streamed = open.status === "pending"
35
+ ? `${open.partialInput || state.toolInputJson[part.id] || ""}${opts.tail ?? ""}`
36
+ : "";
37
+ const meta = streamed ? { ...open._meta, [META_KEYS.partialInput]: streamed } : open._meta;
38
+ const closed = {
39
+ input: open.status === "in_progress" ? open.input : {},
40
+ // A pending tool never started, so the closure stamps both ends.
41
+ time: { start: open.status === "in_progress" ? open.time.start : opts.at, end: opts.at },
42
+ ...(meta !== undefined && { _meta: meta }),
43
+ };
44
+ if (opts.cancelled)
45
+ return { ...part, state: { status: "cancelled", ...closed } };
46
+ const ran = open.status === "in_progress" && !refusedApproval(state, turnId, part.toolCallId);
47
+ const closure = ran ? opts.outcomeUnknown : "never_ran";
48
+ return {
49
+ ...part,
50
+ state: { status: "failed", ...closed, error: CLOSURE_ERRORS[closure], closure },
51
+ };
52
+ }
53
+ /**
54
+ * Whether a tool call's approval was asked for in its turn and refused: every
55
+ * request it got was cancelled, left unanswered or answered with a reject (the
56
+ * harness's own options, or the standard ids a client may send for them).
57
+ * "Never ran" is a claim about side effects, so an answer this build cannot
58
+ * read, an option kind it does not know, may have allowed the call.
59
+ */
60
+ function refusedApproval(state, turnId, toolCallId) {
61
+ const asked = state.permissions.filter((p) => p.turnId === turnId && p.toolCall?.toolCallId === toolCallId);
62
+ return (asked.length > 0 &&
63
+ asked.every((p) => {
64
+ if (p.outcome?.outcome !== "selected")
65
+ return true;
66
+ const optionId = p.outcome.optionId;
67
+ const offered = p.options.find((o) => o.optionId === optionId);
68
+ return isRejectKind((offered ?? STANDARD_PERMISSION_OPTIONS.find((o) => o.optionId === optionId))?.kind);
69
+ }));
70
+ }
@@ -0,0 +1,153 @@
1
+ import { z } from "zod";
2
+ import { MetaSchema } from "./meta.js";
3
+ import { EpochMsSchema, TimeSpanSchema } from "./time.js";
4
+ import { openVocabulary } from "./vocabulary.js";
5
+ /**
6
+ * Runtime tool lifecycle: a tool call moves pending -> in_progress ->
7
+ * completed | failed | cancelled (ACP ToolCallStatus verbatim, incl. v2's
8
+ * `cancelled`). `pending` carries the partial (streaming) JSON input before it
9
+ * parses; the other states carry the fully-parsed input object. `cancelled` is
10
+ * the terminal for tools in flight when a turn is cancelled — the reducer
11
+ * applies it implicitly at `turn.ended{stopReason:"cancelled"}`; after any
12
+ * other end it closes them `failed`, saying the outcome is unknown (a running
13
+ * tool) or that it never ran (a half-written call), with its `closure`.
14
+ * Producers MAY also emit the terminal snapshot explicitly.
15
+ *
16
+ * The status set is a STRUCTURAL discriminator (each status has its own
17
+ * payload), so the union below is closed; new statuses are protocol additions,
18
+ * not extensions.
19
+ */
20
+ export const RUNTIME_TOOL_STATUSES = [
21
+ "pending",
22
+ "in_progress",
23
+ "completed",
24
+ "failed",
25
+ "cancelled",
26
+ ];
27
+ /**
28
+ * What a tool call does, normalized across harnesses — ACP's ToolKind taxonomy
29
+ * verbatim, plus `task` (subagent spawn; ACP has no subagent concept). Lets a
30
+ * consumer pick an icon / verb without knowing provider-native tool names.
31
+ *
32
+ * OPEN vocabulary: unknown non-`_` values are reserved for this
33
+ * protocol and MUST be preserved; `_`-prefixed values are adapter/product
34
+ * extensions. Display groupings (e.g. edit|delete|move -> a "write" card) are
35
+ * consumer maps, not wire vocabulary.
36
+ */
37
+ export const TOOL_KINDS = [
38
+ "read",
39
+ "edit",
40
+ "delete",
41
+ "move",
42
+ "search",
43
+ "execute",
44
+ "think",
45
+ "fetch",
46
+ "switch_mode",
47
+ "task",
48
+ "other",
49
+ ];
50
+ export const ToolKindSchema = openVocabulary(TOOL_KINDS);
51
+ /** A file location a tool call touches — lets UIs "follow along". (ACP shape.) */
52
+ export const ToolLocationSchema = z.object({
53
+ path: z.string(),
54
+ line: z.number().optional(),
55
+ });
56
+ /**
57
+ * The MCP server and tool a call is to, as names, on every harness that
58
+ * knows both: what a product reads instead of each harness's spelling of
59
+ * `toolName` (`mcp__docs__search` on Claude, `docs.search` on Codex).
60
+ */
61
+ export const McpToolSchema = z.object({
62
+ server: z.string(),
63
+ tool: z.string(),
64
+ });
65
+ /**
66
+ * Structured, display-grade tool output. Three-audience doctrine:
67
+ * `ToolStateCompleted.output` (string) is the MODEL-facing factual record and
68
+ * universal rendering fallback; `content` is the display-grade structured
69
+ * view; `metadata` is the machine channel (exitCode, ...).
70
+ */
71
+ export const ToolResultContentSchema = z.discriminatedUnion("type", [
72
+ z.object({ type: z.literal("text"), text: z.string(), _meta: MetaSchema }),
73
+ z.object({
74
+ type: z.literal("image"),
75
+ /** Base64-encoded bytes. */
76
+ data: z.string(),
77
+ mimeType: z.string(),
78
+ _meta: MetaSchema,
79
+ }),
80
+ z.object({
81
+ type: z.literal("diff"),
82
+ path: z.string(),
83
+ /** Absent for file creation. */
84
+ oldText: z.string().optional(),
85
+ newText: z.string(),
86
+ _meta: MetaSchema,
87
+ }),
88
+ z.object({
89
+ type: z.literal("terminal"),
90
+ /** Display anchor only — a separate ID domain from toolCallId. */
91
+ terminalId: z.string(),
92
+ _meta: MetaSchema,
93
+ }),
94
+ ]);
95
+ export const ToolStatePendingSchema = z.object({
96
+ status: z.literal("pending"),
97
+ /** Raw streamed JSON input — possibly invalid; parse best-effort for early render. */
98
+ partialInput: z.string(),
99
+ _meta: MetaSchema,
100
+ });
101
+ export const ToolStateInProgressSchema = z.object({
102
+ status: z.literal("in_progress"),
103
+ input: z.record(z.string(), z.unknown()),
104
+ title: z.string().optional(),
105
+ time: z.object({ start: EpochMsSchema }),
106
+ _meta: MetaSchema,
107
+ });
108
+ export const ToolStateCompletedSchema = z.object({
109
+ status: z.literal("completed"),
110
+ input: z.record(z.string(), z.unknown()),
111
+ /** Model-facing factual record; always present as the rendering fallback. */
112
+ output: z.string(),
113
+ /** Display-grade structured output, when expressible (diffs, images, terminals). */
114
+ content: z.array(ToolResultContentSchema).optional(),
115
+ /** Machine channel: harness-native extras (a command's `exitCode`, …). */
116
+ metadata: z.record(z.string(), z.unknown()).optional(),
117
+ title: z.string().optional(),
118
+ time: TimeSpanSchema,
119
+ _meta: MetaSchema,
120
+ });
121
+ /**
122
+ * How the engine closed a tool its turn left open, for machines: `never_ran`
123
+ * (its call was never complete, or its approval was refused), `outcome_unknown`
124
+ * (it was running when its turn ended) or `interrupted` (it was running when
125
+ * agent-server stopped). The failed state's `error` says the same in words
126
+ * (`tool-closure.ts`). OPEN: read a value you do not know as an outcome unknown.
127
+ */
128
+ export const TOOL_CLOSURES = ["never_ran", "outcome_unknown", "interrupted"];
129
+ export const ToolClosureSchema = openVocabulary(TOOL_CLOSURES);
130
+ export const ToolStateFailedSchema = z.object({
131
+ status: z.literal("failed"),
132
+ input: z.record(z.string(), z.unknown()),
133
+ error: z.string(),
134
+ /** Set when the engine closed the tool, absent when the harness reported the failure. */
135
+ closure: ToolClosureSchema.optional(),
136
+ /** Machine channel, as on a completed tool: a failed command's `exitCode`. */
137
+ metadata: z.record(z.string(), z.unknown()).optional(),
138
+ time: TimeSpanSchema,
139
+ _meta: MetaSchema,
140
+ });
141
+ export const ToolStateCancelledSchema = z.object({
142
+ status: z.literal("cancelled"),
143
+ input: z.record(z.string(), z.unknown()),
144
+ time: TimeSpanSchema,
145
+ _meta: MetaSchema,
146
+ });
147
+ export const ToolStateSchema = z.discriminatedUnion("status", [
148
+ ToolStatePendingSchema,
149
+ ToolStateInProgressSchema,
150
+ ToolStateCompletedSchema,
151
+ ToolStateFailedSchema,
152
+ ToolStateCancelledSchema,
153
+ ]);