@eloxiv/daemon 0.0.0-stage → 0.1.0

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 (114) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +6 -2
  3. package/dist/Acp.d.ts +8 -0
  4. package/dist/Acp.d.ts.map +1 -0
  5. package/dist/Acp.js +268 -0
  6. package/dist/Acp.js.map +1 -0
  7. package/dist/Canonical.d.ts +3 -0
  8. package/dist/Canonical.d.ts.map +1 -0
  9. package/dist/Canonical.js +12 -0
  10. package/dist/Canonical.js.map +1 -0
  11. package/dist/Client.d.ts +100 -0
  12. package/dist/Client.d.ts.map +1 -0
  13. package/dist/Client.js +474 -0
  14. package/dist/Client.js.map +1 -0
  15. package/dist/Commands.d.ts +85 -0
  16. package/dist/Commands.d.ts.map +1 -0
  17. package/dist/Commands.js +370 -0
  18. package/dist/Commands.js.map +1 -0
  19. package/dist/Config.d.ts +74 -0
  20. package/dist/Config.d.ts.map +1 -0
  21. package/dist/Config.js +126 -0
  22. package/dist/Config.js.map +1 -0
  23. package/dist/Daemon.d.ts +243 -0
  24. package/dist/Daemon.d.ts.map +1 -0
  25. package/dist/Daemon.js +965 -0
  26. package/dist/Daemon.js.map +1 -0
  27. package/dist/Harness.d.ts +133 -0
  28. package/dist/Harness.d.ts.map +1 -0
  29. package/dist/Harness.js +734 -0
  30. package/dist/Harness.js.map +1 -0
  31. package/dist/Http.d.ts +15 -0
  32. package/dist/Http.d.ts.map +1 -0
  33. package/dist/Http.js +548 -0
  34. package/dist/Http.js.map +1 -0
  35. package/dist/KernelLink.d.ts +145 -0
  36. package/dist/KernelLink.d.ts.map +1 -0
  37. package/dist/KernelLink.js +109 -0
  38. package/dist/KernelLink.js.map +1 -0
  39. package/dist/LocalAuth.d.ts +99 -0
  40. package/dist/LocalAuth.d.ts.map +1 -0
  41. package/dist/LocalAuth.js +225 -0
  42. package/dist/LocalAuth.js.map +1 -0
  43. package/dist/Main.d.ts +51 -0
  44. package/dist/Main.d.ts.map +1 -0
  45. package/dist/Main.js +219 -0
  46. package/dist/Main.js.map +1 -0
  47. package/dist/Secrets.d.ts +21 -0
  48. package/dist/Secrets.d.ts.map +1 -0
  49. package/dist/Secrets.js +204 -0
  50. package/dist/Secrets.js.map +1 -0
  51. package/dist/SecureUrl.d.ts +11 -0
  52. package/dist/SecureUrl.d.ts.map +1 -0
  53. package/dist/SecureUrl.js +23 -0
  54. package/dist/SecureUrl.js.map +1 -0
  55. package/dist/State.d.ts +77 -0
  56. package/dist/State.d.ts.map +1 -0
  57. package/dist/State.js +38 -0
  58. package/dist/State.js.map +1 -0
  59. package/dist/Terminals.d.ts +49 -0
  60. package/dist/Terminals.d.ts.map +1 -0
  61. package/dist/Terminals.js +203 -0
  62. package/dist/Terminals.js.map +1 -0
  63. package/dist/bin-node.d.ts +2 -0
  64. package/dist/bin-node.d.ts.map +1 -0
  65. package/dist/bin-node.js +4 -0
  66. package/dist/bin-node.js.map +1 -0
  67. package/dist/bin.d.ts +2 -0
  68. package/dist/bin.d.ts.map +1 -0
  69. package/dist/bin.js +4 -0
  70. package/dist/bin.js.map +1 -0
  71. package/dist/index.d.ts +17 -0
  72. package/dist/index.d.ts.map +1 -0
  73. package/dist/index.js +17 -0
  74. package/dist/index.js.map +1 -0
  75. package/dist/runtime/bun.d.ts +11 -0
  76. package/dist/runtime/bun.d.ts.map +1 -0
  77. package/dist/runtime/bun.js +20 -0
  78. package/dist/runtime/bun.js.map +1 -0
  79. package/dist/runtime/node.d.ts +11 -0
  80. package/dist/runtime/node.d.ts.map +1 -0
  81. package/dist/runtime/node.js +21 -0
  82. package/dist/runtime/node.js.map +1 -0
  83. package/dist/testing.d.ts +25 -0
  84. package/dist/testing.d.ts.map +1 -0
  85. package/dist/testing.js +27 -0
  86. package/dist/testing.js.map +1 -0
  87. package/fixtures/claude-code-env-vars.txt +409 -0
  88. package/fixtures/fake-acp-agent.mjs +222 -0
  89. package/fixtures/fake-harness.mjs +299 -0
  90. package/fixtures/recorded/claude-code.jsonl +7 -0
  91. package/fixtures/recorded/codex.jsonl +6 -0
  92. package/package.json +64 -3
  93. package/scripts/build-sidecar.ts +86 -0
  94. package/src/Acp.ts +292 -0
  95. package/src/Canonical.ts +9 -0
  96. package/src/Client.ts +585 -0
  97. package/src/Commands.ts +427 -0
  98. package/src/Config.ts +179 -0
  99. package/src/Daemon.ts +1092 -0
  100. package/src/Harness.ts +839 -0
  101. package/src/Http.ts +563 -0
  102. package/src/KernelLink.ts +197 -0
  103. package/src/LocalAuth.ts +301 -0
  104. package/src/Main.ts +281 -0
  105. package/src/Secrets.ts +226 -0
  106. package/src/SecureUrl.ts +21 -0
  107. package/src/State.ts +109 -0
  108. package/src/Terminals.ts +227 -0
  109. package/src/bin-node.ts +4 -0
  110. package/src/bin.ts +4 -0
  111. package/src/index.ts +16 -0
  112. package/src/runtime/bun.ts +29 -0
  113. package/src/runtime/node.ts +30 -0
  114. package/src/testing.ts +43 -0
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Compile the daemon into a single executable with `bun build --compile` and
3
+ * name it the way Tauri expects an `externalBin`: `eloxiv-daemon-<target-triple>`.
4
+ *
5
+ * bun scripts/build-sidecar.ts [--target <rust-triple>] [--out-dir <dir>] [--entry <file>] [--name <name>]
6
+ *
7
+ * `--entry` compiles an app's own sidecar instead of the generic one: a file that calls the daemon's `runMain`
8
+ * with its `clientApp` (decision 14; the desktop-rune item's `sidecar/daemon.ts`), named `<name>-<target-triple>` (default
9
+ * `eloxiv-daemon`). Relative paths are the caller's.
10
+ *
11
+ * The triple defaults to `TAURI_ENV_TARGET_TRIPLE` (set by the Tauri CLI) and
12
+ * then to the host triple from `rustc -vV`. The output directory defaults to
13
+ * this repository's desktop host template's `src-tauri/binaries`; an app passes
14
+ * its own (the desktop item's `scripts/prepare.ts` finds this script through
15
+ * the package export `@eloxiv/daemon/build-sidecar`).
16
+ */
17
+ import { execFileSync } from "node:child_process"
18
+ import { mkdirSync, statSync } from "node:fs"
19
+ import { dirname, join, resolve } from "node:path"
20
+ import { fileURLToPath } from "node:url"
21
+
22
+ const here = dirname(fileURLToPath(import.meta.url))
23
+ const packageRoot = resolve(here, "..")
24
+ const defaultOutDir = resolve(packageRoot, "../../registry/app/desktop/src-tauri/binaries")
25
+
26
+ /** Rust target triple → Bun `--compile` target. */
27
+ const bunTargets: Readonly<Record<string, string>> = {
28
+ "x86_64-unknown-linux-gnu": "bun-linux-x64",
29
+ "aarch64-unknown-linux-gnu": "bun-linux-arm64",
30
+ "x86_64-unknown-linux-musl": "bun-linux-x64-musl",
31
+ "aarch64-unknown-linux-musl": "bun-linux-arm64-musl",
32
+ "x86_64-apple-darwin": "bun-darwin-x64",
33
+ "aarch64-apple-darwin": "bun-darwin-arm64",
34
+ "x86_64-pc-windows-msvc": "bun-windows-x64",
35
+ "aarch64-pc-windows-msvc": "bun-windows-arm64",
36
+ }
37
+
38
+ const flag = (name: string): string | undefined => {
39
+ const args = process.argv.slice(2)
40
+ const index = args.indexOf(name)
41
+ if (index >= 0) return args[index + 1]
42
+ return args.find((arg) => arg.startsWith(`${name}=`))?.slice(name.length + 1)
43
+ }
44
+
45
+ const hostTriple = (): string => {
46
+ const output = execFileSync("rustc", ["-vV"], { encoding: "utf8" })
47
+ const host = /^host:\s*(\S+)$/m.exec(output)?.[1]
48
+ if (host === undefined) throw new Error(`Could not read the host triple from \`rustc -vV\`:\n${output}`)
49
+ return host
50
+ }
51
+
52
+ const triple = flag("--target") ?? process.env["TAURI_ENV_TARGET_TRIPLE"] ?? hostTriple()
53
+ const outDir = resolve(flag("--out-dir") ?? defaultOutDir)
54
+ const extension = triple.includes("windows") ? ".exe" : ""
55
+ const entry = flag("--entry") === undefined ? join(packageRoot, "src/bin.ts") : resolve(flag("--entry")!)
56
+ const name = flag("--name") ?? "eloxiv-daemon"
57
+ if (!/^[a-z0-9][a-z0-9-]*$/u.test(name))
58
+ throw new Error(`--name must be lower-case letters, digits and dashes: ${name}`)
59
+ const outfile = join(outDir, `${name}-${triple}${extension}`)
60
+
61
+ const args = [
62
+ "build",
63
+ "--compile",
64
+ "--minify",
65
+ "--sourcemap",
66
+ "--bytecode",
67
+ "--conditions=@eloxiv/source",
68
+ // A release build: the development origins (the Vite dev server) are not trusted.
69
+ "--define",
70
+ `ELOXIV_DAEMON_BUILD="release"`,
71
+ entry,
72
+ "--outfile",
73
+ outfile,
74
+ ]
75
+ const host = hostTriple()
76
+ if (triple !== host) {
77
+ const target = bunTargets[triple]
78
+ if (target === undefined) throw new Error(`No Bun compile target for ${triple}`)
79
+ args.splice(2, 0, `--target=${target}`)
80
+ }
81
+
82
+ mkdirSync(outDir, { recursive: true })
83
+ console.log(`bun ${args.join(" ")}`)
84
+ execFileSync(process.execPath, args, { stdio: "inherit", cwd: packageRoot })
85
+ const size = statSync(outfile).size
86
+ console.log(`sidecar: ${outfile} (${(size / 1024 / 1024).toFixed(1)} MiB)`)
package/src/Acp.ts ADDED
@@ -0,0 +1,292 @@
1
+ /**
2
+ * Harnesses that speak the Agent Client Protocol (ACP: JSON-RPC 2.0 over the agent's stdin and stdout, one message
3
+ * per line): OpenCode (`opencode acp`) and any agent the person configures (`ELOXIV_DAEMON_ACP_COMMAND`: Gemini
4
+ * CLI's `gemini --experimental-acp`, an ACP bridge for Claude Code or Pi, ...). The daemon is the ACP client: it
5
+ * starts a session (`session/new`, or `session/load` to follow one up) with the Eloxiv tools as an HTTP MCP server
6
+ * through the relay, sends the prompt (`session/prompt`), turns the agent's `session/update` notifications into
7
+ * normalised events, answers its permission requests, and cancels with `session/cancel`.
8
+ *
9
+ * Tools: the client offers no file system or terminal of its own (`clientCapabilities` all false, and such requests
10
+ * are refused). Without workspace tools a permission request for anything but an Eloxiv tool is rejected; but an
11
+ * agent can run code without asking (its own tools, or configuration and plugins it discovers in the working
12
+ * directory), so only an agent the person declares tools-only (`ELOXIV_DAEMON_ACP_TOOLS_ONLY=1`) runs a turn without
13
+ * workspace tools; any other, OpenCode included (a repository's `.opencode/plugins` run before any permission
14
+ * request), runs only turns that ask for workspace tools. OpenCode still gets its permission configuration
15
+ * (`OPENCODE_CONFIG_CONTENT`), as defence in depth.
16
+ */
17
+ import type { HarnessEvent } from "@eloxiv/contracts"
18
+ import { spawn } from "node:child_process"
19
+ import {
20
+ MCP_SERVER,
21
+ NOT_FORWARDED,
22
+ harnessEnv,
23
+ type HarnessConfig,
24
+ type HarnessResult,
25
+ type HarnessRunInput,
26
+ } from "./Harness.ts"
27
+
28
+ const GRACE_MS = 3_000
29
+ const clip = (text: string, limit = 4000) => (text.length > limit ? `${text.slice(0, limit)}…` : text)
30
+
31
+ const object = (value: unknown): Record<string, unknown> | undefined =>
32
+ typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined
33
+ const str = (value: unknown) => (typeof value === "string" ? value : null)
34
+
35
+ /** Whether an ACP tool call is one of the Eloxiv tools (OpenCode names them `eloxiv_<tool>`). */
36
+ export const isEloxivTool = (title: string | null) =>
37
+ title !== null && new RegExp(`^(mcp__)?${MCP_SERVER}[_.]`, "u").test(title)
38
+
39
+ /** The text of an ACP content block or a tool call's content list. */
40
+ const contentText = (content: unknown): string => {
41
+ if (Array.isArray(content)) return content.map(contentText).join("")
42
+ const record = object(content)
43
+ if (record === undefined) return typeof content === "string" ? content : ""
44
+ if (record["type"] === "text" && typeof record["text"] === "string") return record["text"]
45
+ if (record["type"] === "content") return contentText(record["content"])
46
+ return ""
47
+ }
48
+
49
+ /** OpenCode's permissions for a turn: only the Eloxiv tools, unless the turn has workspace tools. */
50
+ export const opencodePermissions = (workspaceTools: boolean) =>
51
+ JSON.stringify({
52
+ permission: workspaceTools ? { "*": "allow" } : { "*": "deny", [`${MCP_SERVER}_*`]: "allow" },
53
+ })
54
+
55
+ /** Run one turn with an ACP agent. Never throws: failures are the result's `outcome` and `error`. */
56
+ export const runAcpHarness = (config: HarnessConfig, input: HarnessRunInput): Promise<HarnessResult> =>
57
+ new Promise((resolve) => {
58
+ const events: Array<HarnessEvent> = []
59
+ const emit = (event: HarnessEvent) => {
60
+ events.push(event)
61
+ input.onEvent?.(event)
62
+ }
63
+ const workspaceTools = input.workspaceTools === true
64
+ const refuseEarly = (error: string) =>
65
+ resolve({ outcome: "failed", result: null, usage: null, error, events, sessionId: null })
66
+ if (!workspaceTools && config.toolsOnly !== true) {
67
+ refuseEarly(
68
+ `${config.kind} cannot be limited to the Eloxiv tools (it may run code its working directory configures, or its own tools, without asking): send the turn with workspace tools${config.kind === "acp" ? ", or declare the configured agent tools-only (ELOXIV_DAEMON_ACP_TOOLS_ONLY=1)" : ""}`,
69
+ )
70
+ return
71
+ }
72
+ const env: Record<string, string> = {
73
+ ...(config.kind === "opencode" ? { OPENCODE_CONFIG_CONTENT: opencodePermissions(workspaceTools) } : {}),
74
+ ...config.env,
75
+ }
76
+ const [command, ...prefix] = config.command
77
+ const child = spawn(command!, [...prefix, ...(config.extraArgs ?? [])], {
78
+ cwd: input.cwd,
79
+ env: harnessEnv(env, config.passEnv),
80
+ stdio: ["pipe", "pipe", "pipe"],
81
+ detached: process.platform !== "win32",
82
+ })
83
+ const signalGroup = (name: NodeJS.Signals) => {
84
+ try {
85
+ if (process.platform !== "win32" && child.pid !== undefined) process.kill(-child.pid, name)
86
+ else child.kill(name)
87
+ } catch {
88
+ // Already gone.
89
+ }
90
+ }
91
+ let nextId = 0
92
+ const pending = new Map<number, { resolve: (value: unknown) => void; reject: (error: Error) => void }>()
93
+ const send = (message: Record<string, unknown>) => {
94
+ try {
95
+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`)
96
+ } catch {
97
+ // The agent is gone; its exit settles the turn.
98
+ }
99
+ }
100
+ const request = (method: string, params: unknown) =>
101
+ new Promise<unknown>((ok, fail) => {
102
+ const id = ++nextId
103
+ pending.set(id, { resolve: ok, reject: fail })
104
+ send({ id, method, params })
105
+ })
106
+ let sessionId: string | null = input.resume ?? null
107
+ let loading = input.resume !== null && input.resume !== undefined
108
+ let text = ""
109
+ const texts: Array<string> = []
110
+ const tools = new Map<string, string | null>()
111
+ const flushText = () => {
112
+ if (text.length === 0) return
113
+ texts.push(text)
114
+ emit({ type: "text", data: { text } })
115
+ text = ""
116
+ }
117
+ let stderr = ""
118
+ let ended: HarnessResult["outcome"] | undefined
119
+ let finished = false
120
+ const finish = (outcome: HarnessResult["outcome"], error: string | null) => {
121
+ if (finished) return
122
+ finished = true
123
+ clearTimeout(timer)
124
+ input.signal?.removeEventListener("abort", onAbort)
125
+ flushText()
126
+ signalGroup("SIGKILL")
127
+ for (const waiting of pending.values()) waiting.reject(new Error("The agent exited"))
128
+ const final = ended ?? outcome
129
+ emit({ type: "finished", data: { succeeded: final === "succeeded" } })
130
+ resolve({
131
+ outcome: final,
132
+ result: texts.length > 0 ? texts.join("\n") : null,
133
+ usage: null,
134
+ error:
135
+ final === "succeeded"
136
+ ? null
137
+ : final === "cancelled"
138
+ ? "The turn was cancelled"
139
+ : final === "timed-out"
140
+ ? `The turn exceeded its time limit (${input.timeoutMs} ms)`
141
+ : (error ?? (stderr.trim().slice(-2_000) || "The agent exited without a result")),
142
+ events,
143
+ sessionId,
144
+ })
145
+ }
146
+ const stop = (reason: "cancelled" | "timed-out") => {
147
+ if (ended !== undefined || finished) return
148
+ ended = reason
149
+ if (sessionId !== null) send({ method: "session/cancel", params: { sessionId } })
150
+ setTimeout(() => signalGroup("SIGTERM"), GRACE_MS / 2).unref()
151
+ setTimeout(() => finish(reason, null), GRACE_MS).unref()
152
+ }
153
+ const timer = setTimeout(() => stop("timed-out"), input.timeoutMs)
154
+ const onAbort = () => stop("cancelled")
155
+ if (input.signal?.aborted) onAbort()
156
+ input.signal?.addEventListener("abort", onAbort, { once: true })
157
+
158
+ /** What the agent sends: answers to our requests, its notifications, and its own requests (permissions). */
159
+ const onMessage = (message: Record<string, unknown>) => {
160
+ const id = message["id"]
161
+ if (typeof id === "number" && message["method"] === undefined) {
162
+ const waiting = pending.get(id)
163
+ pending.delete(id)
164
+ const error = object(message["error"])
165
+ if (error !== undefined) waiting?.reject(new Error(str(error["message"]) ?? "ACP error"))
166
+ else waiting?.resolve(message["result"])
167
+ return
168
+ }
169
+ const params = object(message["params"]) ?? {}
170
+ if (message["method"] === "session/update") {
171
+ // A loaded session's history is replayed first: not this turn's.
172
+ if (loading) return
173
+ const update = object(params["update"]) ?? {}
174
+ switch (update["sessionUpdate"]) {
175
+ case "agent_message_chunk":
176
+ text += contentText(update["content"])
177
+ return
178
+ case "tool_call": {
179
+ flushText()
180
+ const callId = str(update["toolCallId"])
181
+ const title = str(update["title"])
182
+ if (callId !== null) tools.set(callId, title)
183
+ emit({ type: "tool-call", data: { id: callId, name: title, input: update["rawInput"] ?? null } })
184
+ return
185
+ }
186
+ case "tool_call_update": {
187
+ const status = update["status"]
188
+ if (status !== "completed" && status !== "failed") return
189
+ const callId = str(update["toolCallId"])
190
+ const eloxiv = isEloxivTool(tools.get(callId ?? "") ?? str(update["title"]))
191
+ emit({
192
+ type: "tool-result",
193
+ data: {
194
+ id: callId,
195
+ isError: status === "failed",
196
+ // A built-in tool's output stays on the machine.
197
+ output: eloxiv
198
+ ? clip(contentText(update["content"]) || JSON.stringify(update["rawOutput"] ?? ""))
199
+ : NOT_FORWARDED,
200
+ },
201
+ })
202
+ return
203
+ }
204
+ default:
205
+ return
206
+ }
207
+ }
208
+ if (message["method"] === "session/request_permission" && id !== undefined) {
209
+ const call = object(params["toolCall"]) ?? {}
210
+ const title = str(call["title"]) ?? tools.get(str(call["toolCallId"]) ?? "") ?? null
211
+ const options = Array.isArray(params["options"]) ? params["options"].map(object) : []
212
+ const allow = workspaceTools || isEloxivTool(title)
213
+ const chosen = options.find((option) => option?.["kind"] === (allow ? "allow_once" : "reject_once"))
214
+ send({
215
+ id,
216
+ result: {
217
+ outcome:
218
+ chosen === undefined ? { outcome: "cancelled" } : { outcome: "selected", optionId: chosen["optionId"] },
219
+ },
220
+ })
221
+ return
222
+ }
223
+ // The client offers no file system or terminal: anything else it is asked is refused.
224
+ if (id !== undefined && message["method"] !== undefined) {
225
+ send({
226
+ id,
227
+ error: { code: -32601, message: `${JSON.stringify(message["method"])} is not offered by this client` },
228
+ })
229
+ }
230
+ }
231
+
232
+ let buffer = ""
233
+ child.stdout.setEncoding("utf8").on("data", (chunk: string) => {
234
+ buffer += chunk
235
+ let newline = buffer.indexOf("\n")
236
+ while (newline >= 0) {
237
+ const line = buffer.slice(0, newline).trim()
238
+ buffer = buffer.slice(newline + 1)
239
+ if (line.length > 0) {
240
+ input.onRawLine?.(line)
241
+ try {
242
+ const parsed = object(JSON.parse(line))
243
+ if (parsed !== undefined) onMessage(parsed)
244
+ } catch {
245
+ // Not a protocol message.
246
+ }
247
+ }
248
+ newline = buffer.indexOf("\n")
249
+ }
250
+ })
251
+ child.stderr.setEncoding("utf8").on("data", (chunk: string) => {
252
+ stderr = (stderr + chunk).slice(-8_000)
253
+ })
254
+ child.on("error", (error) => finish("failed", `Could not start ${config.command.join(" ")}: ${error.message}`))
255
+ child.on("close", (code) => finish("failed", `${config.kind} exited with ${code ?? "a signal"}`))
256
+
257
+ const mcpServers = [
258
+ {
259
+ type: "http",
260
+ name: MCP_SERVER,
261
+ url: input.mcp.url,
262
+ headers: [{ name: "authorization", value: `Bearer ${input.mcp.token}` }],
263
+ },
264
+ ]
265
+ void (async () => {
266
+ try {
267
+ await request("initialize", {
268
+ protocolVersion: 1,
269
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
270
+ clientInfo: { name: "eloxiv-daemon", version: "0.0.0" },
271
+ })
272
+ if (sessionId !== null) {
273
+ await request("session/load", { sessionId, cwd: input.cwd, mcpServers })
274
+ loading = false
275
+ } else {
276
+ const created = object(await request("session/new", { cwd: input.cwd, mcpServers }))
277
+ sessionId = str(created?.["sessionId"])
278
+ }
279
+ emit({ type: "started", data: { harness: config.kind, sessionId } })
280
+ const answer = object(
281
+ await request("session/prompt", { sessionId, prompt: [{ type: "text", text: input.prompt }] }),
282
+ )
283
+ const stopReason = str(answer?.["stopReason"])
284
+ finish(
285
+ stopReason === "end_turn" ? "succeeded" : stopReason === "cancelled" ? "cancelled" : "failed",
286
+ `The agent stopped (${stopReason ?? "no reason"})`,
287
+ )
288
+ } catch (error) {
289
+ finish("failed", (error as Error).message)
290
+ }
291
+ })()
292
+ })
@@ -0,0 +1,9 @@
1
+ /** Canonical JSON (sorted keys, no undefined), for hashing tool inputs into idempotency keys. */
2
+ export const canonicalize = (value: unknown): string => {
3
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null"
4
+ if (Array.isArray(value)) return `[${value.map(canonicalize).join(",")}]`
5
+ const entries = Object.entries(value as Record<string, unknown>)
6
+ .filter(([, v]) => v !== undefined)
7
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
8
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalize(v)}`).join(",")}}`
9
+ }