@useavalon/caelence-agent 0.4.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/src/runtime.ts CHANGED
@@ -63,15 +63,17 @@ import { type ChatFn, createOpenRouterChat } from "./evals/runner.ts";
63
63
  import { buildRemoteMcpTools } from "./integrations/remote-mcp.ts";
64
64
  import { linkedMcpSources } from "./integrations/store.ts";
65
65
  import { listUserMcpServers, userMcpToolPrefix } from "./mcp/user-servers.ts";
66
+ import { createOpenAICompatEmbedder } from "./memory/embeddings.ts";
66
67
  import { extractMemories, turnMemorySource } from "./memory/extract.ts";
68
+ import { createFileMemoryStore, type MemoryStore } from "./memory/memory-store.ts";
67
69
  import { isMemoryEnabled } from "./memory/prefs.ts";
68
70
  import { formatRetrievedMemory } from "./memory/prompt.ts";
69
- import { searchFacts } from "./memory/store.ts";
70
71
  import { createObservability } from "./observability/create.ts";
71
72
  import { noopObservability } from "./observability/noop.ts";
72
73
  import { harnessPromptRecords, syncPrompts } from "./observability/prompts.ts";
73
74
  import type { Observability } from "./observability/types.ts";
74
75
  import { resolveAgentVersion } from "./observability/version.ts";
76
+ import { PRODUCT_NAME } from "./product.ts";
75
77
  import { authorSkillMarkdown } from "./skills/author-skill.ts";
76
78
  import { createHostSkill, parseSkillNewArgs } from "./skills/create-skill.ts";
77
79
  import {
@@ -96,8 +98,18 @@ import {
96
98
  skillNameFromCatalogId,
97
99
  } from "./skills/registry.ts";
98
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";
99
110
  import { createGitTools } from "./tools/git.ts";
100
111
  import { createLocalTools } from "./tools/local.ts";
112
+ import { createMemoryTools } from "./tools/memory.ts";
101
113
  import { createReadSkillTool } from "./tools/read-skill.ts";
102
114
  import { createTaskTool } from "./tools/subagent.ts";
103
115
  import { createMemoryTodoStore, createTodoTool } from "./tools/todo.ts";
@@ -190,6 +202,11 @@ export interface CreateHarnessOptions {
190
202
  approvalPolicy?: ExecApprovalPolicy;
191
203
  extraTools?: McpToolDefinition[];
192
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;
193
210
  mode?: AgentMode;
194
211
  /** Load one-click MCP connections from ~/.harness. Default on unless a test provider is passed. */
195
212
  loadIntegrations?: boolean;
@@ -392,6 +409,32 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
392
409
  let activeEmit: AgentEventEmitter = () => undefined;
393
410
  let activeApproval: ApprovalGate | undefined;
394
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 });
395
438
 
396
439
  const baseTools = (): McpToolDefinition[] =>
397
440
  filterToolsForMode(mode, [
@@ -405,12 +448,26 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
405
448
  createReadSkillTool(skills),
406
449
  ]);
407
450
 
408
- 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 =>
409
466
  [
410
467
  buildSystemPrompt({
411
468
  name: `${config.name} subagent`,
412
469
  cwd,
413
- projectInstructions: SUBAGENT_INSTRUCTIONS,
470
+ projectInstructions: kind === "explore" ? EXPLORE_INSTRUCTIONS : SUBAGENT_INSTRUCTIONS,
414
471
  skillCatalog: skillCatalogPrompt(skills),
415
472
  mode,
416
473
  }),
@@ -606,42 +663,90 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
606
663
  activeEmit = emit;
607
664
  activeApproval = approval;
608
665
  await resolveBrowser(userText, turnOptions?.browser === true, turnOptions?.trustedHosts);
609
- const tools = baseTools();
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
+ };
610
708
  if (subagentsEnabled && toolsAllowedInMode(mode, "task")) {
611
709
  tools.push(
612
710
  createTaskTool({
613
711
  skills,
614
712
  parentEmit: () => activeEmit,
615
- async run({ prompt, extraSystem, emit: nestedEmit }) {
616
- const nestedDeps: RunTurnDeps = {
617
- cwd,
618
- name: `${config.name} subagent`,
619
- systemPrompt: nestedSystem(extraSystem),
620
- tools: baseTools(),
621
- approval: activeApproval ?? approval,
622
- store: createMemorySessionStore(),
623
- provider,
624
- constructAgent,
625
- resolveProvider: options.provider ? undefined : (id) => makeProvider(id),
626
- observability,
627
- traceName: "subagent",
628
- requestType: "chat",
629
- agentVersion,
630
- hooks,
631
- mode,
632
- };
633
- 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,
634
719
  signal: turnOptions?.signal,
635
- });
636
- },
720
+ }),
637
721
  }),
