@0gfoundation/0g-agentdna 0.0.0-stage → 0.2.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 (206) hide show
  1. package/GUIDE.md +975 -0
  2. package/LICENSE +21 -0
  3. package/MIGRATION.md +84 -0
  4. package/MIGRATION.zh.md +70 -0
  5. package/PROVIDERS.md +273 -0
  6. package/PROVIDERS.zh.md +234 -0
  7. package/README.md +334 -2
  8. package/dist/AgentClient.d.ts +312 -0
  9. package/dist/AgentClient.d.ts.map +1 -0
  10. package/dist/AgentClient.js +715 -0
  11. package/dist/AgentClient.js.map +1 -0
  12. package/dist/AgenticID.d.ts +823 -0
  13. package/dist/AgenticID.d.ts.map +1 -0
  14. package/dist/AgenticID.js +1188 -0
  15. package/dist/AgenticID.js.map +1 -0
  16. package/dist/AgenticIDClient.d.ts +68 -0
  17. package/dist/AgenticIDClient.d.ts.map +1 -0
  18. package/dist/AgenticIDClient.js +198 -0
  19. package/dist/AgenticIDClient.js.map +1 -0
  20. package/dist/AttestorClient.d.ts +465 -0
  21. package/dist/AttestorClient.d.ts.map +1 -0
  22. package/dist/AttestorClient.js +1030 -0
  23. package/dist/AttestorClient.js.map +1 -0
  24. package/dist/Providers.d.ts +72 -0
  25. package/dist/Providers.d.ts.map +1 -0
  26. package/dist/Providers.js +182 -0
  27. package/dist/Providers.js.map +1 -0
  28. package/dist/ReputationClient.d.ts +213 -0
  29. package/dist/ReputationClient.d.ts.map +1 -0
  30. package/dist/ReputationClient.js +708 -0
  31. package/dist/ReputationClient.js.map +1 -0
  32. package/dist/SandboxClient.d.ts +107 -0
  33. package/dist/SandboxClient.d.ts.map +1 -0
  34. package/dist/SandboxClient.js +200 -0
  35. package/dist/SandboxClient.js.map +1 -0
  36. package/dist/ServeProof.d.ts +161 -0
  37. package/dist/ServeProof.d.ts.map +1 -0
  38. package/dist/ServeProof.js +230 -0
  39. package/dist/ServeProof.js.map +1 -0
  40. package/dist/ServeSession.d.ts +180 -0
  41. package/dist/ServeSession.d.ts.map +1 -0
  42. package/dist/ServeSession.js +336 -0
  43. package/dist/ServeSession.js.map +1 -0
  44. package/dist/Settings.d.ts +179 -0
  45. package/dist/Settings.d.ts.map +1 -0
  46. package/dist/Settings.js +247 -0
  47. package/dist/Settings.js.map +1 -0
  48. package/dist/abi.d.ts +2216 -0
  49. package/dist/abi.d.ts.map +1 -0
  50. package/dist/abi.js +1248 -0
  51. package/dist/abi.js.map +1 -0
  52. package/dist/cli/commands/cells.d.ts +34 -0
  53. package/dist/cli/commands/cells.d.ts.map +1 -0
  54. package/dist/cli/commands/cells.js +66 -0
  55. package/dist/cli/commands/cells.js.map +1 -0
  56. package/dist/cli/commands/doctor.d.ts +15 -0
  57. package/dist/cli/commands/doctor.d.ts.map +1 -0
  58. package/dist/cli/commands/doctor.js +236 -0
  59. package/dist/cli/commands/doctor.js.map +1 -0
  60. package/dist/cli/commands/interactive.d.ts +107 -0
  61. package/dist/cli/commands/interactive.d.ts.map +1 -0
  62. package/dist/cli/commands/interactive.js +3034 -0
  63. package/dist/cli/commands/interactive.js.map +1 -0
  64. package/dist/cli/commands/list.d.ts +31 -0
  65. package/dist/cli/commands/list.d.ts.map +1 -0
  66. package/dist/cli/commands/list.js +115 -0
  67. package/dist/cli/commands/list.js.map +1 -0
  68. package/dist/cli/commands/providers.d.ts +3 -0
  69. package/dist/cli/commands/providers.d.ts.map +1 -0
  70. package/dist/cli/commands/providers.js +21 -0
  71. package/dist/cli/commands/providers.js.map +1 -0
  72. package/dist/cli/commands/settings.d.ts +22 -0
  73. package/dist/cli/commands/settings.d.ts.map +1 -0
  74. package/dist/cli/commands/settings.js +188 -0
  75. package/dist/cli/commands/settings.js.map +1 -0
  76. package/dist/cli/commands/status.d.ts +16 -0
  77. package/dist/cli/commands/status.d.ts.map +1 -0
  78. package/dist/cli/commands/status.js +148 -0
  79. package/dist/cli/commands/status.js.map +1 -0
  80. package/dist/cli/commands/update.d.ts +21 -0
  81. package/dist/cli/commands/update.d.ts.map +1 -0
  82. package/dist/cli/commands/update.js +95 -0
  83. package/dist/cli/commands/update.js.map +1 -0
  84. package/dist/cli/config.d.ts +73 -0
  85. package/dist/cli/config.d.ts.map +1 -0
  86. package/dist/cli/config.js +239 -0
  87. package/dist/cli/config.js.map +1 -0
  88. package/dist/cli/env.d.ts +36 -0
  89. package/dist/cli/env.d.ts.map +1 -0
  90. package/dist/cli/env.js +74 -0
  91. package/dist/cli/env.js.map +1 -0
  92. package/dist/cli/envelope.d.ts +33 -0
  93. package/dist/cli/envelope.d.ts.map +1 -0
  94. package/dist/cli/envelope.js +62 -0
  95. package/dist/cli/envelope.js.map +1 -0
  96. package/dist/cli/errors.d.ts +48 -0
  97. package/dist/cli/errors.d.ts.map +1 -0
  98. package/dist/cli/errors.js +81 -0
  99. package/dist/cli/errors.js.map +1 -0
  100. package/dist/cli/inference.d.ts +21 -0
  101. package/dist/cli/inference.d.ts.map +1 -0
  102. package/dist/cli/inference.js +60 -0
  103. package/dist/cli/inference.js.map +1 -0
  104. package/dist/cli/logo.d.ts +21 -0
  105. package/dist/cli/logo.d.ts.map +1 -0
  106. package/dist/cli/logo.js +131 -0
  107. package/dist/cli/logo.js.map +1 -0
  108. package/dist/cli/main.d.ts +14 -0
  109. package/dist/cli/main.d.ts.map +1 -0
  110. package/dist/cli/main.js +223 -0
  111. package/dist/cli/main.js.map +1 -0
  112. package/dist/cli/proofs.d.ts +67 -0
  113. package/dist/cli/proofs.d.ts.map +1 -0
  114. package/dist/cli/proofs.js +133 -0
  115. package/dist/cli/proofs.js.map +1 -0
  116. package/dist/cli/ref.d.ts +39 -0
  117. package/dist/cli/ref.d.ts.map +1 -0
  118. package/dist/cli/ref.js +48 -0
  119. package/dist/cli/ref.js.map +1 -0
  120. package/dist/cli/sdk.d.ts +24 -0
  121. package/dist/cli/sdk.d.ts.map +1 -0
  122. package/dist/cli/sdk.js +65 -0
  123. package/dist/cli/sdk.js.map +1 -0
  124. package/dist/cli/settings.d.ts +66 -0
  125. package/dist/cli/settings.d.ts.map +1 -0
  126. package/dist/cli/settings.js +137 -0
  127. package/dist/cli/settings.js.map +1 -0
  128. package/dist/cli/tokenize.d.ts +61 -0
  129. package/dist/cli/tokenize.d.ts.map +1 -0
  130. package/dist/cli/tokenize.js +157 -0
  131. package/dist/cli/tokenize.js.map +1 -0
  132. package/dist/cli/types.d.ts +25 -0
  133. package/dist/cli/types.d.ts.map +1 -0
  134. package/dist/cli/types.js +8 -0
  135. package/dist/cli/types.js.map +1 -0
  136. package/dist/constants.d.ts +107 -0
  137. package/dist/constants.d.ts.map +1 -0
  138. package/dist/constants.js +74 -0
  139. package/dist/constants.js.map +1 -0
  140. package/dist/context.d.ts +108 -0
  141. package/dist/context.d.ts.map +1 -0
  142. package/dist/context.js +64 -0
  143. package/dist/context.js.map +1 -0
  144. package/dist/index.d.ts +45 -0
  145. package/dist/index.d.ts.map +1 -0
  146. package/dist/index.js +118 -0
  147. package/dist/index.js.map +1 -0
  148. package/dist/provider-catalog.json +23 -0
  149. package/dist/seal.d.ts +47 -0
  150. package/dist/seal.d.ts.map +1 -0
  151. package/dist/seal.js +145 -0
  152. package/dist/seal.js.map +1 -0
  153. package/dist/secretEnv.d.ts +119 -0
  154. package/dist/secretEnv.d.ts.map +1 -0
  155. package/dist/secretEnv.js +199 -0
  156. package/dist/secretEnv.js.map +1 -0
  157. package/dist/taskHash.d.ts +39 -0
  158. package/dist/taskHash.d.ts.map +1 -0
  159. package/dist/taskHash.js +119 -0
  160. package/dist/taskHash.js.map +1 -0
  161. package/dist/types.d.ts +336 -0
  162. package/dist/types.d.ts.map +1 -0
  163. package/dist/types.js +19 -0
  164. package/dist/types.js.map +1 -0
  165. package/package.json +75 -4
  166. package/scripts/sync-providers.cjs +8 -0
  167. package/src/AgentClient.ts +897 -0
  168. package/src/AgenticID.ts +1382 -0
  169. package/src/AgenticIDClient.ts +238 -0
  170. package/src/AttestorClient.ts +1306 -0
  171. package/src/Providers.ts +176 -0
  172. package/src/ReputationClient.ts +821 -0
  173. package/src/SandboxClient.ts +227 -0
  174. package/src/ServeProof.ts +290 -0
  175. package/src/ServeSession.ts +421 -0
  176. package/src/Settings.ts +296 -0
  177. package/src/abi.ts +1282 -0
  178. package/src/cli/commands/cells.ts +61 -0
  179. package/src/cli/commands/doctor.ts +235 -0
  180. package/src/cli/commands/interactive.ts +2715 -0
  181. package/src/cli/commands/list.ts +117 -0
  182. package/src/cli/commands/providers.ts +16 -0
  183. package/src/cli/commands/settings.ts +197 -0
  184. package/src/cli/commands/status.ts +170 -0
  185. package/src/cli/commands/update.ts +86 -0
  186. package/src/cli/config.ts +225 -0
  187. package/src/cli/env.ts +90 -0
  188. package/src/cli/envelope.ts +57 -0
  189. package/src/cli/errors.ts +114 -0
  190. package/src/cli/inference.ts +57 -0
  191. package/src/cli/logo.ts +125 -0
  192. package/src/cli/main.ts +235 -0
  193. package/src/cli/proofs.ts +160 -0
  194. package/src/cli/ref.ts +58 -0
  195. package/src/cli/sdk.ts +65 -0
  196. package/src/cli/settings.ts +153 -0
  197. package/src/cli/tokenize.ts +131 -0
  198. package/src/cli/types.ts +27 -0
  199. package/src/constants.ts +106 -0
  200. package/src/context.ts +161 -0
  201. package/src/index.ts +129 -0
  202. package/src/provider-catalog.json +23 -0
  203. package/src/seal.ts +163 -0
  204. package/src/secretEnv.ts +250 -0
  205. package/src/taskHash.ts +100 -0
  206. package/src/types.ts +357 -0
