@0gfoundation/0g-agentdna 0.2.1 → 0.2.2
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 +60 -11
- package/PROVIDERS.md +6 -4
- package/PROVIDERS.zh.md +4 -3
- package/README.md +18 -2
- package/dist/AgentClient.d.ts +175 -2
- package/dist/AgentClient.d.ts.map +1 -1
- package/dist/AgentClient.js +166 -7
- package/dist/AgentClient.js.map +1 -1
- package/dist/AgenticID.d.ts +45 -6
- package/dist/AgenticID.d.ts.map +1 -1
- package/dist/AgenticID.js +40 -10
- package/dist/AgenticID.js.map +1 -1
- package/dist/AttestorClient.d.ts +66 -1
- package/dist/AttestorClient.d.ts.map +1 -1
- package/dist/AttestorClient.js +161 -32
- package/dist/AttestorClient.js.map +1 -1
- package/dist/cli/commands/interactive.d.ts +71 -2
- package/dist/cli/commands/interactive.d.ts.map +1 -1
- package/dist/cli/commands/interactive.js +423 -46
- package/dist/cli/commands/interactive.js.map +1 -1
- package/dist/cli/commands/settings.d.ts.map +1 -1
- package/dist/cli/commands/settings.js +23 -0
- package/dist/cli/commands/settings.js.map +1 -1
- package/dist/cli/inference.d.ts +25 -0
- package/dist/cli/inference.d.ts.map +1 -1
- package/dist/cli/inference.js +67 -6
- package/dist/cli/inference.js.map +1 -1
- package/dist/cli/settings.d.ts +20 -0
- package/dist/cli/settings.d.ts.map +1 -1
- package/dist/cli/settings.js +40 -1
- package/dist/cli/settings.js.map +1 -1
- package/dist/constants.d.ts +1 -1
- package/dist/constants.js +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -2
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/AgentClient.ts +326 -9
- package/src/AgenticID.ts +62 -8
- package/src/AttestorClient.ts +206 -50
- package/src/cli/commands/interactive.ts +405 -51
- package/src/cli/commands/settings.ts +22 -1
- package/src/cli/inference.ts +82 -5
- package/src/cli/settings.ts +41 -0
- package/src/constants.ts +1 -1
- package/src/index.ts +7 -3
package/src/AgentClient.ts
CHANGED
|
@@ -138,6 +138,120 @@ export interface ChatCompletion {
|
|
|
138
138
|
[k: string]: unknown;
|
|
139
139
|
}
|
|
140
140
|
|
|
141
|
+
/**
|
|
142
|
+
* One unit of work on the agent, as its task list shows it
|
|
143
|
+
* ({@link AgentClient.tasks}): a turn of its conversation, a background
|
|
144
|
+
* command, or a subagent. `actor` says who does the work, `trigger` who asked
|
|
145
|
+
* for it.
|
|
146
|
+
*/
|
|
147
|
+
export interface AgentTaskInfo {
|
|
148
|
+
/** A turn: `resp_…` (the id {@link AgentClient.task} and
|
|
149
|
+
* {@link AgentClient.followTask} take). A command: `bash-N`. A subagent:
|
|
150
|
+
* `subagent-N`. */
|
|
151
|
+
id: string;
|
|
152
|
+
type: 'turn' | 'command' | 'subagent';
|
|
153
|
+
status: AgentTask['status'];
|
|
154
|
+
/** Who does the work: `agent` (the main agent) or `subagent`. */
|
|
155
|
+
actor: 'agent' | 'subagent';
|
|
156
|
+
/** Who asked. A turn: `user` | `job` | `schedule` | `plugin`. A command or
|
|
157
|
+
* a subagent: `agent` (the main agent started it). */
|
|
158
|
+
trigger: string;
|
|
159
|
+
/** What the task is: the prompt, the job notice, the reminder's text. */
|
|
160
|
+
label: string;
|
|
161
|
+
/** Unix seconds. */
|
|
162
|
+
created_at: number;
|
|
163
|
+
started_at?: number;
|
|
164
|
+
finished_at?: number;
|
|
165
|
+
error?: string;
|
|
166
|
+
detail?: string;
|
|
167
|
+
/** Notices that reached the agent while this turn ran, merged into it. */
|
|
168
|
+
merged_notices?: string[];
|
|
169
|
+
/** {@link AgentClient.taskInfo} only: a turn's text, or a finished
|
|
170
|
+
* subagent's final answer. A command's output is never returned. */
|
|
171
|
+
output_text?: string;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** What stopping one task did ({@link AgentClient.stopTask}). */
|
|
175
|
+
export interface AgentTaskStop {
|
|
176
|
+
id: string;
|
|
177
|
+
outcome: 'cancelled' | 'already-finished' | 'not-running';
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* The words of a turn the agent opened itself (a background job finished, a
|
|
182
|
+
* reminder came due), kept in the agent's inbox until the owner reads them.
|
|
183
|
+
*/
|
|
184
|
+
export interface AgentInboxMessage {
|
|
185
|
+
/** Its position in the agent's cursor: ack through it with
|
|
186
|
+
* {@link AgentClient.ackInbox}. */
|
|
187
|
+
seq: number;
|
|
188
|
+
/** The turn's id. */
|
|
189
|
+
id: string;
|
|
190
|
+
/** What opened the turn: `job` | `schedule` | `plugin`. */
|
|
191
|
+
trigger: string;
|
|
192
|
+
/** The job notice, or the reminder's text. */
|
|
193
|
+
label: string;
|
|
194
|
+
status: AgentTask['status'];
|
|
195
|
+
/** What the agent said in that turn. */
|
|
196
|
+
text: string;
|
|
197
|
+
error?: string;
|
|
198
|
+
created_at: number;
|
|
199
|
+
finished_at?: number;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** One page of the inbox ({@link AgentClient.inbox}). */
|
|
203
|
+
export interface AgentInbox {
|
|
204
|
+
data: AgentInboxMessage[];
|
|
205
|
+
/** Messages after the read position. The position is the agent's, so every
|
|
206
|
+
* client sees the same count. */
|
|
207
|
+
unread: number;
|
|
208
|
+
read_through: number;
|
|
209
|
+
/** The agent's cursor now: pass it to {@link AgentClient.events} as
|
|
210
|
+
* `after` and the feed misses nothing that happens after this read. */
|
|
211
|
+
cursor: number;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** A reminder the agent set for itself ({@link AgentClient.schedules}). */
|
|
215
|
+
export interface AgentSchedule {
|
|
216
|
+
id: string;
|
|
217
|
+
kind: 'after' | 'at' | 'every';
|
|
218
|
+
/** The reminder's own text. */
|
|
219
|
+
prompt: string;
|
|
220
|
+
afterSeconds?: number;
|
|
221
|
+
everySeconds?: number;
|
|
222
|
+
/** When it comes due next (ISO 8601). */
|
|
223
|
+
scheduledAt: string;
|
|
224
|
+
state: 'scheduled' | 'overdue';
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* One event of the agent's live feed ({@link AgentClient.events}). `data` is
|
|
229
|
+
* the payload as the agent sent it (its `seq` and `time` included), by
|
|
230
|
+
* `type`:
|
|
231
|
+
*
|
|
232
|
+
* | type | data |
|
|
233
|
+
* |---|---|
|
|
234
|
+
* | `turn.queued` / `turn.started` / `turn.completed` / `turn.failed` / `turn.cancelled` | an {@link AgentTaskInfo} (a turn) |
|
|
235
|
+
* | `task.updated` | an {@link AgentTaskInfo} (a command or a subagent) |
|
|
236
|
+
* | `inbox.message` | an {@link AgentInboxMessage} |
|
|
237
|
+
* | `inbox.read` | `{ read_through }` |
|
|
238
|
+
* | `schedule.changed` | `{ operation: "create" \| "delete" \| "dispatch", id }` |
|
|
239
|
+
* | `reset` | `{ cursor, read_through }` |
|
|
240
|
+
*
|
|
241
|
+
* `reset` means the agent could not serve the position asked for (it is
|
|
242
|
+
* older than the agent's in-memory window, or from before a `/clear`):
|
|
243
|
+
* re-read the inbox, tasks and schedules; the feed carries on from `cursor`.
|
|
244
|
+
* A type this list does not name is passed through as it came.
|
|
245
|
+
*/
|
|
246
|
+
export interface AgentEvent {
|
|
247
|
+
type: string;
|
|
248
|
+
/** Its position in the agent's cursor. */
|
|
249
|
+
seq: number;
|
|
250
|
+
/** Agent clock, ms since the epoch. */
|
|
251
|
+
time: number;
|
|
252
|
+
data: Record<string, unknown>;
|
|
253
|
+
}
|
|
254
|
+
|
|
141
255
|
/**
|
|
142
256
|
* A live handle to an agent. Always carries `base` and the declared
|
|
143
257
|
* `services`/`routes`. Owner affordances (`chat`/`chatStream`) are
|
|
@@ -196,14 +310,15 @@ export interface AgentClient {
|
|
|
196
310
|
*
|
|
197
311
|
* Pass `signal` to interrupt a turn in flight: aborting tears down the HTTP
|
|
198
312
|
* connection, which is the OpenAI-conventional cancel signal — the runtime
|
|
199
|
-
* side stops the turn where the framework supports cancellation (
|
|
313
|
+
* side stops the turn where the framework supports cancellation (0g-harness
|
|
314
|
+
* does).
|
|
200
315
|
* The generator then throws the abort error (`err.name === "AbortError"`).
|
|
201
316
|
*/
|
|
202
317
|
chatStream?(messages: ChatMessage[], opts?: {
|
|
203
318
|
model?: string;
|
|
204
319
|
signal?: AbortSignal;
|
|
205
320
|
/** Tool-activity progress, when the agent's bridge streams it (SSE
|
|
206
|
-
* ": activity tool/call <name>" comments —
|
|
321
|
+
* ": activity tool/call <name>" comments — 0g-harness does). Labels like
|
|
207
322
|
* "tool/call bash", "tool/result", "turn/end". Advisory: absence just
|
|
208
323
|
* means the bridge doesn't narrate. */
|
|
209
324
|
onActivity?: (label: string) => void;
|
|
@@ -265,6 +380,55 @@ export interface AgentClient {
|
|
|
265
380
|
* `tail` to keep only the last N lines.
|
|
266
381
|
*/
|
|
267
382
|
logs?(opts?: { tail?: number }): Promise<string>;
|
|
383
|
+
/**
|
|
384
|
+
* Read the agent's inbox: the words of turns the agent opened itself (a
|
|
385
|
+
* background job finished, a reminder came due), oldest first. Without
|
|
386
|
+
* `after`, the messages after the read position; `after: 0` returns all of
|
|
387
|
+
* them. Present only when the agent declares a `kind: "inbox"` route and
|
|
388
|
+
* this handle holds the owner token.
|
|
389
|
+
*/
|
|
390
|
+
inbox?(opts?: { after?: number; limit?: number }): Promise<AgentInbox>;
|
|
391
|
+
/** Move the inbox read position forward to `through` (it never moves
|
|
392
|
+
* back). Present under the same conditions as {@link inbox}. */
|
|
393
|
+
ackInbox?(through: number): Promise<{ read_through: number; unread: number }>;
|
|
394
|
+
/**
|
|
395
|
+
* Follow the agent's live feed: turn, task, inbox and schedule changes, as
|
|
396
|
+
* they happen. Runs until `signal` aborts: a dropped or silent connection
|
|
397
|
+
* is reopened from the last event seen, so nothing is lost or repeated. Pass
|
|
398
|
+
* `after` (e.g. {@link AgentInbox.cursor}) to start from a known position;
|
|
399
|
+
* without it the feed starts at the agent's current one. Throws only on an
|
|
400
|
+
* answer that retrying cannot change (an HTTP 4xx). Present only when the
|
|
401
|
+
* agent declares a `kind: "events"` route and this handle holds the owner
|
|
402
|
+
* token.
|
|
403
|
+
*/
|
|
404
|
+
events?(opts?: { after?: number; signal?: AbortSignal }): AsyncGenerator<AgentEvent>;
|
|
405
|
+
/**
|
|
406
|
+
* Everything running or that has run on the agent, newest first: turns,
|
|
407
|
+
* background commands and subagents, with who does each (`actor`) and who
|
|
408
|
+
* asked (`trigger`). `status` filters: `"active"` (queued or running) or one
|
|
409
|
+
* status name. Present only when the agent declares a `kind: "tasks"` route
|
|
410
|
+
* and this handle holds the owner token.
|
|
411
|
+
*/
|
|
412
|
+
tasks?(opts?: { status?: string; limit?: number }): Promise<AgentTaskInfo[]>;
|
|
413
|
+
/** One task of {@link tasks}, by id, with its `output_text` where there
|
|
414
|
+
* is one. Present under the same conditions as {@link tasks}. */
|
|
415
|
+
taskInfo?(id: string): Promise<AgentTaskInfo>;
|
|
416
|
+
/**
|
|
417
|
+
* Stop one task of {@link tasks}: a turn is cancelled (a queued one never
|
|
418
|
+
* starts), a command or subagent is killed. Already-executed actions are
|
|
419
|
+
* not rolled back. Present under the same conditions as {@link tasks}.
|
|
420
|
+
*/
|
|
421
|
+
stopTask?(id: string): Promise<AgentTaskStop>;
|
|
422
|
+
/** Stop everything: queued turns first, then the running turn, then every
|
|
423
|
+
* running command and subagent. Present under the same conditions as
|
|
424
|
+
* {@link tasks}. */
|
|
425
|
+
stopAllTasks?(): Promise<AgentTaskStop[]>;
|
|
426
|
+
/**
|
|
427
|
+
* The reminders the agent set for itself. `enabled: false` means the
|
|
428
|
+
* agent's reminders are switched off. Present only when the agent declares
|
|
429
|
+
* a `kind: "schedules"` route and this handle holds the owner token.
|
|
430
|
+
*/
|
|
431
|
+
schedules?(): Promise<{ enabled: boolean; data: AgentSchedule[] }>;
|
|
268
432
|
}
|
|
269
433
|
|
|
270
434
|
/** Longest-prefix match over declared routes, or undefined if none match. */
|
|
@@ -304,7 +468,7 @@ async function* iterSseChunks(
|
|
|
304
468
|
for (const line of frame.split('\n')) {
|
|
305
469
|
const t = line.replace(/^/, '').trimStart();
|
|
306
470
|
// SSE comments (":...") are invisible to the payload, but a caller may
|
|
307
|
-
// want them:
|
|
471
|
+
// want them: 0g-harness streams tool-activity progress as
|
|
308
472
|
// ": activity <kind>" comments (keepalives pass through too — the
|
|
309
473
|
// callback filters).
|
|
310
474
|
if (t.startsWith(':') && onComment) onComment(t.slice(1).trim());
|
|
@@ -504,7 +668,7 @@ export function makeAgentClient(params: {
|
|
|
504
668
|
const path = `${chat.prefix}chat/completions`;
|
|
505
669
|
|
|
506
670
|
client.interrupt = async () => {
|
|
507
|
-
//
|
|
671
|
+
// 0g-harness and the prime bridge expose a real endpoint; call it. openclaw/hermes
|
|
508
672
|
// serve /v1 themselves (404 here) and both stop the turn when the
|
|
509
673
|
// client disconnects — LAB- and live-verified for openclaw (the run
|
|
510
674
|
// ends stopReason=aborted the moment the stream drops; no
|
|
@@ -617,11 +781,11 @@ export function makeAgentClient(params: {
|
|
|
617
781
|
|
|
618
782
|
// ── Responses transport (the long-task surface) ──────────────────────────
|
|
619
783
|
//
|
|
620
|
-
// When the agent declares a `kind: "responses"` route (prime
|
|
621
|
-
// natively; openclaw/hermes via the sealed proxy's synthesized
|
|
622
|
-
// turn is owned by a server-side response id, not by the HTTP
|
|
623
|
-
// so it survives network drops and the sandbox preview proxy's
|
|
624
|
-
// duration cap (~300s on mainnet, 0g-sandbox#122). chat/chatStream are
|
|
784
|
+
// When the agent declares a `kind: "responses"` route (the prime bridge and
|
|
785
|
+
// 0g-harness natively; openclaw/hermes via the sealed proxy's synthesized
|
|
786
|
+
// layer), a turn is owned by a server-side response id, not by the HTTP
|
|
787
|
+
// connection — so it survives network drops and the sandbox preview proxy's
|
|
788
|
+
// request-duration cap (~300s on mainnet, 0g-sandbox#122). chat/chatStream are
|
|
625
789
|
// REPLACED to ride it: same signatures, but a dropped connection now means
|
|
626
790
|
// "resume from the last sequence number", not "the task died". task/
|
|
627
791
|
// followTask/cancelTask expose the id-level surface for re-attaching later.
|
|
@@ -873,6 +1037,159 @@ export function makeAgentClient(params: {
|
|
|
873
1037
|
};
|
|
874
1038
|
}
|
|
875
1039
|
|
|
1040
|
+
// ── The agent's own work: inbox, live feed, tasks, reminders ─────────────
|
|
1041
|
+
//
|
|
1042
|
+
// An agent that works in the background (commands, subagents, reminders)
|
|
1043
|
+
// also opens turns by itself, and their words belong to no chat request.
|
|
1044
|
+
// These kinds are where they surface (0g-harness, docs/PROTOCOL.md). Each
|
|
1045
|
+
// method is attached only for a kind the agent declares, like chat; agents
|
|
1046
|
+
// that declare none of them are unaffected.
|
|
1047
|
+
const ownerBase = (kind: string): string | undefined => {
|
|
1048
|
+
const r = routes.find((x) => x.kind === kind);
|
|
1049
|
+
return r && canAuth ? r.prefix.replace(/\/$/, '') : undefined;
|
|
1050
|
+
};
|
|
1051
|
+
const query = (params: Record<string, string | number | undefined>): string => {
|
|
1052
|
+
const q = new URLSearchParams();
|
|
1053
|
+
for (const [k, v] of Object.entries(params)) if (v !== undefined) q.set(k, String(v));
|
|
1054
|
+
const s = q.toString();
|
|
1055
|
+
return s ? `?${s}` : '';
|
|
1056
|
+
};
|
|
1057
|
+
const getJSON = async <T>(what: string, path: string): Promise<T> => {
|
|
1058
|
+
const r = await doFetch(path);
|
|
1059
|
+
if (!r.ok) throw new Error(`${what}: HTTP ${r.status}: ${await r.text()}`);
|
|
1060
|
+
return (await r.json()) as T;
|
|
1061
|
+
};
|
|
1062
|
+
const postJSON = async <T>(what: string, path: string, body?: unknown): Promise<T> => {
|
|
1063
|
+
const r = await doFetch(path, {
|
|
1064
|
+
method: 'POST',
|
|
1065
|
+
...(body === undefined ? {} : { headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }),
|
|
1066
|
+
});
|
|
1067
|
+
if (!r.ok) throw new Error(`${what}: HTTP ${r.status}: ${await r.text()}`);
|
|
1068
|
+
return (await r.json()) as T;
|
|
1069
|
+
};
|
|
1070
|
+
|
|
1071
|
+
const inboxBase = ownerBase('inbox');
|
|
1072
|
+
if (inboxBase) {
|
|
1073
|
+
client.inbox = (opts) => getJSON<AgentInbox>('inbox', `${inboxBase}${query({ after: opts?.after, limit: opts?.limit })}`);
|
|
1074
|
+
client.ackInbox = (through) => postJSON('ackInbox', `${inboxBase}/ack`, { through });
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
const tasksBase = ownerBase('tasks');
|
|
1078
|
+
if (tasksBase) {
|
|
1079
|
+
client.tasks = async (opts) =>
|
|
1080
|
+
(await getJSON<{ data: AgentTaskInfo[] }>('tasks', `${tasksBase}${query({ status: opts?.status, limit: opts?.limit })}`)).data;
|
|
1081
|
+
client.taskInfo = (id) => getJSON<AgentTaskInfo>('taskInfo', `${tasksBase}/${encodeURIComponent(id)}`);
|
|
1082
|
+
client.stopTask = async (id) => {
|
|
1083
|
+
// `all` is a different request with a different answer.
|
|
1084
|
+
if (id === 'all') throw new Error('stopTask: "all" is stopAllTasks()');
|
|
1085
|
+
return postJSON<AgentTaskStop>('stopTask', `${tasksBase}/${encodeURIComponent(id)}/cancel`);
|
|
1086
|
+
};
|
|
1087
|
+
client.stopAllTasks = async () =>
|
|
1088
|
+
(await postJSON<{ data: AgentTaskStop[] }>('stopAllTasks', `${tasksBase}/all/cancel`)).data;
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
const schedulesBase = ownerBase('schedules');
|
|
1092
|
+
if (schedulesBase) {
|
|
1093
|
+
client.schedules = async () => {
|
|
1094
|
+
const j = await getJSON<{ enabled?: boolean; data?: AgentSchedule[] }>('schedules', schedulesBase);
|
|
1095
|
+
return { enabled: j.enabled !== false, data: j.data ?? [] };
|
|
1096
|
+
};
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
const eventsBase = ownerBase('events');
|
|
1100
|
+
if (eventsBase) {
|
|
1101
|
+
// The agent sends a keepalive every 10s, so this much silence means the
|
|
1102
|
+
// connection is gone — the responses transport's rule, and its knob.
|
|
1103
|
+
const stallMs = params.stallMs ?? 90_000;
|
|
1104
|
+
const pollMs = Math.max(50, Math.floor(stallMs / 6));
|
|
1105
|
+
// A feed has no end to wait for, so a failure never ends it: it backs off
|
|
1106
|
+
// to a ceiling and keeps trying. An agent restarting (a settings push
|
|
1107
|
+
// restarts its process) is a normal reason to be away for a while.
|
|
1108
|
+
const backoff = (n: number): number => Math.min(500 * 2 ** n, 30_000, Math.max(50, stallMs * 4));
|
|
1109
|
+
const sleep = (ms: number, signal?: AbortSignal): Promise<void> =>
|
|
1110
|
+
new Promise((resolve) => {
|
|
1111
|
+
const done = (): void => {
|
|
1112
|
+
clearTimeout(t);
|
|
1113
|
+
signal?.removeEventListener('abort', done);
|
|
1114
|
+
resolve();
|
|
1115
|
+
};
|
|
1116
|
+
const t = setTimeout(done, ms);
|
|
1117
|
+
signal?.addEventListener('abort', done, { once: true });
|
|
1118
|
+
});
|
|
1119
|
+
|
|
1120
|
+
client.events = async function* (opts) {
|
|
1121
|
+
const signal = opts?.signal;
|
|
1122
|
+
let pos = opts?.after;
|
|
1123
|
+
let failures = 0;
|
|
1124
|
+
while (!signal?.aborted) {
|
|
1125
|
+
const attempt = new AbortController();
|
|
1126
|
+
const onAbort = (): void => attempt.abort();
|
|
1127
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
1128
|
+
let lastByteAt = Date.now();
|
|
1129
|
+
let sawBytes = false;
|
|
1130
|
+
const watchdog = setInterval(() => {
|
|
1131
|
+
if (Date.now() - lastByteAt > stallMs) attempt.abort();
|
|
1132
|
+
}, pollMs);
|
|
1133
|
+
try {
|
|
1134
|
+
let res: Response | undefined;
|
|
1135
|
+
try {
|
|
1136
|
+
res = await doFetch(`${eventsBase}${query({ after: pos })}`, { signal: attempt.signal });
|
|
1137
|
+
} catch {
|
|
1138
|
+
// the network, or an agent that is not up: try again below
|
|
1139
|
+
}
|
|
1140
|
+
if (res && !res.ok) {
|
|
1141
|
+
const text = await res.text().catch(() => '');
|
|
1142
|
+
// A 4xx is an answer (the route is gone, the handle is refused),
|
|
1143
|
+
// and asking again gets the same one.
|
|
1144
|
+
if (res.status < 500 && res.status !== 408 && res.status !== 429) {
|
|
1145
|
+
throw new Error(`events: HTTP ${res.status}: ${text}`);
|
|
1146
|
+
}
|
|
1147
|
+
res = undefined;
|
|
1148
|
+
}
|
|
1149
|
+
if (res) {
|
|
1150
|
+
if (!res.body || !(res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream')) {
|
|
1151
|
+
throw new Error('events: expected an SSE stream from the events route');
|
|
1152
|
+
}
|
|
1153
|
+
const heard = (): void => {
|
|
1154
|
+
lastByteAt = Date.now();
|
|
1155
|
+
sawBytes = true;
|
|
1156
|
+
};
|
|
1157
|
+
try {
|
|
1158
|
+
for await (const chunk of iterSseChunks(res.body, heard)) {
|
|
1159
|
+
heard();
|
|
1160
|
+
const { __sseEvent, ...data } = chunk as Record<string, unknown> & { __sseEvent?: string };
|
|
1161
|
+
const { seq, time } = data;
|
|
1162
|
+
if (typeof seq !== 'number') continue;
|
|
1163
|
+
const type = __sseEvent ?? '';
|
|
1164
|
+
if (type === 'reset') {
|
|
1165
|
+
// The position moves to the agent's cursor, backwards too
|
|
1166
|
+
// (after a /clear). The backlog the agent sends after a
|
|
1167
|
+
// reset is older than it, and is skipped below.
|
|
1168
|
+
pos = typeof data.cursor === 'number' ? data.cursor : seq;
|
|
1169
|
+
} else {
|
|
1170
|
+
if (pos !== undefined && seq <= pos) continue;
|
|
1171
|
+
pos = seq;
|
|
1172
|
+
}
|
|
1173
|
+
yield { type, seq, time: typeof time === 'number' ? time : Date.now(), data };
|
|
1174
|
+
}
|
|
1175
|
+
} catch {
|
|
1176
|
+
// cut mid-stream, or the stall watchdog: reopen from `pos`
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
} finally {
|
|
1180
|
+
clearInterval(watchdog);
|
|
1181
|
+
signal?.removeEventListener('abort', onAbort);
|
|
1182
|
+
}
|
|
1183
|
+
if (signal?.aborted) return;
|
|
1184
|
+
// A connection that carried anything (keepalives included) was
|
|
1185
|
+
// healthy until it closed (a proxy's request-duration cap, an agent
|
|
1186
|
+
// restart): reopen at once. One that carried nothing backs off.
|
|
1187
|
+
if (sawBytes) failures = 0;
|
|
1188
|
+
else await sleep(backoff(++failures), signal);
|
|
1189
|
+
}
|
|
1190
|
+
};
|
|
1191
|
+
}
|
|
1192
|
+
|
|
876
1193
|
// Owner-only: read the agent's own process log. Gated on the wallet-backed
|
|
877
1194
|
// signer (not `canAuth`) — /log/agent verifies a per-request owner signature,
|
|
878
1195
|
// so a client holding only a shared bearer token can't read logs.
|
package/src/AgenticID.ts
CHANGED
|
@@ -98,6 +98,30 @@ function acceptedOf(res: DeployCloneResponse): DeployAccepted {
|
|
|
98
98
|
|
|
99
99
|
/** Agent lifecycle (deploy / clone / transfer) + reads. Seal-bound today; the
|
|
100
100
|
* seal branch is reserved for non-seal agents. */
|
|
101
|
+
/**
|
|
102
|
+
* What an agent's current container last reported to the attestor
|
|
103
|
+
* (`POST /status`), as carried on its deployment row. `level` is `starting`,
|
|
104
|
+
* `running`, `warning`, `error` or `stopping`; `reason` is the container's
|
|
105
|
+
* explanation for a `warning` / `error` / `stopping` report, null when it gave
|
|
106
|
+
* none; `at` is when the attestor accepted the report (ISO 8601).
|
|
107
|
+
*/
|
|
108
|
+
export interface ContainerStatus {
|
|
109
|
+
level: string;
|
|
110
|
+
reason: string | null;
|
|
111
|
+
at: string;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Read a row's `container_status`; null when absent or malformed. */
|
|
115
|
+
function containerStatusOf(raw: unknown): ContainerStatus | null {
|
|
116
|
+
const s = raw as { level?: unknown; reason?: unknown; at?: unknown } | null | undefined;
|
|
117
|
+
if (!s || typeof s !== 'object' || typeof s.level !== 'string') return null;
|
|
118
|
+
return {
|
|
119
|
+
level: s.level,
|
|
120
|
+
reason: typeof s.reason === 'string' ? s.reason : null,
|
|
121
|
+
at: typeof s.at === 'string' ? s.at : '',
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
101
125
|
export class AgentApi {
|
|
102
126
|
private readonly id: AgenticIDClient;
|
|
103
127
|
private readonly attestor: AttestorClient;
|
|
@@ -620,8 +644,8 @@ export class AgentApi {
|
|
|
620
644
|
* Compact the agent's ONE persisted conversation in place: the framework's
|
|
621
645
|
* own compaction replaces the older history with a summary and keeps the
|
|
622
646
|
* newest part verbatim (how much is the framework's: openclaw ~20K tokens,
|
|
623
|
-
*
|
|
624
|
-
* conversation goes on — the middle ground between doing nothing and
|
|
647
|
+
* 0g-harness only its newest item), so later requests carry less of it
|
|
648
|
+
* while the conversation goes on — the middle ground between doing nothing and
|
|
625
649
|
* {@link clearConversation}. No restart. The summary takes one or more
|
|
626
650
|
* model calls, so this can take minutes — longer than Node's fetch waits
|
|
627
651
|
* for an answer (300s). A connection dropped or timed out meanwhile does not
|
|
@@ -802,14 +826,23 @@ export class AgentApi {
|
|
|
802
826
|
* row is currently failed (any pipeline stage) or offline due to a
|
|
803
827
|
* genuine container failure; recovered rows report null.
|
|
804
828
|
*
|
|
829
|
+
* `containerStatus` is what the agent's current container last reported
|
|
830
|
+
* (`{ level, reason, at }`, owner listing only; null until that container
|
|
831
|
+
* reports, and from attestors that predate the field). `phase` shows a
|
|
832
|
+
* `warning` as `running`: the agent is up but needs the owner, for example
|
|
833
|
+
* because its settings give it no model (`reason` says so; write them with
|
|
834
|
+
* {@link AgentApi.setSettings}, then {@link AgentApi.pushSettingsToContainer}
|
|
835
|
+
* applies them to the running container). Check it when a running agent
|
|
836
|
+
* does not answer.
|
|
837
|
+
*
|
|
805
838
|
* When `phase` is `"failed"`, try {@link AgentApi.retry} FIRST — it resumes
|
|
806
839
|
* the failed stages on the same identity. Redeploying instead orphans the
|
|
807
840
|
* already-minted agent; reset only helps once the container stage is
|
|
808
841
|
* reached.
|
|
809
842
|
*
|
|
810
843
|
* This is the PUBLIC listing: the attestor returns only non-sensitive fields
|
|
811
|
-
* for an unauthenticated GET (issue #64), so `sandboxId
|
|
812
|
-
* `lastProvisionError` come back **null** here. No tier carries the owner's
|
|
844
|
+
* for an unauthenticated GET (issue #64), so `sandboxId`,
|
|
845
|
+
* `lastProvisionError` and `containerStatus` come back **null** here. No tier carries the owner's
|
|
813
846
|
* settings document — read it with {@link AgentApi.getSettings}, which is
|
|
814
847
|
* owner-signed. `agentId`/`sealId`/`phase`/`url`/`name` are still
|
|
815
848
|
* present, and `owner` and `agentSeal` appear for MINTED rows (both
|
|
@@ -826,6 +859,7 @@ export class AgentApi {
|
|
|
826
859
|
sandboxId: string | null; url: string | null; owner: Address | null; name: string | null;
|
|
827
860
|
agentSeal: Address | null;
|
|
828
861
|
createdAt: string | null; lastProvisionError: string | null;
|
|
862
|
+
containerStatus: ContainerStatus | null;
|
|
829
863
|
}>> {
|
|
830
864
|
// slim=1 drops the embedded avatar data-URIs (~95% of the payload); servers
|
|
831
865
|
// predating the param ignore it.
|
|
@@ -836,7 +870,7 @@ export class AgentApi {
|
|
|
836
870
|
/**
|
|
837
871
|
* Owner-scoped, authenticated listing — your own agents WITH the fields the
|
|
838
872
|
* public {@link AgentApi.listDeployments} withholds (`sandboxId`,
|
|
839
|
-
* `lastProvisionError`, stages). Signs `0GDeployments:<owner>:<ts>` with
|
|
873
|
+
* `lastProvisionError`, `containerStatus`, stages). Signs `0GDeployments:<owner>:<ts>` with
|
|
840
874
|
* `ctx.account` and sends it as `X-Auth-Message`/`X-Auth-Signature`; the
|
|
841
875
|
* attestor verifies the signer controls `<owner>` before returning its rows.
|
|
842
876
|
* Requires a wallet. This is how you get a container's `sandboxId` for
|
|
@@ -860,13 +894,14 @@ export class AgentApi {
|
|
|
860
894
|
* {@link AgentApi.listMyDeployments}; whatever the tier omits simply
|
|
861
895
|
* comes through as null — public tier: owner/agentSeal only on minted
|
|
862
896
|
* rows (agentSeal only from attestors carrying the field),
|
|
863
|
-
* sandboxId/lastProvisionError never; owner tier: everything present
|
|
897
|
+
* sandboxId/lastProvisionError/containerStatus never; owner tier: everything present
|
|
864
898
|
* for your own rows, including unminted ones. */
|
|
865
899
|
private normalizeDeploymentRow(r: Record<string, unknown>): {
|
|
866
900
|
agentId: bigint | null; sealId: Hash; phase: string; framework: string | null;
|
|
867
901
|
sandboxId: string | null; url: string | null; owner: Address | null; name: string | null;
|
|
868
902
|
agentSeal: Address | null;
|
|
869
903
|
createdAt: string | null; lastProvisionError: string | null;
|
|
904
|
+
containerStatus: ContainerStatus | null;
|
|
870
905
|
} {
|
|
871
906
|
const card = (r.agent_card as Record<string, unknown>) ?? {};
|
|
872
907
|
// The card's url points at the /hello card endpoint; the base (origin)
|
|
@@ -875,8 +910,9 @@ export class AgentApi {
|
|
|
875
910
|
try { url = card.url ? new URL(card.url as string).origin : null; } catch { /* malformed → null */ }
|
|
876
911
|
// Failure reasons live on the per-track stage objects
|
|
877
912
|
// (storage/mint/container_stage.reason); last_provision_error is a
|
|
878
|
-
// sticky DB column (only
|
|
879
|
-
//
|
|
913
|
+
// sticky DB column (cleared only by the next accepted /provision or a
|
|
914
|
+
// new container's boot ticket) so it is only consulted for
|
|
915
|
+
// phase=failed, as a backstop — same gating and priority as the
|
|
880
916
|
// attestor console's failureReason(). phase=offline surfaces only a
|
|
881
917
|
// genuine container failure (a clean owner stop carries no reason);
|
|
882
918
|
// recovered rows report null rather than a stale sticky error. (These
|
|
@@ -908,6 +944,7 @@ export class AgentApi {
|
|
|
908
944
|
name: (card.name as string) ?? null,
|
|
909
945
|
createdAt: (r.created_at as string) ?? null,
|
|
910
946
|
lastProvisionError: failureReason,
|
|
947
|
+
containerStatus: containerStatusOf(r.container_status),
|
|
911
948
|
// No `settings`: the owner's configuration document is owner-gated on
|
|
912
949
|
// READ as well as write and is served only by {@link getSettings}. No
|
|
913
950
|
// listing tier carries it, so advertising it here would have meant a
|
|
@@ -933,6 +970,13 @@ export class AgentApi {
|
|
|
933
970
|
* supplies the key, pass its {@link sealApiKey} output as
|
|
934
971
|
* `sealedSecretEnv` instead of `apiKey`, so the key never reaches the
|
|
935
972
|
* signer at all.
|
|
973
|
+
*
|
|
974
|
+
* Both shapes, like {@link reset}, first store the default model
|
|
975
|
+
* (`DEFAULT_PERSONA_INFERENCE`) as the agent's settings document when it
|
|
976
|
+
* has none and could boot without a model: a clone, or an agent that has
|
|
977
|
+
* provisioned before (`needsDefaultSettings`). That write is one more
|
|
978
|
+
* owner signature, made after every check that can refuse the call; an
|
|
979
|
+
* existing document is never replaced.
|
|
936
980
|
*/
|
|
937
981
|
start(sealId: Hash, sandboxId: string): Promise<void>;
|
|
938
982
|
start(sealId: Hash, opts?: { provider?: string; framework?: string; sealedImage?: string; apiKey?: string; sealedSecretEnv?: string; secretEnv?: SecretEnvMode }): Promise<void>;
|
|
@@ -954,6 +998,16 @@ export class AgentApi {
|
|
|
954
998
|
* signed envelope in clear (`secretEnv`, default `'auto'`; `'sealed'`
|
|
955
999
|
* refuses the clear path). The attestor keeps no reusable copy, which
|
|
956
1000
|
* is WHY it must be passed again on every recreate.
|
|
1001
|
+
*
|
|
1002
|
+
* An agent with no settings document boots on the model pinned in its
|
|
1003
|
+
* minted persona, which leaves the chain at its first commit. So when the
|
|
1004
|
+
* agent has none and is a clone or has provisioned before
|
|
1005
|
+
* (`needsDefaultSettings`), the default model (`DEFAULT_PERSONA_INFERENCE`,
|
|
1006
|
+
* 0g-compute) is stored as its first document before the envelope is
|
|
1007
|
+
* signed (one more owner signature, after every check that can refuse the
|
|
1008
|
+
* call); an existing document is never replaced. Such an agent cannot be
|
|
1009
|
+
* reset onto another `provider` until its settings name one: write them
|
|
1010
|
+
* with {@link setSettings} first.
|
|
957
1011
|
*/
|
|
958
1012
|
reset(sealId: Hash, opts?: { provider?: string; framework?: string; sealedImage?: string; apiKey?: string; sealedSecretEnv?: string; secretEnv?: SecretEnvMode }): Promise<void> {
|
|
959
1013
|
return this.attestor.lifecycle('reset', { sealId, provider: opts?.provider, framework: opts?.framework, sealedImage: opts?.sealedImage, apiKey: opts?.apiKey, sealedSecretEnv: opts?.sealedSecretEnv, secretEnv: opts?.secretEnv });
|