638
722
  );
639
723
  }
640
- 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
+ }
641
742
  const deps: RunTurnDeps = {
642
743
  cwd,
643
744
  name: config.name,
644
- systemPrompt: [systemPromptWithMemory(systemPrompt, cwd, userText, memoryOn), browserNote]
745
+ systemPrompt: [
746
+ await systemPromptWithMemory(systemPrompt, memoryStore, userText, memoryOn),
747
+ background ? BACKGROUND_AGENTS_PROMPT : "",
748
+ browserNote,
749
+ ]
645
750
  .filter(Boolean)
646
751
  .join("\n\n"),
647
752
  tools,
@@ -660,6 +765,9 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
660
765
  decisions,
661
766
  shortcut: options.shortcut,
662
767
  intercept: options.intercept,
768
+ ...(statusVerbPool.length > 0
769
+ ? { statusVerbs: { pool: statusVerbPool, perTurn: config.statusVerbs?.perTurn } }
770
+ : {}),
663
771
  };
664
772
  const capture: AgentEventEmitter = (event) => {
665
773
  if (event.kind === "usage") {
@@ -690,10 +798,10 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
690
798
  },
691
799
  capture,
692
800
  { signal: turnOptions?.signal },
693
- );
801
+ ).finally(() => background?.close());
694
802
  // Assign the variable, not the setter: a new chat's first turn must keep the browser on.
695
803
  if (session) activeSessionId = session.id;
696
- scheduleMemoryExtract(memoryOn, cwd, session, provider, decisions);
804
+ scheduleMemoryExtract(memoryOn, cwd, memoryStore, session, provider, decisions);
697
805
  return session;
698
806
  },
699
807
  close() {
@@ -708,14 +816,15 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
708
816
  return runtime;
709
817
  }
710
818
 
