@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,241 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import type { z } from "zod";
|
|
5
|
+
import { AgentError } from "../errors";
|
|
6
|
+
import type { AppPaths } from "./paths";
|
|
7
|
+
import { configSchema, withHostSettings } from "./schema";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Writing one setting, from inside the application, into one layer's file.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** `project` is the team's committed file, written only when a host names it. */
|
|
14
|
+
export type ConfigLayer = "user" | "project" | "projectLocal";
|
|
15
|
+
|
|
16
|
+
export interface SetConfigValue {
|
|
17
|
+
/** Defaults to the personal project layer when there is a project directory. */
|
|
18
|
+
layer?: ConfigLayer;
|
|
19
|
+
/** Dotted, e.g. "defaultModel" or "permissions.classifier.enabled". */
|
|
20
|
+
path: string;
|
|
21
|
+
/** `undefined` removes the key, which is not the same as setting it to null. */
|
|
22
|
+
value: unknown;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface SetConfigOptions {
|
|
26
|
+
/** The extension `loadConfig` was given, or a host's setting is refused as unknown. */
|
|
27
|
+
extend?: z.ZodObject;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const RENAME_RETRIES = 5;
|
|
31
|
+
|
|
32
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
33
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function hasPath(source: unknown, path: string): boolean {
|
|
37
|
+
let cursor = source;
|
|
38
|
+
for (const segment of path.split(".")) {
|
|
39
|
+
if (!isPlainObject(cursor) || !Object.hasOwn(cursor, segment)) return false;
|
|
40
|
+
cursor = cursor[segment];
|
|
41
|
+
}
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function invalid(message: string, details: Record<string, unknown> = {}): AgentError {
|
|
46
|
+
return new AgentError("config/invalid", message, { details });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Which file a change belongs in. Never the team's `.wraith/config.json`, which
|
|
51
|
+
* is committed, unless asked for by name: the personal layer beside it, or the
|
|
52
|
+
* user's own file when this is not a project at all.
|
|
53
|
+
*/
|
|
54
|
+
export function targetFor(paths: AppPaths, layer?: ConfigLayer): string {
|
|
55
|
+
if (layer === "user") return paths.userConfig;
|
|
56
|
+
const local = layer === "project" ? paths.projectConfig : paths.projectLocalConfig;
|
|
57
|
+
if (layer !== undefined) {
|
|
58
|
+
if (local === undefined) {
|
|
59
|
+
throw invalid(
|
|
60
|
+
`${paths.projectRoot} is not a project: its settings directory is your own. Write to the user layer instead.`,
|
|
61
|
+
{ projectRoot: paths.projectRoot },
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
return local;
|
|
65
|
+
}
|
|
66
|
+
// The directory of the file itself: in a worktree that is the main
|
|
67
|
+
// checkout's.
|
|
68
|
+
return local !== undefined && existsSync(dirname(local)) ? local : paths.userConfig;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Windows renames fail transiently while an indexer holds the target open. */
|
|
72
|
+
async function renameWithRetry(from: string, to: string): Promise<void> {
|
|
73
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
74
|
+
try {
|
|
75
|
+
await rename(from, to);
|
|
76
|
+
return;
|
|
77
|
+
} catch (error) {
|
|
78
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
79
|
+
if (attempt >= RENAME_RETRIES || (code !== "EPERM" && code !== "EBUSY")) throw error;
|
|
80
|
+
await new Promise((resolve) => setTimeout(resolve, 10 * (attempt + 1)));
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* One layer's file, as it was written, never the merge. Adding a rule reads
|
|
87
|
+
* this file and writes it back longer; reading the merged config would copy the
|
|
88
|
+
* team's rules into the personal layer.
|
|
89
|
+
*/
|
|
90
|
+
export async function readConfigLayer(path: string): Promise<Record<string, unknown>> {
|
|
91
|
+
let contents: string;
|
|
92
|
+
try {
|
|
93
|
+
contents = await readFile(path, "utf8");
|
|
94
|
+
} catch {
|
|
95
|
+
return {};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
let parsed: unknown;
|
|
99
|
+
try {
|
|
100
|
+
// Same tolerance as the loader: Windows editors add a BOM and JSON.parse
|
|
101
|
+
// refuses it. Written back without one.
|
|
102
|
+
parsed = JSON.parse(contents.replace(/^/, ""));
|
|
103
|
+
} catch (cause) {
|
|
104
|
+
throw new AgentError("config/unreadable", `Config file is not valid JSON: ${path}`, {
|
|
105
|
+
cause,
|
|
106
|
+
details: { path },
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (!isPlainObject(parsed)) {
|
|
111
|
+
throw new AgentError("config/unreadable", `Config file must contain an object: ${path}`, {
|
|
112
|
+
details: { path },
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
return parsed;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Applies the change to a copy, leaving the caller's object alone. */
|
|
119
|
+
export function withValueAt(
|
|
120
|
+
source: Record<string, unknown>,
|
|
121
|
+
path: string,
|
|
122
|
+
value: unknown,
|
|
123
|
+
): Record<string, unknown> {
|
|
124
|
+
const segments = path.split(".");
|
|
125
|
+
if (segments.length === 0 || segments.some((segment) => segment === "")) {
|
|
126
|
+
throw invalid(`"${path}" is not a settings path.`, { path });
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const root: Record<string, unknown> = { ...source };
|
|
130
|
+
let cursor = root;
|
|
131
|
+
|
|
132
|
+
for (const [index, segment] of segments.entries()) {
|
|
133
|
+
const last = index === segments.length - 1;
|
|
134
|
+
|
|
135
|
+
if (last) {
|
|
136
|
+
if (value === undefined) delete cursor[segment];
|
|
137
|
+
else cursor[segment] = value;
|
|
138
|
+
break;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const existing = cursor[segment];
|
|
142
|
+
if (existing !== undefined && !isPlainObject(existing)) {
|
|
143
|
+
// Overwriting a scalar would silently discard whatever is there.
|
|
144
|
+
throw invalid(
|
|
145
|
+
`"${segments.slice(0, index + 1).join(".")}" is not a group of settings, so "${path}" cannot be set.`,
|
|
146
|
+
{ path },
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
// Copied on the way down, so nothing shared with the caller is mutated.
|
|
150
|
+
const next = isPlainObject(existing) ? { ...existing } : {};
|
|
151
|
+
cursor[segment] = next;
|
|
152
|
+
cursor = next;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
return root;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Secrets have their own command and their own file.
|
|
160
|
+
*
|
|
161
|
+
* `redactConfig` protects what gets printed; nothing else protects what gets
|
|
162
|
+
* written. Without this refusal, `config set` would put an API key into a file
|
|
163
|
+
* meant to be shareable.
|
|
164
|
+
*/
|
|
165
|
+
function assertNotASecret(path: string): void {
|
|
166
|
+
const provider = /^providers\.([^.]+)\.apiKey$/.exec(path)?.[1];
|
|
167
|
+
if (provider !== undefined) {
|
|
168
|
+
// `keyFor` is the hook a host uses for its own key storage.
|
|
169
|
+
throw invalid("Provider keys are not settings and are never written to a configuration file.", {
|
|
170
|
+
path,
|
|
171
|
+
keyFor: provider,
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async function namesProviders(paths: AppPaths): Promise<boolean> {
|
|
177
|
+
for (const file of [paths.userConfig, paths.projectConfig, paths.projectLocalConfig]) {
|
|
178
|
+
if (file !== undefined && "providers" in (await readConfigLayer(file))) return true;
|
|
179
|
+
}
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Sets one key and answers with the file it changed.
|
|
185
|
+
*
|
|
186
|
+
* - Writes the layer, never the merge. Saving the merge would freeze today's
|
|
187
|
+
* defaults into the file, so no later default change would reach this user.
|
|
188
|
+
* - Writes the personal file (`targetFor`).
|
|
189
|
+
* - Returns that path, because a write to the wrong layer looks like a
|
|
190
|
+
* setting that did not save.
|
|
191
|
+
* - Validates the result before it is written: a file that fails the schema
|
|
192
|
+
* breaks the next start, when the command that wrote it is out of sight.
|
|
193
|
+
*/
|
|
194
|
+
export async function setConfigValue(
|
|
195
|
+
paths: AppPaths,
|
|
196
|
+
change: SetConfigValue,
|
|
197
|
+
options: SetConfigOptions = {},
|
|
198
|
+
): Promise<string> {
|
|
199
|
+
assertNotASecret(change.path);
|
|
200
|
+
|
|
201
|
+
const target = targetFor(paths, change.layer);
|
|
202
|
+
let layer = await readConfigLayer(target);
|
|
203
|
+
// The default provider exists only until some file names `providers`, so the
|
|
204
|
+
// first entry written would make it vanish; it is written down alongside.
|
|
205
|
+
if (change.path.startsWith("providers.") && !(await namesProviders(paths))) {
|
|
206
|
+
for (const [name, entry] of Object.entries(configSchema.parse({}).providers)) {
|
|
207
|
+
layer = withValueAt(layer, `providers.${name}.type`, entry.type);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
const next = withValueAt(layer, change.path, change.value);
|
|
211
|
+
|
|
212
|
+
const parsed = withHostSettings(options.extend).safeParse(next);
|
|
213
|
+
if (!parsed.success) {
|
|
214
|
+
const summary = parsed.error.issues
|
|
215
|
+
.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`)
|
|
216
|
+
.join("; ");
|
|
217
|
+
throw invalid(`That setting would make the configuration invalid — ${summary}`, {
|
|
218
|
+
path: change.path,
|
|
219
|
+
file: target,
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
// The schema strips a name it does not know and still says yes, so a typo
|
|
223
|
+
// would be written and never read back.
|
|
224
|
+
if (change.value !== undefined && !hasPath(parsed.data, change.path)) {
|
|
225
|
+
throw invalid(`"${change.path}" is not a setting.`, { path: change.path, file: target });
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
await mkdir(dirname(target), { recursive: true });
|
|
229
|
+
|
|
230
|
+
// Written aside and moved into place: a reader — including the next start of
|
|
231
|
+
// this very process — sees the old file or the new one, never half of either.
|
|
232
|
+
const temporary = `${target}.${String(process.pid)}.tmp`;
|
|
233
|
+
try {
|
|
234
|
+
await writeFile(temporary, `${JSON.stringify(next, null, 2)}\n`, "utf8");
|
|
235
|
+
await renameWithRetry(temporary, target);
|
|
236
|
+
} finally {
|
|
237
|
+
await rm(temporary, { force: true }).catch(() => undefined);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
return target;
|
|
241
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every failure the core raises is an AgentError with a stable `code`.
|
|
3
|
+
* Front ends branch on the code, never on the message text, so messages stay
|
|
4
|
+
* free to change without breaking a UI.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export type AgentErrorCode =
|
|
8
|
+
| "config/invalid"
|
|
9
|
+
| "config/unreadable"
|
|
10
|
+
| "config/missing-api-key"
|
|
11
|
+
| "config/not-signed-in"
|
|
12
|
+
| "provider/unknown"
|
|
13
|
+
| "provider/load-failed"
|
|
14
|
+
| "provider/unauthorized"
|
|
15
|
+
| "provider/rate-limited"
|
|
16
|
+
| "provider/unsupported-parameter"
|
|
17
|
+
| "provider/request-failed"
|
|
18
|
+
| "model/unknown-alias"
|
|
19
|
+
| "model/not-configured"
|
|
20
|
+
| "run/aborted"
|
|
21
|
+
| "run/nothing-to-run"
|
|
22
|
+
| "conversation/busy"
|
|
23
|
+
| "conversation/no-agent"
|
|
24
|
+
| "attachment/invalid"
|
|
25
|
+
| "attachment/unsupported-type"
|
|
26
|
+
| "attachment/too-large"
|
|
27
|
+
| "session/not-found"
|
|
28
|
+
| "session/exists"
|
|
29
|
+
| "session/concurrent-write"
|
|
30
|
+
| "session/corrupt"
|
|
31
|
+
| "session/unsupported-version"
|
|
32
|
+
| "tool/not-found"
|
|
33
|
+
| "tool/duplicate-name"
|
|
34
|
+
| "tool/invalid-input"
|
|
35
|
+
| "tool/denied"
|
|
36
|
+
| "tool/timeout"
|
|
37
|
+
| "tool/path-escape"
|
|
38
|
+
| "tool/too-large"
|
|
39
|
+
| "tool/binary-file"
|
|
40
|
+
| "tool/missing-binary"
|
|
41
|
+
| "tool/unknown-task"
|
|
42
|
+
| "tool/task-running"
|
|
43
|
+
| "tool/failed"
|
|
44
|
+
| "mcp/unavailable"
|
|
45
|
+
| "mcp/tool-error"
|
|
46
|
+
| "mcp/needs-sign-in"
|
|
47
|
+
| "mcp/sign-in-failed";
|
|
48
|
+
|
|
49
|
+
export interface AgentErrorOptions {
|
|
50
|
+
cause?: unknown;
|
|
51
|
+
details?: Record<string, unknown>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export class AgentError extends Error {
|
|
55
|
+
override readonly name = "AgentError";
|
|
56
|
+
readonly code: AgentErrorCode;
|
|
57
|
+
readonly details: Record<string, unknown>;
|
|
58
|
+
|
|
59
|
+
constructor(code: AgentErrorCode, message: string, options: AgentErrorOptions = {}) {
|
|
60
|
+
super(message, { cause: options.cause });
|
|
61
|
+
this.code = code;
|
|
62
|
+
this.details = options.details ?? {};
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function isAgentError(value: unknown): value is AgentError {
|
|
67
|
+
return value instanceof AgentError;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** JSON-safe shape carried by events and printed by front ends. */
|
|
71
|
+
export interface SerializedError {
|
|
72
|
+
code: AgentErrorCode | "unknown";
|
|
73
|
+
message: string;
|
|
74
|
+
details: Record<string, unknown>;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function serializeError(value: unknown): SerializedError {
|
|
78
|
+
if (isAgentError(value)) {
|
|
79
|
+
return { code: value.code, message: value.message, details: value.details };
|
|
80
|
+
}
|
|
81
|
+
if (value instanceof Error) {
|
|
82
|
+
return { code: "unknown", message: value.message, details: {} };
|
|
83
|
+
}
|
|
84
|
+
return { code: "unknown", message: typeof value === "string" ? value : JSON.stringify(value), details: {} };
|
|
85
|
+
}
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import type { InboxRecord } from "../agent/inbox";
|
|
2
|
+
import type { SerializedError } from "../errors";
|
|
3
|
+
import type { ApprovalDecidedBy, ApprovalDecision } from "../permissions/types";
|
|
4
|
+
import type { SessionRecordInput } from "../session/format";
|
|
5
|
+
import type { FileChange } from "../tools/change";
|
|
6
|
+
import type { DangerLevel } from "../tools/define";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The contract between the core and every front end.
|
|
10
|
+
*
|
|
11
|
+
* Rules that keep it usable from a terminal, a browser and a log file:
|
|
12
|
+
* - every event is plain JSON, so JSON.stringify is a ready SSE payload
|
|
13
|
+
* and a ready NDJSON line; no classes, no Error, no Date
|
|
14
|
+
* - a renderer must ignore event types it does not know, so adding one is
|
|
15
|
+
* never a breaking change
|
|
16
|
+
* - `parentRunId` is present from the start; adding it to a shipped UI
|
|
17
|
+
* would be the breaking change
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/** Where a cost figure came from. A mixture is only as good as its worst half. */
|
|
21
|
+
export type CostSource = "provider" | "estimate";
|
|
22
|
+
|
|
23
|
+
export interface Usage {
|
|
24
|
+
/**
|
|
25
|
+
* The whole prompt, cache reads included: that is the SDK's contract.
|
|
26
|
+
*
|
|
27
|
+
* It is the right number for a context meter and the wrong one for a bill:
|
|
28
|
+
* multiplying it by the input rate charges cache reads at ten times their
|
|
29
|
+
* price. The bill uses `noCacheTokens`.
|
|
30
|
+
*/
|
|
31
|
+
inputTokens?: number;
|
|
32
|
+
/** The part of the input billed at the full rate. */
|
|
33
|
+
noCacheTokens?: number;
|
|
34
|
+
outputTokens?: number;
|
|
35
|
+
totalTokens?: number;
|
|
36
|
+
/** Read from the prompt cache — billed at 0.1x the input rate. */
|
|
37
|
+
cacheReadTokens?: number;
|
|
38
|
+
/** Written to the prompt cache — billed at 1.25x (5m) or 2x (1h). */
|
|
39
|
+
cacheWriteTokens?: number;
|
|
40
|
+
/** Micro-dollars, integer. Absent means unknown, never free. */
|
|
41
|
+
costMicros?: number;
|
|
42
|
+
costSource?: CostSource;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** A list as well as a type, so a stored reason can be checked against it. */
|
|
46
|
+
export const FINISH_REASONS = [
|
|
47
|
+
"stop",
|
|
48
|
+
"tool-calls",
|
|
49
|
+
"length",
|
|
50
|
+
"content-filter",
|
|
51
|
+
"max-steps",
|
|
52
|
+
"aborted",
|
|
53
|
+
"error",
|
|
54
|
+
"other",
|
|
55
|
+
] as const;
|
|
56
|
+
|
|
57
|
+
export type FinishReason = (typeof FINISH_REASONS)[number];
|
|
58
|
+
|
|
59
|
+
interface EventBase {
|
|
60
|
+
runId: string;
|
|
61
|
+
/** Set for sub-agent runs; null at the top level. */
|
|
62
|
+
parentRunId: string | null;
|
|
63
|
+
ts: number;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export type AgentEvent = EventBase &
|
|
67
|
+
(
|
|
68
|
+
/**
|
|
69
|
+
* `contextLimit` is optional because it is knowledge, not state: a host
|
|
70
|
+
* without a capability catalog omits it, and a front end draws no meter
|
|
71
|
+
* rather than one against an invented window.
|
|
72
|
+
*/
|
|
73
|
+
| {
|
|
74
|
+
type: "run-start";
|
|
75
|
+
sessionId: string;
|
|
76
|
+
model: string;
|
|
77
|
+
provider: string;
|
|
78
|
+
contextLimit?: number;
|
|
79
|
+
}
|
|
80
|
+
| { type: "step-start"; step: number }
|
|
81
|
+
/**
|
|
82
|
+
* The first chunk of the step's answer. Before it, a request is out and nothing has come
|
|
83
|
+
* back; after it, the model is working even when its reasoning is encrypted.
|
|
84
|
+
*/
|
|
85
|
+
| { type: "response-start"; step: number }
|
|
86
|
+
/** A summary is being written; ends with `compaction` or `compaction-failed`, never neither. */
|
|
87
|
+
| { type: "compaction-start" }
|
|
88
|
+
/**
|
|
89
|
+
* History was summarized mid-run. Without this a front end sees half the
|
|
90
|
+
* conversation vanish and cannot tell it apart from a failure.
|
|
91
|
+
*/
|
|
92
|
+
| {
|
|
93
|
+
type: "compaction";
|
|
94
|
+
summary: string;
|
|
95
|
+
droppedMessages: number;
|
|
96
|
+
tokensBefore: number;
|
|
97
|
+
tokensAfter: number;
|
|
98
|
+
}
|
|
99
|
+
/** The summary did not happen; the run goes on without it, or ends if cancelled. */
|
|
100
|
+
| { type: "compaction-failed"; error: SerializedError }
|
|
101
|
+
/**
|
|
102
|
+
* A part of the step's answer, text or reasoning, is `(step, index)`: `index` counts the
|
|
103
|
+
* step's parts in the order they start. Every start gets exactly one end, carrying the
|
|
104
|
+
* part's whole text, also when the stream breaks off inside it.
|
|
105
|
+
*/
|
|
106
|
+
| { type: "text-start"; step: number; index: number }
|
|
107
|
+
| { type: "text-delta"; step: number; index: number; text: string }
|
|
108
|
+
| { type: "text-end"; step: number; index: number; text: string }
|
|
109
|
+
/** Said only when the provider says it: encrypted reasoning on OpenRouter has no start. */
|
|
110
|
+
| { type: "reasoning-start"; step: number; index: number }
|
|
111
|
+
| { type: "reasoning-delta"; step: number; index: number; text: string }
|
|
112
|
+
/** `text` is empty when the reasoning came encrypted. */
|
|
113
|
+
| { type: "reasoning-end"; step: number; index: number; text: string }
|
|
114
|
+
/** The model began writing a call's arguments, which can stream for a long time. */
|
|
115
|
+
| { type: "tool-input-start"; toolCallId: string; toolName: string }
|
|
116
|
+
| { type: "tool-call"; toolCallId: string; toolName: string; input: unknown }
|
|
117
|
+
/** Running now, not just asked for — what tells a call in a group from one still queued. */
|
|
118
|
+
| { type: "tool-start"; toolCallId: string; toolName: string }
|
|
119
|
+
| {
|
|
120
|
+
type: "tool-approval-request";
|
|
121
|
+
approvalId: string;
|
|
122
|
+
toolCallId: string;
|
|
123
|
+
toolName: string;
|
|
124
|
+
input: unknown;
|
|
125
|
+
danger: DangerLevel;
|
|
126
|
+
summary: string;
|
|
127
|
+
/** What the call would change on disk, for the screen alone. */
|
|
128
|
+
change?: FileChange;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* `decidedBy` and `reason` are recorded: a log that records "denied"
|
|
132
|
+
* without recording who decided leaves the most useful question
|
|
133
|
+
* unanswerable.
|
|
134
|
+
*/
|
|
135
|
+
| {
|
|
136
|
+
type: "tool-approval-resolved";
|
|
137
|
+
approvalId: string;
|
|
138
|
+
decision: ApprovalDecision;
|
|
139
|
+
decidedBy: ApprovalDecidedBy;
|
|
140
|
+
reason?: string;
|
|
141
|
+
/**
|
|
142
|
+
* What deciding cost, when deciding cost anything. A classifier runs
|
|
143
|
+
* outside the loop, so this is the only route by which its tokens reach
|
|
144
|
+
* the log.
|
|
145
|
+
*/
|
|
146
|
+
usage?: Usage;
|
|
147
|
+
}
|
|
148
|
+
/** `change` is what a write did, for the screen alone — never in what the model gets. */
|
|
149
|
+
| {
|
|
150
|
+
type: "tool-result";
|
|
151
|
+
toolCallId: string;
|
|
152
|
+
toolName: string;
|
|
153
|
+
output: unknown;
|
|
154
|
+
change?: FileChange;
|
|
155
|
+
}
|
|
156
|
+
| { type: "tool-error"; toolCallId: string; toolName: string; error: SerializedError }
|
|
157
|
+
/** `usage` is the run's running total; `stepUsage` is this request alone. */
|
|
158
|
+
| { type: "step-finish"; step: number; usage: Usage; stepUsage: Usage }
|
|
159
|
+
/**
|
|
160
|
+
* `text` is what the run's last step said: the answer, or for a run cut at the step limit
|
|
161
|
+
* whatever came before its tool calls, which may be nothing. `durationMs` is the same
|
|
162
|
+
* reading the run's `finish` record keeps, so a replay agrees.
|
|
163
|
+
*/
|
|
164
|
+
| { type: "run-finish"; reason: FinishReason; usage: Usage; text: string; durationMs: number }
|
|
165
|
+
| { type: "error"; error: SerializedError }
|
|
166
|
+
/** Something from outside entered the conversation: the record that went into the log. */
|
|
167
|
+
| { type: "delivery"; record: InboxRecord }
|
|
168
|
+
/**
|
|
169
|
+
* A record for the session's journal, sent as the run makes it and in journal order.
|
|
170
|
+
* What a host stores; a screen has nothing to draw from it.
|
|
171
|
+
*/
|
|
172
|
+
| { type: "record"; record: SessionRecordInput }
|
|
173
|
+
);
|
|
174
|
+
|
|
175
|
+
export type AgentEventType = AgentEvent["type"];
|
|
176
|
+
|
|
177
|
+
/** Omit over a union collapses it to the shared keys, so distribute first. */
|
|
178
|
+
type DistributiveOmit<T, K extends keyof never> = T extends unknown ? Omit<T, K> : never;
|
|
179
|
+
|
|
180
|
+
/** An event without the fields the loop fills in for every one of them. */
|
|
181
|
+
export type AgentEventPayload = DistributiveOmit<AgentEvent, "runId" | "parentRunId" | "ts">;
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Every counter in `Usage`, in one place. Anything that walks the fields walks
|
|
185
|
+
* this list. A second hand-written list that misses a new counter drops it
|
|
186
|
+
* when a session is read back from disk.
|
|
187
|
+
*/
|
|
188
|
+
export const USAGE_KEYS = [
|
|
189
|
+
"inputTokens",
|
|
190
|
+
"noCacheTokens",
|
|
191
|
+
"outputTokens",
|
|
192
|
+
"totalTokens",
|
|
193
|
+
"cacheReadTokens",
|
|
194
|
+
"cacheWriteTokens",
|
|
195
|
+
"costMicros",
|
|
196
|
+
] as const satisfies readonly (keyof Usage)[];
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* The weakest source wins, and the empty accumulator is not a source: a
|
|
200
|
+
* mixture of provider and estimate figures degrades to "estimate".
|
|
201
|
+
*
|
|
202
|
+
* `costSource` stays out of `USAGE_KEYS`, because added there it would be
|
|
203
|
+
* summed like a number.
|
|
204
|
+
*/
|
|
205
|
+
function mergeCostSource(left?: CostSource, right?: CostSource): CostSource | undefined {
|
|
206
|
+
if (left === undefined) return right;
|
|
207
|
+
if (right === undefined) return left;
|
|
208
|
+
return left === "provider" && right === "provider" ? "provider" : "estimate";
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* The SDK's usage object, reduced to ours. Structural: no import from `ai`.
|
|
213
|
+
*
|
|
214
|
+
* Counters are copied, never computed: what the bill does when a provider omits
|
|
215
|
+
* `noCacheTokens` is `cost.ts`'s decision, and a number derived here would be
|
|
216
|
+
* indistinguishable from one the provider sent.
|
|
217
|
+
*/
|
|
218
|
+
export function normaliseUsage(usage: {
|
|
219
|
+
inputTokens?: number | undefined;
|
|
220
|
+
outputTokens?: number | undefined;
|
|
221
|
+
totalTokens?: number | undefined;
|
|
222
|
+
inputTokenDetails?:
|
|
223
|
+
| {
|
|
224
|
+
noCacheTokens?: number | undefined;
|
|
225
|
+
cacheReadTokens?: number | undefined;
|
|
226
|
+
cacheWriteTokens?: number | undefined;
|
|
227
|
+
}
|
|
228
|
+
| undefined;
|
|
229
|
+
}): Usage {
|
|
230
|
+
const result: Usage = {};
|
|
231
|
+
if (typeof usage.inputTokens === "number") result.inputTokens = usage.inputTokens;
|
|
232
|
+
if (typeof usage.outputTokens === "number") result.outputTokens = usage.outputTokens;
|
|
233
|
+
if (typeof usage.totalTokens === "number") result.totalTokens = usage.totalTokens;
|
|
234
|
+
|
|
235
|
+
const details = usage.inputTokenDetails;
|
|
236
|
+
if (typeof details?.noCacheTokens === "number") result.noCacheTokens = details.noCacheTokens;
|
|
237
|
+
if (typeof details?.cacheReadTokens === "number") {
|
|
238
|
+
result.cacheReadTokens = details.cacheReadTokens;
|
|
239
|
+
}
|
|
240
|
+
if (typeof details?.cacheWriteTokens === "number") {
|
|
241
|
+
result.cacheWriteTokens = details.cacheWriteTokens;
|
|
242
|
+
}
|
|
243
|
+
return result;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export function addUsage(left: Usage, right: Usage): Usage {
|
|
247
|
+
const total: Usage = {};
|
|
248
|
+
for (const key of USAGE_KEYS) {
|
|
249
|
+
const a = left[key];
|
|
250
|
+
const b = right[key];
|
|
251
|
+
if (a === undefined && b === undefined) continue;
|
|
252
|
+
total[key] = (a ?? 0) + (b ?? 0);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const source = mergeCostSource(left.costSource, right.costSource);
|
|
256
|
+
if (source !== undefined) total.costSource = source;
|
|
257
|
+
return total;
|
|
258
|
+
}
|