@runappsai/agent 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +162 -2
- package/dist/agent-core.umd.js +266 -0
- package/dist/agent.d.ts +222 -0
- package/dist/agent.js +1331 -0
- package/dist/agent.umd.js +732 -0
- package/dist/browser.d.ts +2 -0
- package/dist/browser.js +4 -0
- package/dist/chat-theme.d.ts +24 -0
- package/dist/chat-theme.js +101 -0
- package/dist/chat.d.ts +271 -0
- package/dist/chat.js +4097 -0
- package/dist/compaction.d.ts +48 -0
- package/dist/compaction.js +208 -0
- package/dist/completion.d.ts +29 -0
- package/dist/completion.js +88 -0
- package/dist/context.d.ts +44 -0
- package/dist/context.js +177 -0
- package/dist/debug-panel.d.ts +40 -0
- package/dist/debug-panel.js +262 -0
- package/dist/dialogs.d.ts +7 -0
- package/dist/dialogs.js +231 -0
- package/dist/directory-fs.d.ts +5 -0
- package/dist/directory-fs.js +118 -0
- package/dist/dom.d.ts +83 -0
- package/dist/dom.js +163 -0
- package/dist/edit.d.ts +22 -0
- package/dist/edit.js +133 -0
- package/dist/file-guard.d.ts +46 -0
- package/dist/file-guard.js +153 -0
- package/dist/file-tools.d.ts +16 -0
- package/dist/file-tools.js +339 -0
- package/dist/files-panel.d.ts +60 -0
- package/dist/files-panel.js +613 -0
- package/dist/index.cjs +4848 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +44 -0
- package/dist/json-schema.d.ts +3 -0
- package/dist/json-schema.js +141 -0
- package/dist/llm.d.ts +95 -0
- package/dist/llm.js +5 -0
- package/dist/markdown.d.ts +4 -0
- package/dist/markdown.js +265 -0
- package/dist/mcp.d.ts +82 -0
- package/dist/mcp.js +325 -0
- package/dist/node.cjs +402 -0
- package/dist/node.d.ts +78 -0
- package/dist/node.js +432 -0
- package/dist/pdf.d.ts +52 -0
- package/dist/pdf.js +77 -0
- package/dist/provider.d.ts +135 -0
- package/dist/provider.js +181 -0
- package/dist/sandbox.d.ts +33 -0
- package/dist/sandbox.js +219 -0
- package/dist/select.d.ts +30 -0
- package/dist/select.js +185 -0
- package/dist/skill-zips.d.ts +28 -0
- package/dist/skill-zips.js +123 -0
- package/dist/skills.d.ts +20 -0
- package/dist/skills.js +111 -0
- package/dist/templates.d.ts +24 -0
- package/dist/templates.js +136 -0
- package/dist/tool.d.ts +28 -0
- package/dist/tool.js +102 -0
- package/dist/types.d.ts +571 -0
- package/dist/types.js +7 -0
- package/dist/ui.cjs +6246 -0
- package/dist/ui.d.ts +6 -0
- package/dist/ui.js +11 -0
- package/dist/vlist.d.ts +80 -0
- package/dist/vlist.js +277 -0
- package/dist/workspace.d.ts +343 -0
- package/dist/workspace.js +1203 -0
- package/dist/zip.d.ts +26 -0
- package/dist/zip.js +204 -0
- package/docs/agent.md +228 -0
- package/docs/chat-ui.md +307 -0
- package/docs/node.md +135 -0
- package/docs/providers.md +176 -0
- package/docs/reference.md +143 -0
- package/docs/skills.md +131 -0
- package/docs/tools.md +254 -0
- package/docs/workspace.md +198 -0
- package/package.json +59 -4
package/dist/agent.js
ADDED
|
@@ -0,0 +1,1331 @@
|
|
|
1
|
+
// Agent: the model ↔ tool loop. One `prompt()` is a run; a run is turns
|
|
2
|
+
// of one model call each followed by that call's tool batch, until the
|
|
3
|
+
// model answers without tools (or the run is stopped). Everything the
|
|
4
|
+
// app shows comes through `on()` events; what the app owns (dialogs,
|
|
5
|
+
// files, skills, tools) comes in through the options.
|
|
6
|
+
import { errorStatus, modelAccepts, ProviderError, toProvider } from "./provider.js";
|
|
7
|
+
import { planCut, resolveSettings, serializeConversation, shouldCompact, splitForSummary, summaryMessage, summaryOf, summarizationMessages } from "./compaction.js";
|
|
8
|
+
import { collectCompletion } from "./completion.js";
|
|
9
|
+
import { buildSystemPrompt, estimateTokens, fitBudget } from "./context.js";
|
|
10
|
+
import { expandSlash } from "./templates.js";
|
|
11
|
+
import { fileTools } from "./file-tools.js";
|
|
12
|
+
import { validateSchema } from "./json-schema.js";
|
|
13
|
+
import { sandboxTool } from "./sandbox.js";
|
|
14
|
+
import { normalizeResult, textOf, toChatTool } from "./tool.js";
|
|
15
|
+
import { askUserTool, domUI } from "./dialogs.js";
|
|
16
|
+
import { fileGuard } from "./file-guard.js";
|
|
17
|
+
import { isMachineTitle, normalizePath, titleOf, UNTITLED } from "./workspace.js";
|
|
18
|
+
const DEFAULT_MAX_TURNS = 100;
|
|
19
|
+
const DEFAULT_MAX_TOKENS = 8192;
|
|
20
|
+
const DEFAULT_INPUT_TOKENS = 128_000;
|
|
21
|
+
const MEMORY_PATH = "/memory/notes.md";
|
|
22
|
+
const AGENTS_PATH = "/AGENTS.md";
|
|
23
|
+
const MAX_NOTES_CHARS = 6000;
|
|
24
|
+
const MAX_RETRIES = 3;
|
|
25
|
+
const LOOP_WARN = 3;
|
|
26
|
+
const LOOP_STOP = 6;
|
|
27
|
+
/**
|
|
28
|
+
* The message as the model sees it: without the chat's own bookkeeping
|
|
29
|
+
* (`ts`), and without the reasoning of turns before the latest user
|
|
30
|
+
* message — a thinking model needs it back only within the current tool
|
|
31
|
+
* loop (DeepSeek), and older reasoning is just tokens.
|
|
32
|
+
*/
|
|
33
|
+
function toWire(m, older) {
|
|
34
|
+
const meta = "ts" in m || "typed" in m || "runUsage" in m;
|
|
35
|
+
const dropReasoning = older && m.role === "assistant" && m.reasoning_content !== undefined;
|
|
36
|
+
if (!meta && !dropReasoning)
|
|
37
|
+
return m;
|
|
38
|
+
const { ts: _ts, typed: _typed, runUsage: _runUsage, ...rest } = m;
|
|
39
|
+
if (dropReasoning)
|
|
40
|
+
delete rest.reasoning_content;
|
|
41
|
+
return rest;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* A tool message may only carry text (OpenAI's format); pictures, audio or
|
|
45
|
+
* video a tool returned go to the model in a user message right after the
|
|
46
|
+
* batch's tool results, each named by the call it came from.
|
|
47
|
+
*/
|
|
48
|
+
function moveToolImages(messages) {
|
|
49
|
+
const hasMedia = (m) => m.role === "tool" && Array.isArray(m.content) && m.content.some((p) => p.type !== "text");
|
|
50
|
+
if (!messages.some(hasMedia))
|
|
51
|
+
return messages;
|
|
52
|
+
// Only the latest batches' media are sent again (each costs thousands of tokens); older ones are named.
|
|
53
|
+
// A batch is a run of tool messages; note where each one with media starts.
|
|
54
|
+
const starts = [];
|
|
55
|
+
let start = -1, counted = false;
|
|
56
|
+
messages.forEach((m, i) => {
|
|
57
|
+
if (m.role !== "tool") {
|
|
58
|
+
start = -1;
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if (start < 0) {
|
|
62
|
+
start = i;
|
|
63
|
+
counted = false;
|
|
64
|
+
}
|
|
65
|
+
if (!counted && hasMedia(m)) {
|
|
66
|
+
starts.push(start);
|
|
67
|
+
counted = true;
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
const keepFrom = starts.length > KEEP_TOOL_MEDIA_BATCHES ? starts[starts.length - KEEP_TOOL_MEDIA_BATCHES] : 0;
|
|
71
|
+
const out = [];
|
|
72
|
+
let carried = [];
|
|
73
|
+
const flush = () => {
|
|
74
|
+
if (carried.length)
|
|
75
|
+
out.push({ role: "user", content: carried });
|
|
76
|
+
carried = [];
|
|
77
|
+
};
|
|
78
|
+
for (const [i, m] of messages.entries()) {
|
|
79
|
+
if (m.role !== "tool")
|
|
80
|
+
flush();
|
|
81
|
+
if (hasMedia(m)) {
|
|
82
|
+
const parts = m.content;
|
|
83
|
+
const media = parts.filter((p) => p.type !== "text");
|
|
84
|
+
const text = parts.filter((p) => p.type === "text").map((p) => p.text).join("\n");
|
|
85
|
+
const n = `${media.length} attachment${media.length === 1 ? "" : "s"}`;
|
|
86
|
+
if (i < keepFrom) {
|
|
87
|
+
out.push({ ...m, content: `${text}${text ? "\n" : ""}[${n} no longer shown; call the tool again to see the current state]` });
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
out.push({ ...m, content: `${text}${text ? "\n" : ""}[${n} follow${media.length === 1 ? "s" : ""} in the next message]` });
|
|
91
|
+
carried.push({ type: "text", text: `Attachments from tool call ${m.tool_call_id ?? ""}:`.trim() }, ...media);
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
out.push(m);
|
|
95
|
+
}
|
|
96
|
+
flush();
|
|
97
|
+
return out;
|
|
98
|
+
}
|
|
99
|
+
const KEEP_TOOL_MEDIA_BATCHES = 2;
|
|
100
|
+
const MEDIA_PART = { image: "image_url", video: "video_url", audio: "audio_url" };
|
|
101
|
+
const MEDIA_NAME = { image: "picture", video: "video", audio: "audio clip" };
|
|
102
|
+
/** Pictures (video, audio) the model is known not to take are replaced by a line saying one was there. */
|
|
103
|
+
function withoutMedia(messages, media, model) {
|
|
104
|
+
const refused = Object.keys(MEDIA_PART).filter((k) => media[k] === false);
|
|
105
|
+
if (!refused.length)
|
|
106
|
+
return messages;
|
|
107
|
+
const kindOf = (p) => refused.find((k) => MEDIA_PART[k] === p.type);
|
|
108
|
+
return messages.map((m) => {
|
|
109
|
+
if (!Array.isArray(m.content) || !m.content.some((p) => kindOf(p)))
|
|
110
|
+
return m;
|
|
111
|
+
const content = m.content.map((p) => {
|
|
112
|
+
const k = kindOf(p);
|
|
113
|
+
return k ? { type: "text", text: `[A ${MEDIA_NAME[k]} was attached here; the model in use${model ? ` (${model})` : ""} does not take ${MEDIA_NAME[k]}s, so it is not shown. Say so if it matters.]` } : p;
|
|
114
|
+
});
|
|
115
|
+
return { ...m, content };
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
const emptyUsage = () => ({ total_cost: 0, prompt_tokens: 0, completion_tokens: 0, calls: 0 });
|
|
119
|
+
const abortedResult = () => ({ runId: "", reason: "aborted", text: "", usage: emptyUsage() });
|
|
120
|
+
const SKIPPED_STOP = "Skipped: the user stopped the run.";
|
|
121
|
+
const balanceError = () => new ProviderError(402, "The reply was cut short because the balance could not cover a full answer; top up to continue", { code: "insufficient_balance" });
|
|
122
|
+
/** Settles with `p`, or rejects as soon as `signal` aborts (the work itself may go on; its result is ignored). */
|
|
123
|
+
function raceAbort(p, signal) {
|
|
124
|
+
if (signal.aborted) {
|
|
125
|
+
// The work may still fail (it may even be what aborted): its result is ignored, and so is its error.
|
|
126
|
+
p.catch(() => undefined);
|
|
127
|
+
return Promise.reject(signal.reason ?? new Error("aborted"));
|
|
128
|
+
}
|
|
129
|
+
return new Promise((resolve, reject) => {
|
|
130
|
+
const onAbort = () => reject(signal.reason ?? new Error("aborted"));
|
|
131
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
132
|
+
p.then((v) => { signal.removeEventListener("abort", onAbort); resolve(v); }, (e) => { signal.removeEventListener("abort", onAbort); reject(e); });
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
export class Agent {
|
|
136
|
+
id;
|
|
137
|
+
/** Where the model calls go. */
|
|
138
|
+
provider;
|
|
139
|
+
ui;
|
|
140
|
+
workspace;
|
|
141
|
+
tools;
|
|
142
|
+
opts;
|
|
143
|
+
history = [];
|
|
144
|
+
committed = 0;
|
|
145
|
+
droppedTurns = 0;
|
|
146
|
+
_usage = emptyUsage();
|
|
147
|
+
handlers = new Map();
|
|
148
|
+
anyHandlers = new Set();
|
|
149
|
+
queue = [];
|
|
150
|
+
current = null;
|
|
151
|
+
chain = Promise.resolve();
|
|
152
|
+
pendingSkills = [];
|
|
153
|
+
/** The catalogue's entry for the model in use (undefined: not listed, or no catalogue); asked once per model. */
|
|
154
|
+
catalogue = null;
|
|
155
|
+
/** The guard against calls that go nowhere: results seen since the last change, rounds in a row without anything new. */
|
|
156
|
+
loop = { seen: new Set(), idle: 0, warned: false };
|
|
157
|
+
/** The turn of the running run (0 outside one), for events of calls made outside the turn's own request. */
|
|
158
|
+
turnNow = 0;
|
|
159
|
+
loaded;
|
|
160
|
+
createdAt = Date.now();
|
|
161
|
+
/** The session's title, fixed once known (a later compaction must not turn it into the summary's first words). */
|
|
162
|
+
title;
|
|
163
|
+
_ended = null;
|
|
164
|
+
persist;
|
|
165
|
+
/** `provider`: a ModelProvider, or a RunApps SDK client (wrapped in runappsProvider). */
|
|
166
|
+
constructor(provider, opts = {}) {
|
|
167
|
+
this.provider = toProvider(provider);
|
|
168
|
+
this.opts = opts;
|
|
169
|
+
this.id = opts.id || `agent_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
|
|
170
|
+
this.ui = opts.ui ?? domUI();
|
|
171
|
+
this.workspace = opts.workspace ?? null;
|
|
172
|
+
const tools = [...(opts.tools ?? [])];
|
|
173
|
+
// What the model has read, for the file tools and run_js alike; forgotten when the conversation is compacted or rewound.
|
|
174
|
+
const guard = this.workspace ? fileGuard(this.workspace, { enabled: opts.readBeforeWrite !== false }) : undefined;
|
|
175
|
+
if (guard) {
|
|
176
|
+
const sync = () => guard.retain(this.filesInView());
|
|
177
|
+
this.on("compaction", sync);
|
|
178
|
+
this.on("rewind", sync);
|
|
179
|
+
}
|
|
180
|
+
if (this.workspace && opts.fileTools !== false) {
|
|
181
|
+
const want = Array.isArray(opts.fileTools) ? new Set(opts.fileTools) : null;
|
|
182
|
+
tools.push(...fileTools(this.workspace, { guard }).filter((t) => !want || want.has(t.name)));
|
|
183
|
+
}
|
|
184
|
+
if (opts.askUser !== false)
|
|
185
|
+
tools.push(askUserTool());
|
|
186
|
+
if (opts.sandbox !== false)
|
|
187
|
+
tools.push(sandboxTool(this.workspace, { ...(typeof opts.sandbox === "object" ? opts.sandbox : {}), guard }));
|
|
188
|
+
const seen = new Set();
|
|
189
|
+
for (const t of tools) {
|
|
190
|
+
if (seen.has(t.name))
|
|
191
|
+
throw new Error(`two tools are named "${t.name}"`);
|
|
192
|
+
seen.add(t.name);
|
|
193
|
+
}
|
|
194
|
+
this.tools = tools;
|
|
195
|
+
if (opts.serverTools?.length && (opts.tools?.length || this.workspace || opts.sandbox !== false || opts.askUser !== false)) {
|
|
196
|
+
throw new Error("serverTools work only for an agent with no tools of its own (tools: [], workspace: null, sandbox: false, askUser: false) — the gateway runs that loop");
|
|
197
|
+
}
|
|
198
|
+
this.persist = !!this.workspace && opts.persist !== false;
|
|
199
|
+
if (opts.restore) {
|
|
200
|
+
this.applySession(opts.restore);
|
|
201
|
+
this.loaded = Promise.resolve();
|
|
202
|
+
}
|
|
203
|
+
else if (this.persist && opts.id) {
|
|
204
|
+
// An id names a session: continue it when the workspace has one.
|
|
205
|
+
this.loaded = this.workspace.sessions.get(opts.id).then((saved) => {
|
|
206
|
+
if (saved)
|
|
207
|
+
this.applySession(saved);
|
|
208
|
+
}).catch((err) => {
|
|
209
|
+
// Saving now would overwrite a session we could not read: stay in memory only.
|
|
210
|
+
this.persist = false;
|
|
211
|
+
console.warn(`agent: could not load session ${opts.id}; it will not be saved over`, err);
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
this.loaded = Promise.resolve();
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
applySession(data) {
|
|
219
|
+
if (data.v !== 1 && data.v !== 2)
|
|
220
|
+
throw new Error("unknown session format");
|
|
221
|
+
this.history = data.messages.slice();
|
|
222
|
+
this.committed = this.history.length;
|
|
223
|
+
this.droppedTurns = data.droppedTurns ?? 0;
|
|
224
|
+
this._usage = { ...data.usage };
|
|
225
|
+
this.createdAt = data.createdAt ?? data.savedAt ?? Date.now();
|
|
226
|
+
this._ended = data.ended ?? null;
|
|
227
|
+
// Titles saved before titleOf skipped summaries and expanded commands are worked out again.
|
|
228
|
+
this.title = data.title && !isMachineTitle(data.title) ? data.title : undefined;
|
|
229
|
+
if (data.model && !this.opts.model) {
|
|
230
|
+
this.opts.model = data.model;
|
|
231
|
+
this.catalogue = null;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
/** Resolves once a saved session (if any) has been loaded. */
|
|
235
|
+
ready() {
|
|
236
|
+
return this.loaded;
|
|
237
|
+
}
|
|
238
|
+
async saveSession() {
|
|
239
|
+
if (!this.persist || !this.workspace)
|
|
240
|
+
return;
|
|
241
|
+
try {
|
|
242
|
+
await this.workspace.sessions.save(this.export());
|
|
243
|
+
this.emit("session_saved", { id: this.id });
|
|
244
|
+
}
|
|
245
|
+
catch (err) {
|
|
246
|
+
console.warn("[agent] could not save the session:", err);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
on(name, handler) {
|
|
250
|
+
if (name === "*") {
|
|
251
|
+
this.anyHandlers.add(handler);
|
|
252
|
+
return () => { this.anyHandlers.delete(handler); };
|
|
253
|
+
}
|
|
254
|
+
let set = this.handlers.get(name);
|
|
255
|
+
if (!set) {
|
|
256
|
+
set = new Set();
|
|
257
|
+
this.handlers.set(name, set);
|
|
258
|
+
}
|
|
259
|
+
set.add(handler);
|
|
260
|
+
return () => { this.handlers.get(name)?.delete(handler); };
|
|
261
|
+
}
|
|
262
|
+
emit(name, event) {
|
|
263
|
+
for (const h of this.handlers.get(name) ?? []) {
|
|
264
|
+
try {
|
|
265
|
+
h(event);
|
|
266
|
+
}
|
|
267
|
+
catch (err) {
|
|
268
|
+
console.error("[agent] listener for", name, "threw:", err);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
for (const h of this.anyHandlers) {
|
|
272
|
+
try {
|
|
273
|
+
h(name, event);
|
|
274
|
+
}
|
|
275
|
+
catch (err) {
|
|
276
|
+
console.error("[agent] listener threw:", err);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
/* ---------------- state ---------------- */
|
|
281
|
+
/** The transcript (a copy), without the system prompt. */
|
|
282
|
+
get messages() {
|
|
283
|
+
return this.history.slice();
|
|
284
|
+
}
|
|
285
|
+
get usage() {
|
|
286
|
+
return { ...this._usage };
|
|
287
|
+
}
|
|
288
|
+
/** How the last run ended when it did not finish (stopped, turn limit, error) — kept with the session until another run starts. */
|
|
289
|
+
get lastEnd() {
|
|
290
|
+
return this._ended;
|
|
291
|
+
}
|
|
292
|
+
get busy() {
|
|
293
|
+
return this.current !== null;
|
|
294
|
+
}
|
|
295
|
+
get model() {
|
|
296
|
+
return this.opts.model;
|
|
297
|
+
}
|
|
298
|
+
set model(name) {
|
|
299
|
+
this.opts.model = name;
|
|
300
|
+
this.catalogue = null;
|
|
301
|
+
}
|
|
302
|
+
/** The settings a user may change mid-conversation. */
|
|
303
|
+
get settings() {
|
|
304
|
+
const p = this.opts.permissions ?? "ask";
|
|
305
|
+
const re = this.opts.extra?.reasoning_effort;
|
|
306
|
+
return { model: this.opts.model, maxTurns: this.opts.maxTurns ?? DEFAULT_MAX_TURNS, maxTokens: typeof this.opts.maxTokens === "number" ? this.opts.maxTokens : "auto", permissions: typeof p === "function" ? "custom" : p, reasoningEffort: typeof re === "string" ? re : undefined };
|
|
307
|
+
}
|
|
308
|
+
/** Changes settings for the runs that follow (a run in progress keeps its own). `undefined` leaves a field alone; `reasoningEffort: null` takes the model's default. */
|
|
309
|
+
configure(patch) {
|
|
310
|
+
if ("model" in patch)
|
|
311
|
+
this.model = patch.model || undefined;
|
|
312
|
+
if ("reasoningEffort" in patch) {
|
|
313
|
+
const extra = { ...(this.opts.extra ?? {}) };
|
|
314
|
+
if (patch.reasoningEffort)
|
|
315
|
+
extra.reasoning_effort = patch.reasoningEffort;
|
|
316
|
+
else
|
|
317
|
+
delete extra.reasoning_effort;
|
|
318
|
+
this.opts.extra = extra;
|
|
319
|
+
}
|
|
320
|
+
if (typeof patch.maxTurns === "number" && patch.maxTurns > 0)
|
|
321
|
+
this.opts.maxTurns = Math.floor(patch.maxTurns);
|
|
322
|
+
if (patch.maxTokens !== undefined)
|
|
323
|
+
this.opts.maxTokens = patch.maxTokens;
|
|
324
|
+
if (patch.permissions !== undefined)
|
|
325
|
+
this.opts.permissions = patch.permissions;
|
|
326
|
+
}
|
|
327
|
+
/** A snapshot to save (`restore` continues it). Taken at the last complete turn. */
|
|
328
|
+
export() {
|
|
329
|
+
const messages = this.history.slice(0, this.committed);
|
|
330
|
+
const data = {
|
|
331
|
+
v: 2,
|
|
332
|
+
id: this.id,
|
|
333
|
+
model: this.opts.model,
|
|
334
|
+
messages,
|
|
335
|
+
usage: { ...this._usage },
|
|
336
|
+
droppedTurns: this.droppedTurns,
|
|
337
|
+
createdAt: this.createdAt,
|
|
338
|
+
savedAt: Date.now(),
|
|
339
|
+
...(this._ended ? { ended: this._ended } : {}),
|
|
340
|
+
};
|
|
341
|
+
if (!this.title) {
|
|
342
|
+
const tt = titleOf(data);
|
|
343
|
+
if (tt !== UNTITLED)
|
|
344
|
+
this.title = tt;
|
|
345
|
+
}
|
|
346
|
+
data.title = this.title ?? UNTITLED;
|
|
347
|
+
return data;
|
|
348
|
+
}
|
|
349
|
+
/** Forgets the conversation (the workspace stays). */
|
|
350
|
+
reset() {
|
|
351
|
+
if (this.current)
|
|
352
|
+
throw new Error("cannot reset while a run is active; abort() first");
|
|
353
|
+
this.history = [];
|
|
354
|
+
this.title = undefined;
|
|
355
|
+
this._ended = null;
|
|
356
|
+
this.committed = 0;
|
|
357
|
+
this.droppedTurns = 0;
|
|
358
|
+
this.resetLoop();
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Loads a skill for the next prompt: its instructions are placed before
|
|
362
|
+
* the user's message, as if the user had asked for that skill.
|
|
363
|
+
*/
|
|
364
|
+
useSkill(name) {
|
|
365
|
+
if (!this.workspace)
|
|
366
|
+
throw new Error("useSkill needs a workspace");
|
|
367
|
+
this.pendingSkills.push(name);
|
|
368
|
+
}
|
|
369
|
+
/* ---------------- input ---------------- */
|
|
370
|
+
/**
|
|
371
|
+
* Sends a user message and runs until the model answers. While a run is
|
|
372
|
+
* active the message is queued as a follow-up (same as `followUp`).
|
|
373
|
+
*/
|
|
374
|
+
prompt(content, init = {}) {
|
|
375
|
+
const message = this.userMessage(content);
|
|
376
|
+
if (this.current)
|
|
377
|
+
return this.enqueue("followUp", message);
|
|
378
|
+
return this.start(message, init.signal);
|
|
379
|
+
}
|
|
380
|
+
/** Adds guidance that the model sees after the current tool batch; queued when idle like `prompt`. */
|
|
381
|
+
steer(content) {
|
|
382
|
+
const message = this.userMessage(content);
|
|
383
|
+
if (!this.current)
|
|
384
|
+
return this.start(message);
|
|
385
|
+
this.queue.push({ kind: "steer", message });
|
|
386
|
+
this.emit("queued", { kind: "steer", message });
|
|
387
|
+
}
|
|
388
|
+
/** Runs after the current run has finished. */
|
|
389
|
+
followUp(content) {
|
|
390
|
+
const message = this.userMessage(content);
|
|
391
|
+
if (!this.current)
|
|
392
|
+
return this.start(message);
|
|
393
|
+
return this.enqueue("followUp", message);
|
|
394
|
+
}
|
|
395
|
+
/** What waits for the current run: steering (joins the next turn) and follow-ups (run after it). */
|
|
396
|
+
get queued() {
|
|
397
|
+
return this.queue.map((q) => ({ kind: q.kind, message: q.message }));
|
|
398
|
+
}
|
|
399
|
+
/** Drops one queued message (by the object `queued` lists); a waiting `followUp()` resolves as aborted. */
|
|
400
|
+
dequeue(message) {
|
|
401
|
+
const q = this.queue.find((q) => q.message === message);
|
|
402
|
+
if (!q)
|
|
403
|
+
return false;
|
|
404
|
+
this.queue = this.queue.filter((x) => x !== q);
|
|
405
|
+
q.resolve?.(abortedResult());
|
|
406
|
+
return true;
|
|
407
|
+
}
|
|
408
|
+
/** Drops everything queued; a waiting `followUp()` resolves as aborted. */
|
|
409
|
+
clearQueue() {
|
|
410
|
+
const dropped = this.queue;
|
|
411
|
+
this.queue = [];
|
|
412
|
+
for (const q of dropped)
|
|
413
|
+
q.resolve?.(abortedResult());
|
|
414
|
+
}
|
|
415
|
+
/** Stops the current run (pending tool calls get a "skipped" result) and drops the queue. */
|
|
416
|
+
async abort() {
|
|
417
|
+
this.clearQueue();
|
|
418
|
+
const cur = this.current;
|
|
419
|
+
if (!cur)
|
|
420
|
+
return;
|
|
421
|
+
cur.controller.abort();
|
|
422
|
+
await cur.promise.catch(() => undefined);
|
|
423
|
+
}
|
|
424
|
+
enqueue(kind, message) {
|
|
425
|
+
return new Promise((resolve) => {
|
|
426
|
+
this.queue.push({ kind, message, resolve });
|
|
427
|
+
this.emit("queued", { kind, message });
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
userMessage(content) {
|
|
431
|
+
const parts = typeof content === "string" ? [{ type: "text", text: content }] : content.slice();
|
|
432
|
+
// `ts` (when it was sent) rides along in the saved session and is stripped before the model sees it.
|
|
433
|
+
return { role: "user", content: parts.length === 1 && parts[0].type === "text" ? parts[0].text : parts, ts: Date.now() };
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* Goes back to before message `index` (as in `messages`): later messages
|
|
437
|
+
* are dropped and the session saved. The caller re-sends or edits the
|
|
438
|
+
* message. Not while a run is active.
|
|
439
|
+
*/
|
|
440
|
+
async rewind(index) {
|
|
441
|
+
await this.loaded;
|
|
442
|
+
if (this.current)
|
|
443
|
+
throw new Error("cannot rewind while a run is active; abort() first");
|
|
444
|
+
if (!Number.isInteger(index) || index < 0 || index > this.history.length)
|
|
445
|
+
throw new Error(`no message at ${index}`);
|
|
446
|
+
this.clearQueue();
|
|
447
|
+
this.history = this.history.slice(0, index);
|
|
448
|
+
this.committed = this.history.length;
|
|
449
|
+
this._ended = null;
|
|
450
|
+
this.resetLoop();
|
|
451
|
+
await this.saveSession();
|
|
452
|
+
this.emit("rewind", { index });
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Deletes messages `start` to `end` (exclusive; default the end) — a
|
|
456
|
+
* question and its answer, say — and saves. Delete whole turns (from a
|
|
457
|
+
* user message to the next one), so every tool call keeps its result.
|
|
458
|
+
* Listeners get a `rewind` event with index `start`.
|
|
459
|
+
*/
|
|
460
|
+
async remove(start, end = this.history.length) {
|
|
461
|
+
await this.loaded;
|
|
462
|
+
if (this.current)
|
|
463
|
+
throw new Error("Cannot delete messages while a run is active; abort() first");
|
|
464
|
+
if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end > this.history.length || start >= end)
|
|
465
|
+
throw new Error(`No messages ${start}–${end}`);
|
|
466
|
+
this.clearQueue();
|
|
467
|
+
this.history.splice(start, end - start);
|
|
468
|
+
this.committed = this.history.length;
|
|
469
|
+
this._ended = null;
|
|
470
|
+
this.resetLoop();
|
|
471
|
+
await this.saveSession();
|
|
472
|
+
this.emit("rewind", { index: start });
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* Starts the conversation over, keeping its id: stops a run, drops the
|
|
476
|
+
* queue, the messages, the title, how the last run ended and the usage,
|
|
477
|
+
* and saves that. The workspace's files are not touched. Listeners get a
|
|
478
|
+
* `rewind` event with index 0.
|
|
479
|
+
*/
|
|
480
|
+
async clear() {
|
|
481
|
+
await this.loaded;
|
|
482
|
+
await this.abort();
|
|
483
|
+
this.reset();
|
|
484
|
+
this._usage = emptyUsage();
|
|
485
|
+
await this.saveSession();
|
|
486
|
+
this.emit("rewind", { index: 0 });
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Picks the conversation up where it stopped — after a turn limit, an
|
|
490
|
+
* error or a stop — with no new user message and a fresh turn count
|
|
491
|
+
* (pi's `agent.continue()`). The model is called on the history as it
|
|
492
|
+
* is. Not while a run is active; nothing to continue is an error.
|
|
493
|
+
*/
|
|
494
|
+
async continue() {
|
|
495
|
+
await this.loaded;
|
|
496
|
+
if (this.current)
|
|
497
|
+
throw new Error("cannot continue while a run is active");
|
|
498
|
+
if (!this.history.length)
|
|
499
|
+
throw new Error("nothing to continue");
|
|
500
|
+
return this.start(null);
|
|
501
|
+
}
|
|
502
|
+
start(message, signal) {
|
|
503
|
+
const controller = new AbortController();
|
|
504
|
+
if (signal) {
|
|
505
|
+
if (signal.aborted)
|
|
506
|
+
controller.abort();
|
|
507
|
+
else
|
|
508
|
+
signal.addEventListener("abort", () => controller.abort(), { once: true });
|
|
509
|
+
}
|
|
510
|
+
const promise = this.chain.then(() => this.run(message, controller)).finally(() => {
|
|
511
|
+
if (this.current?.controller === controller)
|
|
512
|
+
this.current = null;
|
|
513
|
+
this.drainFollowUps();
|
|
514
|
+
});
|
|
515
|
+
this.current = { controller, promise };
|
|
516
|
+
this.chain = promise.catch(() => undefined);
|
|
517
|
+
return promise;
|
|
518
|
+
}
|
|
519
|
+
drainFollowUps() {
|
|
520
|
+
const next = this.queue.find((q) => q.kind === "followUp");
|
|
521
|
+
if (!next)
|
|
522
|
+
return;
|
|
523
|
+
this.queue = this.queue.filter((q) => q !== next);
|
|
524
|
+
this.start(next.message).then((r) => next.resolve?.(r), (err) => next.resolve?.({ ...abortedResult(), reason: "error", error: err instanceof Error ? err : new Error(String(err)) }));
|
|
525
|
+
}
|
|
526
|
+
/* ---------------- the loop ---------------- */
|
|
527
|
+
async run(message, controller) {
|
|
528
|
+
await this.loaded;
|
|
529
|
+
const runId = `run_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`;
|
|
530
|
+
const signal = controller.signal;
|
|
531
|
+
let reason = "done";
|
|
532
|
+
let error;
|
|
533
|
+
let lastText = "";
|
|
534
|
+
let truncatedRounds = 0;
|
|
535
|
+
// What this run spends (calls, compaction included): put on its last reply when it ends.
|
|
536
|
+
const usageBefore = { ...this._usage };
|
|
537
|
+
const historyBefore = this.history.length;
|
|
538
|
+
// Steering left over from a run that ended (turn limit, error) goes in before the new message, in the order it was typed.
|
|
539
|
+
this.applySteering(runId);
|
|
540
|
+
let prefaced = null;
|
|
541
|
+
let prefaceError;
|
|
542
|
+
if (message) {
|
|
543
|
+
try {
|
|
544
|
+
prefaced = await this.withSkillPrefaces(await this.expandSlashes(message));
|
|
545
|
+
}
|
|
546
|
+
catch (err) {
|
|
547
|
+
prefaced = message;
|
|
548
|
+
prefaceError = err instanceof Error ? err : new Error(String(err));
|
|
549
|
+
}
|
|
550
|
+
this.history.push(prefaced);
|
|
551
|
+
}
|
|
552
|
+
this._ended = null;
|
|
553
|
+
this.emit("run_start", { runId, message: prefaced });
|
|
554
|
+
const maxTurns = this.opts.maxTurns ?? DEFAULT_MAX_TURNS;
|
|
555
|
+
const { output: maxTokens, input: window } = await this.limits();
|
|
556
|
+
const compaction = resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {});
|
|
557
|
+
try {
|
|
558
|
+
if (prefaceError)
|
|
559
|
+
throw prefaceError;
|
|
560
|
+
for (let turn = 1;; turn++) {
|
|
561
|
+
if (signal.aborted) {
|
|
562
|
+
reason = "aborted";
|
|
563
|
+
break;
|
|
564
|
+
}
|
|
565
|
+
if (turn > maxTurns) {
|
|
566
|
+
reason = "max_turns";
|
|
567
|
+
break;
|
|
568
|
+
}
|
|
569
|
+
this.turnNow = turn;
|
|
570
|
+
this.emit("turn_start", { runId, turn });
|
|
571
|
+
// Steering arrives between tool batches.
|
|
572
|
+
this.applySteering(runId);
|
|
573
|
+
const system = await this.systemPrompt();
|
|
574
|
+
// What every request carries besides the transcript: the system prompt and the tools' schemas.
|
|
575
|
+
const fixed = this.fixedText(system);
|
|
576
|
+
// Context management, pi-style: summarise older turns when the
|
|
577
|
+
// window is nearly full; elide/drop as the fallback.
|
|
578
|
+
const tokensBefore = estimateTokens(this.history, fixed);
|
|
579
|
+
if (shouldCompact(tokensBefore, window, compaction)) {
|
|
580
|
+
const summarized = this.opts.compaction === false ? false : await this.compactWith(compaction, runId, signal);
|
|
581
|
+
const after = estimateTokens(this.history, fixed);
|
|
582
|
+
if (!summarized || shouldCompact(after, window, compaction)) {
|
|
583
|
+
// Trim, keeping a compaction summary at the front pinned: it
|
|
584
|
+
// is the memory of everything already dropped.
|
|
585
|
+
const pinned = this.history.length && summaryOf(this.history[0]) !== null ? [this.history[0]] : [];
|
|
586
|
+
const rest = this.history.slice(pinned.length);
|
|
587
|
+
const fit = fitBudget(rest, { budget: window - compaction.reserveTokens - estimateTokens(pinned), keepTurns: this.opts.keepTurns ?? 4, system: fixed });
|
|
588
|
+
if (fit.droppedTurns || fit.elidedResults) {
|
|
589
|
+
this.history = [...pinned, ...fit.messages];
|
|
590
|
+
this.droppedTurns += fit.droppedTurns;
|
|
591
|
+
this.committed = Math.min(this.committed, this.history.length);
|
|
592
|
+
this.emit("compaction", { runId, summary: false, tokensBefore: after, tokensAfter: estimateTokens(this.history, fixed), droppedTurns: fit.droppedTurns, elidedResults: fit.elidedResults });
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
const tools = await this.activeTools();
|
|
597
|
+
const params = {
|
|
598
|
+
...(this.opts.extra ?? {}),
|
|
599
|
+
model: this.opts.model ?? "",
|
|
600
|
+
messages: [{ role: "system", content: system }, ...this.toWireHistory(await this.mediaSupport())],
|
|
601
|
+
max_tokens: maxTokens,
|
|
602
|
+
};
|
|
603
|
+
if (!params.model)
|
|
604
|
+
delete params.model;
|
|
605
|
+
if (tools.length)
|
|
606
|
+
params.tools = tools.map((t) => toChatTool(t));
|
|
607
|
+
if (this.opts.serverTools?.length)
|
|
608
|
+
params.server_tools = this.opts.serverTools;
|
|
609
|
+
if (this.opts.prompt)
|
|
610
|
+
params.prompt = this.opts.prompt;
|
|
611
|
+
if (this.opts.temperature !== undefined)
|
|
612
|
+
params.temperature = this.opts.temperature;
|
|
613
|
+
if (this.opts.top_p !== undefined)
|
|
614
|
+
params.top_p = this.opts.top_p;
|
|
615
|
+
// For debugging views: what went to the model and what came back.
|
|
616
|
+
this.emit("request", { runId, turn, params });
|
|
617
|
+
const asked = Date.now();
|
|
618
|
+
let completion;
|
|
619
|
+
try {
|
|
620
|
+
completion = await this.callModel(params, runId, signal);
|
|
621
|
+
}
|
|
622
|
+
catch (err) {
|
|
623
|
+
this.emit("response", { runId, turn, durationMs: Date.now() - asked, error: err instanceof Error ? err.message : String(err) });
|
|
624
|
+
throw err;
|
|
625
|
+
}
|
|
626
|
+
this.emit("response", { runId, turn, durationMs: Date.now() - asked, finishReason: completion.finishReason, usage: completion.usage, message: completion.message });
|
|
627
|
+
if (completion.usage)
|
|
628
|
+
this.addUsage(completion.usage);
|
|
629
|
+
// `ts` (when it ended) lets a transcript say how long a reply worked; requests never carry it.
|
|
630
|
+
const assistant = { role: "assistant", content: completion.message.content, ts: Date.now() };
|
|
631
|
+
if (completion.message.tool_calls?.length)
|
|
632
|
+
assistant.tool_calls = completion.message.tool_calls;
|
|
633
|
+
// A thinking model's reasoning stays with the turn: DeepSeek in thinking mode wants it back on tool-calling turns, and the transcript shows it.
|
|
634
|
+
if (completion.reasoning)
|
|
635
|
+
assistant.reasoning_content = completion.reasoning;
|
|
636
|
+
this.history.push(assistant);
|
|
637
|
+
if (typeof assistant.content === "string" && assistant.content)
|
|
638
|
+
lastText = assistant.content;
|
|
639
|
+
const truncated = completion.finishReason === "length";
|
|
640
|
+
this.emit("message_end", { runId, message: assistant, truncated });
|
|
641
|
+
this.emit("turn_end", { runId, turn, usage: completion.usage });
|
|
642
|
+
const calls = assistant.tool_calls ?? [];
|
|
643
|
+
if (!calls.length) {
|
|
644
|
+
this.committed = this.history.length;
|
|
645
|
+
await this.saveSession();
|
|
646
|
+
if (truncated && this.balanceLimited(completion.usage, maxTokens)) {
|
|
647
|
+
reason = "error";
|
|
648
|
+
error = balanceError();
|
|
649
|
+
break;
|
|
650
|
+
}
|
|
651
|
+
// pi: steering that arrived during the final reply still gets its turn.
|
|
652
|
+
if (!signal.aborted && this.queue.some((q) => q.kind === "steer"))
|
|
653
|
+
continue;
|
|
654
|
+
break;
|
|
655
|
+
}
|
|
656
|
+
const results = await this.runBatch(calls, runId, signal, truncated);
|
|
657
|
+
this.committed = this.history.length;
|
|
658
|
+
await this.saveSession();
|
|
659
|
+
if (signal.aborted) {
|
|
660
|
+
reason = "aborted";
|
|
661
|
+
break;
|
|
662
|
+
}
|
|
663
|
+
// A reply that said its piece and called only tools that end the run (endsRun): done, no further call.
|
|
664
|
+
if (!truncated && textOf(assistant.content).trim() && calls.every((c) => this.tools.find((x) => x.name === c.function.name)?.endsRun)) {
|
|
665
|
+
if (this.queue.some((q) => q.kind === "steer"))
|
|
666
|
+
continue;
|
|
667
|
+
break;
|
|
668
|
+
}
|
|
669
|
+
if (truncated) {
|
|
670
|
+
truncatedRounds++;
|
|
671
|
+
if (this.balanceLimited(completion.usage, maxTokens)) {
|
|
672
|
+
reason = "error";
|
|
673
|
+
error = balanceError();
|
|
674
|
+
break;
|
|
675
|
+
}
|
|
676
|
+
if (truncatedRounds >= 2) {
|
|
677
|
+
reason = "error";
|
|
678
|
+
error = new Error("the model's tool calls were cut off by the output limit twice in a row");
|
|
679
|
+
break;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
const guard = this.checkLoop(results);
|
|
683
|
+
if (guard === "stop") {
|
|
684
|
+
reason = "error";
|
|
685
|
+
error = new Error("stopped after several rounds of tool calls that brought nothing new (the same results, or lines already read)");
|
|
686
|
+
break;
|
|
687
|
+
}
|
|
688
|
+
if (guard === "warn") {
|
|
689
|
+
this.history.push({
|
|
690
|
+
role: "user",
|
|
691
|
+
content: "[environment] The last rounds of tool calls brought nothing new: the same results, the same errors, or parts of files you had already read. Do not repeat them. Use what you have already read (it is above), read only what is still missing, take a different approach, or explain the blocker and finish.",
|
|
692
|
+
});
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
catch (err) {
|
|
697
|
+
if (signal.aborted)
|
|
698
|
+
reason = "aborted";
|
|
699
|
+
else {
|
|
700
|
+
reason = "error";
|
|
701
|
+
error = err instanceof Error ? err : new Error(String(err));
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
if (reason === "aborted")
|
|
705
|
+
this.closeOpenToolCalls();
|
|
706
|
+
this.markRunUsage(historyBefore, usageBefore);
|
|
707
|
+
this.committed = this.history.length;
|
|
708
|
+
this.resetLoop();
|
|
709
|
+
this._ended = reason === "done" ? null : { reason, ...(error ? { error: error.message } : {}), at: Date.now() };
|
|
710
|
+
await this.saveSession();
|
|
711
|
+
const result = {
|
|
712
|
+
runId,
|
|
713
|
+
reason,
|
|
714
|
+
text: lastText,
|
|
715
|
+
usage: this.usage,
|
|
716
|
+
...(error ? { error } : {}),
|
|
717
|
+
};
|
|
718
|
+
this.emit("run_end", result);
|
|
719
|
+
return result;
|
|
720
|
+
}
|
|
721
|
+
/** Moves queued steering into the history and says so (`steered`), so a UI draws each message once, when it lands. */
|
|
722
|
+
applySteering(runId) {
|
|
723
|
+
const steer = this.queue.filter((q) => q.kind === "steer").map((q) => q.message);
|
|
724
|
+
if (!steer.length)
|
|
725
|
+
return;
|
|
726
|
+
this.queue = this.queue.filter((q) => q.kind !== "steer");
|
|
727
|
+
this.history.push(...steer);
|
|
728
|
+
// New words from the user: whatever the guard counted starts over.
|
|
729
|
+
this.loop.idle = 0;
|
|
730
|
+
this.loop.warned = false;
|
|
731
|
+
this.emit("steered", { runId, messages: steer });
|
|
732
|
+
}
|
|
733
|
+
toWireHistory(media = {}) {
|
|
734
|
+
let lastUser = -1;
|
|
735
|
+
for (let i = this.history.length - 1; i >= 0; i--)
|
|
736
|
+
if (this.history[i].role === "user") {
|
|
737
|
+
lastUser = i;
|
|
738
|
+
break;
|
|
739
|
+
}
|
|
740
|
+
return withoutMedia(moveToolImages(this.history.map((m, i) => toWire(m, i < lastUser))), media, this.opts.model);
|
|
741
|
+
}
|
|
742
|
+
/** What the model in use takes besides text (undefined: not known — then it is sent). */
|
|
743
|
+
async mediaSupport() {
|
|
744
|
+
const [image, video, audio] = await Promise.all([this.accepts("image"), this.accepts("video"), this.accepts("audio")]);
|
|
745
|
+
return { image, video, audio };
|
|
746
|
+
}
|
|
747
|
+
/** The tools offered this turn: `vision` tools only while the model is known to take pictures. */
|
|
748
|
+
async activeTools() {
|
|
749
|
+
if (!this.tools.some((t) => t.vision))
|
|
750
|
+
return this.tools;
|
|
751
|
+
const sees = await this.accepts("image");
|
|
752
|
+
return this.tools.filter((t) => !t.vision || sees === true);
|
|
753
|
+
}
|
|
754
|
+
/** The system prompt for the next request (what the model is told). */
|
|
755
|
+
async systemPrompt() {
|
|
756
|
+
const ws = this.workspace;
|
|
757
|
+
const readOpt = async (path, max) => {
|
|
758
|
+
if (!ws)
|
|
759
|
+
return undefined;
|
|
760
|
+
try {
|
|
761
|
+
const t = await ws.readText(path);
|
|
762
|
+
return t.length > max ? t.slice(t.length - max) : t;
|
|
763
|
+
}
|
|
764
|
+
catch {
|
|
765
|
+
return undefined;
|
|
766
|
+
}
|
|
767
|
+
};
|
|
768
|
+
const tools = await this.activeTools();
|
|
769
|
+
return buildSystemPrompt({
|
|
770
|
+
appName: this.opts.appName,
|
|
771
|
+
instructions: typeof this.opts.instructions === "function" ? this.opts.instructions() : this.opts.instructions,
|
|
772
|
+
tools,
|
|
773
|
+
workspaceDescription: ws ? ws.describe() : undefined,
|
|
774
|
+
skills: ws ? await ws.skills() : [],
|
|
775
|
+
hasSandbox: tools.some((t) => t.name === "run_js"),
|
|
776
|
+
hasAskUser: tools.some((t) => t.name === "ask_user"),
|
|
777
|
+
canWrite: tools.some((t) => t.name === "write_file" || t.name === "edit_file"),
|
|
778
|
+
agentsMd: this.opts.instructionsFile === false ? undefined : await readOpt(this.opts.instructionsFile ?? AGENTS_PATH, 20_000),
|
|
779
|
+
agentsPath: this.opts.instructionsFile || AGENTS_PATH,
|
|
780
|
+
memory: this.opts.memoryFile === false ? undefined : await readOpt(this.opts.memoryFile ?? MEMORY_PATH, MAX_NOTES_CHARS),
|
|
781
|
+
memoryPath: this.opts.memoryFile === false ? undefined : this.opts.memoryFile ?? MEMORY_PATH,
|
|
782
|
+
droppedTurns: this.droppedTurns,
|
|
783
|
+
});
|
|
784
|
+
}
|
|
785
|
+
/**
|
|
786
|
+
* Summarises the older turns into a checkpoint now (the loop does this
|
|
787
|
+
* by itself when the window is nearly full). Resolves true when a
|
|
788
|
+
* summary replaced older turns. `focus` tells the summary what to keep
|
|
789
|
+
* above all. Every turn before the latest may be summarised, even when
|
|
790
|
+
* all of them would fit in `keepRecentTokens`.
|
|
791
|
+
*/
|
|
792
|
+
compact(focus) {
|
|
793
|
+
if (this.current)
|
|
794
|
+
return Promise.reject(new Error("cannot compact while a run is active"));
|
|
795
|
+
// Runs like a run: messages sent meanwhile queue behind it instead of being lost when the history is replaced.
|
|
796
|
+
const controller = new AbortController();
|
|
797
|
+
const work = this.chain.then(async () => {
|
|
798
|
+
await this.loaded;
|
|
799
|
+
const window = await this.contextTokens();
|
|
800
|
+
let settings = resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {});
|
|
801
|
+
// Asked for, so it does something: everything before the latest turn may be summarised.
|
|
802
|
+
const h = this.history;
|
|
803
|
+
let last = h.length - 1;
|
|
804
|
+
while (last > 0 && !(h[last].role === "user" && summaryOf(h[last]) === null))
|
|
805
|
+
last--;
|
|
806
|
+
const latestTurn = last > 0 ? h.slice(last).reduce((n, m) => n + estimateTokens([m]), 0) : Math.floor(estimateTokens(h) / 2);
|
|
807
|
+
settings = { ...settings, keepRecentTokens: Math.min(settings.keepRecentTokens, latestTurn) };
|
|
808
|
+
const done = await this.compactWith(settings, undefined, controller.signal, focus);
|
|
809
|
+
if (done)
|
|
810
|
+
await this.saveSession();
|
|
811
|
+
return done;
|
|
812
|
+
});
|
|
813
|
+
const promise = work.then(() => ({ ...abortedResult(), reason: "done" }), () => abortedResult());
|
|
814
|
+
this.current = { controller, promise };
|
|
815
|
+
this.chain = promise;
|
|
816
|
+
void promise.finally(() => {
|
|
817
|
+
if (this.current?.controller === controller)
|
|
818
|
+
this.current = null;
|
|
819
|
+
this.drainFollowUps();
|
|
820
|
+
});
|
|
821
|
+
return work;
|
|
822
|
+
}
|
|
823
|
+
async compactWith(settings, runId, signal, focus) {
|
|
824
|
+
const plan = planCut(this.history, settings.keepRecentTokens);
|
|
825
|
+
if (!plan)
|
|
826
|
+
return false;
|
|
827
|
+
if (focus?.trim())
|
|
828
|
+
plan.focus = focus.trim();
|
|
829
|
+
this.emit("compaction_start", { runId });
|
|
830
|
+
const tokensBefore = estimateTokens(this.history);
|
|
831
|
+
let summary;
|
|
832
|
+
try {
|
|
833
|
+
if (typeof this.opts.compaction === "function") {
|
|
834
|
+
summary = await this.opts.compaction(plan, this);
|
|
835
|
+
}
|
|
836
|
+
else {
|
|
837
|
+
const limits = await this.limits();
|
|
838
|
+
// pi: the summary may use most of the reserve, never the model's whole output limit.
|
|
839
|
+
const maxTokens = Math.min(limits.output, Math.max(1024, Math.floor(settings.reserveTokens * 0.8)));
|
|
840
|
+
// What one request can carry (3 characters a token, room for the prompt); a longer history is summarised piece by piece.
|
|
841
|
+
const room = Math.max(6000, (limits.input - maxTokens - 1500) * 3);
|
|
842
|
+
let previous = plan.previousSummary;
|
|
843
|
+
for (const piece of splitForSummary(serializeConversation(plan.toSummarize), room)) {
|
|
844
|
+
const params = { model: this.opts.model ?? "", messages: summarizationMessages(piece, previous, plan.focus), max_tokens: maxTokens };
|
|
845
|
+
if (!params.model)
|
|
846
|
+
delete params.model;
|
|
847
|
+
const tag = { runId: runId ?? "", turn: this.turnNow, purpose: "compaction" };
|
|
848
|
+
this.emit("request", { ...tag, params });
|
|
849
|
+
// A listener may have stopped the run on seeing this request (a call limit): then it never goes out.
|
|
850
|
+
signal.throwIfAborted();
|
|
851
|
+
const asked = Date.now();
|
|
852
|
+
let res;
|
|
853
|
+
try {
|
|
854
|
+
res = this.provider.complete
|
|
855
|
+
? await this.provider.complete(params, { signal })
|
|
856
|
+
: await collectCompletion((p, init) => this.provider.stream(p, init), params, { signal }).then((c) => ({ choices: [{ message: { ...c.message, content: typeof c.message.content === "string" ? c.message.content : null }, finish_reason: c.finishReason }], usage: c.usage }));
|
|
857
|
+
}
|
|
858
|
+
catch (err) {
|
|
859
|
+
this.emit("response", { ...tag, durationMs: Date.now() - asked, error: err instanceof Error ? err.message : String(err) });
|
|
860
|
+
throw err;
|
|
861
|
+
}
|
|
862
|
+
if (res.usage)
|
|
863
|
+
this.addUsage(res.usage);
|
|
864
|
+
const choice = res.choices[0];
|
|
865
|
+
this.emit("response", { ...tag, durationMs: Date.now() - asked, finishReason: choice?.finish_reason ?? undefined, usage: res.usage ?? undefined, message: choice?.message });
|
|
866
|
+
if (!choice || choice.finish_reason === "length")
|
|
867
|
+
throw new Error("the summary is incomplete");
|
|
868
|
+
if (choice.message.tool_calls?.length)
|
|
869
|
+
throw new Error("the summariser attempted to call a tool");
|
|
870
|
+
previous = (choice.message.content ?? "").trim();
|
|
871
|
+
if (!previous)
|
|
872
|
+
throw new Error("empty summary");
|
|
873
|
+
}
|
|
874
|
+
summary = previous;
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
catch (err) {
|
|
878
|
+
if (signal.aborted)
|
|
879
|
+
throw err;
|
|
880
|
+
console.warn("[agent] compaction summary failed, falling back to trimming:", err);
|
|
881
|
+
return false;
|
|
882
|
+
}
|
|
883
|
+
this.history = [summaryMessage(summary), ...plan.kept];
|
|
884
|
+
this.committed = this.history.length;
|
|
885
|
+
this.emit("compaction", { runId, summary: true, tokensBefore, tokensAfter: estimateTokens(this.history), droppedTurns: 0, elidedResults: 0 });
|
|
886
|
+
return true;
|
|
887
|
+
}
|
|
888
|
+
/** `/skill:name args` and `/template args` in a user message. */
|
|
889
|
+
async expandSlashes(message) {
|
|
890
|
+
if (!this.workspace)
|
|
891
|
+
return message;
|
|
892
|
+
// The typed text is the content, or the first text part of a message with attachments.
|
|
893
|
+
const parts = Array.isArray(message.content) ? message.content : null;
|
|
894
|
+
const first = parts?.[0];
|
|
895
|
+
const typed = typeof message.content === "string" ? message.content : first?.type === "text" ? first.text : "";
|
|
896
|
+
if (!typed.startsWith("/"))
|
|
897
|
+
return message;
|
|
898
|
+
const expanded = await expandSlash(this.workspace, typed);
|
|
899
|
+
if (expanded === typed)
|
|
900
|
+
return message;
|
|
901
|
+
// `typed` (what the user wrote) rides along for the transcript and rewind; the model gets the expansion.
|
|
902
|
+
const content = parts ? [{ type: "text", text: expanded }, ...parts.slice(1)] : expanded;
|
|
903
|
+
return { ...message, content, typed };
|
|
904
|
+
}
|
|
905
|
+
/** One model call with retries for transient failures. */
|
|
906
|
+
async callModel(params, runId, signal) {
|
|
907
|
+
let text = "";
|
|
908
|
+
let reasoning = "";
|
|
909
|
+
let streamed = false;
|
|
910
|
+
for (let attempt = 1;; attempt++) {
|
|
911
|
+
text = "";
|
|
912
|
+
reasoning = "";
|
|
913
|
+
signal.throwIfAborted();
|
|
914
|
+
try {
|
|
915
|
+
return await collectCompletion((p, init) => this.provider.stream(p, init), params, {
|
|
916
|
+
signal,
|
|
917
|
+
onText: (delta, all) => {
|
|
918
|
+
streamed = true;
|
|
919
|
+
text = all;
|
|
920
|
+
this.emit("text_delta", { runId, delta, text: all });
|
|
921
|
+
},
|
|
922
|
+
onReasoning: (delta, all) => {
|
|
923
|
+
streamed = true;
|
|
924
|
+
reasoning = all;
|
|
925
|
+
this.emit("reasoning_delta", { runId, delta, text: all });
|
|
926
|
+
},
|
|
927
|
+
onToolCall: (call, delta) => {
|
|
928
|
+
streamed = true;
|
|
929
|
+
this.emit("tool_call_delta", { runId, index: call.index, id: call.id, name: call.name, delta, arguments: call.arguments });
|
|
930
|
+
},
|
|
931
|
+
});
|
|
932
|
+
}
|
|
933
|
+
catch (err) {
|
|
934
|
+
if (signal.aborted)
|
|
935
|
+
throw err;
|
|
936
|
+
if (attempt >= MAX_RETRIES || !isTransient(err))
|
|
937
|
+
throw err;
|
|
938
|
+
const wait = retryDelay(err, attempt);
|
|
939
|
+
if (streamed)
|
|
940
|
+
this.emit("message_reset", { runId, reason: err.message });
|
|
941
|
+
streamed = false;
|
|
942
|
+
await sleep(wait, signal);
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
async runBatch(calls, runId, signal, truncated) {
|
|
947
|
+
const run = (call) => this.runTool(call, runId, signal, truncated);
|
|
948
|
+
const outcomes = this.opts.parallelTools
|
|
949
|
+
? await Promise.all(calls.map((c) => run(c)))
|
|
950
|
+
: await (async () => {
|
|
951
|
+
const out = [];
|
|
952
|
+
let interrupted = false;
|
|
953
|
+
for (const c of calls) {
|
|
954
|
+
if (interrupted) {
|
|
955
|
+
out.push(this.skipTool(c, runId, "Skipped: the user sent a new instruction; the following tool calls were not run."));
|
|
956
|
+
continue;
|
|
957
|
+
}
|
|
958
|
+
out.push(await run(c));
|
|
959
|
+
// pi: steering is checked after each tool; when some arrived, the rest of the batch is skipped so the model sees it at once.
|
|
960
|
+
if (this.queue.some((q) => q.kind === "steer"))
|
|
961
|
+
interrupted = true;
|
|
962
|
+
}
|
|
963
|
+
return out;
|
|
964
|
+
})();
|
|
965
|
+
for (const o of outcomes)
|
|
966
|
+
this.history.push(o.message);
|
|
967
|
+
return outcomes;
|
|
968
|
+
}
|
|
969
|
+
skipTool(call, runId, why) {
|
|
970
|
+
const id = call.id ?? "", name = call.function.name;
|
|
971
|
+
this.emit("tool_start", { runId, id, name, args: call.function.arguments });
|
|
972
|
+
this.emit("tool_end", { runId, id, name, status: "skipped", result: why, durationMs: 0 });
|
|
973
|
+
// A batch cut short by the user's new instruction: that is progress of its own.
|
|
974
|
+
return { message: { role: "tool", tool_call_id: id, content: why }, key: "", changed: false, progress: true };
|
|
975
|
+
}
|
|
976
|
+
async runTool(call, runId, signal, truncated) {
|
|
977
|
+
const id = call.id ?? "";
|
|
978
|
+
const name = call.function.name;
|
|
979
|
+
const started = Date.now();
|
|
980
|
+
let progress;
|
|
981
|
+
let tool;
|
|
982
|
+
const finish = (status, content, details) => {
|
|
983
|
+
const result = textOf(content);
|
|
984
|
+
this.emit("tool_end", { runId, id, name, status, result, details, durationMs: Date.now() - started, ...(typeof content === "string" ? {} : { content }) });
|
|
985
|
+
return {
|
|
986
|
+
message: { role: "tool", tool_call_id: id, content },
|
|
987
|
+
// A read is judged by what it returned (another range of the same lines is nothing new); a change by what it was asked to do too.
|
|
988
|
+
key: tool?.readOnly ? `${name}|${status}|${result.slice(0, 4000)}` : `${name}|${call.function.arguments.slice(0, 4000)}|${status}|${result.slice(0, 2000)}`,
|
|
989
|
+
changed: status === "ok" && !!tool && !tool.readOnly,
|
|
990
|
+
// A user who declined or answered moved things on; a stop is not a loop.
|
|
991
|
+
progress: status === "declined" || status === "skipped" ? true : status === "ok" ? progress : undefined,
|
|
992
|
+
};
|
|
993
|
+
};
|
|
994
|
+
if (signal.aborted)
|
|
995
|
+
return finish("skipped", SKIPPED_STOP);
|
|
996
|
+
if (truncated) {
|
|
997
|
+
// pi: nothing from a reply cut by the output limit runs.
|
|
998
|
+
this.emit("tool_start", { runId, id, name, args: call.function.arguments });
|
|
999
|
+
return finish("error", `Tool call "${name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`);
|
|
1000
|
+
}
|
|
1001
|
+
const offered = await this.activeTools();
|
|
1002
|
+
tool = offered.find((t) => t.name === name);
|
|
1003
|
+
let args;
|
|
1004
|
+
try {
|
|
1005
|
+
args = call.function.arguments.trim() ? JSON.parse(call.function.arguments) : {};
|
|
1006
|
+
}
|
|
1007
|
+
catch {
|
|
1008
|
+
this.emit("tool_start", { runId, id, name, args: call.function.arguments });
|
|
1009
|
+
return finish("error", "Error: the arguments are not valid JSON.");
|
|
1010
|
+
}
|
|
1011
|
+
this.emit("tool_start", { runId, id, name, args });
|
|
1012
|
+
if (!tool)
|
|
1013
|
+
return finish("error", `Error: there is no tool named "${name}". Available tools: ${offered.map((t) => t.name).join(", ")}.`);
|
|
1014
|
+
if (args === null || typeof args !== "object" || Array.isArray(args))
|
|
1015
|
+
return finish("error", "Error: the arguments must be a JSON object.");
|
|
1016
|
+
const problems = validateSchema(tool.parameters, args);
|
|
1017
|
+
if (problems.length)
|
|
1018
|
+
return finish("error", `Error: invalid arguments for ${name}:\n- ${problems.join("\n- ")}\nFix the call and try again.`);
|
|
1019
|
+
// The tool's own check, before anyone is asked: a call that would fail is refused here.
|
|
1020
|
+
if (tool.validate) {
|
|
1021
|
+
let why;
|
|
1022
|
+
try {
|
|
1023
|
+
why = await raceAbort(Promise.resolve(tool.validate(args)), signal);
|
|
1024
|
+
}
|
|
1025
|
+
catch (err) {
|
|
1026
|
+
why = err instanceof Error ? err.message : String(err);
|
|
1027
|
+
}
|
|
1028
|
+
if (signal.aborted)
|
|
1029
|
+
return finish("skipped", SKIPPED_STOP);
|
|
1030
|
+
if (why)
|
|
1031
|
+
return finish("error", why.startsWith("Error:") ? why : `Error: ${why}`);
|
|
1032
|
+
}
|
|
1033
|
+
// Gate: hook, permissions, the tool's own confirm.
|
|
1034
|
+
try {
|
|
1035
|
+
const hook = await raceAbort(Promise.resolve(this.opts.onToolCall?.({ id, name, args, tool })), signal);
|
|
1036
|
+
if (hook && hook.block)
|
|
1037
|
+
return finish("blocked", `${hook.reason ?? "This action was not allowed."} Do not retry it another way; say what you would have done.`);
|
|
1038
|
+
const allowed = await raceAbort(this.permitted(tool, args, signal), signal);
|
|
1039
|
+
if (!allowed)
|
|
1040
|
+
return finish("declined", "The user declined this action. Do not retry it another way; say what you would have done.");
|
|
1041
|
+
}
|
|
1042
|
+
catch (err) {
|
|
1043
|
+
if (signal.aborted)
|
|
1044
|
+
return finish("skipped", SKIPPED_STOP);
|
|
1045
|
+
return finish("error", `Error: ${err.message}`);
|
|
1046
|
+
}
|
|
1047
|
+
if (signal.aborted)
|
|
1048
|
+
return finish("skipped", SKIPPED_STOP);
|
|
1049
|
+
// Stopped while it ran: the tool may say how far it got (whenStopped).
|
|
1050
|
+
const stoppedIn = () => {
|
|
1051
|
+
try {
|
|
1052
|
+
const own = tool.whenStopped?.(args);
|
|
1053
|
+
if (own !== undefined) {
|
|
1054
|
+
const norm = normalizeResult(own, tool.maxResultChars);
|
|
1055
|
+
return finish("skipped", norm.content, norm.details);
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
catch { /* the default note */ }
|
|
1059
|
+
return finish("skipped", SKIPPED_STOP);
|
|
1060
|
+
};
|
|
1061
|
+
try {
|
|
1062
|
+
const value = await raceAbort(Promise.resolve(tool.execute(args, {
|
|
1063
|
+
signal,
|
|
1064
|
+
ui: this.ui,
|
|
1065
|
+
workspace: this.workspace,
|
|
1066
|
+
agent: this,
|
|
1067
|
+
callId: id,
|
|
1068
|
+
update: (content) => this.emit("tool_update", { runId, id, name, content }),
|
|
1069
|
+
progress: (made) => { progress = made; },
|
|
1070
|
+
})), signal);
|
|
1071
|
+
if (signal.aborted)
|
|
1072
|
+
return stoppedIn();
|
|
1073
|
+
const norm = normalizeResult(value, tool.maxResultChars);
|
|
1074
|
+
return finish("ok", norm.content, norm.details);
|
|
1075
|
+
}
|
|
1076
|
+
catch (err) {
|
|
1077
|
+
if (signal.aborted)
|
|
1078
|
+
return stoppedIn();
|
|
1079
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1080
|
+
return finish("error", msg.startsWith("Error:") ? msg : `Error: ${msg}`);
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
async permitted(tool, args, signal) {
|
|
1084
|
+
const p = this.opts.permissions ?? "ask";
|
|
1085
|
+
if (typeof p === "function")
|
|
1086
|
+
return p({ name: tool.name, args, tool });
|
|
1087
|
+
if (p === "auto")
|
|
1088
|
+
return true;
|
|
1089
|
+
let question = false;
|
|
1090
|
+
if (tool.confirm)
|
|
1091
|
+
question = await tool.confirm(args);
|
|
1092
|
+
else if (tool.destructive)
|
|
1093
|
+
question = `Allow ${tool.name}?`;
|
|
1094
|
+
if (question === false)
|
|
1095
|
+
return true;
|
|
1096
|
+
const { title, message, always, ok, body } = typeof question === "string" ? { title: question, message: undefined, always: undefined, ok: undefined, body: undefined } : question;
|
|
1097
|
+
return this.ui.confirm(title, message, { danger: !!tool.destructive, signal, always, ...(ok ? { ok } : {}), ...(body ? { body } : {}) });
|
|
1098
|
+
}
|
|
1099
|
+
/** After an abort, every open tool call gets a result so the transcript stays valid. */
|
|
1100
|
+
closeOpenToolCalls() {
|
|
1101
|
+
const last = this.history[this.history.length - 1];
|
|
1102
|
+
if (!last)
|
|
1103
|
+
return;
|
|
1104
|
+
let i = this.history.length - 1;
|
|
1105
|
+
while (i >= 0 && this.history[i].role === "tool")
|
|
1106
|
+
i--;
|
|
1107
|
+
const assistant = this.history[i];
|
|
1108
|
+
if (!assistant || assistant.role !== "assistant" || !assistant.tool_calls?.length)
|
|
1109
|
+
return;
|
|
1110
|
+
const answered = new Set(this.history.slice(i + 1).map((m) => m.tool_call_id));
|
|
1111
|
+
for (const c of assistant.tool_calls) {
|
|
1112
|
+
if (c.id && !answered.has(c.id))
|
|
1113
|
+
this.history.push({ role: "tool", tool_call_id: c.id, content: SKIPPED_STOP });
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
/**
|
|
1117
|
+
* After each batch: did it bring anything new? A tool that changes things
|
|
1118
|
+
* succeeding with arguments it had not had is progress (and what was seen
|
|
1119
|
+
* before may be worth seeing again); otherwise a result counts when the
|
|
1120
|
+
* tool says so, or when the run has not had the same one since the last change.
|
|
1121
|
+
*/
|
|
1122
|
+
checkLoop(outcomes) {
|
|
1123
|
+
const opt = this.opts.loopGuard;
|
|
1124
|
+
if (opt === false)
|
|
1125
|
+
return "ok";
|
|
1126
|
+
const warn = opt?.warn ?? LOOP_WARN, stop = opt?.stop ?? LOOP_STOP;
|
|
1127
|
+
const l = this.loop;
|
|
1128
|
+
const fresh = outcomes.map((o) => o.key !== "" && !l.seen.has(o.key));
|
|
1129
|
+
// A change it had not made before: what was read may be worth reading again.
|
|
1130
|
+
const changed = outcomes.some((o, i) => o.changed && fresh[i]);
|
|
1131
|
+
if (changed)
|
|
1132
|
+
l.seen.clear();
|
|
1133
|
+
for (const o of outcomes)
|
|
1134
|
+
if (o.key)
|
|
1135
|
+
l.seen.add(o.key);
|
|
1136
|
+
const progress = changed || outcomes.some((o, i) => o.progress ?? fresh[i]);
|
|
1137
|
+
if (l.seen.size > 512)
|
|
1138
|
+
l.seen.delete(l.seen.values().next().value);
|
|
1139
|
+
if (progress) {
|
|
1140
|
+
l.idle = 0;
|
|
1141
|
+
l.warned = false;
|
|
1142
|
+
return "ok";
|
|
1143
|
+
}
|
|
1144
|
+
l.idle++;
|
|
1145
|
+
if (l.idle >= stop)
|
|
1146
|
+
return "stop";
|
|
1147
|
+
if (l.idle >= warn && !l.warned) {
|
|
1148
|
+
l.warned = true;
|
|
1149
|
+
return "warn";
|
|
1150
|
+
}
|
|
1151
|
+
return "ok";
|
|
1152
|
+
}
|
|
1153
|
+
resetLoop() {
|
|
1154
|
+
this.loop = { seen: new Set(), idle: 0, warned: false };
|
|
1155
|
+
}
|
|
1156
|
+
balanceLimited(usage, maxTokens) {
|
|
1157
|
+
// The gateway lowers max_tokens to what the balance covers (never
|
|
1158
|
+
// below 1024); a reply cut well short of what we asked for says so.
|
|
1159
|
+
const out = usage?.completion_tokens;
|
|
1160
|
+
return typeof out === "number" && out > 0 && out < maxTokens * 0.9;
|
|
1161
|
+
}
|
|
1162
|
+
/**
|
|
1163
|
+
* Puts what the run spent on the last reply it wrote (`runUsage`): the
|
|
1164
|
+
* chat shows it under that reply, and it is saved with the conversation
|
|
1165
|
+
* (requests never carry it).
|
|
1166
|
+
*/
|
|
1167
|
+
markRunUsage(from, before) {
|
|
1168
|
+
const u = this._usage;
|
|
1169
|
+
if (u.calls === before.calls)
|
|
1170
|
+
return;
|
|
1171
|
+
for (let i = this.history.length - 1; i >= Math.min(from, this.history.length); i--) {
|
|
1172
|
+
const m = this.history[i];
|
|
1173
|
+
if (m.role !== "assistant")
|
|
1174
|
+
continue;
|
|
1175
|
+
m.runUsage = {
|
|
1176
|
+
total_cost: round(u.total_cost - before.total_cost),
|
|
1177
|
+
prompt_tokens: u.prompt_tokens - before.prompt_tokens,
|
|
1178
|
+
completion_tokens: u.completion_tokens - before.completion_tokens,
|
|
1179
|
+
calls: u.calls - before.calls,
|
|
1180
|
+
};
|
|
1181
|
+
return;
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
addUsage(u) {
|
|
1185
|
+
this._usage.total_cost = round(this._usage.total_cost + (u.total_cost ?? 0));
|
|
1186
|
+
this._usage.prompt_tokens += u.prompt_tokens ?? 0;
|
|
1187
|
+
this._usage.completion_tokens += u.completion_tokens ?? 0;
|
|
1188
|
+
this._usage.calls++;
|
|
1189
|
+
}
|
|
1190
|
+
/** How full the model's context is: tokens the next call would send (estimated) against the window. */
|
|
1191
|
+
async context() {
|
|
1192
|
+
const [window, system] = await Promise.all([this.contextTokens(), this.systemPrompt().catch(() => "")]);
|
|
1193
|
+
return { used: estimateTokens(this.history, this.fixedText(system)), window };
|
|
1194
|
+
}
|
|
1195
|
+
/**
|
|
1196
|
+
* The files whose contents are still in the conversation: read (with the
|
|
1197
|
+
* result not trimmed away) or written by the model in a turn that was kept.
|
|
1198
|
+
* The rest were summarised or dropped, so the model must read them again.
|
|
1199
|
+
*/
|
|
1200
|
+
filesInView() {
|
|
1201
|
+
const trimmed = new Set(this.history.filter((m) => m.role === "tool" && typeof m.content === "string" && m.content.startsWith("[result elided")).map((m) => m.tool_call_id));
|
|
1202
|
+
const paths = [];
|
|
1203
|
+
for (const m of this.history) {
|
|
1204
|
+
for (const c of m.role === "assistant" ? m.tool_calls ?? [] : []) {
|
|
1205
|
+
if (trimmed.has(c.id))
|
|
1206
|
+
continue;
|
|
1207
|
+
let args;
|
|
1208
|
+
try {
|
|
1209
|
+
args = JSON.parse(c.function.arguments);
|
|
1210
|
+
}
|
|
1211
|
+
catch {
|
|
1212
|
+
continue;
|
|
1213
|
+
}
|
|
1214
|
+
const path = ["read_file", "write_file", "edit_file"].includes(c.function.name) ? args.path : ["move_file", "copy_file"].includes(c.function.name) ? args.to : undefined;
|
|
1215
|
+
if (typeof path === "string")
|
|
1216
|
+
paths.push(normalizePath(path));
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
return paths;
|
|
1220
|
+
}
|
|
1221
|
+
/** The system prompt and the tools' schemas, as they count against the window. */
|
|
1222
|
+
fixedText(system) {
|
|
1223
|
+
return this.tools.length ? `${system}\n${JSON.stringify(this.tools.map((t) => toChatTool(t)))}` : system;
|
|
1224
|
+
}
|
|
1225
|
+
/**
|
|
1226
|
+
* The model's limits as the agent uses them: `input` is the context
|
|
1227
|
+
* window, `output` the `max_tokens` of each call — the catalogue's
|
|
1228
|
+
* figures for the model (its `max_input_tokens` / `max_tokens`). A number
|
|
1229
|
+
* `maxInputTokens` caps the window (a budget: never more than the model
|
|
1230
|
+
* takes, when the catalogue says); a number `maxTokens` replaces the output.
|
|
1231
|
+
*/
|
|
1232
|
+
async limits() {
|
|
1233
|
+
const cat = await this.catalogueLimits();
|
|
1234
|
+
const known = typeof (await this.modelInfo())?.max_input_tokens === "number";
|
|
1235
|
+
const cap = this.opts.maxInputTokens;
|
|
1236
|
+
return {
|
|
1237
|
+
input: typeof cap === "number" ? (known ? Math.min(cap, cat.input) : cap) : cat.input,
|
|
1238
|
+
output: typeof this.opts.maxTokens === "number" ? this.opts.maxTokens : cat.output,
|
|
1239
|
+
};
|
|
1240
|
+
}
|
|
1241
|
+
contextTokens() {
|
|
1242
|
+
return this.limits().then((l) => l.input);
|
|
1243
|
+
}
|
|
1244
|
+
async catalogueLimits() {
|
|
1245
|
+
const m = await this.modelInfo();
|
|
1246
|
+
const input = typeof m?.max_input_tokens === "number" && m.max_input_tokens > 0 ? m.max_input_tokens : DEFAULT_INPUT_TOKENS;
|
|
1247
|
+
const output = typeof m?.max_tokens === "number" && m.max_tokens > 0 ? m.max_tokens : DEFAULT_MAX_TOKENS;
|
|
1248
|
+
return { input, output };
|
|
1249
|
+
}
|
|
1250
|
+
/**
|
|
1251
|
+
* The catalogue's entry for the model in use — the named model, else the
|
|
1252
|
+
* provider's default chat model — or undefined when the provider has no
|
|
1253
|
+
* catalogue or does not list it.
|
|
1254
|
+
*/
|
|
1255
|
+
modelInfo() {
|
|
1256
|
+
if (!this.catalogue) {
|
|
1257
|
+
this.catalogue = (async () => {
|
|
1258
|
+
try {
|
|
1259
|
+
if (!this.provider.models)
|
|
1260
|
+
return undefined;
|
|
1261
|
+
const models = await this.provider.models();
|
|
1262
|
+
const want = this.opts.model?.toLowerCase();
|
|
1263
|
+
return want ? models.find((x) => x.id.toLowerCase() === want) : models.find((x) => x.is_default && (!x.capability || x.capability === "text" || x.capability === "vision"));
|
|
1264
|
+
}
|
|
1265
|
+
catch {
|
|
1266
|
+
// Offline for a moment: nothing known now, ask the catalogue again next time.
|
|
1267
|
+
queueMicrotask(() => { this.catalogue = null; });
|
|
1268
|
+
return undefined;
|
|
1269
|
+
}
|
|
1270
|
+
})();
|
|
1271
|
+
}
|
|
1272
|
+
return this.catalogue;
|
|
1273
|
+
}
|
|
1274
|
+
/**
|
|
1275
|
+
* Whether the model in use takes pictures (`"image"`), video or audio as
|
|
1276
|
+
* input: the `vision` option when given (for pictures), else the
|
|
1277
|
+
* catalogue's `input_modalities`. Undefined when nothing says.
|
|
1278
|
+
*/
|
|
1279
|
+
async accepts(kind) {
|
|
1280
|
+
if (kind === "image" && typeof this.opts.vision === "boolean")
|
|
1281
|
+
return this.opts.vision;
|
|
1282
|
+
return modelAccepts(await this.modelInfo(), kind);
|
|
1283
|
+
}
|
|
1284
|
+
async withSkillPrefaces(message) {
|
|
1285
|
+
if (!this.pendingSkills.length || !this.workspace)
|
|
1286
|
+
return message;
|
|
1287
|
+
const names = this.pendingSkills.splice(0);
|
|
1288
|
+
const parts = [];
|
|
1289
|
+
for (const name of names) {
|
|
1290
|
+
const { skill, body } = await this.workspace.skillBody(name);
|
|
1291
|
+
parts.push({ type: "text", text: `[The user invoked the skill "${skill.name}" (${skill.path}). Follow these instructions for the request below.]\n\n${body}` });
|
|
1292
|
+
}
|
|
1293
|
+
const own = typeof message.content === "string" ? [{ type: "text", text: message.content }] : (message.content ?? []);
|
|
1294
|
+
const typed = message.typed ?? (typeof message.content === "string" ? message.content : undefined);
|
|
1295
|
+
return { ...message, role: "user", content: [...parts, ...own], ...(typed !== undefined ? { typed } : {}) };
|
|
1296
|
+
}
|
|
1297
|
+
/** Tokens of the transcript alone (estimate, no system prompt); `context()` gives the full figure and the window. */
|
|
1298
|
+
estimateContext() {
|
|
1299
|
+
return estimateTokens(this.history);
|
|
1300
|
+
}
|
|
1301
|
+
/** The model's context window in tokens (from the catalogue); same as `(await limits()).input`. */
|
|
1302
|
+
contextWindow() {
|
|
1303
|
+
return this.contextTokens();
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
/* ------------------------------------------------------------------ */
|
|
1307
|
+
function isTransient(err) {
|
|
1308
|
+
// Any provider's error with an HTTP status (ProviderError, the RunApps SDK's APIError, …).
|
|
1309
|
+
const s = errorStatus(err);
|
|
1310
|
+
if (s !== undefined)
|
|
1311
|
+
return s === 408 || s === 429 || s >= 500 || s === 0;
|
|
1312
|
+
if (err instanceof Error)
|
|
1313
|
+
return /network|fetch failed|ECONNRESET|socket|stream ended before/i.test(err.message) || err.name === "TypeError";
|
|
1314
|
+
return false;
|
|
1315
|
+
}
|
|
1316
|
+
function retryDelay(err, attempt) {
|
|
1317
|
+
const ra = err && typeof err === "object" ? err.retryAfter : undefined;
|
|
1318
|
+
if (typeof ra === "number" && ra > 0)
|
|
1319
|
+
return Math.min(30_000, ra * 1000);
|
|
1320
|
+
return Math.min(8000, 800 * 2 ** (attempt - 1)) + Math.random() * 300;
|
|
1321
|
+
}
|
|
1322
|
+
function sleep(ms, signal) {
|
|
1323
|
+
return new Promise((resolve, reject) => {
|
|
1324
|
+
const onAbort = () => { clearTimeout(t); reject(signal.reason ?? new Error("aborted")); };
|
|
1325
|
+
const t = setTimeout(() => { signal.removeEventListener("abort", onAbort); resolve(); }, ms);
|
|
1326
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1327
|
+
});
|
|
1328
|
+
}
|
|
1329
|
+
function round(n) {
|
|
1330
|
+
return Math.round(n * 1e6) / 1e6;
|
|
1331
|
+
}
|