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