@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.
Files changed (49) hide show
  1. package/README.md +46 -8
  2. package/desktop/src/api.ts +1 -0
  3. package/desktop/src/desktop-turn.ts +7 -0
  4. package/desktop/src/stream.ts +1 -0
  5. package/desktop/src/thought.test.ts +16 -0
  6. package/desktop/src/thought.ts +15 -4
  7. package/desktop/src/turn-verbs.ts +14 -0
  8. package/package.json +12 -4
  9. package/src/browser/browser-use.test.ts +54 -2
  10. package/src/browser/browser-use.ts +75 -3
  11. package/src/browser/own-chrome.test.ts +593 -0
  12. package/src/browser/own-chrome.ts +542 -0
  13. package/src/cli/tui-progress.ts +15 -3
  14. package/src/cli/tui.tsx +7 -0
  15. package/src/config.ts +31 -2
  16. package/src/core/approval.test.ts +126 -0
  17. package/src/core/approval.ts +17 -0
  18. package/src/core/events.ts +12 -1
  19. package/src/core/host-extensions.test.ts +605 -0
  20. package/src/core/mcp.ts +7 -0
  21. package/src/core/mode.ts +5 -0
  22. package/src/core/run-turn.test.ts +85 -0
  23. package/src/core/run-turn.ts +145 -28
  24. package/src/core/strands.test.ts +89 -0
  25. package/src/core/strands.ts +3 -1
  26. package/src/decisions/shortcuts.ts +5 -0
  27. package/src/desktop/bridge.ts +66 -12
  28. package/src/desktop/host.test.ts +244 -0
  29. package/src/desktop/host.ts +59 -0
  30. package/src/index.ts +122 -4
  31. package/src/memory/brief.ts +62 -0
  32. package/src/memory/embeddings.ts +104 -0
  33. package/src/memory/extract.ts +9 -8
  34. package/src/memory/layered.test.ts +202 -0
  35. package/src/memory/layered.ts +125 -0
  36. package/src/memory/memory-store.test.ts +299 -0
  37. package/src/memory/memory-store.ts +295 -0
  38. package/src/memory/store.ts +70 -20
  39. package/src/observability/langfuse.ts +9 -2
  40. package/src/observability/types.ts +5 -0
  41. package/src/runtime.ts +253 -53
  42. package/src/status/categories.ts +64 -0
  43. package/src/status/default-verbs.ts +190 -0
  44. package/src/status/status-verb-categories.json +6167 -0
  45. package/src/status/status-verbs.test.ts +209 -0
  46. package/src/status/status-verbs.ts +62 -0
  47. package/src/tools/background.test.ts +304 -0
  48. package/src/tools/background.ts +432 -0
  49. package/src/tools/memory.ts +94 -0
package/src/runtime.ts CHANGED
@@ -8,6 +8,12 @@ import {
8
8
  mentionsBrowser,
9
9
  startBrowserTools,
10
10
  } from "./browser/browser-use.ts";
11
+ import {
12
+ hostsInText,
13
+ ownChromeFailureHint,
14
+ ownChromePrompt,
15
+ startOwnChromeTools,
16
+ } from "./browser/own-chrome.ts";
11
17
  import { resolveTheme, type Theme } from "./cli/theme.ts";
12
18
  import { type HarnessConfig, loadConfig, resolveOpenRouter } from "./config.ts";