@@ -0,0 +1,897 @@
1
+ /**
2
+ * @file AgentClient.ts
3
+ * @description Discovery-driven handle for interacting with a running agent.
4
+ *
5
+ * `authenticate()` / `connect()` return an {@link AgentClient}: a handle bound
6
+ * to an agent's base URL plus the agent's own declaration of what it exposes
7
+ * (the `services` and `routes` arrays from its signed `/hello`). It knows
8
+ * nothing framework-specific — it decides how to attach the credential and
9
+ * which affordances (`chat`/`chatStream`) to offer purely from what the agent
10
+ * declared. Adding a framework, or an endpoint, needs no SDK change.
11
+ *
12
+ * The same handle serves both callers, the difference being only the token:
13
+ * - owner (with a signer) → the owner token is minted on demand → `chat`/
14
+ * `chatStream` available;
15
+ * - third party (no signer) → no token → calls the agent's public `/api/*`
16
+ * services via `fetch`/`fetchWithProof` and captures the proof.
17
+ */
18
+
19
+ import { proofFromResponse, requestBytesOf, normalizedMethod, type TaskExchange } from './ServeSession';
20
+ import type { ServeProof } from './types';
21
+
22
+ /**
23
+ * One agent-registered service, as listed in `/hello`'s `services` array.
24
+ * These are exact `/api/*` paths the agent's own code serves; they are not
25
+ * gated by the owner token.
26
+ */
27
+ export interface AgentServiceEntry {
28
+ path: string;
29
+ method: string;
30
+ description?: string;
31
+ input_example?: string;
32
+ /**
33
+ * Protocol the consumer should speak. `"mcp"` = an MCP server endpoint:
34
+ * the backend implements the MCP streamable-HTTP protocol (JSON-RPC over
35
+ * POST), so an MCP-capable client can mount `<base><path>` as an MCP
36
+ * server and this agent's tools become the client's tools. Responses
37
+ * carry `X-Agent-Proof` like every agent service (when the runtime has a
38
+ * serve-proof validator configured) — that proof is what makes it a
39
+ * *trust-attributable* MCP server (see {@link mcpServices}).
40
+ */
41
+ transport?: 'mcp';
42
+ }
43
+
44
+ /**
45
+ * The agent's MCP-mountable service endpoints — the `/hello` entries marked
46
+ * `transport: "mcp"`. This is the consumption half of trusted-MCP serving:
47
+ *
48
+ * ```ts
49
+ * const { hello, verification } = await ag.agent.sayHi(agentUrl);
50
+ * // hello.services carries transport: "mcp" on MCP endpoints — sayHi
51
+ * // verified the /hello proof's signer against the on-chain agentSeal.
52
+ * const client = await ag.agent.client(agentUrl); // public handle
53
+ * const mcp = mcpServices(client); // → [{ path: "/api/mcp", … }]
54
+ * // Mount `${client.base}${mcp[0].path}` as a streamable-HTTP MCP server in
55
+ * // any MCP client.
56
+ * ```
57
+ *
58
+ * Per-exchange verification — binding the proof to THIS body, not just the
59
+ * signer. `verifyProof` alone is signer attribution; with the exchange it
60
+ * also checks that the proof's taskHash equals
61
+ * keccak(method ‖ uri ‖ keccak(reqBody) ‖ keccak(respBody) ‖ status)
62
+ * recomputed from YOUR bytes (`taskMatches` in the verdict, required for
63
+ * `ok`). The pieces:
64
+ *
65
+ * ```ts
66
+ * const { response, proof, task } = await client.fetchWithProof(mcp[0].path, {
67
+ * method: 'POST', headers: { 'content-type': 'application/json' },
68
+ * body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),
69
+ * });
70
+ * await response.text(); // your own read still works
71
+ * const v = await session.verifyProof(proof!, { task: task! });
72
+ * // v.ok && v.taskMatches → THIS response came from the attested runtime.
73
+ * // (task === null → ok: false, fail closed: the exchange wasn't recorded.)
74
+ * ```
75
+ * `task` is recorded from the actual bytes (response read via clone()), so a
76
+ * genuine proof replayed next to a swapped body fails (`taskMatches: false`).
77
+ * For hand-rolled fetches, pass the `TaskExchange` you captured (method, url,
78
+ * requestBytes, responseBytes, status) — `verifyProof` derives and tries
79
+ * every URI candidate from it. (`taskRevealOf()` returns an array; its
80
+ * element 0 can name the wrong URI form for a trailing-`?` URL.)
81
+ *
82
+ * Note the proxy pins one HTTP method per path, so an MCP route is POST-only:
83
+ * a stateless MCP server (each JSON-RPC request answered in one response,
84
+ * no server-initiated pushes) is the supported shape — and because the proxy
85
+ * buffers the whole response before signing, progress notifications and
86
+ * server→client requests (sampling, elicitation) inside a POST stream are
87
+ * not supported; keep tool calls short and return one JSON response.
88
+ *
89
+ * Two environment notes for generic MCP clients: (1) the proof envelope's
90
+ * `submitter` comes from the `X-Client-Address` request header — generic
91
+ * MCP clients don't send one, so proofs come back with submitter 0x0 and
92
+ * cannot be redeemed in protocols that require a real submitter; set the
93
+ * header through your MCP client's custom-headers option if you need it.
94
+ * (2) browser MCP clients only get to read `X-Agent-Proof` (the only
95
+ * CORS-exposed header) and an OPTIONS preflight to the service path 405s —
96
+ * use a non-browser client for verified MCP.
97
+ */
98
+ export function mcpServices(client: Pick<AgentClient, 'services'>): AgentServiceEntry[] {
99
+ return client.services.filter((s) => s.transport === 'mcp');
100
+ }
101
+
102
+ /**
103
+ * One framework-declared route, as listed in `/hello`'s `routes` array. A
104
+ * route claims a path prefix (e.g. `/` for a dashboard, `/v1/` for a chat
105
+ * API) and declares how a client should present the owner token (`auth`) and
106
+ * whether responses on it carry a serve-proof (`signed`).
107
+ */
108
+ export interface AgentRoute {
109
+ prefix: string;
110
+ /** discovery hint, e.g. "dashboard" | "chat" */
111
+ kind?: string;
112
+ /** how to present the token: "bearer" | "none" */
113
+ auth?: string;
114
+ signed: boolean;
115
+ description?: string;
116
+ }
117
+
118
+ export interface ChatMessage {
119
+ role: string;
120
+ content: string;
121
+ }
122
+
123
+ /**
124
+ * Snapshot of one long-running task (a "response" in OpenAI Responses API
125
+ * terms) on the agent. Returned by {@link AgentClient.task} /
126
+ * {@link AgentClient.cancelTask}.
127
+ */
128
+ export interface AgentTask {
129
+ id: string;
130
+ status: 'queued' | 'in_progress' | 'completed' | 'failed' | 'cancelled';
131
+ /** Assistant text produced so far (full text once completed). */
132
+ output_text: string;
133
+ error?: { message: string };
134
+ }
135
+
136
+ export interface ChatCompletion {
137
+ choices: Array<{ message: { role: string; content: string } }>;
138
+ [k: string]: unknown;
139
+ }
140
+
141
+ /**
142
+ * A live handle to an agent. Always carries `base` and the declared
143
+ * `services`/`routes`. Owner affordances (`chat`/`chatStream`) are
144
+ * present only when this handle can authenticate — i.e. it was built with a
145
+ * signer (the `ag` that made it holds an owner key) AND the agent declares the
146
+ * matching route. Their tokens are managed internally: minted on first use and
147
+ * re-minted automatically if the agent rotates them (e.g. after a `reset`), so
148
+ * you never pass or refresh a token by hand. `fetch`/`fetchWithProof` work for
149
+ * any path and never need a token for the public `/api/*` surface. `token`
150
+ * reflects the currently-cached credential, if any.
151
+ */
152
+ export interface AgentClient {
153
+ readonly token?: string;
154
+ readonly base: string;
155
+ readonly services: AgentServiceEntry[];
156
+ readonly routes: AgentRoute[];
157
+ /**
158
+ * Fetch a path on the agent. `path` is relative to the agent base (leading
159
+ * slash optional). If the longest-prefix route match declares
160
+ * `auth: "bearer"` and this handle holds a token, an
161
+ * `Authorization: Bearer <token>` header is added (unless the caller already
162
+ * set one).
163
+ */
164
+ fetch(path: string, init?: RequestInit): Promise<Response>;
165
+ /**
166
+ * Like {@link fetch}, but also reads the response's `X-Agent-Proof` (a
167
+ * TEE-signed serve-proof) when present. This is the primary way a third
168
+ * party calls one of the agent's `/api/*` services and captures the proof to
169
+ * verify or submit as on-chain feedback. `proof` is null when the response
170
+ * carries none (e.g. the unsigned owner↔agent chat route).
171
+ */
172
+ fetchWithProof(path: string, init?: RequestInit): Promise<{
173
+ response: Response;
174
+ proof: ServeProof | null;
175
+ /** The exchange that was actually sent/received, for per-exchange
176
+ * verification: `session.verifyProof(proof, { task })` then binds the
177
+ * proof to THIS response's bytes (taskMatches), not just to the signer.
178
+ * The response body is read via clone(), so `response.json()` etc. still
179
+ * work. null when the request could not be recorded. */
180
+ task: TaskExchange | null;
181
+ }>;
182
+ /**
183
+ * Present only if the agent declares a `kind: "chat"` route and this handle
184
+ * holds the owner token. POSTs an OpenAI-shaped chat request to
185
+ * `<prefix>chat/completions` and returns the full reply. Streams under the
186
+ * hood so a long reasoning turn doesn't hit an idle-timeout hop in front of
187
+ * the agent; the completion is reassembled before returning, so the shape is
188
+ * a plain {@link ChatCompletion}.
189
+ */
190
+ chat?(messages: ChatMessage[], opts?: { model?: string; signal?: AbortSignal }): Promise<ChatCompletion>;
191
+ /**
192
+ * Like {@link chat}, but yields each content delta as it is generated — for
193
+ * a live-typing UI. Present under the same conditions as `chat`.
194
+ *
195
+ * for await (const delta of client.chatStream(msgs)) process.stdout.write(delta);
196
+ *
197
+ * Pass `signal` to interrupt a turn in flight: aborting tears down the HTTP
198
+ * connection, which is the OpenAI-conventional cancel signal — the runtime
199
+ * side stops the turn where the framework supports cancellation (dsh does).
200
+ * The generator then throws the abort error (`err.name === "AbortError"`).
201
+ */
202
+ chatStream?(messages: ChatMessage[], opts?: {
203
+ model?: string;
204
+ signal?: AbortSignal;
205
+ /** Tool-activity progress, when the agent's bridge streams it (SSE
206
+ * ": activity tool/call <name>" comments — dsh does). Labels like
207
+ * "tool/call bash", "tool/result", "turn/end". Advisory: absence just
208
+ * means the bridge doesn't narrate. */
209
+ onActivity?: (label: string) => void;
210
+ /** Per-message reasoning-effort override for thinking models. Only the
211
+ * prime bridge honors it today (other frameworks' HTTP surfaces don't
212
+ * take a per-request level — their default is set at deploy/reset via
213
+ * `thinking`); unsupported bridges ignore it. */
214
+ thinking?: 'low' | 'high' | 'max';
215
+ /** Fires once with the server-side task id, as soon as the agent assigns
216
+ * one. Only on the responses transport (see {@link AgentClient.task}):
217
+ * save it and you can re-attach to this turn after a process restart via
218
+ * {@link AgentClient.followTask}, or stop it via
219
+ * {@link AgentClient.cancelTask}. */
220
+ onTask?: (id: string) => void;
221
+ }): AsyncGenerator<string>;
222
+ /**
223
+ * Poll one task's snapshot (status + text so far). Present only when the
224
+ * agent declares a `kind: "responses"` route — the long-task surface where
225
+ * a turn is owned by a server-side id rather than an HTTP connection, so it
226
+ * survives dropped connections and proxy request-duration caps. On such
227
+ * agents `chat`/`chatStream` already ride this transport transparently
228
+ * (auto-resuming when the connection drops); these methods are for
229
+ * re-attaching later or from elsewhere.
230
+ */
231
+ task?(id: string): Promise<AgentTask>;
232
+ /**
233
+ * Re-attach to a running (or finished) task and stream its remaining
234
+ * output. `startingAfter` is the last event sequence number already seen
235
+ * (0 = from the beginning — the agent replays buffered events first, then
236
+ * follows live). Ends when the task completes; throws if it failed.
237
+ * Present under the same conditions as {@link task}.
238
+ */
239
+ followTask?(id: string, opts?: {
240
+ startingAfter?: number;
241
+ signal?: AbortSignal;
242
+ onActivity?: (label: string) => void;
243
+ }): AsyncGenerator<string>;
244
+ /**
245
+ * Stop one task by id — the responses-transport form of {@link interrupt}.
246
+ * Already-executed actions are not rolled back. Present under the same
247
+ * conditions as {@link task}.
248
+ */
249
+ cancelTask?(id: string): Promise<AgentTask>;
250
+ /**
251
+ * Stop the agent's CURRENT task — whoever started it. Esc semantics: the
252
+ * turn stops issuing new tool calls / output; already-executed actions are
253
+ * NOT rolled back. Also the cure for orphaned turns (a turn whose
254
+ * originating connection died keeps running server-side; only this — or a
255
+ * full /reset — stops it). Present under the same conditions as `chat`.
256
+ * `aborted: false` + note means the agent image predates the endpoint.
257
+ */
258
+ interrupt?(): Promise<{ aborted: boolean; note?: string }>;
259
+ /**
260
+ * Present only when this handle holds the owner key: fetch the agent's own
261
+ * process log (the framework subprocess stdout/stderr the runtime serves at
262
+ * `/log/agent`). Owner-private — each call signs a fresh `0GSealLog` owner
263
+ * message bound to this agent's URL (audience-bound, see issue #62), so unlike
264
+ * `chat` it needs the wallet, not just a token. Returns the log as text; pass
265
+ * `tail` to keep only the last N lines.
266
+ */
267
+ logs?(opts?: { tail?: number }): Promise<string>;
268
+ }
269
+
270
+ /** Longest-prefix match over declared routes, or undefined if none match. */
271
+ function matchRoute(routes: AgentRoute[], path: string): AgentRoute | undefined {
272
+ let best: AgentRoute | undefined;
273
+ for (const r of routes) {
274
+ if (path.startsWith(r.prefix) && (!best || r.prefix.length > best.prefix.length)) {
275
+ best = r;
276
+ }
277
+ }
278
+ return best;
279
+ }
280
+
281
+ /**
282
+ * Stream an OpenAI-compatible SSE `chat/completions` body, yielding each parsed
283
+ * `data:` JSON chunk. Skips SSE comment/keepalive lines and the terminal
284
+ * `data: [DONE]`; tolerant of frames split across network reads. The shared
285
+ * core behind both `chat` (fold into one completion) and `chatStream` (map to
286
+ * content deltas).
287
+ */
288
+ async function* iterSseChunks(
289
+ body: ReadableStream<Uint8Array>,
290
+ onComment?: (text: string) => void,
291
+ ): AsyncGenerator<Record<string, unknown>> {
292
+ const reader = body.getReader();
293
+ const decoder = new TextDecoder();
294
+ let buf = '';
295
+
296
+ try {
297
+
298
+ function* parseFrame(frame: string): Generator<Record<string, unknown>> {
299
+ // Named SSE events matter: hermes streams turn activity as
300
+ // "event: hermes.tool.progress" frames on the same chat stream. Track the
301
+ // event name within the frame and attach it to the parsed payload as
302
+ // __sseEvent so chatStream can route it (unnamed frames = normal chunks).
303
+ let eventName = '';
304
+ for (const line of frame.split('\n')) {
305
+ const t = line.replace(/^/, '').trimStart();
306
+ // SSE comments (":...") are invisible to the payload, but a caller may
307
+ // want them: the dsh bridge streams tool-activity progress as
308
+ // ": activity <kind>" comments (keepalives pass through too — the
309
+ // callback filters).
310
+ if (t.startsWith(':') && onComment) onComment(t.slice(1).trim());
311
+ if (t.startsWith('event:')) { eventName = t.slice(6).trim(); continue; }
312
+ if (!t.startsWith('data:')) continue;
313
+ const data = t.slice(5).trim();
314
+ if (data === '' || data === '[DONE]') continue;
315
+ try {
316
+ const parsed = JSON.parse(data) as Record<string, unknown>;
317
+ if (eventName) { (parsed as { __sseEvent?: string }).__sseEvent = eventName; eventName = ''; }
318
+ yield parsed;
319
+ } catch {
320
+ // Non-JSON keepalive payload — ignore.
321
+ }
322
+ }
323
+ }
324
+
325
+ for (;;) {
326
+ const { value, done } = await reader.read();
327
+ if (done) break;
328
+ buf += decoder.decode(value, { stream: true });
329
+ let sep: number;
330
+ // SSE events are delimited by a blank line ("\n\n"); "\r\n\r\n" tolerated.
331
+ while ((sep = buf.search(/\r?\n\r?\n/)) !== -1) {
332
+ const end = sep + (buf[sep] === '\r' ? 4 : 2);
333
+ yield* parseFrame(buf.slice(0, sep));
334
+ buf = buf.slice(end);
335
+ }
336
+ }
337
+ if (buf.trim()) yield* parseFrame(buf); // flush a trailing frame with no blank line
338
+ } finally {
339
+ // A consumer that breaks or throws out of the loop (e.g. the responses
340
+ // transport tearing down on a sequence gap) must not leave the HTTP
341
+ // connection dangling until GC.
342
+ try { await reader.cancel(); } catch { /* already closed */ }
343
+ }
344
+ }
345
+
346
+ /**
347
+ * The content fragment carried by one chunk: `choices[0].delta.content`, or
348
+ * `reasoning_content` for a delta that carries only that (a reasoning model
349
+ * streams its answer there), so a pure-reasoning reply isn't returned empty.
350
+ */
351
+ function chunkDelta(chunk: Record<string, unknown>): { role?: string; content: string } {
352
+ const choice = (chunk.choices as Array<Record<string, unknown>> | undefined)?.[0];
353
+ const delta = choice?.delta as { role?: string; content?: string; reasoning_content?: string } | undefined;
354
+ const content = typeof delta?.content === 'string' ? delta.content
355
+ : typeof delta?.reasoning_content === 'string' ? delta.reasoning_content
356
+ : '';
357
+ return { role: delta?.role, content };
358
+ }
359
+
360
+ /** Fold an SSE chat stream into a single reassembled {@link ChatCompletion}. */
361
+ async function collectChatStream(body: ReadableStream<Uint8Array>): Promise<ChatCompletion> {
362
+ let content = '';
363
+ let role = 'assistant';
364
+ let last: Record<string, unknown> = {};
365
+ for await (const chunk of iterSseChunks(body)) {
366
+ last = chunk;
367
+ const d = chunkDelta(chunk);
368
+ if (d.role) role = d.role;
369
+ content += d.content;
370
+ }
371
+ return { ...last, choices: [{ message: { role, content } }] } as ChatCompletion;
372
+ }
373
+
374
+ /**
375
+ * Build an {@link AgentClient} from a base URL, the agent's declared surface,
376
+ * and (optionally) a way to authenticate:
377
+ * - `reauth` — mints a fresh owner token (sign + POST `/_seal/auth`). When
378
+ * present, the client can do owner ops; it mints the token lazily on first
379
+ * use and re-mints once on a 401 (the agent rotated it, e.g. after a reset).
380
+ * - `token` — a token to start from (optional; `reauth` still refreshes it).
381
+ * - `logAuth` — signs a fresh `0GSealLog` owner message (for `/log/agent`).
382
+ * Present only when the handle holds a wallet; gates `logs`.
383
+ * With none, the client is public: only `fetch` / `fetchWithProof`, which
384
+ * never attach a token (the `/api/*` surface isn't owner-gated). Owner ops
385
+ * (`chat`/`chatStream`) are attached iff the agent declares the route
386
+ * AND the client can authenticate — that presence is the capability signal.
387
+ */
388
+ export function makeAgentClient(params: {
389
+ base: string;
390
+ services: AgentServiceEntry[];
391
+ routes: AgentRoute[];
392
+ token?: string;
393
+ reauth?: () => Promise<string>;
394
+ logAuth?: () => Promise<{ message: string; signature: string }>;
395
+ /** Address that will redeem serve-proofs from this handle's responses. Sent
396
+ * as X-Client-Address so the TEE binds each proof to this redeemer (front-run
397
+ * protection). Omit for anonymous calls (proofs come back unredeemable). */
398
+ clientAddress?: string;
399
+ /** Per-process client id for the agent's single-driver seat (occupancy.go):
400
+ * ride it on every request so a displaced window is told with a 409 the
401
+ * moment it next speaks. Absent = this client does not participate. */
402
+ instanceId?: string;
403
+ /** Stall threshold in ms for the responses transport: no bytes for this long
404
+ * and the follow stream is torn down and resumed by sequence number.
405
+ * Defaults to 90s (nine missed 10s keepalives). Exposed so tests can drive
406
+ * the recovery in milliseconds; tune only with a reason. */
407
+ stallMs?: number;
408
+ }): AgentClient {
409
+ const base = params.base.replace(/\/$/, '');
410
+ const { services, routes, reauth, clientAddress, instanceId } = params;
411
+ const canAuth = !!(reauth || params.token);
412
+
413
+ let cached: string | undefined = params.token;
414
+ const ensureToken = async (): Promise<string | undefined> => {
415
+ if (cached) return cached;
416
+ if (reauth) cached = await reauth();
417
+ return cached;
418
+ };
419
+
420
+ const doFetch = async (path: string, init?: RequestInit): Promise<Response> => {
421
+ const rel = path.startsWith('/') ? path : `/${path}`;
422
+ const route = matchRoute(routes, rel);
423
+ const url = `${base}${rel}`;
424
+ // Attach a bearer only for a bearer route, and never over a caller-set one.
425
+ const needsBearer = route?.auth === 'bearer' && !new Headers(init?.headers).has('Authorization');
426
+
427
+ const send = (tok?: string) => {
428
+ const headers = new Headers(init?.headers);
429
+ if (tok) headers.set('Authorization', `Bearer ${tok}`);
430
+ // Bind serve-proofs from this response to the redeemer, unless the caller
431
+ // set the header explicitly.
432
+ if (clientAddress && !headers.has('X-Client-Address')) {
433
+ headers.set('X-Client-Address', clientAddress);
434
+ }
435
+ if (instanceId && !headers.has('X-Client-Instance')) {
436
+ headers.set('X-Client-Instance', instanceId);
437
+ }
438
+ return fetch(url, { ...init, headers });
439
+ };
440
+
441
+ let res = await send(needsBearer ? await ensureToken() : undefined);
442
+ // Self-heal: the agent rotated its token (e.g. after a reset) → 401. Drop
443
+ // the stale cache, re-mint once, and retry. Only when we own the auth.
444
+ if (res.status === 401 && needsBearer && reauth) {
445
+ cached = undefined;
446
+ res = await send(await ensureToken());
447
+ }
448
+ return res;
449
+ };
450
+
451
+ const client: AgentClient = {
452
+ get token() { return cached; },
453
+ base,
454
+ services,
455
+ routes,
456
+ fetch: doFetch,
457
+ async fetchWithProof(path, init) {
458
+ const rel = path.startsWith('/') ? path : `/${path}`;
459
+ const response = await doFetch(path, init);
460
+ // Per-exchange verification needs the exact bytes that traveled — but
461
+ // the body is read ONLY when the response carries X-Agent-Proof. A
462
+ // signed response is always finite (the proxy buffers it whole to
463
+ // compute the hash), so awaiting it cannot hang; an unsigned/streaming
464
+ // response (SSE chat) is returned immediately with task = null —
465
+ // awaiting its clone would block the caller's incremental reads.
466
+ const proof = proofFromResponse(response);
467
+ let task: TaskExchange | null = null;
468
+ if (proof) {
469
+ try {
470
+ const reqBytes = requestBytesOf(init?.body);
471
+ if (reqBytes !== null) {
472
+ const cloned = response.clone();
473
+ const respBytes = await cloned.arrayBuffer().then((b) => new Uint8Array(b));
474
+ task = {
475
+ method: normalizedMethod(init?.method),
476
+ url: `${base}${rel}`,
477
+ requestBytes: reqBytes,
478
+ responseBytes: respBytes,
479
+ status: response.status,
480
+ };
481
+ }
482
+ } catch {
483
+ task = null;
484
+ }
485
+ }
486
+ return { response, proof, task };
487
+ },
488
+ };
489
+
490
+ // stream:true so the reply flows as SSE — a reasoning turn can take minutes,
491
+ // and a buffered reply sends no bytes until it finishes, so an idle-timeout
492
+ // hop in front of the agent (e.g. a load balancer, ~60s) would cut it.
493
+ // The `model` field is the framework's own selector, NOT an LLM name — e.g.
494
+ // openclaw requires "openclaw" (or "openclaw/<agentId>"); the LLM is fixed at
495
+ // deploy. There's no framework-agnostic default (/hello doesn't declare it),
496
+ // so omit the field when the caller doesn't set one rather than sending a
497
+ // bogus value the framework rejects.
498
+ const chatBody = (messages: ChatMessage[], opts?: { model?: string; signal?: AbortSignal }) =>
499
+ JSON.stringify(opts?.model ? { model: opts.model, messages, stream: true } : { messages, stream: true });
500
+
501
+ const chat = routes.find((r) => r.kind === 'chat');
502
+ if (chat && canAuth) {
503
+ // OpenAI-compatible convention: completions sit at `<prefix>chat/completions`.
504
+ const path = `${chat.prefix}chat/completions`;
505
+
506
+ client.interrupt = async () => {
507
+ // dsh/prime bridges expose a real endpoint; call it. openclaw/hermes
508
+ // serve /v1 themselves (404 here) and both stop the turn when the
509
+ // client disconnects — LAB- and live-verified for openclaw (the run
510
+ // ends stopReason=aborted the moment the stream drops; no
511
+ // auto-continuation). Do NOT send a '/stop' chat message as a fallback:
512
+ // openclaw's /v1 path treats it as a plain user message and burns a
513
+ // full model turn on it (~10s), which is exactly what made the message
514
+ // AFTER an Esc feel slow.
515
+ try {
516
+ const r = await doFetch(`${chat.prefix}interrupt`, { method: 'POST', signal: AbortSignal.timeout(10_000) });
517
+ if (r.ok) {
518
+ const j = (await r.json()) as { aborted?: boolean; note?: string };
519
+ return { aborted: !!j.aborted, note: j.note };
520
+ }
521
+ if (r.status === 404) return { aborted: false, note: 'no bridge endpoint — this framework stops its turn when the stream disconnects' };
522
+ throw new Error(`interrupt: HTTP ${r.status}: ${await r.text()}`);
523
+ } catch (e) {
524
+ if ((e as Error).message.startsWith('interrupt:')) throw e;
525
+ return { aborted: false, note: 'interrupt transport failed — this framework stops its turn when the stream disconnects' };
526
+ }
527
+ };
528
+
529
+ client.chat = async (messages, opts) => {
530
+ const r = await doFetch(path, {
531
+ method: 'POST',
532
+ headers: { 'content-type': 'application/json' },
533
+ body: chatBody(messages, opts),
534
+ signal: opts?.signal,
535
+ });
536
+ if (!r.ok) throw new Error(`chat: HTTP ${r.status}: ${await r.text()}`);
537
+ const ct = r.headers.get('content-type') ?? '';
538
+ if (!r.body || !ct.toLowerCase().includes('text/event-stream')) {
539
+ return (await r.json()) as ChatCompletion; // server didn't stream → plain JSON
540
+ }
541
+ return collectChatStream(r.body);
542
+ };
543
+
544
+ client.chatStream = async function* (messages, opts) {
545
+ const r = await doFetch(path, {
546
+ method: 'POST',
547
+ headers: { 'content-type': 'application/json' },
548
+ body: chatBody(messages, opts),
549
+ signal: opts?.signal,
550
+ });
551
+ if (!r.ok) throw new Error(`chat: HTTP ${r.status}: ${await r.text()}`);
552
+ const ct = r.headers.get('content-type') ?? '';
553
+ if (!r.body || !ct.toLowerCase().includes('text/event-stream')) {
554
+ // Server didn't stream — yield the whole reply as one delta. An EMPTY
555
+ // reply is the same silent-failure symptom as a delta-less stream
556
+ // (review F-C) — surface it, don't swallow it.
557
+ const full = (await r.json()) as ChatCompletion;
558
+ const c = full.choices?.[0]?.message?.content;
559
+ if (!c) throw new Error('chat: empty non-streamed reply — the agent-side model call likely failed (see /agentlog)');
560
+ yield c;
561
+ return;
562
+ }
563
+ // A silent stream is a FAILED stream: when the bridge's upstream model
564
+ // call errors (e.g. provider 400), the SSE connection itself is 200 but
565
+ // carries zero deltas — swallowing that leaves the user staring at an
566
+ // empty reply with the real cause only in /agentlog. Surface it.
567
+ // (feedback.md F15)
568
+ let sawContent = false;
569
+ let streamErr: string | null = null;
570
+ const onComment = opts?.onActivity
571
+ ? (c: string): void => { if (c.startsWith('activity ')) opts.onActivity!(c.slice(9)); }
572
+ : undefined;
573
+ let lastThinkingAt = 0;
574
+ const thinking = (): void => {
575
+ // Throttled: reasoning/thinking progress fires many times a second.
576
+ const now = Date.now();
577
+ if (now - lastThinkingAt > 2000) { lastThinkingAt = now; opts!.onActivity!('thinking'); }
578
+ };
579
+ for await (const chunk of iterSseChunks(r.body, onComment)) {
580
+ // hermes streams turn activity as NAMED SSE events on the chat stream
581
+ // (event: hermes.tool.progress / tool.started / tool.completed / …).
582
+ // Route them to onActivity — they are progress, not reply content.
583
+ const ev = (chunk as { __sseEvent?: string }).__sseEvent;
584
+ if (ev) {
585
+ if (opts?.onActivity) {
586
+ const tool = (chunk as { tool_name?: string }).tool_name ?? '';
587
+ if (tool === '_thinking') thinking();
588
+ else if (ev === 'hermes.tool.progress') { if (tool) opts.onActivity(`tool/call ${tool}`); }
589
+ else opts.onActivity(tool ? `${ev.replace(/^hermes\./, '')} ${tool}` : ev.replace(/^hermes\./, ''));
590
+ }
591
+ continue;
592
+ }
593
+ const e = (chunk as { error?: { message?: string } | string }).error;
594
+ if (e) streamErr = typeof e === 'string' ? e : e.message ?? JSON.stringify(e);
595
+ // OpenAI-standard tool-call deltas (openclaw emits these when the
596
+ // agent invokes a tool mid-turn): narrate, nothing to yield.
597
+ if (opts?.onActivity) {
598
+ const choice = (chunk.choices as Array<Record<string, unknown>> | undefined)?.[0];
599
+ const delta = choice?.delta as { tool_calls?: Array<{ function?: { name?: string } }> } | undefined;
600
+ for (const tc of delta?.tool_calls ?? []) {
601
+ const fn = tc?.function?.name;
602
+ if (fn) opts.onActivity(`tool/call ${fn}`);
603
+ }
604
+ }
605
+ const d = chunkDelta(chunk);
606
+ if (d.content) { sawContent = true; yield d.content; }
607
+ }
608
+ if (!sawContent) {
609
+ throw new Error(
610
+ streamErr
611
+ ? `chat: upstream error: ${streamErr}`
612
+ : 'chat: the stream ended without any output — the agent-side model call likely failed (see /agentlog)',
613
+ );
614
+ }
615
+ };
616
+ }
617
+
618
+ // ── Responses transport (the long-task surface) ──────────────────────────
619
+ //
620
+ // When the agent declares a `kind: "responses"` route (prime/dsh bridges
621
+ // natively; openclaw/hermes via the sealed proxy's synthesized layer), a
622
+ // turn is owned by a server-side response id, not by the HTTP connection —
623
+ // so it survives network drops and the sandbox preview proxy's request-
624
+ // duration cap (~300s on mainnet, 0g-sandbox#122). chat/chatStream are
625
+ // REPLACED to ride it: same signatures, but a dropped connection now means
626
+ // "resume from the last sequence number", not "the task died". task/
627
+ // followTask/cancelTask expose the id-level surface for re-attaching later.
628
+ const responsesRoute = routes.find((r) => r.kind === 'responses');
629
+ if (responsesRoute && canAuth) {
630
+ const rPrefix = responsesRoute.prefix.replace(/\/$/, '');
631
+
632
+ const taskSnapshot = async (id: string): Promise<AgentTask> => {
633
+ const r = await doFetch(`${rPrefix}/${id}`);
634
+ if (!r.ok) throw new Error(`task: HTTP ${r.status}: ${await r.text()}`);
635
+ return (await r.json()) as AgentTask;
636
+ };
637
+
638
+ // Normalize activity labels across serving layers: hermes narrates its
639
+ // reasoning phase as tool_name "_thinking" many times a second — collapse
640
+ // to the throttled "thinking" label the callers already understand.
641
+ const wrapActivity = (onActivity?: (label: string) => void): ((label: string) => void) | undefined => {
642
+ if (!onActivity) return undefined;
643
+ let lastThinkingAt = 0;
644
+ return (label: string) => {
645
+ if (label === '_thinking' || label === 'thinking') {
646
+ const now = Date.now();
647
+ if (now - lastThinkingAt > 2000) { lastThinkingAt = now; onActivity('thinking'); }
648
+ return;
649
+ }
650
+ onActivity(label);
651
+ };
652
+ };
653
+
654
+ /**
655
+ * Follow one response to its terminal event, yielding text deltas. The
656
+ * task id is always known before this runs (chatStream submits first), so
657
+ * every attempt is a fresh GET
658
+ * {prefix}/{id}?stream=true&starting_after={seq} — every event carries a
659
+ * sequence_number, so nothing is duplicated or lost across reconnects.
660
+ * Only an explicit abort or a terminal event ends the loop; repeated
661
+ * failures (connection errors or barren attempts) give up with the id in
662
+ * the message so the caller can re-attach later.
663
+ */
664
+ // No bytes for this long means something between us and the agent has
665
+ // gone quiet: the bridges keepalive every 10s, so 90s of true silence is
666
+ // already pathological. Reconnecting then beats waiting out the runtime's
667
+ // own timeout (undici: 300s), and makes the SDK independent of it.
668
+ // Injectable so tests can exercise the recovery in milliseconds instead
669
+ // of waiting out the real threshold.
670
+ const STALL_MS = params.stallMs ?? 90_000;
671
+ // How often the watchdog checks. Derived from the threshold rather than
672
+ // fixed: a hardcoded interval silently coarsens the effective deadline
673
+ // (a 15s poll turned a 90s stall into a 105s recovery) and makes the
674
+ // guarantee untestable at small thresholds.
675
+ const STALL_POLL_MS = Math.max(50, Math.floor(STALL_MS / 6));
676
+ // Backoff between attempts, capped by the threshold as well as by the
677
+ // absolute ceiling: a fixed ladder dominates the give-up horizon whenever
678
+ // the threshold is small (at stallMs=150 it made the give-up path 24s of
679
+ // a 29s suite) and is the last constant not derived from the threshold.
680
+ const backoffFor = (n: number): number =>
681
+ Math.min(500 * 2 ** n, 8_000, Math.max(50, STALL_MS * 4));
682
+
683
+ const lostAgent = (id: string | undefined, why: string): Error =>
684
+ new Error(
685
+ `task ${id}: lost the agent while following (${why}) — ` +
686
+ `the task may still be running; re-attach with followTask("${id}")`,
687
+ );
688
+
689
+ async function* followResponse(args: {
690
+ id?: string;
691
+ startingAfter?: number;
692
+ signal?: AbortSignal;
693
+ onActivity?: (label: string) => void;
694
+ }): AsyncGenerator<string> {
695
+ const id = args.id;
696
+ let seq = args.startingAfter ?? 0;
697
+ let sawText = false;
698
+ let terminal: AgentTask | undefined;
699
+ let failures = 0;
700
+ const followedAt = Date.now(); // for the give-up message: total wait, not per-attempt
701
+ // Per-attempt controller: the stall watchdog aborts THIS attempt without
702
+ // touching the caller's signal (which means "stop the task").
703
+ let attempt: AbortController | undefined;
704
+ let lastByteAt = Date.now();
705
+
706
+ for (;;) {
707
+ // ONE lifecycle per attempt: the caller's abort link and the stall
708
+ // watchdog are installed before the fetch and torn down only when the
709
+ // attempt is over — headers arriving is not the end of an attempt.
710
+ // (Removing the abort link at the header boundary silently broke Esc
711
+ // mid-stream: the body phase had nothing connecting the caller's
712
+ // signal to this attempt. Review R1.)
713
+ attempt = new AbortController();
714
+ let onOuterAbort: (() => void) | undefined;
715
+ if (args.signal) {
716
+ if (args.signal.aborted) attempt.abort();
717
+ else {
718
+ onOuterAbort = () => attempt?.abort();
719
+ args.signal.addEventListener('abort', onOuterAbort, { once: true });
720
+ }
721
+ }
722
+ lastByteAt = Date.now();
723
+ const progressAt = { seq };
724
+ const watchdog = setInterval(() => {
725
+ if (Date.now() - lastByteAt > STALL_MS) attempt?.abort();
726
+ }, STALL_POLL_MS);
727
+
728
+ try {
729
+ // ── open (or re-open) the follow stream ────────────────────────
730
+ let res: Response;
731
+ try {
732
+ const r = await doFetch(`${rPrefix}/${id}?stream=true&starting_after=${seq}`, { signal: attempt.signal });
733
+ if (!r.ok) throw new Error(`HTTP ${r.status}: ${await r.text()}`);
734
+ res = r;
735
+ lastByteAt = Date.now();
736
+ } catch (e) {
737
+ if (args.signal?.aborted) throw e;
738
+ if (++failures > 5) throw lostAgent(id, (e as Error).message);
739
+ await new Promise((t) => setTimeout(t, backoffFor(failures)));
740
+ continue;
741
+ }
742
+ if (!res.body || !(res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream')) {
743
+ throw new Error('task: expected an SSE stream from the responses route');
744
+ }
745
+
746
+ // ── consume it ─────────────────────────────────────────────────
747
+ try {
748
+ // The comment callback counts keepalives as liveness — they are
749
+ // exactly what the bridges send during a quiet turn.
750
+ for await (const chunk of iterSseChunks(res.body, () => { lastByteAt = Date.now(); })) {
751
+ lastByteAt = Date.now();
752
+ const sn = (chunk as { sequence_number?: number }).sequence_number;
753
+ if (typeof sn === 'number') {
754
+ // Continuity guard: after a reconnect the replay may overlap
755
+ // what we already consumed — skip those. A FORWARD jump means
756
+ // the server dropped events for us (lagging-follower detach);
757
+ // don't consume past the hole — tear down and resume from the
758
+ // last good sequence, replaying the missing span.
759
+ if (sn <= seq) continue;
760
+ if (sn > seq + 1) throw new Error(`sequence gap: got ${sn} after ${seq}`);
761
+ seq = sn; failures = 0;
762
+ }
763
+ switch ((chunk as { type?: string }).type) {
764
+ case 'response.created':
765
+ break; // the id is already known — we submitted before following
766
+
767
+ case 'response.output_text.delta': {
768
+ const d = (chunk as { delta?: string }).delta;
769
+ if (typeof d === 'string' && d) { sawText = true; yield d; }
770
+ break;
771
+ }
772
+ case 'response.activity': {
773
+ const label = (chunk as { label?: string }).label;
774
+ if (args.onActivity && typeof label === 'string') args.onActivity(label);
775
+ break;
776
+ }
777
+ case 'response.completed':
778
+ case 'response.failed': {
779
+ terminal = (chunk as { response?: AgentTask }).response;
780
+ break;
781
+ }
782
+ }
783
+ if (terminal) break;
784
+ }
785
+ } catch (e) {
786
+ if (args.signal?.aborted) throw e;
787
+ // Network cut mid-stream, or our own stall watchdog firing —
788
+ // either way the cure is the same: resume from the last sequence.
789
+ }
790
+
791
+ if (terminal) break;
792
+ if (args.signal?.aborted) {
793
+ const err = new Error('aborted');
794
+ err.name = 'AbortError';
795
+ throw err;
796
+ }
797
+ // An attempt that delivered NO new event is barren. Real mute
798
+ // servers flush their headers and then say nothing, so those
799
+ // attempts never reach the connection-error budget above — count
800
+ // them here or the client reconnects at the stall cadence for ever
801
+ // (review R2: measured 33 reconnects in 6s before this).
802
+ if (seq === progressAt.seq) {
803
+ if (++failures > 5) {
804
+ throw lostAgent(id, `no events across ${failures} attempts over ${Math.round((Date.now() - followedAt) / 1000)}s`);
805
+ }
806
+ await new Promise((t) => setTimeout(t, backoffFor(failures)));
807
+ }
808
+ // reconnect via GET resume (the id is always known here)
809
+ } finally {
810
+ clearInterval(watchdog);
811
+ if (onOuterAbort && args.signal) args.signal.removeEventListener('abort', onOuterAbort);
812
+ }
813
+ }
814
+
815
+ if (terminal.status === 'failed') {
816
+ throw new Error(`chat: ${terminal.error?.message ?? 'task failed'}`);
817
+ }
818
+ if (terminal.status === 'cancelled') return; // owner stopped it — partial text already yielded
819
+ if (!sawText) {
820
+ // Deltas can fall past the agent's replay horizon on a very late
821
+ // re-attach; the terminal snapshot still carries the full text.
822
+ if (terminal.output_text) { yield terminal.output_text; return; }
823
+ throw new Error('chat: the task completed without any output — the agent-side model call likely failed (see /agentlog)');
824
+ }
825
+ }
826
+
827
+ client.chatStream = async function* (messages, opts) {
828
+ // SUBMIT and FOLLOW are deliberately two requests. With `stream: true`
829
+ // the submit IS the long-lived stream, which leaves one unresumable
830
+ // window: a failure before the id arrives cannot be re-attached, and
831
+ // the caller can only report a dead task. Submitting WITHOUT stream
832
+ // returns the id in milliseconds, so every long-lived byte after that
833
+ // travels on a GET we can always resume by id. One extra round trip
834
+ // buys the guarantee that a task is never lost to a dropped connection.
835
+ const payload: Record<string, unknown> = { input: messages };
836
+ if (opts?.model) payload.model = opts.model;
837
+ if (opts?.thinking) payload.reasoning = { effort: opts.thinking };
838
+ const r = await doFetch(rPrefix, {
839
+ method: 'POST',
840
+ headers: { 'content-type': 'application/json' },
841
+ body: JSON.stringify(payload),
842
+ signal: opts?.signal,
843
+ });
844
+ if (!r.ok) throw new Error(`chat: HTTP ${r.status}: ${await r.text()}`);
845
+ const submitted = (await r.json()) as AgentTask;
846
+ if (!submitted?.id) throw new Error('chat: the agent accepted the task but returned no id');
847
+ opts?.onTask?.(submitted.id);
848
+ yield* followResponse({
849
+ id: submitted.id,
850
+ startingAfter: 0,
851
+ signal: opts?.signal,
852
+ onActivity: wrapActivity(opts?.onActivity),
853
+ });
854
+ };
855
+
856
+ client.chat = async (messages, opts) => {
857
+ let content = '';
858
+ for await (const delta of client.chatStream!(messages, opts)) content += delta;
859
+ return { choices: [{ message: { role: 'assistant', content } }] } as ChatCompletion;
860
+ };
861
+
862
+ client.task = taskSnapshot;
863
+ client.followTask = (id, opts) => followResponse({
864
+ id,
865
+ startingAfter: opts?.startingAfter ?? 0,
866
+ signal: opts?.signal,
867
+ onActivity: wrapActivity(opts?.onActivity),
868
+ });
869
+ client.cancelTask = async (id) => {
870
+ const r = await doFetch(`${rPrefix}/${id}/cancel`, { method: 'POST' });
871
+ if (!r.ok) throw new Error(`cancelTask: HTTP ${r.status}: ${await r.text()}`);
872
+ return (await r.json()) as AgentTask;
873
+ };
874
+ }
875
+
876
+ // Owner-only: read the agent's own process log. Gated on the wallet-backed
877
+ // signer (not `canAuth`) — /log/agent verifies a per-request owner signature,
878
+ // so a client holding only a shared bearer token can't read logs.
879
+ if (params.logAuth) {
880
+ const logAuth = params.logAuth;
881
+ client.logs = async (opts) => {
882
+ const { message, signature } = await logAuth();
883
+ const r = await fetch(`${base}/log/agent`, {
884
+ headers: { 'X-Auth-Message': message, 'X-Auth-Signature': signature },
885
+ signal: AbortSignal.timeout(30_000),
886
+ });
887
+ if (!r.ok) throw new Error(`logs: HTTP ${r.status}: ${await r.text()}`);
888
+ const text = await r.text();
889
+ if (opts?.tail && opts.tail > 0) {
890
+ return text.split('\n').slice(-opts.tail).join('\n');
891
+ }
892
+ return text;
893
+ };
894
+ }
895
+
896
+ return client;
897
+ }