@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
@@ -0,0 +1,244 @@
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 { DEFAULT_CONFIG } from "../config.ts";
6
+ import type { AgentEvent, MainModelProvider } from "../core/events.ts";
7
+ import type { ConstructAgent } from "../core/strands.ts";
8
+ import { noopObservability } from "../observability/noop.ts";
9
+ import { createHarness } from "../runtime.ts";
10
+ import { startDesktopBridge } from "./bridge.ts";
11
+ import type { BridgeHost } from "./host.ts";
12
+
13
+ const provider: MainModelProvider = {
14
+ kind: "fake",
15
+ modelId: "fake",
16
+ async *stream() {
17
+ yield { type: "done" };
18
+ },
19
+ };
20
+
21
+ async function withBridge(extensions?: BridgeHost) {
22
+ const cwd = await mkdtemp(join(tmpdir(), "bridge-host-"));
23
+ const prevHome = process.env.HARNESS_HOME;
24
+ process.env.HARNESS_HOME = join(cwd, "home");
25
+ const seen = { message: "", system: "", tools: [] as string[] };
26
+ const constructAgent: ConstructAgent = (input) => {
27
+ seen.system = input.systemPrompt;
28
+ seen.tools = input.tools.map((t) => t.name);
29
+ return {
30
+ async run(message, emit) {
31
+ seen.message = message;
32
+ emit({ kind: "text_delta", text: "the answer" } satisfies AgentEvent);
33
+ },
34
+ };
35
+ };
36
+ const harness = await createHarness({
37
+ cwd,
38
+ config: { ...DEFAULT_CONFIG, name: "desk" },
39
+ provider,
40
+ constructAgent,
41
+ observability: noopObservability,
42
+ });
43
+ const { ready, stop } = await startDesktopBridge({ cwd, harness, token: "t", extensions });
44
+ const headers = { authorization: "Bearer t", "content-type": "application/json" };
45
+ const get = (path: string) => fetch(`${ready.url}${path}`, { headers });
46
+ const post = (path: string, body: unknown) =>
47
+ fetch(`${ready.url}${path}`, { method: "POST", headers, body: JSON.stringify(body) });
48
+ return {
49
+ get,
50
+ post,
51
+ seen,
52
+ harness,
53
+ async close() {
54
+ await stop();
55
+ if (prevHome === undefined) delete process.env.HARNESS_HOME;
56
+ else process.env.HARNESS_HOME = prevHome;
57
+ await rm(cwd, { recursive: true, force: true });
58
+ },
59
+ };
60
+ }
61
+
62
+ async function sse(res: Response): Promise<AgentEvent[]> {
63
+ const text = await res.text();
64
+ return text
65
+ .split("\n\n")
66
+ .map((chunk) => chunk.trim())
67
+ .filter((chunk) => chunk.startsWith("data: "))
68
+ .map((chunk) => JSON.parse(chunk.slice(6)) as AgentEvent);
69
+ }
70
+
71
+ describe("bridge host extensions", () => {
72
+ test("no extensions behaves like the plain bridge", async () => {
73
+ const ctx = await withBridge();
74
+ try {
75
+ expect((await ctx.get("/state")).status).toBe(200);
76
+ expect((await ctx.get("/nope")).status).toBe(404);
77
+ const settings = (await (await ctx.get("/settings")).json()) as Record<string, unknown>;
78
+ expect(settings).toHaveProperty("modelId");
79
+ } finally {
80
+ await ctx.close();
81
+ }
82
+ });
83
+
84
+ test("host routes are served behind the token and can read the harness", async () => {
85
+ const ctx = await withBridge({
86
+ routes: {
87
+ "GET /hello": async ({ harness }) => Response.json({ name: harness.config.name }),
88
+ },
89
+ });
90
+ try {
91
+ const res = await ctx.get("/hello");
92
+ expect(await res.json()).toEqual({ name: "desk" });
93
+ const unauth = await fetch(new URL("/hello", (await ctx.get("/state")).url));
94
+ expect(unauth.status).toBe(401);
95
+ } finally {
96
+ await ctx.close();
97
+ }
98
+ });
99
+
100
+ test("a host route replaces a built-in route with the same key", async () => {
101
+ const ctx = await withBridge({
102
+ routes: { "GET /health": async () => Response.json({ custom: true }) },
103
+ });
104
+ try {
105
+ expect(await (await ctx.get("/health")).json()).toEqual({ custom: true });
106
+ } finally {
107
+ await ctx.close();
108
+ }
109
+ });
110
+
111
+ test("settings fields are merged on read and write, and a host can reject input", async () => {
112
+ let stored = "calm";
113
+ const ctx = await withBridge({
114
+ settings: () => ({ voice: stored }),
115
+ applySettings: (_ctx, body) => {
116
+ if (typeof body.voice !== "string") return undefined;
117
+ if (body.voice === "bad") return "That voice is not available.";
118
+ stored = body.voice;
119
+ return undefined;
120
+ },
121
+ });
122
+ try {
123
+ expect(((await (await ctx.get("/settings")).json()) as { voice: string }).voice).toBe("calm");
124
+ const ok = await ctx.post("/settings", { voice: "warm" });
125
+ expect(((await ok.json()) as { voice: string }).voice).toBe("warm");
126
+ const bad = await ctx.post("/settings", { voice: "bad" });
127
+ expect(bad.status).toBe(400);
128
+ expect(((await bad.json()) as { error: string }).error).toBe("That voice is not available.");
129
+ expect(stored).toBe("warm");
130
+ } finally {
131
+ await ctx.close();
132
+ }
133
+ });
134
+
135
+ test("model rows are listed first and not duplicated", async () => {
136
+ const ctx = await withBridge({
137
+ modelItems: () => [
138
+ { id: "acme/custom", label: "Custom" },
139
+ { id: "openrouter/auto", label: "dupe of a built-in" },
140
+ ],
141
+ });
142
+ try {
143
+ const { items } = (await (await ctx.get("/models")).json()) as {
144
+ items: Array<{ id: string }>;
145
+ };
146
+ expect(items[0]?.id).toBe("acme/custom");
147
+ expect(items.filter((row) => row.id === "openrouter/auto")).toHaveLength(1);
148
+ } finally {
149
+ await ctx.close();
150
+ }
151
+ });
152
+
153
+ test("beforeTurn changes what the model sees, and the chat keeps what the user typed", async () => {
154
+ const ctx = await withBridge({
155
+ displayText: (text) => text.replace(/^\[mode\]\n\n/, ""),
156
+ beforeTurn: (_ctx, { message }) => ({
157
+ message: `[mode]\n\n${message}`,
158
+ options: { systemAppend: "Be brief.", excludeTools: ["exec"] },
159
+ }),
160
+ });
161
+ try {
162
+ const events = await sse(await ctx.post("/turn", { message: "open my notes" }));
163
+ expect(events.at(-1)?.kind).toBe("completion");
164
+ expect(ctx.seen.message).toBe("[mode]\n\nopen my notes");
165
+ expect(ctx.seen.system).toContain("Be brief.");
166
+ expect(ctx.seen.tools).not.toContain("exec");
167
+ const sessionId = events.find((e) => e.kind === "session_meta") as { title: string };
168
+ expect(sessionId.title).toBe("open my notes");
169
+ const transcript = (await (await ctx.get("/state")).json()) as { title: string };
170
+ expect(transcript.title).toBe("open my notes");
171
+ const stored = JSON.stringify(await ctx.harness.store.get(ctx.harness.activeSessionId ?? ""));
172
+ expect(stored).not.toContain("[mode]");
173
+ } finally {
174
+ await ctx.close();
175
+ }
176
+ });
177
+
178
+ test("beforeTurn displayMessage cleans a message that arrives already prefixed", async () => {
179
+ const ctx = await withBridge({
180
+ beforeTurn: (_ctx, { message }) => ({
181
+ displayMessage: message.replace(/^\[banner\]\n\n/, ""),
182
+ }),
183
+ });
184
+ try {
185
+ await sse(await ctx.post("/turn", { message: "[banner]\n\nopen my notes" }));
186
+ // The model still sees the full message the client sent.
187
+ expect(ctx.seen.message).toBe("[banner]\n\nopen my notes");
188
+ const state = (await (await ctx.get("/state")).json()) as { title: string };
189
+ expect(state.title).toBe("open my notes");
190
+ const stored = JSON.stringify(await ctx.harness.store.get(ctx.harness.activeSessionId ?? ""));
191
+ expect(stored).not.toContain("[banner]");
192
+ } finally {
193
+ await ctx.close();
194
+ }
195
+ });
196
+
197
+ test("beforeTurn can answer without the model, and nothing is saved", async () => {
198
+ const ctx = await withBridge({
199
+ beforeTurn: () => ({ reply: "I didn't catch that." }),
200
+ });
201
+ try {
202
+ const events = await sse(await ctx.post("/turn", { message: "..." }));
203
+ expect(events.map((e) => e.kind)).toEqual(["text_delta", "completion"]);
204
+ expect(ctx.seen.message).toBe("");
205
+ expect(await ctx.harness.store.list()).toHaveLength(0);
206
+ } finally {
207
+ await ctx.close();
208
+ }
209
+ });
210
+
211
+ test("a throwing beforeTurn is a 500, not a hung turn", async () => {
212
+ const ctx = await withBridge({
213
+ beforeTurn: () => {
214
+ throw new Error("planner failed");
215
+ },
216
+ });
217
+ try {
218
+ const res = await ctx.post("/turn", { message: "hi" });
219
+ expect(res.status).toBe(500);
220
+ expect(((await res.json()) as { error: string }).error).toBe("planner failed");
221
+ // The bridge must still accept the next turn.
222
+ const next = await ctx.post("/turn", { message: "again" });
223
+ expect(next.status).toBe(500);
224
+ } finally {
225
+ await ctx.close();
226
+ }
227
+ });
228
+
229
+ test("slash commands bypass beforeTurn", async () => {
230
+ let called = 0;
231
+ const ctx = await withBridge({
232
+ beforeTurn: () => {
233
+ called += 1;
234
+ return undefined;
235
+ },
236
+ });
237
+ try {
238
+ await ctx.post("/turn", { message: "/help" });
239
+ expect(called).toBe(0);
240
+ } finally {
241
+ await ctx.close();
242
+ }
243
+ });
244
+ });
@@ -0,0 +1,59 @@
1
+ import type { HarnessRuntime, HarnessTurnOptions } from "../runtime.ts";
2
+
3
+ /**
4
+ * Extension points for a host app built on the desktop bridge, such as a native widget that
5
+ * talks to it over loopback HTTP. Everything is optional. A host that sets nothing gets the
6
+ * same bridge the desktop window uses.
7
+ */
8
+ export interface BridgeHost {
9
+ /**
10
+ * Extra routes, keyed `"METHOD /path"`. They sit behind the same bearer token as the built-in
11
+ * routes, and a host route replaces a built-in route with the same key.
12
+ */
13
+ routes?: Record<string, (ctx: BridgeHostContext, req: Request, url: URL) => Promise<Response>>;
14
+ /** Extra fields merged into `GET /settings` and the `POST /settings` reply. */
15
+ settings?: (ctx: BridgeHostContext) => Record<string, unknown>;
16
+ /**
17
+ * Handle fields of a `POST /settings` body that the bridge does not know. Return an error
18
+ * message to reject the request with 400, or nothing to accept it.
19
+ */
20
+ applySettings?: (
21
+ ctx: BridgeHostContext,
22
+ body: Record<string, unknown>,
23
+ ) => string | undefined | Promise<string | undefined>;
24
+ /** Extra rows for `GET /models`, listed before the built-in ones. */
25
+ modelItems?: (ctx: BridgeHostContext) => Array<{ id: string; label: string }>;
26
+ /**
27
+ * Rewrite stored user and assistant text before it is sent as a transcript, for example to
28
+ * remove a prefix the host adds to messages.
29
+ */
30
+ displayText?: (text: string) => string;
31
+ /**
32
+ * Turn a `POST /turn` request into per-turn options. `message` is what the user typed. Return
33
+ * `message` to change what the model sees and `options` to shape the turn. Return `reply` to
34
+ * answer without running the model at all, for example a placeholder for an empty recording.
35
+ */
36
+ beforeTurn?: (
37
+ ctx: BridgeHostContext,
38
+ input: { message: string; body: Record<string, unknown> },
39
+ ) => BridgeTurnPlan | undefined | Promise<BridgeTurnPlan | undefined>;
40
+ }
41
+
42
+ export interface BridgeTurnPlan {
43
+ /** What the model sees. Defaults to the user's message. */
44
+ message?: string;
45
+ /**
46
+ * What the chat stores and titles the conversation with. Set it when the incoming message
47
+ * already carries a host prefix that should not show up in the chat. Defaults to the user's
48
+ * message, or to the original message when `message` is changed.
49
+ */
50
+ displayMessage?: string;
51
+ /** Per-turn options passed to `runTurn`. The bridge sets `displayMessage` for you. */
52
+ options?: Omit<HarnessTurnOptions, "signal" | "approvalAsk" | "editUserTurn" | "displayMessage">;
53
+ /** Answer with this text and skip the model. */
54
+ reply?: string;
55
+ }
56
+
57
+ export interface BridgeHostContext {
58
+ harness: HarnessRuntime;
59
+ }
package/src/index.ts CHANGED
@@ -1,4 +1,12 @@
1
+ export { resolveAgentCwd } from "./agent-cwd.ts";
1
2
  export type { BrowserConfig } from "./browser/browser-use.ts";
