@useavalon/caelence-agent 0.4.0 → 0.6.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/README.md +29 -4
- package/desktop/src/DeskComposer.tsx +10 -0
- package/desktop/src/SettingsPanel.tsx +18 -0
- package/desktop/src/api.ts +12 -1
- package/desktop/src/app.css +8 -3
- package/desktop/src/desk-types.ts +1 -0
- package/desktop/src/desktop-turn.ts +7 -0
- package/desktop/src/stream.ts +1 -0
- package/desktop/src/thought.test.ts +16 -0
- package/desktop/src/thought.ts +15 -4
- package/desktop/src/turn-verbs.ts +14 -0
- package/desktop/src/useDeskPicker.ts +17 -1
- package/package.json +7 -4
- package/src/cli/main.test.ts +12 -0
- package/src/cli/main.ts +45 -5
- package/src/cli/slash-dispatch.test.ts +43 -0
- package/src/cli/slash-dispatch.ts +34 -0
- package/src/cli/slash.test.ts +1 -0
- package/src/cli/slash.ts +2 -0
- package/src/cli/tui-progress.ts +15 -3
- package/src/cli/tui.tsx +15 -1
- package/src/config.ts +38 -2
- package/src/core/events.ts +12 -9
- package/src/core/mode.ts +5 -0
- package/src/core/reasoning.test.ts +37 -0
- package/src/core/reasoning.ts +32 -0
- package/src/core/run-turn.test.ts +112 -0
- package/src/core/run-turn.ts +13 -1
- package/src/core/strands.test.ts +106 -2
- package/src/core/strands.ts +46 -11
- package/src/core/usage.test.ts +80 -1
- package/src/core/usage.ts +35 -3
- package/src/desktop/bridge.test.ts +27 -0
- package/src/desktop/bridge.ts +17 -5
- package/src/index.ts +77 -1
- package/src/memory/brief.ts +62 -0
- package/src/memory/embeddings.ts +104 -0
- package/src/memory/extract.ts +9 -8
- package/src/memory/layered.test.ts +202 -0
- package/src/memory/layered.ts +125 -0
- package/src/memory/memory-store.test.ts +299 -0
- package/src/memory/memory-store.ts +295 -0
- package/src/memory/store.ts +70 -20
- package/src/observability/langfuse.ts +9 -2
- package/src/observability/types.ts +5 -0
- package/src/runtime.test.ts +27 -0
- package/src/runtime.ts +164 -34
- package/src/status/categories.ts +64 -0
- package/src/status/default-verbs.ts +190 -0
- package/src/status/status-verb-categories.json +6167 -0
- package/src/status/status-verbs.test.ts +209 -0
- package/src/status/status-verbs.ts +62 -0
- package/src/tools/background.test.ts +304 -0
- package/src/tools/background.ts +432 -0
- package/src/tools/memory.ts +94 -0
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
import type { AgentEventEmitter } from "../core/events.ts";
|
|
2
|
+
import {
|
|
3
|
+
errorResult,
|
|
4
|
+
jsonResult,
|
|
5
|
+
type McpToolDefinition,
|
|
6
|
+
READ_ONLY_ANNOTATIONS,
|
|
7
|
+
} from "../core/mcp.ts";
|
|
8
|
+
import { type Skill, skillBodiesForNames } from "../skills/loader.ts";
|
|
9
|
+
|
|
10
|
+
/** explore = read-only search and report. general = the full tool set. */
|
|
11
|
+
export type SubagentKind = "explore" | "general";
|
|
12
|
+
|
|
13
|
+
export type BackgroundAgentStatus = "queued" | "running" | "done" | "failed" | "cancelled";
|
|
14
|
+
|
|
15
|
+
export interface BackgroundAgentSnapshot {
|
|
16
|
+
id: string;
|
|
17
|
+
label: string;
|
|
18
|
+
kind: SubagentKind;
|
|
19
|
+
status: BackgroundAgentStatus;
|
|
20
|
+
elapsedMs: number;
|
|
21
|
+
result?: string;
|
|
22
|
+
error?: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface BackgroundAgentRunInput {
|
|
26
|
+
prompt: string;
|
|
27
|
+
label: string;
|
|
28
|
+
kind: SubagentKind;
|
|
29
|
+
extraSystem: string;
|
|
30
|
+
emit: AgentEventEmitter;
|
|
31
|
+
signal: AbortSignal;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface BackgroundAgentsOptions {
|
|
35
|
+
/** Run one nested turn. Its tools must not include the tools made here. */
|
|
36
|
+
run: (input: BackgroundAgentRunInput) => Promise<void>;
|
|
37
|
+
/** The parent turn's emitter, for nested tool cards and approvals. */
|
|
38
|
+
parentEmit: () => AgentEventEmitter;
|
|
39
|
+
skills?: Skill[];
|
|
40
|
+
/** Kinds the model may spawn. Defaults to both. */
|
|
41
|
+
kinds?: readonly SubagentKind[];
|
|
42
|
+
/** Agents running at once. The rest wait in a queue. Default 4. */
|
|
43
|
+
maxConcurrent?: number;
|
|
44
|
+
/** Agents one registry will ever start. Default 12. */
|
|
45
|
+
maxAgents?: number;
|
|
46
|
+
/** The parent turn's signal. Aborting it cancels every agent. */
|
|
47
|
+
signal?: AbortSignal;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface BackgroundAgents {
|
|
51
|
+
/** spawn_agent, await_agents and cancel_agent. */
|
|
52
|
+
tools: McpToolDefinition[];
|
|
53
|
+
/**
|
|
54
|
+
* Wrap one of the parent's other tools so its result also says which background agents have
|
|
55
|
+
* finished since the model last heard. This is how the model learns of a result without polling.
|
|
56
|
+
*/
|
|
57
|
+
withNotices(tool: McpToolDefinition): McpToolDefinition;
|
|
58
|
+
snapshot(): BackgroundAgentSnapshot[];
|
|
59
|
+
/** Agents that are queued or running. */
|
|
60
|
+
pending(): number;
|
|
61
|
+
/** Cancel what is left and drop later events. Call when the parent turn ends. */
|
|
62
|
+
close(reason?: string): void;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export const DEFAULT_BACKGROUND_MAX_CONCURRENT = 4;
|
|
66
|
+
export const DEFAULT_BACKGROUND_MAX_AGENTS = 12;
|
|
67
|
+
const DEFAULT_AWAIT_SECONDS = 120;
|
|
68
|
+
const MAX_AWAIT_SECONDS = 600;
|
|
69
|
+
const MAX_RESULT_CHARS = 24_000;
|
|
70
|
+
|
|
71
|
+
export const EXPLORE_INSTRUCTIONS = [
|
|
72
|
+
"You are a read-only explorer subagent. Search and read to answer the task, then reply with a short report.",
|
|
73
|
+
"Send independent searches and reads in the same step so they run in parallel.",
|
|
74
|
+
"Report what you found with file paths and line numbers. Quote only the lines that matter; do not paste whole files.",
|
|
75
|
+
"Say plainly what you could not find. Do not edit anything, do not ask the user questions, do not spawn further subagents.",
|
|
76
|
+
].join(" ");
|
|
77
|
+
|
|
78
|
+
export const BACKGROUND_AGENTS_PROMPT = [
|
|
79
|
+
"## Background agents",
|
|
80
|
+
"spawn_agent starts a subagent and returns its id at once, so you can keep working while it runs.",
|
|
81
|
+
"For a broad search or several independent questions, spawn one explore agent per question in the same step, carry on with what you can do yourself, then call await_agents to read the reports.",
|
|
82
|
+
"Explore agents are read-only and fast. Give each a complete, self-contained prompt: it does not see this conversation.",
|
|
83
|
+
"Do not spawn an agent for something one grep or one file read answers.",
|
|
84
|
+
].join("\n");
|
|
85
|
+
|
|
86
|
+
interface Entry {
|
|
87
|
+
id: string;
|
|
88
|
+
label: string;
|
|
89
|
+
kind: SubagentKind;
|
|
90
|
+
status: BackgroundAgentStatus;
|
|
91
|
+
startedAt: number;
|
|
92
|
+
endedAt?: number;
|
|
93
|
+
text: string;
|
|
94
|
+
error?: string;
|
|
95
|
+
controller: AbortController;
|
|
96
|
+
settled: Promise<void>;
|
|
97
|
+
settle: () => void;
|
|
98
|
+
start: () => void;
|
|
99
|
+
/** The model has been told this agent finished, or has read its result. */
|
|
100
|
+
announced: boolean;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function isFinished(status: BackgroundAgentStatus): boolean {
|
|
104
|
+
return status === "done" || status === "failed" || status === "cancelled";
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function clip(text: string): string {
|
|
108
|
+
const trimmed = text.trim();
|
|
109
|
+
if (trimmed.length <= MAX_RESULT_CHARS) return trimmed;
|
|
110
|
+
return `${trimmed.slice(0, MAX_RESULT_CHARS)}\n… (report cut at ${MAX_RESULT_CHARS} characters)`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function createBackgroundAgents(options: BackgroundAgentsOptions): BackgroundAgents {
|
|
114
|
+
const kinds: readonly SubagentKind[] = options.kinds?.length
|
|
115
|
+
? options.kinds
|
|
116
|
+
: ["explore", "general"];
|
|
117
|
+
const defaultKind: SubagentKind = kinds.includes("explore") ? "explore" : (kinds[0] ?? "general");
|
|
118
|
+
const maxConcurrent = Math.max(1, options.maxConcurrent ?? DEFAULT_BACKGROUND_MAX_CONCURRENT);
|
|
119
|
+
const maxAgents = Math.max(1, options.maxAgents ?? DEFAULT_BACKGROUND_MAX_AGENTS);
|
|
120
|
+
const entries = new Map<string, Entry>();
|
|
121
|
+
const queue: Entry[] = [];
|
|
122
|
+
let running = 0;
|
|
123
|
+
let closed = false;
|
|
124
|
+
let counter = 0;
|
|
125
|
+
|
|
126
|
+
const snapshotOf = (entry: Entry): BackgroundAgentSnapshot => ({
|
|
127
|
+
id: entry.id,
|
|
128
|
+
label: entry.label,
|
|
129
|
+
kind: entry.kind,
|
|
130
|
+
status: entry.status,
|
|
131
|
+
elapsedMs: (entry.endedAt ?? Date.now()) - entry.startedAt,
|
|
132
|
+
...(isFinished(entry.status) && entry.status !== "cancelled"
|
|
133
|
+
? { result: clip(entry.text) || "(the agent produced no text)" }
|
|
134
|
+
: {}),
|
|
135
|
+
...(entry.error ? { error: entry.error } : {}),
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
const finish = (entry: Entry, status: BackgroundAgentStatus, error?: string): void => {
|
|
139
|
+
if (isFinished(entry.status)) return;
|
|
140
|
+
entry.status = status;
|
|
141
|
+
entry.endedAt = Date.now();
|
|
142
|
+
if (error) entry.error = error;
|
|
143
|
+
entry.settle();
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
const pump = (): void => {
|
|
147
|
+
while (running < maxConcurrent) {
|
|
148
|
+
const next = queue.shift();
|
|
149
|
+
if (!next) return;
|
|
150
|
+
if (next.status !== "queued") continue;
|
|
151
|
+
next.start();
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
const cancel = (entry: Entry, reason: string): void => {
|
|
156
|
+
if (isFinished(entry.status)) return;
|
|
157
|
+
const wasQueued = entry.status === "queued";
|
|
158
|
+
finish(entry, "cancelled", reason);
|
|
159
|
+
if (!wasQueued) entry.controller.abort();
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
const close = (reason = "The turn ended before this agent finished."): void => {
|
|
163
|
+
if (closed) return;
|
|
164
|
+
closed = true;
|
|
165
|
+
for (const entry of entries.values()) cancel(entry, reason);
|
|
166
|
+
queue.length = 0;
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
if (options.signal) {
|
|
170
|
+
if (options.signal.aborted) close("The turn was stopped.");
|
|
171
|
+
else
|
|
172
|
+
options.signal.addEventListener("abort", () => close("The turn was stopped."), {
|
|
173
|
+
once: true,
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const spawn = (input: {
|
|
178
|
+
prompt: string;
|
|
179
|
+
label: string;
|
|
180
|
+
kind: SubagentKind;
|
|
181
|
+
extraSystem: string;
|
|
182
|
+
}): Entry => {
|
|
183
|
+
counter += 1;
|
|
184
|
+
let settle: () => void = () => undefined;
|
|
185
|
+
const settled = new Promise<void>((resolve) => {
|
|
186
|
+
settle = resolve;
|
|
187
|
+
});
|
|
188
|
+
const entry: Entry = {
|
|
189
|
+
id: `bg_${counter}`,
|
|
190
|
+
label: input.label,
|
|
191
|
+
kind: input.kind,
|
|
192
|
+
status: "queued",
|
|
193
|
+
startedAt: Date.now(),
|
|
194
|
+
text: "",
|
|
195
|
+
controller: new AbortController(),
|
|
196
|
+
settled,
|
|
197
|
+
settle,
|
|
198
|
+
start: () => undefined,
|
|
199
|
+
announced: false,
|
|
200
|
+
};
|
|
201
|
+
const emit: AgentEventEmitter = (event) => {
|
|
202
|
+
if (event.kind === "text_delta") {
|
|
203
|
+
entry.text += event.text;
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
if (event.kind === "error") {
|
|
207
|
+
entry.error = event.message;
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
if (closed || isFinished(entry.status)) return;
|
|
211
|
+
// The parent's own stream carries the rest. A nested error or completion would end it.
|
|
212
|
+
if (
|
|
213
|
+
event.kind === "tool_call_start" ||
|
|
214
|
+
event.kind === "tool_call_end" ||
|
|
215
|
+
event.kind === "approval_request" ||
|
|
216
|
+
event.kind === "usage"
|
|
217
|
+
) {
|
|
218
|
+
options.parentEmit()(event);
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
entry.start = () => {
|
|
222
|
+
running += 1;
|
|
223
|
+
entry.status = "running";
|
|
224
|
+
entry.startedAt = Date.now();
|
|
225
|
+
void (async () => {
|
|
226
|
+
try {
|
|
227
|
+
await options.run({
|
|
228
|
+
prompt: input.prompt,
|
|
229
|
+
label: input.label,
|
|
230
|
+
kind: input.kind,
|
|
231
|
+
extraSystem: input.extraSystem,
|
|
232
|
+
emit,
|
|
233
|
+
signal: entry.controller.signal,
|
|
234
|
+
});
|
|
235
|
+
if (entry.error) finish(entry, "failed", entry.error);
|
|
236
|
+
else finish(entry, "done");
|
|
237
|
+
} catch (err) {
|
|
238
|
+
finish(entry, "failed", err instanceof Error ? err.message : String(err));
|
|
239
|
+
} finally {
|
|
240
|
+
running -= 1;
|
|
241
|
+
pump();
|
|
242
|
+
}
|
|
243
|
+
})();
|
|
244
|
+
};
|
|
245
|
+
entries.set(entry.id, entry);
|
|
246
|
+
queue.push(entry);
|
|
247
|
+
pump();
|
|
248
|
+
return entry;
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
const waitFor = async (targets: Entry[], timeoutMs: number): Promise<void> => {
|
|
252
|
+
const open = targets.filter((entry) => !isFinished(entry.status));
|
|
253
|
+
if (open.length === 0) return;
|
|
254
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
255
|
+
const timeout = new Promise<void>((resolve) => {
|
|
256
|
+
timer = setTimeout(resolve, timeoutMs);
|
|
257
|
+
});
|
|
258
|
+
try {
|
|
259
|
+
await Promise.race([Promise.all(open.map((entry) => entry.settled)), timeout]);
|
|
260
|
+
} finally {
|
|
261
|
+
if (timer) clearTimeout(timer);
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
const takeNotices = (): BackgroundAgentSnapshot[] => {
|
|
266
|
+
const done: BackgroundAgentSnapshot[] = [];
|
|
267
|
+
for (const entry of entries.values()) {
|
|
268
|
+
if (entry.announced || !isFinished(entry.status)) continue;
|
|
269
|
+
entry.announced = true;
|
|
270
|
+
done.push(snapshotOf(entry));
|
|
271
|
+
}
|
|
272
|
+
return done;
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
const spawnTool: McpToolDefinition = {
|
|
276
|
+
name: "spawn_agent",
|
|
277
|
+
description:
|
|
278
|
+
"Start a subagent in the background and return its id at once. You keep working while it runs. " +
|
|
279
|
+
"Use kind explore (read-only, fast) for search and research; spawn several in one step for independent questions. " +
|
|
280
|
+
"Pass a complete prompt: the agent does not see this conversation. Read the report with await_agents.",
|
|
281
|
+
annotations: {
|
|
282
|
+
readOnlyHint: false,
|
|
283
|
+
destructiveHint: false,
|
|
284
|
+
idempotentHint: false,
|
|
285
|
+
openWorldHint: true,
|
|
286
|
+
},
|
|
287
|
+
inputSchema: {
|
|
288
|
+
type: "object",
|
|
289
|
+
properties: {
|
|
290
|
+
prompt: { type: "string", description: "The full task for the agent." },
|
|
291
|
+
label: { type: "string", description: "Short name shown in the transcript." },
|
|
292
|
+
kind: {
|
|
293
|
+
type: "string",
|
|
294
|
+
enum: [...kinds],
|
|
295
|
+
description: `explore = read-only search and report. general = full tools. Default ${defaultKind}.`,
|
|
296
|
+
},
|
|
297
|
+
skills: {
|
|
298
|
+
type: "array",
|
|
299
|
+
items: { type: "string" },
|
|
300
|
+
description: "Skill names to load into the agent's system prompt.",
|
|
301
|
+
},
|
|
302
|
+
},
|
|
303
|
+
required: ["prompt"],
|
|
304
|
+
},
|
|
305
|
+
async handler(raw) {
|
|
306
|
+
if (closed) return errorResult("This turn is over; no agent was started.");
|
|
307
|
+
const prompt = typeof raw.prompt === "string" ? raw.prompt.trim() : "";
|
|
308
|
+
if (!prompt) return errorResult("prompt is empty");
|
|
309
|
+
if (entries.size >= maxAgents) {
|
|
310
|
+
return errorResult(
|
|
311
|
+
`This turn already started ${maxAgents} background agents. Read their reports with await_agents.`,
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
const requested = raw.kind === "general" || raw.kind === "explore" ? raw.kind : defaultKind;
|
|
315
|
+
if (!kinds.includes(requested)) {
|
|
316
|
+
return errorResult(`kind ${requested} is not available here. Use ${kinds.join(" or ")}.`);
|
|
317
|
+
}
|
|
318
|
+
const label =
|
|
319
|
+
typeof raw.label === "string" && raw.label.trim() ? raw.label.trim() : requested;
|
|
320
|
+
const names = Array.isArray(raw.skills)
|
|
321
|
+
? raw.skills.filter((s): s is string => typeof s === "string")
|
|
322
|
+
: [];
|
|
323
|
+
const extraSystem = options.skills ? skillBodiesForNames(options.skills, names) : "";
|
|
324
|
+
const entry = spawn({ prompt, label, kind: requested, extraSystem });
|
|
325
|
+
return jsonResult({ id: entry.id, label, kind: requested, status: entry.status });
|
|
326
|
+
},
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
const awaitTool: McpToolDefinition = {
|
|
330
|
+
name: "await_agents",
|
|
331
|
+
description:
|
|
332
|
+
"Wait for background agents and return their reports. With no ids it waits for every agent started this turn. " +
|
|
333
|
+
"An agent still running when the wait ends comes back with status running; call again to keep waiting.",
|
|
334
|
+
annotations: READ_ONLY_ANNOTATIONS,
|
|
335
|
+
inputSchema: {
|
|
336
|
+
type: "object",
|
|
337
|
+
properties: {
|
|
338
|
+
ids: {
|
|
339
|
+
type: "array",
|
|
340
|
+
items: { type: "string" },
|
|
341
|
+
description: "Agent ids from spawn_agent. Omit for all.",
|
|
342
|
+
},
|
|
343
|
+
timeout_seconds: {
|
|
344
|
+
type: "number",
|
|
345
|
+
description: `How long to wait (default ${DEFAULT_AWAIT_SECONDS}, max ${MAX_AWAIT_SECONDS}). 0 returns the current state without waiting.`,
|
|
346
|
+
},
|
|
347
|
+
},
|
|
348
|
+
},
|
|
349
|
+
async handler(raw) {
|
|
350
|
+
const ids = Array.isArray(raw.ids)
|
|
351
|
+
? raw.ids.filter((id): id is string => typeof id === "string")
|
|
352
|
+
: [];
|
|
353
|
+
const unknown = ids.filter((id) => !entries.has(id));
|
|
354
|
+
if (unknown.length > 0) return errorResult(`No background agent ${unknown.join(", ")}.`);
|
|
355
|
+
const targets =
|
|
356
|
+
ids.length > 0
|
|
357
|
+
? ids.map((id) => entries.get(id)).filter((entry): entry is Entry => Boolean(entry))
|
|
358
|
+
: [...entries.values()];
|
|
359
|
+
if (targets.length === 0) return errorResult("No background agents were started this turn.");
|
|
360
|
+
const seconds =
|
|
361
|
+
typeof raw.timeout_seconds === "number" && Number.isFinite(raw.timeout_seconds)
|
|
362
|
+
? Math.min(Math.max(raw.timeout_seconds, 0), MAX_AWAIT_SECONDS)
|
|
363
|
+
: DEFAULT_AWAIT_SECONDS;
|
|
364
|
+
if (seconds > 0) await waitFor(targets, seconds * 1000);
|
|
365
|
+
for (const entry of targets) {
|
|
366
|
+
if (isFinished(entry.status)) entry.announced = true;
|
|
367
|
+
}
|
|
368
|
+
return jsonResult({ agents: targets.map(snapshotOf) });
|
|
369
|
+
},
|
|
370
|
+
};
|
|
371
|
+
|
|
372
|
+
const cancelTool: McpToolDefinition = {
|
|
373
|
+
name: "cancel_agent",
|
|
374
|
+
description: "Stop a background agent whose result is no longer needed.",
|
|
375
|
+
annotations: {
|
|
376
|
+
readOnlyHint: false,
|
|
377
|
+
destructiveHint: false,
|
|
378
|
+
idempotentHint: true,
|
|
379
|
+
openWorldHint: false,
|
|
380
|
+
},
|
|
381
|
+
inputSchema: {
|
|
382
|
+
type: "object",
|
|
383
|
+
properties: { id: { type: "string", description: "Agent id from spawn_agent." } },
|
|
384
|
+
required: ["id"],
|
|
385
|
+
},
|
|
386
|
+
async handler(raw) {
|
|
387
|
+
const id = typeof raw.id === "string" ? raw.id.trim() : "";
|
|
388
|
+
const entry = entries.get(id);
|
|
389
|
+
if (!entry) return errorResult(`No background agent ${id || "(empty id)"}.`);
|
|
390
|
+
cancel(entry, "Cancelled by the agent.");
|
|
391
|
+
entry.announced = true;
|
|
392
|
+
pump();
|
|
393
|
+
return jsonResult({ id: entry.id, status: entry.status });
|
|
394
|
+
},
|
|
395
|
+
};
|
|
396
|
+
|
|
397
|
+
return {
|
|
398
|
+
tools: [spawnTool, awaitTool, cancelTool],
|
|
399
|
+
withNotices(tool) {
|
|
400
|
+
return {
|
|
401
|
+
...tool,
|
|
402
|
+
async handler(input) {
|
|
403
|
+
const result = await tool.handler(input);
|
|
404
|
+
const done = takeNotices();
|
|
405
|
+
if (done.length === 0) return result;
|
|
406
|
+
const names = done.map((agent) => `${agent.id} (${agent.label}, ${agent.status})`);
|
|
407
|
+
const note = `[background agents] finished: ${names.join(", ")}. Call await_agents to read the reports.`;
|
|
408
|
+
return {
|
|
409
|
+
...result,
|
|
410
|
+
content: [...result.content, { type: "text" as const, text: note }],
|
|
411
|
+
...(result.structuredContent
|
|
412
|
+
? {
|
|
413
|
+
structuredContent: {
|
|
414
|
+
...result.structuredContent,
|
|
415
|
+
background_agents_finished: done.map((agent) => agent.id),
|
|
416
|
+
},
|
|
417
|
+
}
|
|
418
|
+
: {}),
|
|
419
|
+
};
|
|
420
|
+
},
|
|
421
|
+
};
|
|
422
|
+
},
|
|
423
|
+
snapshot: () => [...entries.values()].map(snapshotOf),
|
|
424
|
+
pending: () => [...entries.values()].filter((entry) => !isFinished(entry.status)).length,
|
|
425
|
+
close,
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** The tools an explore agent may use: the ones that declare themselves read-only. */
|
|
430
|
+
export function readOnlyTools(tools: McpToolDefinition[]): McpToolDefinition[] {
|
|
431
|
+
return tools.filter((tool) => tool.annotations.readOnlyHint);
|
|
432
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import {
|
|
2
|
+
errorResult,
|
|
3
|
+
jsonResult,
|
|
4
|
+
type McpToolDefinition,
|
|
5
|
+
READ_ONLY_ANNOTATIONS,
|
|
6
|
+
} from "../core/mcp.ts";
|
|
7
|
+
import type { MemoryStore } from "../memory/memory-store.ts";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Let the model look things up in memory mid-turn, and save a fact the user asked it to keep.
|
|
11
|
+
* The facts recalled for the user's message are already in the system prompt; these cover a
|
|
12
|
+
* question that only comes up later in the turn.
|
|
13
|
+
*/
|
|
14
|
+
export function createMemoryTools(
|
|
15
|
+
store: MemoryStore,
|
|
16
|
+
options: { sessionId?: () => string | undefined } = {},
|
|
17
|
+
): McpToolDefinition[] {
|
|
18
|
+
return [
|
|
19
|
+
{
|
|
20
|
+
name: "memory_search",
|
|
21
|
+
description:
|
|
22
|
+
"Search facts remembered from earlier chats: the user's preferences, stack and tool choices, project decisions. " +
|
|
23
|
+
"Use it when you need something that is not in this conversation.",
|
|
24
|
+
annotations: READ_ONLY_ANNOTATIONS,
|
|
25
|
+
inputSchema: {
|
|
26
|
+
type: "object",
|
|
27
|
+
properties: {
|
|
28
|
+
query: { type: "string", description: "What to look for, in plain words." },
|
|
29
|
+
limit: { type: "number", description: "How many facts to return (default 8, max 25)." },
|
|
30
|
+
},
|
|
31
|
+
required: ["query"],
|
|
32
|
+
},
|
|
33
|
+
async handler(raw) {
|
|
34
|
+
const query = typeof raw.query === "string" ? raw.query.trim() : "";
|
|
35
|
+
if (!query) return errorResult("query is empty");
|
|
36
|
+
const limit =
|
|
37
|
+
typeof raw.limit === "number" && Number.isFinite(raw.limit)
|
|
38
|
+
? Math.min(Math.max(Math.floor(raw.limit), 1), 25)
|
|
39
|
+
: 8;
|
|
40
|
+
const facts = await store.search(query, limit);
|
|
41
|
+
return jsonResult({
|
|
42
|
+
query,
|
|
43
|
+
facts: facts.map((fact) => ({ text: fact.text, scope: fact.scope })),
|
|
44
|
+
});
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
name: "memory_save",
|
|
49
|
+
description:
|
|
50
|
+
"Remember one durable fact for later chats: a preference, a stack or tool choice, a project decision. " +
|
|
51
|
+
"One short sentence. Never a secret, a key, or a detail of the current task only.",
|
|
52
|
+
annotations: {
|
|
53
|
+
readOnlyHint: false,
|
|
54
|
+
destructiveHint: false,
|
|
55
|
+
idempotentHint: true,
|
|
56
|
+
openWorldHint: false,
|
|
57
|
+
},
|
|
58
|
+
inputSchema: {
|
|
59
|
+
type: "object",
|
|
60
|
+
properties: {
|
|
61
|
+
text: { type: "string", description: "The fact, as one short sentence." },
|
|
62
|
+
scope: {
|
|
63
|
+
type: "string",
|
|
64
|
+
enum: ["user", "project"],
|
|
65
|
+
description: "user = about the person. project = about this project. Default project.",
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
required: ["text"],
|
|
69
|
+
},
|
|
70
|
+
async handler(raw) {
|
|
71
|
+
const text = typeof raw.text === "string" ? raw.text.trim() : "";
|
|
72
|
+
if (!text) return errorResult("text is empty");
|
|
73
|
+
try {
|
|
74
|
+
const sessionId = options.sessionId?.();
|
|
75
|
+
const added = await store.add([
|
|
76
|
+
{
|
|
77
|
+
text,
|
|
78
|
+
scope: raw.scope === "user" ? "user" : "project",
|
|
79
|
+
...(sessionId ? { sessionId } : {}),
|
|
80
|
+
},
|
|
81
|
+
]);
|
|
82
|
+
return jsonResult({
|
|
83
|
+
saved: added.length > 0,
|
|
84
|
+
...(added.length === 0
|
|
85
|
+
? { reason: "Already remembered, too short or long, or it looked like a secret." }
|
|
86
|
+
: {}),
|
|
87
|
+
});
|
|
88
|
+
} catch (err) {
|
|
89
|
+
return errorResult(err instanceof Error ? err.message : String(err));
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
},
|
|
93
|
+
];
|
|
94
|
+
}
|