711
- function systemPromptWithMemory(
819
+ async function systemPromptWithMemory(
712
820
  base: string,
713
- cwd: string,
821
+ store: MemoryStore,
714
822
  message: string,
715
823
  enabled: boolean,
716
- ): string {
824
+ ): Promise<string> {
717
825
  if (!enabled) return base;
718
- const block = formatRetrievedMemory(searchFacts(cwd, message));
826
+ const facts = await store.search(message).catch(() => []);
827
+ const block = formatRetrievedMemory(facts);
719
828
  if (!block) return base;
720
829
  return `${base}\n\n## Memory\n${block}`;
721
830
  }
@@ -723,6 +832,7 @@ function systemPromptWithMemory(
723
832
  function scheduleMemoryExtract(
724
833
  enabled: boolean,
725
834
  cwd: string,
835
+ store: MemoryStore,
726
836
  session: Session | undefined,
727
837
  provider: MainModelProvider,
728
838
  decisions?: ResolvedDecisions,
@@ -733,6 +843,6 @@ function scheduleMemoryExtract(
733
843
  const source = turnMemorySource(session);
734
844
  if (!source.trim() || !(await turnHasDurableFact(decisions, source))) return;
735
845
  }
736
- await extractMemories({ cwd, session, provider });
846
+ await extractMemories({ cwd, session, provider, store });
737
847
  })().catch(() => undefined);
738
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
+ }
@@ -0,0 +1,190 @@
1
+ /**
2
+ * The built-in verbs shown while the agent is thinking or between steps. Kept as a plain module
3
+ * (no file reads) so the desktop webview and other browser hosts can import it.
4
+ */
5
+ export const DEFAULT_STATUS_VERBS: readonly string[] = [
6
+ "Accomplishing",
7
+ "Actioning",
8
+ "Actualizing",
9
+ "Architecting",
10
+ "Baking",
11
+ "Beaming",
12
+ "Beboppin'",
13
+ "Befuddling",
14
+ "Billowing",
15
+ "Blanching",
16
+ "Bloviating",
17
+ "Boogieing",
18
+ "Boondoggling",
19
+ "Booping",
20
+ "Bootstrapping",
21
+ "Brewing",
22
+ "Burrowing",
23
+ "Calculating",
24
+ "Canoodling",
25
+ "Caramelizing",
26
+ "Cascading",
27
+ "Catapulting",
28
+ "Cerebrating",
29
+ "Channeling",
30
+ "Channelling",
31
+ "Choreographing",
32
+ "Churning",
33
+ "Coalescing",
34
+ "Cogitating",
35
+ "Combobulating",
36
+ "Composing",
37
+ "Computing",
38
+ "Concocting",
39
+ "Considering",
40
+ "Contemplating",
41
+ "Cooking",
42
+ "Crafting",
43
+ "Creating",
44
+ "Crunching",
45
+ "Crystallizing",
46
+ "Cultivating",
47
+ "Deciphering",
48
+ "Deliberating",
49
+ "Determining",
50
+ "Dilly-dallying",
51
+ "Discombobulating",
52
+ "Doing",
53
+ "Doodling",
54
+ "Drizzling",
55
+ "Ebbing",
56
+ "Effecting",
57
+ "Elucidating",
58
+ "Embellishing",
59
+ "Enchanting",
60
+ "Envisioning",
61
+ "Evaporating",
62
+ "Fermenting",
63
+ "Fiddle-faddling",
64
+ "Finagling",
65
+ "Flambeing",
66
+ "Flibbertigibbeting",
67
+ "Flowing",
68
+ "Flummoxing",
69
+ "Fluttering",
70
+ "Forging",
71
+ "Forming",
72
+ "Frolicking",
73
+ "Frosting",
74
+ "Gallivanting",
75
+ "Galloping",
76
+ "Garnishing",
77
+ "Generating",
78
+ "Germinating",
79
+ "Gitifying",
80
+ "Grooving",
81
+ "Gusting",
82
+ "Harmonizing",
83
+ "Hashing",
84
+ "Hatching",
85
+ "Herding",
86
+ "Honking",
87
+ "Hullaballooing",
88
+ "Hyperspacing",
89
+ "Ideating",
90
+ "Imagining",
91
+ "Improvising",
92
+ "Incubating",
93
+ "Inferring",
94
+ "Infusing",
95
+ "Ionizing",
96
+ "Jitterbugging",
97
+ "Julienning",
98
+ "Kneading",
99
+ "Leavening",
100
+ "Levitating",
101
+ "Lollygagging",
102
+ "Manifesting",
103
+ "Marinating",
104
+ "Meandering",
105
+ "Metamorphosing",
106
+ "Misting",
107
+ "Moonwalking",
108
+ "Moseying",
109
+ "Mulling",
110
+ "Mustering",
111
+ "Musing",
112
+ "Nebulizing",
113
+ "Nesting",
114
+ "Newspapering",
115
+ "Noodling",
116
+ "Nucleating",
117
+ "Orbiting",
118
+ "Orchestrating",
119
+ "Osmosing",
120
+ "Perambulating",
121
+ "Percolating",
122
+ "Perusing",
123
+ "Philosophising",
124
+ "Photosynthesizing",
125
+ "Pollinating",
126
+ "Pondering",
127
+ "Pontificating",
128
+ "Pouncing",
129
+ "Precipitating",
130
+ "Prestidigitating",
131
+ "Processing",
132
+ "Proofing",
133
+ "Propagating",
134
+ "Puttering",
135
+ "Puzzling",
136
+ "Quantumizing",
137
+ "Razzle-dazzling",
138
+ "Razzmatazzing",
139
+ "Recombobulating",
140
+ "Reticulating",
141
+ "Roosting",
142
+ "Ruminating",
143
+ "Sauteing",
144
+ "Scampering",
145
+ "Schlepping",
146
+ "Scurrying",
147
+ "Seasoning",
148
+ "Shenaniganing",
149
+ "Shimmying",
150
+ "Simmering",
151
+ "Skedaddling",
152
+ "Sketching",
153
+ "Slithering",
154
+ "Smooshing",
155
+ "Sock-hopping",
156
+ "Spelunking",
157
+ "Spinning",
158
+ "Sprouting",
159
+ "Stewing",
160
+ "Sublimating",
161
+ "Swirling",
162
+ "Swooping",
163
+ "Symbioting",
164
+ "Synthesizing",
165
+ "Tempering",
166
+ "Thinking",
167
+ "Thundering",
168
+ "Tinkering",
169
+ "Tomfoolering",
170
+ "Topsy-turvying",
171
+ "Transfiguring",
172
+ "Transmuting",
173
+ "Twisting",
174
+ "Undulating",
175
+ "Unfurling",
176
+ "Unravelling",
177
+ "Vibing",
178
+ "Waddling",
179
+ "Wandering",
180
+ "Warping",
181
+ "Whatchamacalliting",
182
+ "Whirlpooling",
183
+ "Whirring",
184
+ "Whisking",
185
+ "Wibbling",
186
+ "Working",
187
+ "Wrangling",
188
+ "Zesting",
189
+ "Zigzagging",
190
+ ];