13
19
  import {
@@ -32,6 +38,7 @@ import {
32
38
  defaultSummarizer,
33
39
  type RunTurnDeps,
34
40
  runTurn,
41
+ type TurnInterceptor,
35
42
  } from "./core/run-turn.ts";
36
43
  import {
37
44
  createFileSessionStore,
@@ -56,15 +63,17 @@ import { type ChatFn, createOpenRouterChat } from "./evals/runner.ts";
56
63
  import { buildRemoteMcpTools } from "./integrations/remote-mcp.ts";
57
64
  import { linkedMcpSources } from "./integrations/store.ts";
58
65
  import { listUserMcpServers, userMcpToolPrefix } from "./mcp/user-servers.ts";
66
+ import { createOpenAICompatEmbedder } from "./memory/embeddings.ts";
59
67
  import { extractMemories, turnMemorySource } from "./memory/extract.ts";
68
+ import { createFileMemoryStore, type MemoryStore } from "./memory/memory-store.ts";
60
69
  import { isMemoryEnabled } from "./memory/prefs.ts";
61
70
  import { formatRetrievedMemory } from "./memory/prompt.ts";
62
- import { searchFacts } from "./memory/store.ts";
63
71
  import { createObservability } from "./observability/create.ts";
64
72
  import { noopObservability } from "./observability/noop.ts";
65
73
  import { harnessPromptRecords, syncPrompts } from "./observability/prompts.ts";
66
74
  import type { Observability } from "./observability/types.ts";
67
75
  import { resolveAgentVersion } from "./observability/version.ts";
76
+ import { PRODUCT_NAME } from "./product.ts";
68
77
  import { authorSkillMarkdown } from "./skills/author-skill.ts";
69
78
  import { createHostSkill, parseSkillNewArgs } from "./skills/create-skill.ts";
70
79
  import {
@@ -89,12 +98,58 @@ import {
89
98
  skillNameFromCatalogId,
90
99
  } from "./skills/registry.ts";
91
100
  import { userSkillsDir } from "./skills/user-dir.ts";
101
+ import { resolveStatusVerbPool } from "./status/categories.ts";
102
+ import {
103
+ BACKGROUND_AGENTS_PROMPT,
104
+ type BackgroundAgents,
105
+ createBackgroundAgents,
106
+ EXPLORE_INSTRUCTIONS,
107
+ readOnlyTools,
108
+ type SubagentKind,
109
+ } from "./tools/background.ts";
92
110
  import { createGitTools } from "./tools/git.ts";
93
111
  import { createLocalTools } from "./tools/local.ts";
112
+ import { createMemoryTools } from "./tools/memory.ts";
94
113
  import { createReadSkillTool } from "./tools/read-skill.ts";
95
114
  import { createTaskTool } from "./tools/subagent.ts";
96
115
  import { createMemoryTodoStore, createTodoTool } from "./tools/todo.ts";
97
116
 
117
+ /** Per-turn options a host can pass to `runTurn`. */
118
+ export interface HarnessTurnOptions {
119
+ signal?: AbortSignal;
120
+ approvalAsk?: (req: ApprovalRequest) => Promise<boolean>;
121
+ editUserTurn?: number;
122
+ /**
123
+ * What the chat shows and stores, and what decisions and `@browser` read, when it differs from
124
+ * the `message` the model sees. Lets a host prefix instructions without them reaching the chat.
125
+ */
126
+ displayMessage?: string;
127
+ /** Appended to the system prompt for this turn only. */
128
+ systemAppend?: string;
129
+ /** Tool names hidden from the model for this turn only. */
130
+ excludeTools?: readonly string[];
131
+ /**
132
+ * Turn the browser tools on for this turn and the rest of the chat, as if the user had written
133
+ * `@browser`. Ignored when `browser.enabled` is false in the config or the mode is not `agent`.
134
+ */
135
+ browser?: boolean;
136
+ /**
137
+ * Sites the user asked for, as a host app resolved them from their words ("x" to x.com). The
138
+ * browser opens these without asking. Hosts written out in the message are trusted already.
139
+ */
140
+ trustedHosts?: readonly string[];
141
+ /**
142
+ * Data for this turn that the harness passes back to the host's `intercept` hook untouched, for
143
+ * example flags the host's UI sent with the request.
144
+ */
145
+ hostData?: Record<string, unknown>;
146
+ /**
147
+ * Ask the user only about requests this returns true for. Every other tool call runs without a
148
+ * prompt. The `deny` policy and the host denylist still apply to the calls it lets through.
149
+ */
150
+ promptOnly?: (req: ApprovalRequest) => boolean;
151
+ }
152
+
98
153
  export interface HarnessRuntime {
99
154
  cwd: string;
100
155
  config: HarnessConfig;
@@ -105,17 +160,15 @@ export interface HarnessRuntime {
105
160
  modelId: string;
106
161
  mode: AgentMode;
107
162
  activeSessionId?: string;
163
+ /** True when the browser tools are on for the current chat, by `@browser`, a turn option, or config. */
164
+ readonly browserActive: boolean;
108
165
  spend?: TokenUsage;
109
166
  hasApiKey: boolean;
110
167
  setApiKey(key: string): void;
111
168
  runTurn(
112
169
  message: string,
113
170
  emit: AgentEventEmitter,
114
- options?: {
115
- signal?: AbortSignal;
116
- approvalAsk?: (req: ApprovalRequest) => Promise<boolean>;
117
- editUserTurn?: number;
118
- },
171
+ options?: HarnessTurnOptions,
119
172
  ): Promise<Session | undefined>;
120
173
  setModel(modelId: string): void;
121
174
  setMode(mode: AgentMode): void;
@@ -149,6 +202,11 @@ export interface CreateHarnessOptions {
149
202
  approvalPolicy?: ExecApprovalPolicy;
150
203
  extraTools?: McpToolDefinition[];
151
204
  observability?: Observability;
205
+ /**
206
+ * Where cross-session memory is kept. A host passes its own store (a database scoped to one
207
+ * user or project). Defaults to the facts files under `cwd` and the harness home.
208
+ */
209
+ memory?: MemoryStore;
152
210
  mode?: AgentMode;
153
211
  /** Load one-click MCP connections from ~/.harness. Default on unless a test provider is passed. */
154
212
  loadIntegrations?: boolean;
@@ -161,6 +219,10 @@ export interface CreateHarnessOptions {
161
219
  decisions?: boolean;
162
220
  /** Host judgment of which messages are one direct tool call. See ShortcutPlanner. */
163
221
  shortcut?: ShortcutPlanner;
222
+ /** Host handler that can answer a whole turn without the chat model. See TurnInterceptor. */
223
+ intercept?: TurnInterceptor;
224
+ /** Appended to the system prompt on every turn, for example a host persona. */
225
+ systemAppend?: string;
164
226
  /** Replaces fetch for decision calls. Tests only. */
165
227
  decisionsFetch?: FetchImpl;
166
228
  }
@@ -191,8 +253,9 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
191
253
  let skills = loadActiveSkills();
192
254
  const layers = loadInstructionLayers({ cwd, projectFile: config.instructionsFile });
193
255
  let mode = parseAgentMode(options.mode ?? config.mode);
194
- const composePrompt = (nextMode: AgentMode) =>
195
- buildSystemPrompt({
256
+ const hostAppend = options.systemAppend?.trim();
257
+ const composePrompt = (nextMode: AgentMode) => {
258
+ const base = buildSystemPrompt({
196
259
  name: config.name,
197
260
  cwd,
198
261
  userInstructions: layers.user,
@@ -200,6 +263,8 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
200
263
  skillCatalog: skillCatalogPrompt(skills),
201
264
  mode: nextMode,
202
265
  });
266
+ return hostAppend ? `${base}\n\n${hostAppend}` : base;
267
+ };
203
268
  let systemPrompt = composePrompt(mode);
204
269
  const store = createFileSessionStore(cwd);
205
270
  const local = createLocalTools({
@@ -274,22 +339,49 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
274
339
  let browserSticky = false;
275
340
  let browserTools: McpToolDefinition[] = [];
276
341
  let browserNote = "";
277
- const resolveBrowser = async (message: string): Promise<void> => {
342
+ const ownChrome = config.browser?.backend === "chrome";
343
+ const resolveBrowser = async (
344
+ message: string,
345
+ requested = false,
346
+ trustedHosts: readonly string[] = [],
347
+ ): Promise<void> => {
278
348
  browserTools = [];
279
349
  browserNote = "";
280
350
  const access = browserAccess(config.browser);
281
351
  if (access === "off" || mode !== "agent") return;
282
- if (mentionsBrowser(message)) browserSticky = true;
352
+ if (requested || mentionsBrowser(message)) browserSticky = true;
283
353
  if (access !== "always" && !browserSticky) return;
284
354
  try {
285
- browserStart ??= startBrowserTools(config.browser, cwd, options.browserLoader);
286
- browserTools = (await browserStart).tools;
287
- browserNote = browserPrompt();
355
+ browserStart ??= ownChrome
356
+ ? startOwnChromeTools(config.browser, cwd, options.browserLoader)
357
+ : startBrowserTools(config.browser, cwd, options.browserLoader);
358
+ let started = await browserStart;
359
+ if (started.stale?.()) {
360
+ // The browser was not reachable last time and the server is fixed to the address it
361
+ // started with. The user may have set the browser up since, so start a fresh one.
362
+ started.close();
363
+ browserStart = startOwnChromeTools(config.browser, cwd, options.browserLoader);
364
+ started = await browserStart;
365
+ }
366
+ // Sites the user wrote, or the host app resolved from their words, open without asking.
367
+ started.trust?.([...hostsInText(message), ...trustedHosts]);
368
+ browserTools = started.tools;
369
+ browserNote = ownChrome ? ownChromePrompt() : browserPrompt();
288
370
  } catch (err) {
289
371
  browserStart = undefined;
290
- browserNote = browserFailurePrompt(browserSetupHint(err));
372
+ browserNote = browserFailurePrompt(
373
+ ownChrome ? ownChromeFailureHint(err) : browserSetupHint(err),
374
+ );
291
375
  }
292
376
  };
377
+ /** A new chat starts clean: the agent's tab, approvals, and trusted sites do not carry over. */
378
+ const resetBrowserChat = (): void => {
379
+ browserSticky = false;
380
+ void browserStart?.then(
381
+ (started) => started.reset?.(),
382
+ () => undefined,
383
+ );
384
+ };
293
385
 
294
386
  const or = resolveOpenRouter(config);
295
387
  let apiKey = or.apiKey;
@@ -302,13 +394,14 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
302
394
  : await createObservability({ enabled: config.observability?.enabled }));
303
395
  if (!options.observability) void syncPrompts({ prompts: harnessPromptRecords() });
304
396
  const agentVersion = resolveAgentVersion();
305
- const makeProvider = (id: string): MainModelProvider =>
397
+ const makeProvider = (id: string, title?: string): MainModelProvider =>
306
398
  options.provider ??
307
399
  constructOpenRouterProvider({
308
400
  apiKey,
309
401
  model: id,
310
402
  baseUrl: or.baseUrl,
311
403
  sessionId: () => activeSessionId,
404
+ ...(title ? { title } : {}),
312
405
  });
313
406
  let provider = makeProvider(modelId);
314
407
  const constructAgent = options.constructAgent ?? createConstructAgent();
@@ -316,6 +409,32 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
316
409
  let activeEmit: AgentEventEmitter = () => undefined;
317
410
  let activeApproval: ApprovalGate | undefined;
318
411
  const subagentsEnabled = config.subagents?.enabled !== false;
412
+ const statusVerbPool = resolveStatusVerbPool(config.statusVerbs).pool;
413
+ // Semantic recall sends fact text to the embeddings provider, so it is off until asked for.
414
+ const embeddingModel =
415
+ process.env.HARNESS_MEMORY_EMBEDDINGS?.trim() ||
416
+ (config.memory?.embeddings?.enabled ? config.memory.embeddings.model?.trim() || "default" : "");
417
+ const memoryStore: MemoryStore =
418
+ options.memory ??
419
+ createFileMemoryStore({
420
+ cwd,
421
+ ...(embeddingModel && embeddingModel !== "0" && embeddingModel !== "off"
422
+ ? {
423
+ embedder: createOpenAICompatEmbedder({
424
+ apiKey: () => apiKey,
425
+ baseUrl: or.baseUrl,
426
+ ...(embeddingModel === "default" || embeddingModel === "1"
427
+ ? {}
428
+ : { model: embeddingModel }),
429
+ }),
430
+ }
431
+ : {}),
432
+ });
433
+ /** A host that brings its own store has asked for memory; otherwise the user's setting decides. */
434
+ const memoryEnabled = (): boolean =>
435
+ options.memory
436
+ ? config.memory?.enabled !== false
437
+ : isMemoryEnabled({ configEnabled: config.memory?.enabled });
319
438
 
320
439
  const baseTools = (): McpToolDefinition[] =>
321
440
  filterToolsForMode(mode, [
@@ -329,12 +448,26 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
329
448
  createReadSkillTool(skills),
330
449
  ]);
331
450
 
332
- const nestedSystem = (extraSystem: string): string =>
451
+ /** The model a subagent runs on. Explore agents can use a smaller, faster one than the chat. */
452
+ const subagentModel = (kind: SubagentKind): string => {
453
+ const general = process.env.HARNESS_SUBAGENT_MODEL?.trim() || config.subagents?.model?.trim();
454
+ if (kind === "explore") {
455
+ return (
456
+ process.env.HARNESS_EXPLORE_MODEL?.trim() ||
457
+ config.subagents?.exploreModel?.trim() ||
458
+ general ||
459
+ modelId
460
+ );
461
+ }
462
+ return general || modelId;
463
+ };
464
+
465
+ const nestedSystem = (extraSystem: string, kind: SubagentKind = "general"): string =>
333
466
  [
334
467
  buildSystemPrompt({
335
468
  name: `${config.name} subagent`,
336
469
  cwd,
337
- projectInstructions: SUBAGENT_INSTRUCTIONS,
470
+ projectInstructions: kind === "explore" ? EXPLORE_INSTRUCTIONS : SUBAGENT_INSTRUCTIONS,
338
471
  skillCatalog: skillCatalogPrompt(skills),
339
472
  mode,
340
473
  }),
@@ -365,8 +498,13 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
365
498
  get activeSessionId() {
366
499
  return activeSessionId;
367
500
  },
501
+ get browserActive() {
502
+ const access = browserAccess(config.browser);
503
+ if (access === "off" || mode !== "agent") return false;
504
+ return access === "always" || browserSticky;
505
+ },
368
506
  set activeSessionId(id: string | undefined) {
369
- if (id !== activeSessionId) browserSticky = false;
507
+ if (id !== activeSessionId) resetBrowserChat();
370
508
  activeSessionId = id;
371
509
  },
372
510
  get hasApiKey() {
@@ -388,7 +526,7 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
388
526
  systemPrompt = composePrompt(mode);
389
527
  },
390
528
  setSession(id) {
391
- if (id !== activeSessionId) browserSticky = false;
529
+ if (id !== activeSessionId) resetBrowserChat();
392
530
  activeSessionId = id;
393
531
  },
394
532
  allowExecAlways() {
@@ -502,6 +640,7 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
502
640
  return undefined;
503
641
  }
504
642
  const policy = options.approvalPolicy ?? config.tools.exec.approval;
643
+ const userText = turnOptions?.displayMessage ?? message;
505
644
  const decisions: ResolvedDecisions | undefined =
506
645
  options.provider && options.decisions !== true
507
646
  ? undefined
@@ -511,9 +650,10 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
511
650
  alwaysAllow,
512
651
  emit,
513
652
  assist: decisions?.approvals
514
- ? (req) => classifyToolApproval(decisions, req, message, turnOptions?.signal)
653
+ ? (req) => classifyToolApproval(decisions, req, userText, turnOptions?.signal)
515
654
  : undefined,
516
655
  resolveUploadEdit: (path) => matchUploadEdit(cwd, path),
656
+ promptOnly: turnOptions?.promptOnly,
517
657
  ask: async (req) => {
518
658
  if (turnOptions?.approvalAsk) return turnOptions.approvalAsk(req);
519
659
  if (policy === "prompt") return false;
@@ -522,43 +662,91 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
522
662
  });
523
663
  activeEmit = emit;
524
664
  activeApproval = approval;
525
- await resolveBrowser(message);
526
- const tools = baseTools();
665
+ await resolveBrowser(userText, turnOptions?.browser === true, turnOptions?.trustedHosts);
666
+ const memoryOn = memoryEnabled();
667
+ let tools = baseTools();
668
+ if (memoryOn) {
669
+ tools.push(
670
+ ...filterToolsForMode(
671
+ mode,
672
+ createMemoryTools(memoryStore, { sessionId: () => activeSessionId }),
673
+ ),
674
+ );
675
+ }
676
+ /** One nested turn for a subagent. Explore agents get the read-only tools and their own model. */
677
+ const runNested = async (input: {
678
+ prompt: string;
679
+ kind: SubagentKind;
680
+ extraSystem: string;
681
+ emit: AgentEventEmitter;
682
+ signal?: AbortSignal;
683
+ }): Promise<void> => {
684
+ const nestedModel = subagentModel(input.kind);
685
+ const nestedDeps: RunTurnDeps = {
686
+ cwd,
687
+ name: `${config.name} subagent`,
688
+ systemPrompt: nestedSystem(input.extraSystem, input.kind),
689
+ tools: input.kind === "explore" ? readOnlyTools(baseTools()) : baseTools(),
690
+ approval: activeApproval ?? approval,
691
+ store: createMemorySessionStore(),
692
+ provider:
693
+ options.provider || nestedModel === modelId
694
+ ? provider
695
+ : makeProvider(nestedModel, `${PRODUCT_NAME} subagent`),
696
+ constructAgent,
697
+ observability,
698
+ traceName: input.kind === "explore" ? "explore_subagent" : "subagent",
699
+ requestType: "chat",
700
+ agentVersion,
701
+ hooks,
702
+ mode,
703
+ };
704
+ await runTurn(nestedDeps, { message: input.prompt }, input.emit, {
705
+ signal: input.signal,
706
+ });
707
+ };
527
708
  if (subagentsEnabled && toolsAllowedInMode(mode, "task")) {
528
709
  tools.push(
529
710
  createTaskTool({
530
711
  skills,
531
712
  parentEmit: () => activeEmit,
532
- async run({ prompt, extraSystem, emit: nestedEmit }) {
533
- const nestedDeps: RunTurnDeps = {
534
- cwd,
535
- name: `${config.name} subagent`,
536
- systemPrompt: nestedSystem(extraSystem),
537
- tools: baseTools(),
538
- approval: activeApproval ?? approval,
539
- store: createMemorySessionStore(),
540
- provider,
541
- constructAgent,
542
- resolveProvider: options.provider ? undefined : (id) => makeProvider(id),
543
- observability,
544
- traceName: "subagent",
545
- requestType: "chat",
546
- agentVersion,
547
- hooks,
548
- mode,
549
- };
550
- await runTurn(nestedDeps, { message: prompt, model: modelId }, nestedEmit, {
713
+ run: ({ prompt, extraSystem, emit: nestedEmit }) =>
714
+ runNested({
715
+ prompt,
716
+ kind: "general",
717
+ extraSystem,
718
+ emit: nestedEmit,
551
719
  signal: turnOptions?.signal,
552
- });
553
- },
720
+ }),
554
721
  }),
555
722
  );
556
723
  }
557
- const memoryOn = isMemoryEnabled({ configEnabled: config.memory?.enabled });
724
+ // Explore agents only read, so they are offered in ask and plan mode too.
725
+ let background: BackgroundAgents | undefined;
726
+ if (subagentsEnabled && config.subagents?.background !== false) {
727
+ background = createBackgroundAgents({
728
+ skills,
729
+ parentEmit: () => activeEmit,
730
+ kinds: mode === "agent" ? ["explore", "general"] : ["explore"],
731
+ maxConcurrent: config.subagents?.maxConcurrent,
732
+ maxAgents: config.subagents?.maxPerTurn,
733
+ signal: turnOptions?.signal,
734
+ run: ({ prompt, kind, extraSystem, emit: nestedEmit, signal }) =>
735
+ runNested({ prompt, kind, extraSystem, emit: nestedEmit, signal }),
736
+ });
737
+ tools = [
738
+ ...tools.map((tool) => background?.withNotices(tool) ?? tool),
739
+ ...background.tools,
740
+ ];
741
+ }
558
742
  const deps: RunTurnDeps = {
559
743
  cwd,
560
744
  name: config.name,
561
- systemPrompt: [systemPromptWithMemory(systemPrompt, cwd, message, memoryOn), browserNote]
745
+ systemPrompt: [
746
+ await systemPromptWithMemory(systemPrompt, memoryStore, userText, memoryOn),
747
+ background ? BACKGROUND_AGENTS_PROMPT : "",
748
+ browserNote,
749
+ ]
562
750
  .filter(Boolean)
563
751
  .join("\n\n"),
564
752
  tools,
@@ -566,7 +754,7 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
566
754
  store,
567
755
  provider,
568
756
  constructAgent,
569
- resolveProvider: options.provider ? undefined : (id) => makeProvider(id),
757
+ resolveProvider: options.provider ? undefined : (id, title) => makeProvider(id, title),
570
758
  summarize: defaultSummarizer(provider),
571
759
  observability,
572
760
  traceName: "agent_turn",
@@ -576,6 +764,10 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
576
764
  mode,
577
765
  decisions,
578
766
  shortcut: options.shortcut,
767
+ intercept: options.intercept,
768
+ ...(statusVerbPool.length > 0
769
+ ? { statusVerbs: { pool: statusVerbPool, perTurn: config.statusVerbs?.perTurn } }
770
+ : {}),
579
771
  };
580
772
  const capture: AgentEventEmitter = (event) => {
581
773
  if (event.kind === "usage") {
@@ -597,13 +789,19 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
597
789
  ...(turnOptions?.editUserTurn !== undefined
598
790
  ? { editUserTurn: turnOptions.editUserTurn }
599
791
  : {}),
792
+ ...(turnOptions?.displayMessage !== undefined
793
+ ? { displayMessage: turnOptions.displayMessage }
794
+ : {}),
795
+ ...(turnOptions?.systemAppend ? { systemAppend: turnOptions.systemAppend } : {}),
796
+ ...(turnOptions?.excludeTools?.length ? { excludeTools: turnOptions.excludeTools } : {}),
797
+ ...(turnOptions?.hostData ? { hostData: turnOptions.hostData } : {}),
600
798
  },
601
799
  capture,
602
800
  { signal: turnOptions?.signal },
603
- );
801
+ ).finally(() => background?.close());
604
802
  // Assign the variable, not the setter: a new chat's first turn must keep the browser on.
605
803
  if (session) activeSessionId = session.id;
606
- scheduleMemoryExtract(memoryOn, cwd, session, provider, decisions);
804
+ scheduleMemoryExtract(memoryOn, cwd, memoryStore, session, provider, decisions);
607
805
  return session;
608
806
  },
609
807
  close() {
@@ -618,14 +816,15 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
618
816
  return runtime;
619
817
  }
620
818
 
621
- function systemPromptWithMemory(
819
+ async function systemPromptWithMemory(
622
820
  base: string,
623
- cwd: string,
821
+ store: MemoryStore,
624
822
  message: string,
625
823
  enabled: boolean,
626
- ): string {
824
+ ): Promise<string> {
627
825
  if (!enabled) return base;
628
- const block = formatRetrievedMemory(searchFacts(cwd, message));
826
+ const facts = await store.search(message).catch(() => []);
827
+ const block = formatRetrievedMemory(facts);
629
828
  if (!block) return base;
630
829
  return `${base}\n\n## Memory\n${block}`;
631
830
  }
@@ -633,6 +832,7 @@ function systemPromptWithMemory(
633
832
  function scheduleMemoryExtract(
634
833
  enabled: boolean,
635
834
  cwd: string,
835
+ store: MemoryStore,
636
836
  session: Session | undefined,
637
837
  provider: MainModelProvider,
638
838
  decisions?: ResolvedDecisions,
@@ -643,6 +843,6 @@ function scheduleMemoryExtract(
643
843
  const source = turnMemorySource(session);
644
844
  if (!source.trim() || !(await turnHasDurableFact(decisions, source))) return;
645
845
  }
646
- await extractMemories({ cwd, session, provider });
846
+ await extractMemories({ cwd, session, provider, store });
647
847
  })().catch(() => undefined);
648
848
  }
@@ -0,0 +1,64 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { DEFAULT_STATUS_VERBS, type StatusVerbsConfig } from "./status-verbs.ts";
4
+
5
+ let cached: Record<string, string[]> | undefined;
6
+
7
+ /** The themed verb lists, by name. Read from disk on first use. */
8
+ export function statusVerbCategories(): Record<string, string[]> {
9
+ if (cached) return cached;
10
+ try {
11
+ const parsed = JSON.parse(
12
+ readFileSync(join(import.meta.dir, "status-verb-categories.json"), "utf8"),
13
+ ) as Record<string, unknown>;
14
+ const out: Record<string, string[]> = {};
15
+ for (const [name, value] of Object.entries(parsed)) {
16
+ if (!Array.isArray(value)) continue;
17
+ out[name] = value.filter((item): item is string => typeof item === "string");
18
+ }
19
+ cached = out;
20
+ } catch {
21
+ cached = {};
22
+ }
23
+ return cached;
24
+ }
25
+
26
+ export function statusVerbCategoryNames(): string[] {
27
+ return Object.keys(statusVerbCategories());
28
+ }
29
+
30
+ /**
31
+ * The verbs a config asks for: the built-in list, the named categories and any custom ones,
32
+ * without duplicates. Empty when verbs are turned off. `unknown` lists category names that
33
+ * matched nothing, so a host can tell the user about a typo.
34
+ */
35
+ export function resolveStatusVerbPool(config: StatusVerbsConfig | undefined): {
36
+ pool: string[];
37
+ unknown: string[];
38
+ } {
39
+ if (config?.enabled === false) return { pool: [], unknown: [] };
40
+ const pool = new Set<string>();
41
+ const unknown: string[] = [];
42
+ if (config?.defaults !== false) for (const verb of DEFAULT_STATUS_VERBS) pool.add(verb);
43
+ if (config?.categories) {
44
+ const all = statusVerbCategories();
45
+ const byLower = new Map(Object.keys(all).map((name) => [name.toLowerCase(), name]));
46
+ const names =
47
+ config.categories === "all"
48
+ ? Object.keys(all)
49
+ : config.categories.map((raw) => {
50
+ const name = byLower.get(raw.trim().toLowerCase());
51
+ if (!name) unknown.push(raw);
52
+ return name;
53
+ });
54
+ for (const name of names) {
55
+ if (!name) continue;
56
+ for (const verb of all[name] ?? []) pool.add(verb);
57
+ }
58
+ }
59
+ for (const verb of config?.custom ?? []) {
60
+ const text = verb.trim();
61
+ if (text) pool.add(text);
62
+ }
63
+ return { pool: [...pool], unknown };
64
+ }