@useavalon/caelence-agent 0.3.0 → 0.5.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 +46 -8
- package/desktop/src/api.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/package.json +12 -4
- package/src/browser/browser-use.test.ts +54 -2
- package/src/browser/browser-use.ts +75 -3
- package/src/browser/own-chrome.test.ts +593 -0
- package/src/browser/own-chrome.ts +542 -0
- package/src/cli/tui-progress.ts +15 -3
- package/src/cli/tui.tsx +7 -0
- package/src/config.ts +31 -2
- package/src/core/approval.test.ts +126 -0
- package/src/core/approval.ts +17 -0
- package/src/core/events.ts +12 -1
- package/src/core/host-extensions.test.ts +605 -0
- package/src/core/mcp.ts +7 -0
- package/src/core/mode.ts +5 -0
- package/src/core/run-turn.test.ts +85 -0
- package/src/core/run-turn.ts +145 -28
- package/src/core/strands.test.ts +89 -0
- package/src/core/strands.ts +3 -1
- package/src/decisions/shortcuts.ts +5 -0
- package/src/desktop/bridge.ts +66 -12
- package/src/desktop/host.test.ts +244 -0
- package/src/desktop/host.ts +59 -0
- package/src/index.ts +122 -4
- 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.ts +253 -53
- 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,209 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { turnProgressLabel } from "../cli/tui-progress.ts";
|
|
6
|
+
import { DEFAULT_CONFIG } from "../config.ts";
|
|
7
|
+
import type { AgentEvent, MainModelProvider } from "../core/events.ts";
|
|
8
|
+
import type { ConstructAgent } from "../core/strands.ts";
|
|
9
|
+
import { createHarness } from "../runtime.ts";
|
|
10
|
+
import {
|
|
11
|
+
resolveStatusVerbPool,
|
|
12
|
+
statusVerbCategories,
|
|
13
|
+
statusVerbCategoryNames,
|
|
14
|
+
} from "./categories.ts";
|
|
15
|
+
import {
|
|
16
|
+
DEFAULT_STATUS_VERBS,
|
|
17
|
+
DEFAULT_STATUS_VERBS_PER_TURN,
|
|
18
|
+
pickStatusVerbs,
|
|
19
|
+
seededRandom,
|
|
20
|
+
statusVerbAt,
|
|
21
|
+
} from "./status-verbs.ts";
|
|
22
|
+
|
|
23
|
+
describe("status verb data", () => {
|
|
24
|
+
test("the built-in list and the categories are present and clean", () => {
|
|
25
|
+
expect(DEFAULT_STATUS_VERBS.length).toBeGreaterThan(150);
|
|
26
|
+
expect(DEFAULT_STATUS_VERBS).toContain("Pondering");
|
|
27
|
+
expect(new Set(DEFAULT_STATUS_VERBS).size).toBe(DEFAULT_STATUS_VERBS.length);
|
|
28
|
+
const categories = statusVerbCategories();
|
|
29
|
+
expect(statusVerbCategoryNames().length).toBeGreaterThan(100);
|
|
30
|
+
expect(categories["Coffee / Barista"]).toContain("Grinding beans");
|
|
31
|
+
// Left out on purpose: a verb naming another product, and lists that joke about the agent
|
|
32
|
+
// deleting files or misbehaving, which reads badly next to a real agent with file access.
|
|
33
|
+
expect(DEFAULT_STATUS_VERBS).not.toContain("Clauding");
|
|
34
|
+
const names = statusVerbCategoryNames().map((name) => name.toLowerCase());
|
|
35
|
+
expect(names.some((name) => name.startsWith("rogue agent"))).toBe(false);
|
|
36
|
+
expect(names.some((name) => name.startsWith("trolling"))).toBe(false);
|
|
37
|
+
expect(names.some((name) => name.includes("claude"))).toBe(false);
|
|
38
|
+
for (const [name, verbs] of Object.entries(categories)) {
|
|
39
|
+
expect(name.trim()).toBe(name);
|
|
40
|
+
expect(verbs.length).toBeGreaterThan(0);
|
|
41
|
+
expect(verbs.every((verb) => verb.trim().length > 0)).toBe(true);
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
describe("picking verbs", () => {
|
|
47
|
+
test("picks distinct verbs from the pool", () => {
|
|
48
|
+
const picked = pickStatusVerbs(DEFAULT_STATUS_VERBS, 6);
|
|
49
|
+
expect(picked).toHaveLength(6);
|
|
50
|
+
expect(new Set(picked).size).toBe(6);
|
|
51
|
+
expect(picked.every((verb) => DEFAULT_STATUS_VERBS.includes(verb))).toBe(true);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test("the same seed gives the same pick, a different seed another", () => {
|
|
55
|
+
const first = pickStatusVerbs(DEFAULT_STATUS_VERBS, 6, seededRandom(7));
|
|
56
|
+
expect(pickStatusVerbs(DEFAULT_STATUS_VERBS, 6, seededRandom(7))).toEqual(first);
|
|
57
|
+
expect(pickStatusVerbs(DEFAULT_STATUS_VERBS, 6, seededRandom(8))).not.toEqual(first);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test("a small or messy pool gives what it has", () => {
|
|
61
|
+
expect(pickStatusVerbs(["Brewing", " Brewing ", "", "Baking"], 6).sort()).toEqual([
|
|
62
|
+
"Baking",
|
|
63
|
+
"Brewing",
|
|
64
|
+
]);
|
|
65
|
+
expect(pickStatusVerbs([], 6)).toEqual([]);
|
|
66
|
+
expect(pickStatusVerbs(["Brewing"], 0)).toEqual([]);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test("statusVerbAt walks the verbs and falls back to Thinking", () => {
|
|
70
|
+
expect(statusVerbAt(["A", "B"], 0, 3)).toBe("A");
|
|
71
|
+
expect(statusVerbAt(["A", "B"], 2, 3)).toBe("A");
|
|
72
|
+
expect(statusVerbAt(["A", "B"], 3, 3)).toBe("B");
|
|
73
|
+
expect(statusVerbAt(["A", "B"], 6, 3)).toBe("A");
|
|
74
|
+
expect(statusVerbAt([], 4)).toBe("Thinking");
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
describe("resolving the pool from config", () => {
|
|
79
|
+
test("defaults to the built-in list", () => {
|
|
80
|
+
expect(resolveStatusVerbPool(undefined).pool).toEqual([...DEFAULT_STATUS_VERBS]);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test("off means no verbs", () => {
|
|
84
|
+
expect(resolveStatusVerbPool({ enabled: false, custom: ["Brewing"] }).pool).toEqual([]);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test("categories match without case, and a typo is reported", () => {
|
|
88
|
+
const { pool, unknown } = resolveStatusVerbPool({
|
|
89
|
+
defaults: false,
|
|
90
|
+
categories: ["coffee / barista", "Coffe"],
|
|
91
|
+
});
|
|
92
|
+
expect(pool).toEqual(statusVerbCategories()["Coffee / Barista"] ?? []);
|
|
93
|
+
expect(unknown).toEqual(["Coffe"]);
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test("custom verbs are added once, and all categories can be asked for", () => {
|
|
97
|
+
const custom = resolveStatusVerbPool({
|
|
98
|
+
defaults: false,
|
|
99
|
+
custom: ["Shipping", "Shipping", " "],
|
|
100
|
+
});
|
|
101
|
+
expect(custom.pool).toEqual(["Shipping"]);
|
|
102
|
+
const all = resolveStatusVerbPool({ categories: "all" });
|
|
103
|
+
expect(all.pool.length).toBeGreaterThan(5000);
|
|
104
|
+
expect(new Set(all.pool).size).toBe(all.pool.length);
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
describe("the TUI progress label", () => {
|
|
109
|
+
test("shows the turn's verbs while thinking and between tools", () => {
|
|
110
|
+
const verbs = ["Brewing", "Baking"];
|
|
111
|
+
expect(
|
|
112
|
+
turnProgressLabel({ tools: [], assistantStarted: false, tick: 0, warmupSeed: 0, verbs }),
|
|
113
|
+
).toBe("Brewing");
|
|
114
|
+
expect(
|
|
115
|
+
turnProgressLabel({ tools: [], assistantStarted: false, tick: 7, warmupSeed: 0, verbs }),
|
|
116
|
+
).toBe("Baking...");
|
|
117
|
+
const done = [{ name: "grep", preview: "x", status: "ok" as const }];
|
|
118
|
+
expect(
|
|
119
|
+
turnProgressLabel({
|
|
120
|
+
tools: done as never,
|
|
121
|
+
assistantStarted: false,
|
|
122
|
+
tick: 0,
|
|
123
|
+
warmupSeed: 0,
|
|
124
|
+
verbs,
|
|
125
|
+
}),
|
|
126
|
+
).toBe("Brewing…");
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
test("a running tool and the reply keep their own labels", () => {
|
|
130
|
+
const running = [{ name: "read_file", preview: "a.ts", status: "running" as const }];
|
|
131
|
+
expect(
|
|
132
|
+
turnProgressLabel({
|
|
133
|
+
tools: running as never,
|
|
134
|
+
assistantStarted: false,
|
|
135
|
+
tick: 0,
|
|
136
|
+
warmupSeed: 0,
|
|
137
|
+
verbs: ["Brewing"],
|
|
138
|
+
}),
|
|
139
|
+
).toBe("Reading a.ts");
|
|
140
|
+
expect(
|
|
141
|
+
turnProgressLabel({
|
|
142
|
+
tools: [],
|
|
143
|
+
assistantStarted: true,
|
|
144
|
+
tick: 0,
|
|
145
|
+
warmupSeed: 0,
|
|
146
|
+
verbs: ["Brewing"],
|
|
147
|
+
}),
|
|
148
|
+
).toBe("Writing");
|
|
149
|
+
});
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
describe("the status event", () => {
|
|
153
|
+
const fakeProvider: MainModelProvider = {
|
|
154
|
+
kind: "fake",
|
|
155
|
+
modelId: "fake",
|
|
156
|
+
async *stream() {
|
|
157
|
+
yield { type: "done" };
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
const sayOk: ConstructAgent = () => ({
|
|
161
|
+
async run(_message, emit) {
|
|
162
|
+
emit({ kind: "text_delta", text: "ok" });
|
|
163
|
+
},
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
async function statusEvents(config: Partial<typeof DEFAULT_CONFIG>): Promise<AgentEvent[]> {
|
|
167
|
+
const cwd = await mkdtemp(join(tmpdir(), "harness-verbs-"));
|
|
168
|
+
try {
|
|
169
|
+
const harness = await createHarness({
|
|
170
|
+
cwd,
|
|
171
|
+
config: { ...DEFAULT_CONFIG, ...config },
|
|
172
|
+
provider: fakeProvider,
|
|
173
|
+
constructAgent: sayOk,
|
|
174
|
+
});
|
|
175
|
+
const events: AgentEvent[] = [];
|
|
176
|
+
await harness.runTurn("hi", (event) => events.push(event));
|
|
177
|
+
harness.close();
|
|
178
|
+
return events;
|
|
179
|
+
} finally {
|
|
180
|
+
await rm(cwd, { recursive: true, force: true });
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
test("a turn starts with one status event carrying verbs from the built-in list", async () => {
|
|
185
|
+
const events = await statusEvents({});
|
|
186
|
+
const status = events.filter((event) => event.kind === "status");
|
|
187
|
+
expect(status).toHaveLength(1);
|
|
188
|
+
const verbs = status[0]?.kind === "status" ? status[0].verbs : [];
|
|
189
|
+
expect(verbs).toHaveLength(DEFAULT_STATUS_VERBS_PER_TURN);
|
|
190
|
+
expect(verbs.every((verb) => DEFAULT_STATUS_VERBS.includes(verb))).toBe(true);
|
|
191
|
+
const kinds = events.map((event) => event.kind);
|
|
192
|
+
expect(kinds.indexOf("status")).toBeLessThan(kinds.indexOf("text_delta"));
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
test("config picks the pool and the count", async () => {
|
|
196
|
+
const events = await statusEvents({
|
|
197
|
+
statusVerbs: { defaults: false, custom: ["Shipping", "Polishing", "Testing"], perTurn: 2 },
|
|
198
|
+
});
|
|
199
|
+
const status = events.find((event) => event.kind === "status");
|
|
200
|
+
const verbs = status?.kind === "status" ? status.verbs : [];
|
|
201
|
+
expect(verbs).toHaveLength(2);
|
|
202
|
+
expect(verbs.every((verb) => ["Shipping", "Polishing", "Testing"].includes(verb))).toBe(true);
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
test("turned off, no status event is sent", async () => {
|
|
206
|
+
const events = await statusEvents({ statusVerbs: { enabled: false } });
|
|
207
|
+
expect(events.some((event) => event.kind === "status")).toBe(false);
|
|
208
|
+
});
|
|
209
|
+
});
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { DEFAULT_STATUS_VERBS } from "./default-verbs.ts";
|
|
2
|
+
|
|
3
|
+
export { DEFAULT_STATUS_VERBS };
|
|
4
|
+
|
|
5
|
+
/** What a UI shows when a turn carries no verbs. */
|
|
6
|
+
export const FALLBACK_STATUS_VERB = "Thinking";
|
|
7
|
+
|
|
8
|
+
/** How many verbs a turn gets. A UI rotates through them while the agent is thinking. */
|
|
9
|
+
export const DEFAULT_STATUS_VERBS_PER_TURN = 6;
|
|
10
|
+
|
|
11
|
+
export interface StatusVerbsConfig {
|
|
12
|
+
/** false sends no verbs; UIs then show their plain "Thinking". Default on. */
|
|
13
|
+
enabled?: boolean;
|
|
14
|
+
/** Include the built-in list. Default true. */
|
|
15
|
+
defaults?: boolean;
|
|
16
|
+
/** Themed lists to add, by name ("Coffee / Barista"), or "all". Names match without case. */
|
|
17
|
+
categories?: readonly string[] | "all";
|
|
18
|
+
/** Your own verbs or short phrases, added to the pool. */
|
|
19
|
+
custom?: readonly string[];
|
|
20
|
+
/** Verbs sent with each turn. Default 6. */
|
|
21
|
+
perTurn?: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Pick `count` different verbs from the pool, in random order. `random` returns a number in
|
|
26
|
+
* [0, 1) and exists so a test can make the pick repeatable.
|
|
27
|
+
*/
|
|
28
|
+
export function pickStatusVerbs(
|
|
29
|
+
pool: readonly string[],
|
|
30
|
+
count = DEFAULT_STATUS_VERBS_PER_TURN,
|
|
31
|
+
random: () => number = Math.random,
|
|
32
|
+
): string[] {
|
|
33
|
+
const unique = [...new Set(pool.map((verb) => verb.trim()).filter(Boolean))];
|
|
34
|
+
const wanted = Math.max(0, Math.min(Math.floor(count), unique.length));
|
|
35
|
+
// A partial Fisher-Yates shuffle: only the first `wanted` places are settled.
|
|
36
|
+
for (let i = 0; i < wanted; i += 1) {
|
|
37
|
+
const j = i + Math.floor(random() * (unique.length - i));
|
|
38
|
+
const held = unique[i] as string;
|
|
39
|
+
unique[i] = unique[j] as string;
|
|
40
|
+
unique[j] = held;
|
|
41
|
+
}
|
|
42
|
+
return unique.slice(0, wanted);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** A repeatable random source, for UIs that pick from a seed such as the turn number. */
|
|
46
|
+
export function seededRandom(seed: number): () => number {
|
|
47
|
+
let state = (Math.floor(seed) ^ 0x9e3779b9) >>> 0;
|
|
48
|
+
return () => {
|
|
49
|
+
state = (state + 0x6d2b79f5) >>> 0;
|
|
50
|
+
let t = state;
|
|
51
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
52
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
53
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The verb to show now: the turn's verbs in order, one every `every` ticks. */
|
|
58
|
+
export function statusVerbAt(verbs: readonly string[], tick: number, every = 1): string {
|
|
59
|
+
if (verbs.length === 0) return FALLBACK_STATUS_VERB;
|
|
60
|
+
const step = Math.floor(Math.max(0, tick) / Math.max(1, every));
|
|
61
|
+
return verbs[step % verbs.length] ?? FALLBACK_STATUS_VERB;
|
|
62
|
+
}
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { DEFAULT_CONFIG } from "../config.ts";
|
|
6
|
+
import type { AgentEvent, AgentEventEmitter, MainModelProvider } from "../core/events.ts";
|
|
7
|
+
import { jsonResult, type McpToolDefinition, READ_ONLY_ANNOTATIONS } from "../core/mcp.ts";
|
|
8
|
+
import type { ConstructAgent } from "../core/strands.ts";
|
|
9
|
+
import { createHarness } from "../runtime.ts";
|
|
10
|
+
import {
|
|
11
|
+
type BackgroundAgentRunInput,
|
|
12
|
+
type BackgroundAgentSnapshot,
|
|
13
|
+
createBackgroundAgents,
|
|
14
|
+
readOnlyTools,
|
|
15
|
+
} from "./background.ts";
|
|
16
|
+
|
|
17
|
+
const fakeProvider: MainModelProvider = {
|
|
18
|
+
kind: "fake",
|
|
19
|
+
modelId: "fake",
|
|
20
|
+
async *stream() {
|
|
21
|
+
yield { type: "done" };
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** A run function the test finishes by hand, one agent at a time. */
|
|
26
|
+
function manualRuns() {
|
|
27
|
+
const started: Array<BackgroundAgentRunInput & { finish(text?: string): void }> = [];
|
|
28
|
+
const run = (input: BackgroundAgentRunInput): Promise<void> =>
|
|
29
|
+
new Promise<void>((resolve, reject) => {
|
|
30
|
+
input.signal.addEventListener("abort", () => reject(new Error("aborted")), { once: true });
|
|
31
|
+
started.push({
|
|
32
|
+
...input,
|
|
33
|
+
finish(text = "report") {
|
|
34
|
+
input.emit({ kind: "text_delta", text });
|
|
35
|
+
resolve();
|
|
36
|
+
},
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
return { started, run };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function toolNamed(tools: McpToolDefinition[], name: string): McpToolDefinition {
|
|
43
|
+
const tool = tools.find((item) => item.name === name);
|
|
44
|
+
if (!tool) throw new Error(`${name} missing`);
|
|
45
|
+
return tool;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function agentsOf(result: { structuredContent?: Record<string, unknown> }) {
|
|
49
|
+
return (result.structuredContent?.agents ?? []) as BackgroundAgentSnapshot[];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const noEmit: AgentEventEmitter = () => undefined;
|
|
53
|
+
|
|
54
|
+
describe("background agents", () => {
|
|
55
|
+
test("spawn returns at once and await returns the report", async () => {
|
|
56
|
+
const runs = manualRuns();
|
|
57
|
+
const bg = createBackgroundAgents({ run: runs.run, parentEmit: () => noEmit });
|
|
58
|
+
const spawned = await toolNamed(bg.tools, "spawn_agent").handler({
|
|
59
|
+
prompt: "find the router",
|
|
60
|
+
label: "router",
|
|
61
|
+
});
|
|
62
|
+
expect(spawned.isError).toBeFalsy();
|
|
63
|
+
expect(spawned.structuredContent).toMatchObject({ id: "bg_1", kind: "explore" });
|
|
64
|
+
expect(bg.pending()).toBe(1);
|
|
65
|
+
expect(runs.started[0]?.kind).toBe("explore");
|
|
66
|
+
|
|
67
|
+
const waiting = toolNamed(bg.tools, "await_agents").handler({});
|
|
68
|
+
runs.started[0]?.finish("router is in src/router.ts:12");
|
|
69
|
+
const [agent] = agentsOf(await waiting);
|
|
70
|
+
expect(agent).toMatchObject({
|
|
71
|
+
id: "bg_1",
|
|
72
|
+
status: "done",
|
|
73
|
+
result: "router is in src/router.ts:12",
|
|
74
|
+
});
|
|
75
|
+
expect(bg.pending()).toBe(0);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test("runs at most maxConcurrent at once and queues the rest", async () => {
|
|
79
|
+
const runs = manualRuns();
|
|
80
|
+
const bg = createBackgroundAgents({
|
|
81
|
+
run: runs.run,
|
|
82
|
+
parentEmit: () => noEmit,
|
|
83
|
+
maxConcurrent: 2,
|
|
84
|
+
});
|
|
85
|
+
const spawn = toolNamed(bg.tools, "spawn_agent");
|
|
86
|
+
await Promise.all(["a", "b", "c"].map((label) => spawn.handler({ prompt: label, label })));
|
|
87
|
+
expect(runs.started).toHaveLength(2);
|
|
88
|
+
expect(bg.snapshot().map((agent) => agent.status)).toEqual(["running", "running", "queued"]);
|
|
89
|
+
runs.started[0]?.finish();
|
|
90
|
+
await Bun.sleep(0);
|
|
91
|
+
expect(runs.started).toHaveLength(3);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
test("refuses more agents than the per-turn cap", async () => {
|
|
95
|
+
const runs = manualRuns();
|
|
96
|
+
const bg = createBackgroundAgents({ run: runs.run, parentEmit: () => noEmit, maxAgents: 1 });
|
|
97
|
+
const spawn = toolNamed(bg.tools, "spawn_agent");
|
|
98
|
+
expect((await spawn.handler({ prompt: "one" })).isError).toBeFalsy();
|
|
99
|
+
expect((await spawn.handler({ prompt: "two" })).isError).toBe(true);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
test("refuses a kind the host did not offer", async () => {
|
|
103
|
+
const runs = manualRuns();
|
|
104
|
+
const bg = createBackgroundAgents({
|
|
105
|
+
run: runs.run,
|
|
106
|
+
parentEmit: () => noEmit,
|
|
107
|
+
kinds: ["explore"],
|
|
108
|
+
});
|
|
109
|
+
const result = await toolNamed(bg.tools, "spawn_agent").handler({
|
|
110
|
+
prompt: "edit it",
|
|
111
|
+
kind: "general",
|
|
112
|
+
});
|
|
113
|
+
expect(result.isError).toBe(true);
|
|
114
|
+
expect(runs.started).toHaveLength(0);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
test("await with a timeout reports an agent that is still running", async () => {
|
|
118
|
+
const runs = manualRuns();
|
|
119
|
+
const bg = createBackgroundAgents({ run: runs.run, parentEmit: () => noEmit });
|
|
120
|
+
await toolNamed(bg.tools, "spawn_agent").handler({ prompt: "slow" });
|
|
121
|
+
const result = await toolNamed(bg.tools, "await_agents").handler({ timeout_seconds: 0.01 });
|
|
122
|
+
expect(agentsOf(result)[0]?.status).toBe("running");
|
|
123
|
+
expect(agentsOf(result)[0]?.result).toBeUndefined();
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
test("a failed run is reported as failed, with the error", async () => {
|
|
127
|
+
const bg = createBackgroundAgents({
|
|
128
|
+
run: async () => {
|
|
129
|
+
throw new Error("model unavailable");
|
|
130
|
+
},
|
|
131
|
+
parentEmit: () => noEmit,
|
|
132
|
+
});
|
|
133
|
+
await toolNamed(bg.tools, "spawn_agent").handler({ prompt: "x" });
|
|
134
|
+
const [agent] = agentsOf(await toolNamed(bg.tools, "await_agents").handler({}));
|
|
135
|
+
expect(agent).toMatchObject({ status: "failed", error: "model unavailable" });
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
test("another tool's result announces a finished agent once", async () => {
|
|
139
|
+
const runs = manualRuns();
|
|
140
|
+
const bg = createBackgroundAgents({ run: runs.run, parentEmit: () => noEmit });
|
|
141
|
+
const grep = bg.withNotices({
|
|
142
|
+
name: "grep",
|
|
143
|
+
description: "search",
|
|
144
|
+
annotations: READ_ONLY_ANNOTATIONS,
|
|
145
|
+
inputSchema: { type: "object", properties: {} },
|
|
146
|
+
handler: async () => jsonResult({ hits: [] }),
|
|
147
|
+
});
|
|
148
|
+
await toolNamed(bg.tools, "spawn_agent").handler({ prompt: "x", label: "auth" });
|
|
149
|
+
expect((await grep.handler({})).content).toHaveLength(1);
|
|
150
|
+
|
|
151
|
+
runs.started[0]?.finish();
|
|
152
|
+
await Bun.sleep(0);
|
|
153
|
+
const noticed = await grep.handler({});
|
|
154
|
+
expect(noticed.content[1]?.text).toContain("bg_1 (auth, done)");
|
|
155
|
+
expect(noticed.structuredContent).toMatchObject({
|
|
156
|
+
hits: [],
|
|
157
|
+
background_agents_finished: ["bg_1"],
|
|
158
|
+
});
|
|
159
|
+
expect((await grep.handler({})).content).toHaveLength(1);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
test("close cancels what is running and stops forwarding its events", async () => {
|
|
163
|
+
const runs = manualRuns();
|
|
164
|
+
const seen: AgentEvent[] = [];
|
|
165
|
+
const bg = createBackgroundAgents({
|
|
166
|
+
run: runs.run,
|
|
167
|
+
parentEmit: () => (event) => {
|
|
168
|
+
seen.push(event);
|
|
169
|
+
},
|
|
170
|
+
});
|
|
171
|
+
await toolNamed(bg.tools, "spawn_agent").handler({ prompt: "x" });
|
|
172
|
+
const agent = runs.started[0];
|
|
173
|
+
agent?.emit({ kind: "tool_call_start", toolName: "grep", callId: "c1", input: {} });
|
|
174
|
+
expect(seen).toHaveLength(1);
|
|
175
|
+
bg.close();
|
|
176
|
+
expect(agent?.signal.aborted).toBe(true);
|
|
177
|
+
agent?.emit({ kind: "tool_call_start", toolName: "grep", callId: "c2", input: {} });
|
|
178
|
+
expect(seen).toHaveLength(1);
|
|
179
|
+
expect(bg.snapshot()[0]?.status).toBe("cancelled");
|
|
180
|
+
expect((await toolNamed(bg.tools, "spawn_agent").handler({ prompt: "late" })).isError).toBe(
|
|
181
|
+
true,
|
|
182
|
+
);
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
test("the parent signal cancels every agent", async () => {
|
|
186
|
+
const runs = manualRuns();
|
|
187
|
+
const controller = new AbortController();
|
|
188
|
+
const bg = createBackgroundAgents({
|
|
189
|
+
run: runs.run,
|
|
190
|
+
parentEmit: () => noEmit,
|
|
191
|
+
signal: controller.signal,
|
|
192
|
+
});
|
|
193
|
+
await toolNamed(bg.tools, "spawn_agent").handler({ prompt: "x" });
|
|
194
|
+
controller.abort();
|
|
195
|
+
expect(bg.snapshot()[0]?.status).toBe("cancelled");
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
test("nested errors and text never reach the parent stream", async () => {
|
|
199
|
+
const seen: AgentEvent[] = [];
|
|
200
|
+
const bg = createBackgroundAgents({
|
|
201
|
+
run: async ({ emit }) => {
|
|
202
|
+
emit({ kind: "text_delta", text: "partial" });
|
|
203
|
+
emit({ kind: "error", message: "boom" });
|
|
204
|
+
emit({ kind: "completion" });
|
|
205
|
+
},
|
|
206
|
+
parentEmit: () => (event) => {
|
|
207
|
+
seen.push(event);
|
|
208
|
+
},
|
|
209
|
+
});
|
|
210
|
+
await toolNamed(bg.tools, "spawn_agent").handler({ prompt: "x" });
|
|
211
|
+
const [agent] = agentsOf(await toolNamed(bg.tools, "await_agents").handler({}));
|
|
212
|
+
expect(agent).toMatchObject({ status: "failed", error: "boom", result: "partial" });
|
|
213
|
+
expect(seen).toHaveLength(0);
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
test("readOnlyTools keeps only tools that declare themselves read-only", () => {
|
|
217
|
+
const make = (name: string, readOnlyHint: boolean): McpToolDefinition => ({
|
|
218
|
+
name,
|
|
219
|
+
description: name,
|
|
220
|
+
annotations: { ...READ_ONLY_ANNOTATIONS, readOnlyHint },
|
|
221
|
+
inputSchema: { type: "object", properties: {} },
|
|
222
|
+
handler: async () => jsonResult({}),
|
|
223
|
+
});
|
|
224
|
+
expect(
|
|
225
|
+
readOnlyTools([make("grep", true), make("write_file", false)]).map((t) => t.name),
|
|
226
|
+
).toEqual(["grep"]);
|
|
227
|
+
});
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
describe("background agents in the harness", () => {
|
|
231
|
+
test("an explore agent runs in the background with read-only tools", async () => {
|
|
232
|
+
const cwd = await mkdtemp(join(tmpdir(), "harness-bg-"));
|
|
233
|
+
try {
|
|
234
|
+
await writeFile(join(cwd, "notes.txt"), "the answer is 42");
|
|
235
|
+
let exploreTools: string[] = [];
|
|
236
|
+
let exploreSystem = "";
|
|
237
|
+
let report = "";
|
|
238
|
+
const constructAgent: ConstructAgent = (input) => ({
|
|
239
|
+
async run(_message, emit) {
|
|
240
|
+
const spawn = input.tools.find((t) => t.name === "spawn_agent");
|
|
241
|
+
if (spawn) {
|
|
242
|
+
await spawn.invoke({ prompt: "read notes.txt", label: "notes" });
|
|
243
|
+
const waited = await input.tools
|
|
244
|
+
.find((t) => t.name === "await_agents")
|
|
245
|
+
?.invoke({ timeout_seconds: 5 });
|
|
246
|
+
report = JSON.stringify(waited?.structuredContent ?? {});
|
|
247
|
+
emit({ kind: "text_delta", text: "parent" });
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
exploreTools = input.tools.map((t) => t.name);
|
|
251
|
+
exploreSystem = input.systemPrompt;
|
|
252
|
+
const read = input.tools.find((t) => t.name === "read_file");
|
|
253
|
+
const result = await read?.invoke({ path: "notes.txt" });
|
|
254
|
+
emit({ kind: "text_delta", text: JSON.stringify(result ?? {}) });
|
|
255
|
+
},
|
|
256
|
+
});
|
|
257
|
+
const harness = await createHarness({
|
|
258
|
+
cwd,
|
|
259
|
+
config: { ...DEFAULT_CONFIG, tools: { exec: { approval: "deny" } } },
|
|
260
|
+
provider: fakeProvider,
|
|
261
|
+
constructAgent,
|
|
262
|
+
approvalPolicy: "deny",
|
|
263
|
+
});
|
|
264
|
+
await harness.runTurn("where is the answer", () => undefined);
|
|
265
|
+
expect(exploreTools).toContain("read_file");
|
|
266
|
+
expect(exploreTools).toContain("grep");
|
|
267
|
+
expect(exploreTools).not.toContain("write_file");
|
|
268
|
+
expect(exploreTools).not.toContain("exec");
|
|
269
|
+
expect(exploreTools).not.toContain("spawn_agent");
|
|
270
|
+
expect(exploreTools).not.toContain("task");
|
|
271
|
+
expect(exploreSystem).toContain("read-only explorer");
|
|
272
|
+
expect(report).toContain("the answer is 42");
|
|
273
|
+
expect(report).toContain('"status":"done"');
|
|
274
|
+
harness.close();
|
|
275
|
+
} finally {
|
|
276
|
+
await rm(cwd, { recursive: true, force: true });
|
|
277
|
+
}
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
test("background agents can be turned off", async () => {
|
|
281
|
+
const cwd = await mkdtemp(join(tmpdir(), "harness-bg-off-"));
|
|
282
|
+
try {
|
|
283
|
+
let names: string[] = [];
|
|
284
|
+
const constructAgent: ConstructAgent = (input) => ({
|
|
285
|
+
async run(_message, emit) {
|
|
286
|
+
names = input.tools.map((t) => t.name);
|
|
287
|
+
emit({ kind: "text_delta", text: "ok" });
|
|
288
|
+
},
|
|
289
|
+
});
|
|
290
|
+
const harness = await createHarness({
|
|
291
|
+
cwd,
|
|
292
|
+
config: { ...DEFAULT_CONFIG, subagents: { background: false } },
|
|
293
|
+
provider: fakeProvider,
|
|
294
|
+
constructAgent,
|
|
295
|
+
});
|
|
296
|
+
await harness.runTurn("hi", () => undefined);
|
|
297
|
+
expect(names).toContain("task");
|
|
298
|
+
expect(names).not.toContain("spawn_agent");
|
|
299
|
+
harness.close();
|
|
300
|
+
} finally {
|
|
301
|
+
await rm(cwd, { recursive: true, force: true });
|
|
302
|
+
}
|
|
303
|
+
});
|
|
304
|
+
});
|