3
+ export {
4
+ COMMIT_RE,
5
+ covers as hostCovers,
6
+ FIELD_ROLES,
7
+ hostOf,
8
+ hostsInText,
9
+ } from "./browser/own-chrome.ts";
2
10
  export {
3
11
  CAELENCE_THEME,
4
12
  PLAIN_THEME,
@@ -11,8 +19,10 @@ export {
11
19
  DEFAULT_CONFIG,
12
20
  DEFAULT_MODEL,
13
21
  loadConfig,
22
+ OPENROUTER_DEFAULT_BASE_URL,
14
23
  resolveConfigPath,
15
24
  resolveOpenRouter,
25
+ stripTrailingSlashes,
16
26
  } from "./config.ts";
17
27
  export {
18
28
  type ApprovalGate,
@@ -24,7 +34,16 @@ export {
24
34
  isUploadEditRequest,
25
35
  parseExecApprovalPolicy,
26
36
  } from "./core/approval.ts";
27
- export type { AgentEvent, AgentEventEmitter, MainModelProvider } from "./core/events.ts";
37
+ export { errorMessage } from "./core/errors.ts";
38
+ export type {
39
+ AgentEvent,
40
+ AgentEventEmitter,
41
+ MainModelProvider,
42
+ ProviderMessage,
43
+ ProviderStreamEvent,
44
+ ProviderToolDefinition,
45
+ ProviderTurnRequest,
46
+ } from "./core/events.ts";
28
47
  export { isTerminalAgentEvent } from "./core/events.ts";
29
48
  export { createHookRunner, type HookConfig, type HookRunner } from "./core/hooks.ts";
30
49
  export { newId } from "./core/ids.ts";
@@ -43,6 +62,7 @@ export {
43
62
  mcpToolListItem,
44
63
  READ_ONLY_ANNOTATIONS,
45
64
  resolveToolAnnotations,
65
+ type ToolResult,
46
66
  textResult,
47
67
  toolResultText,
48
68
  UNKNOWN_TOOL_ANNOTATIONS,
@@ -55,7 +75,14 @@ export {
55
75
  toolsAllowedInMode,
56
76
  tryParseAgentMode,
57
77
  } from "./core/mode.ts";
58
- export { buildSystemPrompt, type RunTurnDeps, runTurn, type TurnRequest } from "./core/run-turn.ts";
78
+ export {
79
+ buildSystemPrompt,
80
+ type RunTurnDeps,
81
+ runTurn,
82
+ type TurnInterceptContext,
83
+ type TurnInterceptor,
84
+ type TurnRequest,
85
+ } from "./core/run-turn.ts";
59
86
  export {
60
87
  createFileSessionStore,
61
88
  createMemorySessionStore,
@@ -70,6 +97,15 @@ export {
70
97
  sessionTranscript,
71
98
  titleFromUserMessage,
72
99
  } from "./core/session.ts";
100
+ export {
101
+ type AgentConstructionInput,
102
+ type AgentTool,
103
+ type ConstructAgent,
104
+ type ConstructedAgent,
105
+ constructOpenRouterProvider,
106
+ createConstructAgent,
107
+ type StrandsBackedProvider,
108
+ } from "./core/strands.ts";
73
109
  export { addUsage, formatUsage, parseTokenUsage, type TokenUsage } from "./core/usage.ts";
74
110
  export { type ApprovalVerdict, classifyToolApproval } from "./decisions/approval.ts";
75
111
  export {
@@ -90,6 +126,14 @@ export {
90
126
  } from "./decisions/config.ts";
91
127
  export { turnHasDurableFact } from "./decisions/memory.ts";
92
128
  export type { ShortcutContext, ShortcutPlan, ShortcutPlanner } from "./decisions/shortcuts.ts";
129
+ export {
130
+ type BridgeReady,
131
+ type DesktopState,
132
+ type StartDesktopBridgeOptions,
133
+ startDesktopBridge,
134
+ } from "./desktop/bridge.ts";
135
+ export type { BridgeHost, BridgeHostContext, BridgeTurnPlan } from "./desktop/host.ts";
136
+ export { harnessHome } from "./desktop/secrets.ts";
93
137
  export {
94
138
  type ChatFn,
95
139
  createOpenRouterChat,
@@ -102,7 +146,47 @@ export {
102
146
  runNamedEval,
103
147
  } from "./evals/runner.ts";
104
148
  export { initHost } from "./init.ts";
105
- export { extractMemories, parseExtractedFacts } from "./memory/extract.ts";
149
+ export { listedMcpCatalog, type McpCatalogEntry } from "./integrations/catalog.ts";
150
+ export { connectMcp } from "./integrations/connect.ts";
151
+ export { withOAuthLoopback } from "./integrations/loopback.ts";
152
+ export { openRemoteMcp } from "./integrations/remote-mcp.ts";
153
+ export { listStoredConnections } from "./integrations/store.ts";
154
+ export {
155
+ DEFAULT_BRIEF_WORDS,
156
+ formatMemoryBriefs,
157
+ memoryBriefSystem,
158
+ synthesizeMemoryBrief,
159
+ } from "./memory/brief.ts";
160
+ export {
161
+ cosineSimilarity,
162
+ createOpenAICompatEmbedder,
163
+ DEFAULT_EMBEDDING_MODEL,
164
+ type Embedder,
165
+ fuseRankings,
166
+ } from "./memory/embeddings.ts";
167
+ export {
168
+ extractMemories,
169
+ MEMORY_EXTRACT_SYSTEM,
170
+ parseExtractedFacts,
171
+ turnMemorySource,
172
+ } from "./memory/extract.ts";
173
+ export {
174
+ createLayeredMemoryStore,
175
+ type LayeredMemoryStore,
176
+ type MemoryLayer,
177
+ } from "./memory/layered.ts";
178
+ export {
179
+ type CreateMemoryStoreOptions,
180
+ createFileMemoryBackend,
181
+ createFileMemoryStore,
182
+ createInMemoryMemoryBackend,
183
+ createMemoryStore,
184
+ type MemoryBackend,
185
+ type MemoryEmbeddingRow,
186
+ type MemoryRecord,
187
+ type MemoryStore,
188
+ type NewMemoryFact,
189
+ } from "./memory/memory-store.ts";
106
190
  export { isMemoryEnabled, readMemoryPrefs, writeMemoryPrefs } from "./memory/prefs.ts";
107
191
  export { formatMemoryList, formatRetrievedMemory } from "./memory/prompt.ts";
108
192
  export {
@@ -112,6 +196,8 @@ export {
112
196
  type MemoryFact,
113
197
  type MemoryScope,
114
198
  pinFact,
199
+ prepareFacts,
200
+ rankFacts,
115
201
  searchFacts,
116
202
  unpinFact,
117
203
  } from "./memory/store.ts";
@@ -131,7 +217,12 @@ export {
131
217
  WEBSITE_GENERATION_REGRESSION,
132
218
  } from "./observability/index.ts";
133
219
  export { CLI_NAME, PRODUCT_NAME } from "./product.ts";
134
- export { type CreateHarnessOptions, createHarness, type HarnessRuntime } from "./runtime.ts";
220
+ export {
221
+ type CreateHarnessOptions,
222
+ createHarness,
223
+ type HarnessRuntime,
224
+ type HarnessTurnOptions,
225
+ } from "./runtime.ts";
135
226
  export { authorSkillMarkdown, SKILL_AUTHOR_SYSTEM } from "./skills/author-skill.ts";
136
227
  export {
137
228
  browseSkillCatalog,
@@ -188,8 +279,35 @@ export {
188
279
  } from "./skills/registry.ts";
189
280
  export { parseSkillCommand, SKILL_COMMAND_USAGE, SKILL_FIND_HINT } from "./skills/skill-command.ts";
190
281
  export { userSkillsDir } from "./skills/user-dir.ts";
282
+ export {
283
+ resolveStatusVerbPool,
284
+ statusVerbCategories,
285
+ statusVerbCategoryNames,
286
+ } from "./status/categories.ts";
287
+ export {
288
+ DEFAULT_STATUS_VERBS,
289
+ DEFAULT_STATUS_VERBS_PER_TURN,
290
+ FALLBACK_STATUS_VERB,
291
+ pickStatusVerbs,
292
+ type StatusVerbsConfig,
293
+ seededRandom,
294
+ statusVerbAt,
295
+ } from "./status/status-verbs.ts";
296
+ export {
297
+ BACKGROUND_AGENTS_PROMPT,
298
+ type BackgroundAgentRunInput,
299
+ type BackgroundAgentSnapshot,
300
+ type BackgroundAgentStatus,
301
+ type BackgroundAgents,
302
+ type BackgroundAgentsOptions,
303
+ createBackgroundAgents,
304
+ EXPLORE_INSTRUCTIONS,
305
+ readOnlyTools,
306
+ type SubagentKind,
307
+ } from "./tools/background.ts";
191
308
  export { createGitTools } from "./tools/git.ts";
192
309
  export { createLocalTools } from "./tools/local.ts";
310
+ export { createMemoryTools } from "./tools/memory.ts";
193
311
  export { PathEscapeError, resolveUnderCwd } from "./tools/paths.ts";
194
312
  export { createReadSkillTool } from "./tools/read-skill.ts";
195
313
  export { createTaskTool } from "./tools/subagent.ts";
@@ -0,0 +1,62 @@
1
+ import type { MainModelProvider } from "../core/events.ts";
2
+ import type { MemoryFact } from "./store.ts";
3
+
4
+ export const DEFAULT_BRIEF_WORDS = 180;
5
+ /** Facts handed to the model for one brief. The newest are kept when there are more. */
6
+ export const MAX_BRIEF_FACTS = 200;
7
+
8
+ /**
9
+ * The system prompt that turns a pile of remembered facts into one short brief. A brief is what
10
+ * a new chat, or a new project in the same workspace, starts from.
11
+ */
12
+ export function memoryBriefSystem(subject: string, maxWords = DEFAULT_BRIEF_WORDS): string {
13
+ return [
14
+ `Write a short brief of what is known about ${subject}, from the remembered facts below.`,
15
+ "The facts are listed oldest first. When two disagree, the later one is right; leave the earlier one out.",
16
+ "Group related points and say each thing once. Use plain sentences or short bullets.",
17
+ "Use only what the facts say. Do not add advice, guesses, or anything they do not state.",
18
+ `Stay under ${maxWords} words. Reply with the brief only, no heading and no preamble.`,
19
+ ].join(" ");
20
+ }
21
+
22
+ /**
23
+ * Consolidate facts into a brief with one model call. Returns an empty string when there are no
24
+ * facts or the model fails, so the caller keeps whatever brief it already had.
25
+ */
26
+ export async function synthesizeMemoryBrief(input: {
27
+ facts: readonly MemoryFact[];
28
+ provider: MainModelProvider;
29
+ /** What the facts are about: "this project", "the Acme workspace". */
30
+ subject: string;
31
+ maxWords?: number;
32
+ signal?: AbortSignal;
33
+ }): Promise<string> {
34
+ const facts = input.facts.slice(-MAX_BRIEF_FACTS);
35
+ if (facts.length === 0) return "";
36
+ const maxWords = input.maxWords ?? DEFAULT_BRIEF_WORDS;
37
+ let raw = "";
38
+ for await (const event of input.provider.stream(
39
+ {
40
+ system: memoryBriefSystem(input.subject, maxWords),
41
+ messages: [{ role: "user", content: facts.map((fact) => `- ${fact.text}`).join("\n") }],
42
+ maxTokens: Math.ceil(maxWords * 2.5),
43
+ },
44
+ input.signal ? { signal: input.signal } : undefined,
45
+ )) {
46
+ if (event.type === "text_delta") raw += event.text;
47
+ if (event.type === "error") return "";
48
+ }
49
+ const words = raw.trim().split(/\s+/).filter(Boolean);
50
+ // A model that ignores the limit is cut rather than trusted with the whole prompt budget.
51
+ if (words.length > maxWords * 1.5)
52
+ return `${words.slice(0, Math.floor(maxWords * 1.5)).join(" ")} …`;
53
+ return raw.trim();
54
+ }
55
+
56
+ /** The briefs as system-prompt sections, widest first so the narrower one has the last word. */
57
+ export function formatMemoryBriefs(briefs: ReadonlyArray<{ title: string; text: string }>): string {
58
+ return briefs
59
+ .filter((brief) => brief.text.trim())
60
+ .map((brief) => `### ${brief.title}\n${brief.text.trim()}`)
61
+ .join("\n\n");
62
+ }
@@ -0,0 +1,104 @@
1
+ import { OPENROUTER_DEFAULT_BASE_URL } from "../config.ts";
2
+ import { PRODUCT_NAME } from "../product.ts";
3
+
4
+ /** Turns text into vectors. One vector per input, in the same order. */
5
+ export interface Embedder {
6
+ /** Names the vector space. Vectors from two models are never compared. */
7
+ readonly model: string;
8
+ embed(texts: string[]): Promise<number[][]>;
9
+ }
10
+
11
+ export const DEFAULT_EMBEDDING_MODEL = "openai/text-embedding-3-small";
12
+
13
+ const EMBED_BATCH = 96;
14
+
15
+ /**
16
+ * An embedder for any OpenAI-compatible `/embeddings` endpoint. OpenRouter is the default.
17
+ * The texts are sent to that provider, so a host turns this on deliberately.
18
+ */
19
+ export function createOpenAICompatEmbedder(options: {
20
+ apiKey: string | (() => string);
21
+ baseUrl?: string;
22
+ model?: string;
23
+ fetch?: typeof fetch;
24
+ }): Embedder {
25
+ const baseUrl = (options.baseUrl ?? OPENROUTER_DEFAULT_BASE_URL).replace(/\/+$/, "");
26
+ const model = options.model?.trim() || DEFAULT_EMBEDDING_MODEL;
27
+ const doFetch = options.fetch ?? fetch;
28
+ const embedBatch = async (texts: string[]): Promise<number[][]> => {
29
+ const apiKey = typeof options.apiKey === "function" ? options.apiKey() : options.apiKey;
30
+ if (!apiKey.trim()) throw new Error("No API key for embeddings.");
31
+ const res = await doFetch(`${baseUrl}/embeddings`, {
32
+ method: "POST",
33
+ headers: {
34
+ Authorization: `Bearer ${apiKey}`,
35
+ "Content-Type": "application/json",
36
+ "HTTP-Referer": "https://caelence.com",
37
+ "X-Title": `${PRODUCT_NAME} memory`,
38
+ },
39
+ body: JSON.stringify({ model, input: texts }),
40
+ });
41
+ if (!res.ok) {
42
+ const body = await res.text();
43
+ throw new Error(`Embeddings ${res.status}: ${body.slice(0, 300)}`);
44
+ }
45
+ const json = (await res.json()) as {
46
+ data?: Array<{ index?: number; embedding?: unknown }>;
47
+ };
48
+ const rows = json.data ?? [];
49
+ const out: number[][] = new Array(texts.length);
50
+ rows.forEach((row, position) => {
51
+ const index = typeof row.index === "number" ? row.index : position;
52
+ if (Array.isArray(row.embedding) && index >= 0 && index < texts.length) {
53
+ out[index] = row.embedding as number[];
54
+ }
55
+ });
56
+ for (let i = 0; i < texts.length; i += 1) {
57
+ if (!Array.isArray(out[i])) throw new Error("Embeddings reply was missing a vector.");
58
+ }
59
+ return out;
60
+ };
61
+ return {
62
+ model,
63
+ async embed(texts) {
64
+ const out: number[][] = [];
65
+ for (let i = 0; i < texts.length; i += EMBED_BATCH) {
66
+ out.push(...(await embedBatch(texts.slice(i, i + EMBED_BATCH))));
67
+ }
68
+ return out;
69
+ },
70
+ };
71
+ }
72
+
73
+ export function cosineSimilarity(a: readonly number[], b: readonly number[]): number {
74
+ if (a.length === 0 || a.length !== b.length) return 0;
75
+ let dot = 0;
76
+ let normA = 0;
77
+ let normB = 0;
78
+ for (let i = 0; i < a.length; i += 1) {
79
+ const x = a[i] ?? 0;
80
+ const y = b[i] ?? 0;
81
+ dot += x * y;
82
+ normA += x * x;
83
+ normB += y * y;
84
+ }
85
+ if (normA === 0 || normB === 0) return 0;
86
+ return dot / Math.sqrt(normA * normB);
87
+ }
88
+
89
+ /**
90
+ * Merge ranked lists into one. An item's score is the sum of 1 / (k + rank) over the lists it
91
+ * appears in, so something both lists like beats something one list loves.
92
+ */
93
+ export function fuseRankings<T>(lists: T[][], keyOf: (item: T) => string, k = 60): T[] {
94
+ const scores = new Map<string, { item: T; score: number }>();
95
+ for (const list of lists) {
96
+ list.forEach((item, rank) => {
97
+ const key = keyOf(item);
98
+ const row = scores.get(key) ?? { item, score: 0 };
99
+ row.score += 1 / (k + rank + 1);
100
+ scores.set(key, row);
101
+ });
102
+ }
103
+ return [...scores.values()].sort((a, b) => b.score - a.score).map((row) => row.item);
104
+ }