@wraith-ai/core 0.1.0 → 0.1.1
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/README.md +1 -1
- package/dist/{attempt-BeB7EltG.d.mts → attempt-HgararU3.d.mts} +2 -1
- package/dist/attempt-HgararU3.d.mts.map +1 -0
- package/dist/{capabilities-BPb5HSH6.d.mts → capabilities-CNsPrkB7.d.mts} +2 -1
- package/dist/capabilities-CNsPrkB7.d.mts.map +1 -0
- package/dist/index.d.mts +6 -5
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +11 -9
- package/dist/index.mjs.map +1 -0
- package/dist/{methods-CZp6XGn8.mjs → methods-7Ryz6zbd.mjs} +4 -2
- package/dist/methods-7Ryz6zbd.mjs.map +1 -0
- package/dist/{model-B6tJ9kX_.mjs → model-C16NUwXW.mjs} +2 -0
- package/dist/model-C16NUwXW.mjs.map +1 -0
- package/dist/{model-D6LQSveS.d.mts → model-_wqePNTL.d.mts} +4 -3
- package/dist/model-_wqePNTL.d.mts.map +1 -0
- package/dist/{models-dev-Y0ZikMBQ.d.mts → models-dev-DNgymZy3.d.mts} +3 -2
- package/dist/models-dev-DNgymZy3.d.mts.map +1 -0
- package/dist/{openai-codex-BhtZvNpm.mjs → openai-codex-Bz1EFPEi.mjs} +3 -1
- package/dist/openai-codex-Bz1EFPEi.mjs.map +1 -0
- package/dist/{openai-codex-Bk-iG7MZ.mjs → openai-codex-uvjhVoVy.mjs} +6 -4
- package/dist/openai-codex-uvjhVoVy.mjs.map +1 -0
- package/dist/{openai-compatible-hkXv-P74.mjs → openai-compatible-DBppnQ_N.mjs} +4 -2
- package/dist/openai-compatible-DBppnQ_N.mjs.map +1 -0
- package/dist/{openrouter-BflQBug2.mjs → openrouter-D8nTOAQo.mjs} +5 -3
- package/dist/openrouter-D8nTOAQo.mjs.map +1 -0
- package/dist/providers/openai-codex.d.mts +4 -3
- package/dist/providers/openai-codex.d.mts.map +1 -0
- package/dist/providers/openai-codex.mjs +1 -1
- package/dist/providers/openai-compatible.d.mts +3 -2
- package/dist/providers/openai-compatible.d.mts.map +1 -0
- package/dist/providers/openai-compatible.mjs +1 -1
- package/dist/providers/openrouter.d.mts +3 -2
- package/dist/providers/openrouter.d.mts.map +1 -0
- package/dist/providers/openrouter.mjs +1 -1
- package/dist/{shared-8d7RsyPH.mjs → shared-BIJaPhMm.mjs} +3 -1
- package/dist/shared-BIJaPhMm.mjs.map +1 -0
- package/dist/snapshot.d.mts +3 -2
- package/dist/snapshot.d.mts.map +1 -0
- package/dist/snapshot.mjs +4999 -4977
- package/dist/snapshot.mjs.map +1 -0
- package/dist/{turn-effort-DquDDwdE.mjs → turn-effort-C61L4JIt.mjs} +2 -0
- package/dist/turn-effort-C61L4JIt.mjs.map +1 -0
- package/package.json +3 -2
- package/src/agent/agent.ts +90 -0
- package/src/agent/attachments.ts +195 -0
- package/src/agent/classifier.ts +525 -0
- package/src/agent/compact.ts +384 -0
- package/src/agent/conversation.ts +300 -0
- package/src/agent/cost.ts +164 -0
- package/src/agent/inbox.ts +80 -0
- package/src/agent/instructions.ts +62 -0
- package/src/agent/loop.ts +675 -0
- package/src/agent/messages.ts +252 -0
- package/src/agent/on-demand.ts +58 -0
- package/src/agent/prompts.ts +35 -0
- package/src/agent/request-images.ts +94 -0
- package/src/agent/stop.ts +37 -0
- package/src/agent/title.ts +122 -0
- package/src/agent/tool-groups.ts +186 -0
- package/src/agent/tools.ts +106 -0
- package/src/app.ts +67 -0
- package/src/config/credential-file-store.ts +66 -0
- package/src/config/environment.ts +105 -0
- package/src/config/instructions.ts +157 -0
- package/src/config/load.ts +667 -0
- package/src/config/locked-file.ts +85 -0
- package/src/config/paths.ts +368 -0
- package/src/config/schema.ts +363 -0
- package/src/config/subagents.ts +156 -0
- package/src/config/trust.ts +53 -0
- package/src/config/write.ts +241 -0
- package/src/errors.ts +85 -0
- package/src/events/types.ts +258 -0
- package/src/glob.ts +161 -0
- package/src/index.ts +681 -0
- package/src/logger.ts +47 -0
- package/src/paths.ts +143 -0
- package/src/permissions/chain.ts +42 -0
- package/src/permissions/command.ts +233 -0
- package/src/permissions/layered.ts +77 -0
- package/src/permissions/match.ts +80 -0
- package/src/permissions/modes.ts +48 -0
- package/src/permissions/policy.ts +160 -0
- package/src/permissions/types.ts +159 -0
- package/src/providers/cache.ts +107 -0
- package/src/providers/capabilities.ts +77 -0
- package/src/providers/catalog-view.ts +91 -0
- package/src/providers/catalog.ts +65 -0
- package/src/providers/errors.ts +108 -0
- package/src/providers/factories/index.ts +15 -0
- package/src/providers/factories/openai-codex.ts +382 -0
- package/src/providers/factories/openai-compatible.ts +81 -0
- package/src/providers/factories/openrouter.ts +165 -0
- package/src/providers/factories/shared.ts +22 -0
- package/src/providers/model.ts +197 -0
- package/src/providers/models-dev.ts +355 -0
- package/src/providers/oauth/methods.ts +10 -0
- package/src/providers/oauth/openai-codex.ts +228 -0
- package/src/providers/oauth.ts +177 -0
- package/src/providers/openai-codex.ts +7 -0
- package/src/providers/openai-compatible.ts +2 -0
- package/src/providers/openrouter.ts +2 -0
- package/src/providers/registry.ts +464 -0
- package/src/providers/turn-effort.ts +156 -0
- package/src/providers/types.ts +83 -0
- package/src/session/backend.ts +44 -0
- package/src/session/file-store.ts +278 -0
- package/src/session/format.ts +1037 -0
- package/src/session/memory-store.ts +73 -0
- package/src/session/session.ts +153 -0
- package/src/session/store.ts +219 -0
- package/src/sign-in/attempt.ts +166 -0
- package/src/sign-in/loopback.ts +74 -0
- package/src/snapshot/data.json +8936 -0
- package/src/snapshot/index.ts +37 -0
- package/src/tools/bin.ts +364 -0
- package/src/tools/builtin.ts +48 -0
- package/src/tools/change.ts +88 -0
- package/src/tools/define.ts +267 -0
- package/src/tools/describe.ts +96 -0
- package/src/tools/fs/edit-file.ts +129 -0
- package/src/tools/fs/glob.ts +75 -0
- package/src/tools/fs/grep.ts +212 -0
- package/src/tools/fs/line-endings.ts +17 -0
- package/src/tools/fs/list-dir.ts +85 -0
- package/src/tools/fs/read-file.ts +230 -0
- package/src/tools/fs/ripgrep.ts +211 -0
- package/src/tools/fs/write-file.ts +97 -0
- package/src/tools/job.ts +252 -0
- package/src/tools/mcp/auth-store.ts +127 -0
- package/src/tools/mcp/command.ts +151 -0
- package/src/tools/mcp/config.ts +168 -0
- package/src/tools/mcp/servers.ts +463 -0
- package/src/tools/mcp/sign-in.ts +226 -0
- package/src/tools/mcp/stdio.ts +204 -0
- package/src/tools/mcp/tools.ts +173 -0
- package/src/tools/on-demand.ts +184 -0
- package/src/tools/registry.ts +935 -0
- package/src/tools/shell/bash.ts +217 -0
- package/src/tools/shell/find-bash.ts +162 -0
- package/src/tools/source.ts +35 -0
- package/src/tools/spill.ts +127 -0
- package/src/tools/subagents.ts +597 -0
- package/src/tools/tasks.ts +603 -0
- package/src/tools/to-model.ts +33 -0
- package/src/tools/web/address.ts +95 -0
- package/src/tools/web/exa.ts +163 -0
- package/src/tools/web/fetch.ts +373 -0
- package/src/tools/web/html.ts +173 -0
- package/src/tools/web/search.ts +111 -0
- package/src/tools/web/source.ts +51 -0
- package/src/units.ts +18 -0
- package/src/version.ts +23 -0
|
@@ -0,0 +1,603 @@
|
|
|
1
|
+
import { Buffer } from "node:buffer";
|
|
2
|
+
import { closeSync, mkdirSync, openSync, rmSync, writeSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import type { InboxQueue } from "../agent/inbox";
|
|
6
|
+
import { AgentError, serializeError } from "../errors";
|
|
7
|
+
import { addUsage, type Usage } from "../events/types";
|
|
8
|
+
import { toPosix } from "../paths";
|
|
9
|
+
import {
|
|
10
|
+
type SessionRecord,
|
|
11
|
+
type SessionRecordInput,
|
|
12
|
+
type TaskStopper,
|
|
13
|
+
unfinishedTasks,
|
|
14
|
+
} from "../session/format";
|
|
15
|
+
import { defineTool, type AgentTool, type ToolTask } from "./define";
|
|
16
|
+
import { SPILL_LIMIT_BYTES } from "./spill";
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Calls that outlive their turn. The tool registry opens one for every call
|
|
20
|
+
* that may be deferred; it becomes a task only when the registry stops waiting.
|
|
21
|
+
* From then on the conversation hears about it through the inbox.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/** How much of a task's output its notice carries; the rest is in the log. */
|
|
25
|
+
export const TASK_TAIL_BYTES = 4 * 1024;
|
|
26
|
+
|
|
27
|
+
/** How many ended tasks a listing still shows. */
|
|
28
|
+
const ENDED_SHOWN = 25;
|
|
29
|
+
|
|
30
|
+
/** What a task registry needs of an inbox: to announce, and to tell a waiter there is news. */
|
|
31
|
+
export type TaskInbox = Pick<InboxQueue, "push" | "wakes" | "subscribe">;
|
|
32
|
+
|
|
33
|
+
/** How a wait ended: something is waiting to be read, nothing is left to wait for, or neither. */
|
|
34
|
+
export type TaskWaitOutcome = "news" | "idle" | "timeout" | "cancelled";
|
|
35
|
+
|
|
36
|
+
export interface TaskRegistryOptions {
|
|
37
|
+
/** Live logs, one file per task. */
|
|
38
|
+
dir: string;
|
|
39
|
+
/** Where tasks announce themselves. */
|
|
40
|
+
inbox: TaskInbox;
|
|
41
|
+
/** How long a call asked into the background is given to end by itself. */
|
|
42
|
+
graceMs?: number;
|
|
43
|
+
newId?: (prefix: string) => string;
|
|
44
|
+
now?: () => number;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface TaskSnapshot {
|
|
48
|
+
id: string;
|
|
49
|
+
label: string;
|
|
50
|
+
toolName: string;
|
|
51
|
+
startedAt: number;
|
|
52
|
+
/** Absent while it runs. */
|
|
53
|
+
endedAt?: number;
|
|
54
|
+
status: "running" | "finished" | "failed" | "stopped";
|
|
55
|
+
outputPath?: string;
|
|
56
|
+
/** The task this one was started for, when it belongs to a registry made by `child`. */
|
|
57
|
+
owner?: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface TaskSpec {
|
|
61
|
+
toolName: string;
|
|
62
|
+
toolCallId: string;
|
|
63
|
+
label: string;
|
|
64
|
+
log: boolean;
|
|
65
|
+
/**
|
|
66
|
+
* The id to run under, for work that goes on in rounds and keeps one name.
|
|
67
|
+
* Absent: a fresh one. Refused with `tool/task-running` while that id runs.
|
|
68
|
+
*/
|
|
69
|
+
id?: string;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface TaskRegistry {
|
|
73
|
+
readonly graceMs: number;
|
|
74
|
+
/** For the tool registry: a call that may outlive its turn. */
|
|
75
|
+
open(spec: TaskSpec): OpenTask;
|
|
76
|
+
/** What a person should see: tasks in the background, and the last few that ended. */
|
|
77
|
+
list(): TaskSnapshot[];
|
|
78
|
+
/** Stops a task, and with it every task of the registry `child` made under its id. */
|
|
79
|
+
stop(id: string, by: "user" | "model"): boolean;
|
|
80
|
+
/**
|
|
81
|
+
* A registry for what one task starts itself, such as a sub-agent's own
|
|
82
|
+
* commands: logs in a folder of this one's, endings to `inbox`. This one
|
|
83
|
+
* lists them, stops them and closes them. One per id.
|
|
84
|
+
*/
|
|
85
|
+
child(id: string, inbox: TaskInbox): TaskRegistry;
|
|
86
|
+
/**
|
|
87
|
+
* Settles when this registry's inbox holds something worth a run, when
|
|
88
|
+
* nothing of its own is left running, or when the time is up. Tasks of a
|
|
89
|
+
* `child` do not count: their endings go to another inbox.
|
|
90
|
+
*/
|
|
91
|
+
wait(options: { timeoutMs: number; signal: AbortSignal }): Promise<TaskWaitOutcome>;
|
|
92
|
+
/** Called when the list changes. */
|
|
93
|
+
subscribe(listener: () => void): () => void;
|
|
94
|
+
/**
|
|
95
|
+
* Tasks a session's log started and never ended, which this registry did not
|
|
96
|
+
* run: the process that ran them is gone. Each goes to the inbox as `lost`,
|
|
97
|
+
* once and without waking, and is returned. A task this registry ran is never
|
|
98
|
+
* lost here, so a host that keeps tasks across conversations calls it safely.
|
|
99
|
+
*/
|
|
100
|
+
recover(records: readonly (SessionRecord | SessionRecordInput)[]): { id: string; label: string }[];
|
|
101
|
+
/** Stops what is left. Their records go to the inbox at once. */
|
|
102
|
+
close(): void;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export interface OpenTask {
|
|
106
|
+
readonly id: string;
|
|
107
|
+
readonly signal: AbortSignal;
|
|
108
|
+
readonly outputPath?: string;
|
|
109
|
+
/** What the tool sees as `context.task`. */
|
|
110
|
+
readonly context: ToolTask;
|
|
111
|
+
/** What it has written so far, capped. */
|
|
112
|
+
output(): string;
|
|
113
|
+
/**
|
|
114
|
+
* What the tool said it spent. For a call that ends in the foreground, whose
|
|
115
|
+
* outcome carries it; one that ends in the background says it in its record.
|
|
116
|
+
*/
|
|
117
|
+
spent(): Usage | undefined;
|
|
118
|
+
/** From here on the conversation hears about it. */
|
|
119
|
+
background(done: Promise<unknown>): void;
|
|
120
|
+
/** The call ended in the foreground: forget it and delete its log. */
|
|
121
|
+
discard(): void;
|
|
122
|
+
stop(by: TaskStopper): void;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
interface Log {
|
|
126
|
+
path: string;
|
|
127
|
+
descriptor: number | undefined;
|
|
128
|
+
bytes: number;
|
|
129
|
+
failed: boolean;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
interface Entry {
|
|
133
|
+
id: string;
|
|
134
|
+
label: string;
|
|
135
|
+
toolName: string;
|
|
136
|
+
toolCallId: string;
|
|
137
|
+
startedAt: number;
|
|
138
|
+
controller: AbortController;
|
|
139
|
+
log: Log | undefined;
|
|
140
|
+
/** The last bytes written, and whether anything came before them. */
|
|
141
|
+
tail: Buffer;
|
|
142
|
+
cut: boolean;
|
|
143
|
+
/** `open`: still an ordinary call. `discarded`: it ended as one. */
|
|
144
|
+
status: "open" | "discarded" | TaskSnapshot["status"];
|
|
145
|
+
/** What the call spent on models of its own, so far. */
|
|
146
|
+
usage: Usage | undefined;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Where the log ended up, as the closing record says it. */
|
|
150
|
+
interface LogEnd {
|
|
151
|
+
tail?: string;
|
|
152
|
+
bytes?: number;
|
|
153
|
+
outputPath?: string;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function createTaskRegistry(options: TaskRegistryOptions): TaskRegistry {
|
|
157
|
+
return makeTaskRegistry(options);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** A registry as its parent holds it: stoppable on anybody's account, not only the host's. */
|
|
161
|
+
interface OwnedRegistry extends TaskRegistry {
|
|
162
|
+
/** Stops everything, here and below. True when anything was running. */
|
|
163
|
+
stopAll(by: TaskStopper): boolean;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function makeTaskRegistry(options: TaskRegistryOptions): OwnedRegistry {
|
|
167
|
+
const now = options.now ?? Date.now;
|
|
168
|
+
const entries = new Map<string, Entry>();
|
|
169
|
+
const ended: TaskSnapshot[] = [];
|
|
170
|
+
const listeners = new Set<() => void>();
|
|
171
|
+
const children = new Map<string, { registry: OwnedRegistry; inbox: TaskInbox }>();
|
|
172
|
+
// Every task this registry opened, ended ones too: one whose end is still on its
|
|
173
|
+
// way to the log is not lost. And every loss already said, so it is said once.
|
|
174
|
+
const ran = new Set<string>();
|
|
175
|
+
const announced = new Set<string>();
|
|
176
|
+
|
|
177
|
+
const changed = (): void => {
|
|
178
|
+
for (const listener of listeners) listener();
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
// Random, not counted: a counter restarts with the process and would land on
|
|
182
|
+
// the log file of a task from the run before.
|
|
183
|
+
const freshId = (): string => {
|
|
184
|
+
for (;;) {
|
|
185
|
+
const id = options.newId?.("task") ?? Math.random().toString(36).slice(2, 8).padEnd(6, "0");
|
|
186
|
+
if (!entries.has(id)) return id;
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
const openLog = (log: Log): void => {
|
|
191
|
+
if (log.descriptor !== undefined || log.failed) return;
|
|
192
|
+
try {
|
|
193
|
+
mkdirSync(options.dir, { recursive: true });
|
|
194
|
+
log.descriptor = openSync(log.path, "w");
|
|
195
|
+
} catch {
|
|
196
|
+
// A full disk costs the log, never the task.
|
|
197
|
+
log.failed = true;
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
const closeLog = (log: Log): void => {
|
|
202
|
+
if (log.descriptor === undefined) return;
|
|
203
|
+
try {
|
|
204
|
+
closeSync(log.descriptor);
|
|
205
|
+
} catch {
|
|
206
|
+
log.failed = true;
|
|
207
|
+
}
|
|
208
|
+
log.descriptor = undefined;
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
const write = (entry: Entry, chunk: string | Uint8Array): void => {
|
|
212
|
+
const log = entry.log;
|
|
213
|
+
if (log === undefined || (entry.status !== "open" && entry.status !== "running")) return;
|
|
214
|
+
const data = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : Buffer.from(chunk);
|
|
215
|
+
if (data.length === 0) return;
|
|
216
|
+
|
|
217
|
+
const joined = Buffer.concat([entry.tail, data]);
|
|
218
|
+
if (joined.length > TASK_TAIL_BYTES) entry.cut = true;
|
|
219
|
+
entry.tail = joined.subarray(Math.max(0, joined.length - TASK_TAIL_BYTES));
|
|
220
|
+
|
|
221
|
+
const room = SPILL_LIMIT_BYTES - log.bytes;
|
|
222
|
+
if (room <= 0) return;
|
|
223
|
+
openLog(log);
|
|
224
|
+
if (log.descriptor === undefined) return;
|
|
225
|
+
const part = data.length > room ? data.subarray(0, room) : data;
|
|
226
|
+
try {
|
|
227
|
+
writeSync(log.descriptor, part);
|
|
228
|
+
log.bytes += part.length;
|
|
229
|
+
} catch {
|
|
230
|
+
log.failed = true;
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
/** Closes the log and leaves it where the model was told it is; the host's sweep of temp takes it. */
|
|
235
|
+
const settle = (entry: Entry): LogEnd => {
|
|
236
|
+
const log = entry.log;
|
|
237
|
+
if (log === undefined) return {};
|
|
238
|
+
closeLog(log);
|
|
239
|
+
if (log.failed || log.bytes === 0) return {};
|
|
240
|
+
return { tail: tailText(entry.tail, entry.cut), bytes: log.bytes, outputPath: toPosix(log.path) };
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
const snapshot = (entry: Entry, status: TaskSnapshot["status"], outputPath?: string): TaskSnapshot => ({
|
|
244
|
+
id: entry.id,
|
|
245
|
+
label: entry.label,
|
|
246
|
+
toolName: entry.toolName,
|
|
247
|
+
startedAt: entry.startedAt,
|
|
248
|
+
status,
|
|
249
|
+
...(outputPath === undefined ? {} : { outputPath }),
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
/** One way out of the background, so a late settlement after a stop finds nothing to do. */
|
|
253
|
+
const end = (
|
|
254
|
+
entry: Entry,
|
|
255
|
+
how:
|
|
256
|
+
| { state: "finished"; output: unknown }
|
|
257
|
+
| { state: "failed"; error: unknown }
|
|
258
|
+
| { state: "stopped"; by: TaskStopper },
|
|
259
|
+
): void => {
|
|
260
|
+
if (entry.status !== "running") return;
|
|
261
|
+
entry.status = how.state;
|
|
262
|
+
const endedAt = now();
|
|
263
|
+
const { tail, bytes, outputPath } = settle(entry);
|
|
264
|
+
const base = {
|
|
265
|
+
type: "task" as const,
|
|
266
|
+
id: entry.id,
|
|
267
|
+
label: entry.label,
|
|
268
|
+
durationMs: endedAt - entry.startedAt,
|
|
269
|
+
...(tail === undefined ? {} : { tail }),
|
|
270
|
+
...(bytes === undefined ? {} : { bytes }),
|
|
271
|
+
...(outputPath === undefined ? {} : { outputPath }),
|
|
272
|
+
// On every ending: a round that was stopped cost what it cost.
|
|
273
|
+
...(entry.usage === undefined ? {} : { usage: entry.usage }),
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
entries.delete(entry.id);
|
|
277
|
+
ended.push({ ...snapshot(entry, how.state, outputPath), endedAt });
|
|
278
|
+
if (ended.length > ENDED_SHOWN) ended.shift();
|
|
279
|
+
|
|
280
|
+
if (how.state === "stopped") {
|
|
281
|
+
options.inbox.push({ ...base, state: "stopped", by: how.by });
|
|
282
|
+
} else {
|
|
283
|
+
options.inbox.push(
|
|
284
|
+
how.state === "finished"
|
|
285
|
+
? { ...base, state: "finished", output: how.output }
|
|
286
|
+
: { ...base, state: "failed", error: serializeError(how.error) },
|
|
287
|
+
{ wake: true },
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
changed();
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
const stopAll = (by: TaskStopper): boolean => {
|
|
294
|
+
let stopped = false;
|
|
295
|
+
for (const entry of [...entries.values()]) {
|
|
296
|
+
if (entry.status !== "running") continue;
|
|
297
|
+
entry.controller.abort();
|
|
298
|
+
end(entry, { state: "stopped", by });
|
|
299
|
+
stopped = true;
|
|
300
|
+
}
|
|
301
|
+
for (const child of children.values()) {
|
|
302
|
+
if (child.registry.stopAll(by)) stopped = true;
|
|
303
|
+
}
|
|
304
|
+
return stopped;
|
|
305
|
+
};
|
|
306
|
+
|
|
307
|
+
const anythingRunning = (): boolean =>
|
|
308
|
+
[...entries.values()].some((entry) => entry.status === "running");
|
|
309
|
+
|
|
310
|
+
return {
|
|
311
|
+
graceMs: options.graceMs ?? 1_000,
|
|
312
|
+
|
|
313
|
+
open(spec) {
|
|
314
|
+
const id = spec.id ?? freshId();
|
|
315
|
+
// Two rounds of one task at once would end under one name, and nobody could tell which.
|
|
316
|
+
if (entries.has(id)) {
|
|
317
|
+
throw new AgentError("tool/task-running", `Task ${id} is still running.`, {
|
|
318
|
+
details: { taskId: id },
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
const entry: Entry = {
|
|
322
|
+
id,
|
|
323
|
+
label: spec.label,
|
|
324
|
+
toolName: spec.toolName,
|
|
325
|
+
toolCallId: spec.toolCallId,
|
|
326
|
+
startedAt: now(),
|
|
327
|
+
controller: new AbortController(),
|
|
328
|
+
log: spec.log
|
|
329
|
+
? { path: join(options.dir, `${id}.log`), descriptor: undefined, bytes: 0, failed: false }
|
|
330
|
+
: undefined,
|
|
331
|
+
tail: Buffer.alloc(0),
|
|
332
|
+
cut: false,
|
|
333
|
+
status: "open",
|
|
334
|
+
usage: undefined,
|
|
335
|
+
};
|
|
336
|
+
entries.set(id, entry);
|
|
337
|
+
ran.add(id);
|
|
338
|
+
const outputPath = entry.log === undefined ? undefined : toPosix(entry.log.path);
|
|
339
|
+
|
|
340
|
+
return {
|
|
341
|
+
id,
|
|
342
|
+
signal: entry.controller.signal,
|
|
343
|
+
...(outputPath === undefined ? {} : { outputPath }),
|
|
344
|
+
context: {
|
|
345
|
+
id,
|
|
346
|
+
get background() {
|
|
347
|
+
return entry.status !== "open" && entry.status !== "discarded";
|
|
348
|
+
},
|
|
349
|
+
write: (chunk) => write(entry, chunk),
|
|
350
|
+
spend: (usage) => {
|
|
351
|
+
entry.usage = addUsage(entry.usage ?? {}, usage);
|
|
352
|
+
},
|
|
353
|
+
},
|
|
354
|
+
output: () => tailText(entry.tail, entry.cut),
|
|
355
|
+
spent: () => entry.usage,
|
|
356
|
+
|
|
357
|
+
background(done) {
|
|
358
|
+
if (entry.status !== "open") return;
|
|
359
|
+
entry.status = "running";
|
|
360
|
+
// An earlier round under this id is the same task to whoever reads the list.
|
|
361
|
+
const earlier = ended.findIndex((snapshot) => snapshot.id === id);
|
|
362
|
+
if (earlier !== -1) ended.splice(earlier, 1);
|
|
363
|
+
// The path is in the tool's result, so it has to exist before anything is written.
|
|
364
|
+
if (entry.log !== undefined) openLog(entry.log);
|
|
365
|
+
options.inbox.push({
|
|
366
|
+
type: "task",
|
|
367
|
+
id,
|
|
368
|
+
state: "started",
|
|
369
|
+
label: entry.label,
|
|
370
|
+
toolName: entry.toolName,
|
|
371
|
+
toolCallId: entry.toolCallId,
|
|
372
|
+
...(outputPath === undefined ? {} : { outputPath }),
|
|
373
|
+
});
|
|
374
|
+
changed();
|
|
375
|
+
done.then(
|
|
376
|
+
(output) => end(entry, { state: "finished", output }),
|
|
377
|
+
(error: unknown) => end(entry, { state: "failed", error }),
|
|
378
|
+
);
|
|
379
|
+
},
|
|
380
|
+
|
|
381
|
+
discard() {
|
|
382
|
+
if (entry.status !== "open") return;
|
|
383
|
+
entry.status = "discarded";
|
|
384
|
+
entries.delete(id);
|
|
385
|
+
if (entry.log !== undefined) {
|
|
386
|
+
closeLog(entry.log);
|
|
387
|
+
rmSync(entry.log.path, { force: true });
|
|
388
|
+
}
|
|
389
|
+
},
|
|
390
|
+
|
|
391
|
+
stop(by) {
|
|
392
|
+
entry.controller.abort();
|
|
393
|
+
// Still an ordinary call: its own error tells the model.
|
|
394
|
+
end(entry, { state: "stopped", by });
|
|
395
|
+
},
|
|
396
|
+
};
|
|
397
|
+
},
|
|
398
|
+
|
|
399
|
+
list: () => [
|
|
400
|
+
...[...entries.values()]
|
|
401
|
+
.filter((entry) => entry.status === "running")
|
|
402
|
+
.map((entry) =>
|
|
403
|
+
snapshot(entry, "running", entry.log === undefined ? undefined : toPosix(entry.log.path)),
|
|
404
|
+
),
|
|
405
|
+
...[...children].flatMap(([owner, child]) =>
|
|
406
|
+
// The nearest owner: a list is read by a person, who started the outer task.
|
|
407
|
+
child.registry.list().map((task) => ({ ...task, owner: task.owner ?? owner })),
|
|
408
|
+
),
|
|
409
|
+
...ended,
|
|
410
|
+
],
|
|
411
|
+
|
|
412
|
+
stop(id, by) {
|
|
413
|
+
let stopped = false;
|
|
414
|
+
const entry = entries.get(id);
|
|
415
|
+
if (entry !== undefined && entry.status === "running") {
|
|
416
|
+
entry.controller.abort();
|
|
417
|
+
end(entry, { state: "stopped", by });
|
|
418
|
+
stopped = true;
|
|
419
|
+
}
|
|
420
|
+
// What a task started goes with it, also between its rounds, when it is not running itself.
|
|
421
|
+
if (children.get(id)?.registry.stopAll(by) === true) stopped = true;
|
|
422
|
+
if (stopped) return true;
|
|
423
|
+
for (const child of children.values()) {
|
|
424
|
+
if (child.registry.stop(id, by)) return true;
|
|
425
|
+
}
|
|
426
|
+
return false;
|
|
427
|
+
},
|
|
428
|
+
|
|
429
|
+
stopAll,
|
|
430
|
+
|
|
431
|
+
child(id, inbox) {
|
|
432
|
+
const made = children.get(id);
|
|
433
|
+
if (made !== undefined) {
|
|
434
|
+
if (made.inbox === inbox) return made.registry;
|
|
435
|
+
throw new AgentError(
|
|
436
|
+
"config/invalid",
|
|
437
|
+
`Task ${id} already has a registry for its own tasks, announcing to another inbox.`,
|
|
438
|
+
{ details: { taskId: id } },
|
|
439
|
+
);
|
|
440
|
+
}
|
|
441
|
+
const registry = makeTaskRegistry({
|
|
442
|
+
dir: join(options.dir, id),
|
|
443
|
+
inbox,
|
|
444
|
+
graceMs: options.graceMs ?? 1_000,
|
|
445
|
+
...(options.newId === undefined ? {} : { newId: options.newId }),
|
|
446
|
+
now,
|
|
447
|
+
});
|
|
448
|
+
children.set(id, { registry, inbox });
|
|
449
|
+
registry.subscribe(changed);
|
|
450
|
+
return registry;
|
|
451
|
+
},
|
|
452
|
+
|
|
453
|
+
wait({ timeoutMs, signal }) {
|
|
454
|
+
const verdict = (): TaskWaitOutcome | undefined =>
|
|
455
|
+
options.inbox.wakes() ? "news" : anythingRunning() ? undefined : "idle";
|
|
456
|
+
|
|
457
|
+
return new Promise((resolve) => {
|
|
458
|
+
if (signal.aborted) return resolve("cancelled");
|
|
459
|
+
const first = verdict();
|
|
460
|
+
if (first !== undefined) return resolve(first);
|
|
461
|
+
|
|
462
|
+
const finish = (outcome: TaskWaitOutcome): void => {
|
|
463
|
+
clearTimeout(timer);
|
|
464
|
+
offInbox();
|
|
465
|
+
listeners.delete(look);
|
|
466
|
+
signal.removeEventListener("abort", onAbort);
|
|
467
|
+
resolve(outcome);
|
|
468
|
+
};
|
|
469
|
+
const look = (): void => {
|
|
470
|
+
const outcome = verdict();
|
|
471
|
+
if (outcome !== undefined) finish(outcome);
|
|
472
|
+
};
|
|
473
|
+
const onAbort = (): void => finish("cancelled");
|
|
474
|
+
const timer = setTimeout(() => finish("timeout"), timeoutMs);
|
|
475
|
+
const offInbox = options.inbox.subscribe(look);
|
|
476
|
+
// A stop pushes without waking, so the list is watched as well as the inbox.
|
|
477
|
+
listeners.add(look);
|
|
478
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
479
|
+
});
|
|
480
|
+
},
|
|
481
|
+
|
|
482
|
+
subscribe(listener) {
|
|
483
|
+
listeners.add(listener);
|
|
484
|
+
return () => {
|
|
485
|
+
listeners.delete(listener);
|
|
486
|
+
};
|
|
487
|
+
},
|
|
488
|
+
|
|
489
|
+
recover(records) {
|
|
490
|
+
const lost = unfinishedTasks(records).filter((task) => !ran.has(task.id) && !announced.has(task.id));
|
|
491
|
+
for (const task of lost) {
|
|
492
|
+
announced.add(task.id);
|
|
493
|
+
options.inbox.push({ type: "task", id: task.id, state: "lost", label: task.label });
|
|
494
|
+
}
|
|
495
|
+
return lost;
|
|
496
|
+
},
|
|
497
|
+
|
|
498
|
+
close() {
|
|
499
|
+
// Tasks still in the foreground are told to stop too; `end` records only what runs.
|
|
500
|
+
for (const entry of [...entries.values()]) entry.controller.abort();
|
|
501
|
+
stopAll("host");
|
|
502
|
+
},
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/** The end of the output as text; a cut never lands inside a character or a short line. */
|
|
507
|
+
function tailText(tail: Buffer, cut: boolean): string {
|
|
508
|
+
if (!cut) return tail.toString("utf8");
|
|
509
|
+
let start = 0;
|
|
510
|
+
while (start < tail.length && ((tail[start] ?? 0) & 0xc0) === 0x80) start += 1;
|
|
511
|
+
const newline = tail.indexOf(0x0a, start);
|
|
512
|
+
if (newline !== -1 && newline + 1 < tail.length) start = newline + 1;
|
|
513
|
+
return tail.subarray(start).toString("utf8");
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/** The id the tool registry lists this tool under. */
|
|
517
|
+
export const TASKS_SOURCE_ID = "tasks";
|
|
518
|
+
|
|
519
|
+
export const TASK_STOP_NAME = "task_stop";
|
|
520
|
+
export const TASK_WAIT_NAME = "task_wait";
|
|
521
|
+
|
|
522
|
+
/** A wait that times out costs a step, so the default is long and the floor is not a poll. */
|
|
523
|
+
export const TASK_WAIT_DEFAULT_MS = 5 * 60_000;
|
|
524
|
+
export const TASK_WAIT_MIN_MS = 10_000;
|
|
525
|
+
export const TASK_WAIT_MAX_MS = 60 * 60_000;
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* `safe`: it reads nothing and changes nothing. Never beside other calls: next
|
|
529
|
+
* to a call still on its way to the background it would see nothing running.
|
|
530
|
+
*/
|
|
531
|
+
export function taskWaitTool(tasks: Pick<TaskRegistry, "wait" | "list">): AgentTool {
|
|
532
|
+
return defineTool({
|
|
533
|
+
name: TASK_WAIT_NAME,
|
|
534
|
+
description:
|
|
535
|
+
"Wait until a background task or agent has something to report, the user writes, or the " +
|
|
536
|
+
"time runs out. Use it only when nothing else is left to do until then. It returns no " +
|
|
537
|
+
"report: what arrived is given to you right after it. Never wait for something that does " +
|
|
538
|
+
"not end by itself, such as a server.",
|
|
539
|
+
danger: "safe",
|
|
540
|
+
parallel: false,
|
|
541
|
+
inputSchema: z.object({
|
|
542
|
+
timeout_ms: z
|
|
543
|
+
.number()
|
|
544
|
+
.int()
|
|
545
|
+
.positive()
|
|
546
|
+
.optional()
|
|
547
|
+
.describe(
|
|
548
|
+
`The longest to wait, in milliseconds. Default ${String(TASK_WAIT_DEFAULT_MS)}, ` +
|
|
549
|
+
`at least ${String(TASK_WAIT_MIN_MS)}, at most ${String(TASK_WAIT_MAX_MS)}.`,
|
|
550
|
+
),
|
|
551
|
+
}),
|
|
552
|
+
describe: (input) => (input.timeout_ms === undefined ? "" : `${String(input.timeout_ms)} ms`),
|
|
553
|
+
execute: async (input, context) => {
|
|
554
|
+
const asked = input.timeout_ms ?? TASK_WAIT_DEFAULT_MS;
|
|
555
|
+
const timeoutMs = Math.min(TASK_WAIT_MAX_MS, Math.max(TASK_WAIT_MIN_MS, asked));
|
|
556
|
+
const outcome = await tasks.wait({ timeoutMs, signal: context.signal });
|
|
557
|
+
|
|
558
|
+
if (outcome === "cancelled") {
|
|
559
|
+
throw new AgentError("run/aborted", `${TASK_WAIT_NAME} was cancelled.`, {
|
|
560
|
+
details: { toolName: TASK_WAIT_NAME },
|
|
561
|
+
});
|
|
562
|
+
}
|
|
563
|
+
if (outcome === "news") {
|
|
564
|
+
return { status: "news", notice: "Something arrived. It follows this result." };
|
|
565
|
+
}
|
|
566
|
+
if (outcome === "idle") {
|
|
567
|
+
return {
|
|
568
|
+
status: "idle",
|
|
569
|
+
notice: "Nothing of yours is running in the background, so there is nothing to wait for.",
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
const running = tasks.list().filter((task) => task.status === "running" && task.owner === undefined);
|
|
573
|
+
const clamped = timeoutMs === asked ? "" : ` (the time asked for was outside the limits)`;
|
|
574
|
+
return {
|
|
575
|
+
status: "timeout",
|
|
576
|
+
notice:
|
|
577
|
+
`Nothing arrived in ${String(Math.round(timeoutMs / 1_000))} s${clamped}. Still running: ` +
|
|
578
|
+
`${running.map((task) => `${task.id} ${task.label}`).join("; ")}. ` +
|
|
579
|
+
"Wait again, do something else, or stop what is no longer needed.",
|
|
580
|
+
};
|
|
581
|
+
},
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/** `safe`: it stops only what the agent started itself. */
|
|
586
|
+
export function taskStopTool(tasks: Pick<TaskRegistry, "stop">): AgentTool {
|
|
587
|
+
return defineTool({
|
|
588
|
+
name: TASK_STOP_NAME,
|
|
589
|
+
description:
|
|
590
|
+
"Stop a background task. Takes the taskId a tool returned when it went to the background.",
|
|
591
|
+
danger: "safe",
|
|
592
|
+
inputSchema: z.object({ task_id: z.string() }),
|
|
593
|
+
describe: (input) => input.task_id,
|
|
594
|
+
execute: async (input) => {
|
|
595
|
+
if (!tasks.stop(input.task_id, "model")) {
|
|
596
|
+
throw new AgentError("tool/unknown-task", `No running task ${input.task_id}.`, {
|
|
597
|
+
details: { taskId: input.task_id },
|
|
598
|
+
});
|
|
599
|
+
}
|
|
600
|
+
return { taskId: input.task_id, stopped: true };
|
|
601
|
+
},
|
|
602
|
+
});
|
|
603
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { AgentTool } from "./define";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* What the model is allowed to see: a name, a description and a schema.
|
|
5
|
+
*
|
|
6
|
+
* No `execute`: the SDK validates the arguments and returns the call instead
|
|
7
|
+
* of running it, so the loop can ask for approval before it runs.
|
|
8
|
+
*
|
|
9
|
+
* Built by hand, not with the SDK's `tool()` helper (an identity function at
|
|
10
|
+
* runtime), so `ai` stays out of this directory, which the layer guard checks.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export interface ModelToolDefinition {
|
|
14
|
+
description: string;
|
|
15
|
+
inputSchema: unknown;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function toModelTool(tool: AgentTool): ModelToolDefinition {
|
|
19
|
+
return { description: tool.description, inputSchema: tool.inputSchema };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Sorted by name. Tool declarations open every request, so their order is part
|
|
24
|
+
* of the cached prefix: a different order discards the cache without an error.
|
|
25
|
+
*/
|
|
26
|
+
export function toModelTools(tools: ReadonlyMap<string, AgentTool>): Record<string, unknown> {
|
|
27
|
+
const result: Record<string, unknown> = {};
|
|
28
|
+
for (const name of [...tools.keys()].sort()) {
|
|
29
|
+
const tool = tools.get(name);
|
|
30
|
+
if (tool !== undefined) result[name] = toModelTool(tool);
|
|
31
|
+
}
|
|
32
|
+
return result;
|
|
33
|
+
}
|