@useavalon/caelence-agent 0.2.3-canary.0 → 0.2.3-canary.2

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 (67) hide show
  1. package/README.md +7 -0
  2. package/desktop/src/App.tsx +9 -2919
  3. package/desktop/src/BubbleClip.tsx +1 -1
  4. package/desktop/src/ComposerAttach.tsx +2 -2
  5. package/desktop/src/DeskBoot.tsx +28 -0
  6. package/desktop/src/DeskChrome.tsx +360 -0
  7. package/desktop/src/DeskComposer.tsx +311 -0
  8. package/desktop/src/DeskSidebar.tsx +191 -0
  9. package/desktop/src/FilesPanel.tsx +104 -36
  10. package/desktop/src/FloatNotice.test.ts +12 -0
  11. package/desktop/src/FloatNotice.tsx +5 -2
  12. package/desktop/src/IntegrationsPanel.tsx +273 -0
  13. package/desktop/src/McpPanel.tsx +8 -8
  14. package/desktop/src/MemoryPanel.tsx +138 -0
  15. package/desktop/src/QueuePanel.tsx +123 -0
  16. package/desktop/src/SessionsPanel.tsx +174 -0
  17. package/desktop/src/SettingsPanel.tsx +181 -0
  18. package/desktop/src/SkillsPanel.tsx +28 -12
  19. package/desktop/src/TranscriptViews.tsx +637 -0
  20. package/desktop/src/api.ts +36 -0
  21. package/desktop/src/app.css +159 -11
  22. package/desktop/src/composer-files.ts +2 -2
  23. package/desktop/src/desk-keys.ts +45 -0
  24. package/desktop/src/desk-prefs.ts +29 -0
  25. package/desktop/src/desk-types.ts +92 -0
  26. package/desktop/src/desktop-turn.ts +271 -0
  27. package/desktop/src/preview-render.ts +322 -36
  28. package/desktop/src/queue.ts +1 -1
  29. package/desktop/src/session-search.test.ts +20 -0
  30. package/desktop/src/session-search.ts +13 -0
  31. package/desktop/src/session-select.test.ts +23 -0
  32. package/desktop/src/session-select.ts +32 -0
  33. package/desktop/src/useDeskDictation.ts +123 -0
  34. package/desktop/src/useDeskFiles.ts +180 -0
  35. package/desktop/src/useDeskNotice.ts +20 -0
  36. package/desktop/src/useDeskPicker.ts +189 -0
  37. package/desktop/src/useDeskPrefs.ts +30 -0
  38. package/desktop/src/useDeskRuntime.ts +109 -0
  39. package/desktop/src/useDeskSessions.ts +195 -0
  40. package/desktop/src/useDeskSlash.ts +31 -0
  41. package/desktop/src/useDeskTurns.ts +264 -0
  42. package/desktop/src/useDesktopApp.ts +286 -0
  43. package/desktop/src/user-display.ts +2 -2
  44. package/package.json +2 -2
  45. package/src/cli/openrouter-live.ts +30 -21
  46. package/src/cli/slash-dispatch.test.ts +25 -0
  47. package/src/cli/slash-dispatch.ts +41 -0
  48. package/src/cli/slash.ts +1 -0
  49. package/src/config.ts +10 -1
  50. package/src/core/run-turn.test.ts +3 -0
  51. package/src/core/run-turn.ts +74 -41
  52. package/src/desktop/bridge.test.ts +43 -0
  53. package/src/desktop/bridge.ts +91 -19
  54. package/src/desktop/uploads.test.ts +6 -0
  55. package/src/desktop/uploads.ts +178 -66
  56. package/src/index.ts +13 -0
  57. package/src/integrations/remote-mcp.ts +51 -21
  58. package/src/memory/extract.test.ts +81 -0
  59. package/src/memory/extract.ts +88 -0
  60. package/src/memory/prefs.test.ts +53 -0
  61. package/src/memory/prefs.ts +47 -0
  62. package/src/memory/prompt.ts +24 -0
  63. package/src/memory/store.test.ts +191 -0
  64. package/src/memory/store.ts +382 -0
  65. package/src/runtime.test.ts +37 -0
  66. package/src/runtime.ts +29 -1
  67. package/src/tools/local.ts +86 -39
@@ -1,7 +1,15 @@
1
- import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
1
+ import {
2
+ existsSync,
3
+ mkdirSync,
4
+ readdirSync,
5
+ readFileSync,
6
+ statSync,
7
+ unlinkSync,
8
+ writeFileSync,
9
+ } from "node:fs";
2
10
  import { homedir } from "node:os";
3
- import { isAbsolute, resolve } from "node:path";
4
- import { toProjectRel } from "../tools/paths.ts";
11
+ import { basename, isAbsolute, resolve } from "node:path";
12
+ import { resolveUnderCwd, toProjectRel } from "../tools/paths.ts";
5
13
  import { composeUploadMessage as buildUploadMessage } from "./upload-message.ts";
6
14
 
7
15
  export const MAX_UPLOADS = 8;
@@ -10,10 +18,51 @@ const TEXT_EXCERPT_BYTES = 100_000;
10
18
  const INDEX_NAME = "index.json";
11
19
  const MAX_LISTED = 40;
12
20
 
13
- const TEXT_MIME =
14
- /^(text\/|application\/(json|xml|javascript|sql|yaml|x-yaml|toml|x-sh|x-httpd-php))/i;
15
- const TEXT_EXT =
16
- /\.(txt|md|markdown|json|csv|tsv|ts|tsx|js|jsx|mjs|cjs|css|scss|html|htm|xml|yml|yaml|toml|py|rs|go|sh|bash|zsh|env|svg|log|ini|cfg)$/i;
21
+ const TEXT_MIME_PREFIXES = [
22
+ "text/",
23
+ "application/json",
24
+ "application/xml",
25
+ "application/javascript",
26
+ "application/sql",
27
+ "application/yaml",
28
+ "application/x-yaml",
29
+ "application/toml",
30
+ "application/x-sh",
31
+ "application/x-httpd-php",
32
+ ];
33
+ const TEXT_EXTS = new Set([
34
+ "txt",
35
+ "md",
36
+ "markdown",
37
+ "json",
38
+ "csv",
39
+ "tsv",
40
+ "ts",
41
+ "tsx",
42
+ "js",
43
+ "jsx",
44
+ "mjs",
45
+ "cjs",
46
+ "css",
47
+ "scss",
48
+ "html",
49
+ "htm",
50
+ "xml",
51
+ "yml",
52
+ "yaml",
53
+ "toml",
54
+ "py",
55
+ "rs",
56
+ "go",
57
+ "sh",
58
+ "bash",
59
+ "zsh",
60
+ "env",
61
+ "svg",
62
+ "log",
63
+ "ini",
64
+ "cfg",
65
+ ]);
17
66
 
18
67
  export interface IncomingUpload {
19
68
  name: string;
@@ -38,21 +87,25 @@ export interface UploadRecord {
38
87
  addedAt: string;
39
88
  }
40
89
 
90
+ function incomingFromUnknown(item: unknown): IncomingUpload | undefined {
91
+ if (!item || typeof item !== "object") return undefined;
92
+ const rec = item as Record<string, unknown>;
93
+ const name = typeof rec.name === "string" ? rec.name.trim() : "";
94
+ const data = typeof rec.data === "string" ? rec.data.trim() : "";
95
+ if (!name || !data) return undefined;
96
+ const mime =
97
+ typeof rec.mime === "string" && rec.mime.trim() ? rec.mime.trim() : "application/octet-stream";
98
+ const sourcePath = parseSourcePath(rec.sourcePath);
99
+ return { name, mime, data, ...(sourcePath ? { sourcePath } : {}) };
100
+ }
101
+
41
102
  export function parseIncomingUploads(raw: unknown): IncomingUpload[] {
42
103
  if (!Array.isArray(raw)) return [];
43
104
  const out: IncomingUpload[] = [];
44
105
  for (const item of raw) {
45
- if (!item || typeof item !== "object") continue;
46
- const rec = item as Record<string, unknown>;
47
- const name = typeof rec.name === "string" ? rec.name.trim() : "";
48
- const data = typeof rec.data === "string" ? rec.data.trim() : "";
49
- const mime =
50
- typeof rec.mime === "string" && rec.mime.trim()
51
- ? rec.mime.trim()
52
- : "application/octet-stream";
53
- if (!name || !data) continue;
54
- const sourcePath = parseSourcePath(rec.sourcePath);
55
- out.push({ name, mime, data, ...(sourcePath ? { sourcePath } : {}) });
106
+ const parsed = incomingFromUnknown(item);
107
+ if (!parsed) continue;
108
+ out.push(parsed);
56
109
  if (out.length >= MAX_UPLOADS) break;
57
110
  }
58
111
  return out;
@@ -61,7 +114,13 @@ export function parseIncomingUploads(raw: unknown): IncomingUpload[] {
61
114
  export function parseSourcePath(raw: unknown): string | undefined {
62
115
  if (typeof raw !== "string") return undefined;
63
116
  const trimmed = raw.trim();
64
- if (!trimmed || trimmed.includes("\0") || /\n|\r/.test(trimmed) || trimmed.length > 1024) {
117
+ if (
118
+ !trimmed ||
119
+ trimmed.includes("\0") ||
120
+ trimmed.includes("\n") ||
121
+ trimmed.includes("\r") ||
122
+ trimmed.length > 1024
123
+ ) {
65
124
  return undefined;
66
125
  }
67
126
  if (trimmed.startsWith("file://")) return undefined;
@@ -84,7 +143,11 @@ export function displaySourcePath(abs: string): string {
84
143
  }
85
144
 
86
145
  export function isTextUpload(name: string, mime: string): boolean {
87
- return TEXT_MIME.test(mime) || TEXT_EXT.test(name);
146
+ const lowerMime = mime.toLowerCase();
147
+ if (TEXT_MIME_PREFIXES.some((prefix) => lowerMime.startsWith(prefix))) return true;
148
+ const dot = name.lastIndexOf(".");
149
+ if (dot < 0) return false;
150
+ return TEXT_EXTS.has(name.slice(dot + 1).toLowerCase());
88
151
  }
89
152
 
90
153
  export function safeUploadName(name: string): string {
@@ -101,31 +164,28 @@ function storedDisplayName(filename: string): string {
101
164
  return filename.replace(/^\d+-\d+-/, "") || filename;
102
165
  }
103
166
 
167
+ function recordFromUnknown(item: unknown): UploadRecord | undefined {
168
+ if (!item || typeof item !== "object") return undefined;
169
+ const rec = item as Record<string, unknown>;
170
+ const name = typeof rec.name === "string" ? rec.name : "";
171
+ const rel = typeof rec.rel === "string" ? rec.rel : "";
172
+ if (!name || !rel) return undefined;
173
+ const mime = typeof rec.mime === "string" ? rec.mime : "application/octet-stream";
174
+ const addedAt = typeof rec.addedAt === "string" ? rec.addedAt : "";
175
+ const sourcePath = parseSourcePath(rec.sourcePath);
176
+ return { name, rel, mime, addedAt, ...(sourcePath ? { sourcePath } : {}) };
177
+ }
178
+
104
179
  function readIndex(dir: string): UploadRecord[] {
105
180
  try {
106
181
  const parsed: unknown = JSON.parse(readFileSync(resolve(dir, INDEX_NAME), "utf8"));
107
182
  if (!parsed || typeof parsed !== "object") return [];
108
183
  const files = (parsed as { files?: unknown }).files;
109
184
  if (!Array.isArray(files)) return [];
110
- const out: UploadRecord[] = [];
111
- for (const item of files) {
112
- if (!item || typeof item !== "object") continue;
113
- const rec = item as Record<string, unknown>;
114
- const name = typeof rec.name === "string" ? rec.name : "";
115
- const rel = typeof rec.rel === "string" ? rec.rel : "";
116
- if (!name || !rel) continue;
117
- const mime = typeof rec.mime === "string" ? rec.mime : "application/octet-stream";
118
- const addedAt = typeof rec.addedAt === "string" ? rec.addedAt : "";
119
- const sourcePath = parseSourcePath(rec.sourcePath);
120
- out.push({
121
- name,
122
- rel,
123
- mime,
124
- addedAt,
125
- ...(sourcePath ? { sourcePath } : {}),
126
- });
127
- }
128
- return out;
185
+ return files.flatMap((item) => {
186
+ const rec = recordFromUnknown(item);
187
+ return rec ? [rec] : [];
188
+ });
129
189
  } catch {
130
190
  return [];
131
191
  }
@@ -157,7 +217,7 @@ export function listUploads(cwd: string): UploadRecord[] {
157
217
  // no uploads folder yet
158
218
  }
159
219
  return [...byRel.values()]
160
- .sort((a, b) => (a.addedAt < b.addedAt ? 1 : a.addedAt > b.addedAt ? -1 : 0))
220
+ .sort((left, right) => right.addedAt.localeCompare(left.addedAt))
161
221
  .slice(0, MAX_LISTED);
162
222
  }
163
223
 
@@ -202,6 +262,41 @@ export function matchUploadEdit(
202
262
  return undefined;
203
263
  }
204
264
 
265
+ function existingSourcePath(raw: string | undefined): string | undefined {
266
+ if (!raw) return undefined;
267
+ const abs = expandSourcePath(raw);
268
+ return existsSync(abs) ? abs : undefined;
269
+ }
270
+
271
+ function excerptForUpload(item: IncomingUpload, bytes: Buffer): string | undefined {
272
+ if (!isTextUpload(item.name, item.mime) || bytes.byteLength > TEXT_EXCERPT_BYTES) {
273
+ return undefined;
274
+ }
275
+ return bytes.toString("utf8");
276
+ }
277
+
278
+ function writeOneUpload(
279
+ cwd: string,
280
+ dir: string,
281
+ item: IncomingUpload,
282
+ index: number,
283
+ ): SavedUpload | undefined {
284
+ const bytes = Buffer.from(item.data, "base64");
285
+ if (bytes.byteLength === 0 || bytes.byteLength > MAX_UPLOAD_BYTES) return undefined;
286
+ const unique = `${Date.now()}-${index}-${safeUploadName(item.name)}`;
287
+ const abs = resolve(dir, unique);
288
+ writeFileSync(abs, bytes);
289
+ const excerpt = excerptForUpload(item, bytes);
290
+ const sourcePath = existingSourcePath(item.sourcePath);
291
+ return {
292
+ name: item.name,
293
+ rel: toProjectRel(cwd, abs),
294
+ mime: item.mime,
295
+ ...(excerpt !== undefined ? { excerpt } : {}),
296
+ ...(sourcePath ? { sourcePath } : {}),
297
+ };
298
+ }
299
+
205
300
  export function saveUploads(cwd: string, items: IncomingUpload[]): SavedUpload[] {
206
301
  if (items.length === 0) return [];
207
302
  const dir = uploadsDir(cwd);
@@ -209,40 +304,57 @@ export function saveUploads(cwd: string, items: IncomingUpload[]): SavedUpload[]
209
304
  const saved: SavedUpload[] = [];
210
305
  const records = listUploads(cwd);
211
306
  for (const item of items) {
212
- const bytes = Buffer.from(item.data, "base64");
213
- if (bytes.byteLength === 0 || bytes.byteLength > MAX_UPLOAD_BYTES) continue;
214
- const unique = `${Date.now()}-${saved.length}-${safeUploadName(item.name)}`;
215
- const abs = resolve(dir, unique);
216
- writeFileSync(abs, bytes);
217
- const rel = toProjectRel(cwd, abs);
218
- const excerpt =
219
- isTextUpload(item.name, item.mime) && bytes.byteLength <= TEXT_EXCERPT_BYTES
220
- ? bytes.toString("utf8")
221
- : undefined;
222
- const sourcePath = item.sourcePath
223
- ? existsSync(expandSourcePath(item.sourcePath))
224
- ? expandSourcePath(item.sourcePath)
225
- : undefined
226
- : undefined;
227
- saved.push({
228
- name: item.name,
229
- rel,
230
- mime: item.mime,
231
- ...(excerpt !== undefined ? { excerpt } : {}),
232
- ...(sourcePath ? { sourcePath } : {}),
233
- });
307
+ const next = writeOneUpload(cwd, dir, item, saved.length);
308
+ if (!next) continue;
309
+ saved.push(next);
234
310
  records.unshift({
235
- name: item.name,
236
- rel,
237
- mime: item.mime,
311
+ name: next.name,
312
+ rel: next.rel,
313
+ mime: next.mime,
238
314
  addedAt: new Date().toISOString(),
239
- ...(sourcePath ? { sourcePath } : {}),
315
+ ...(next.sourcePath ? { sourcePath: next.sourcePath } : {}),
240
316
  });
241
317
  }
242
318
  writeIndex(dir, records.slice(0, MAX_LISTED));
243
319
  return saved;
244
320
  }
245
321
 
322
+ export function deleteUploads(cwd: string, rels: readonly string[]): UploadRecord[] {
323
+ const wanted = new Set(rels.filter((rel) => rel.trim().length > 0));
324
+ if (wanted.size === 0) return listUploads(cwd);
325
+ const dir = uploadsDir(cwd);
326
+ const keep: UploadRecord[] = [];
327
+ for (const item of listUploads(cwd)) {
328
+ if (!wanted.has(item.rel) || !isListedUploadRel(cwd, dir, item.rel)) {
329
+ keep.push(item);
330
+ continue;
331
+ }
332
+ try {
333
+ const abs = resolveUnderCwd(cwd, item.rel);
334
+ if (existsSync(abs) && statSync(abs).isFile()) unlinkSync(abs);
335
+ } catch {
336
+ keep.push(item);
337
+ }
338
+ }
339
+ try {
340
+ writeIndex(dir, keep);
341
+ } catch {
342
+ // no uploads folder
343
+ }
344
+ return keep;
345
+ }
346
+
347
+ function isListedUploadRel(cwd: string, dir: string, rel: string): boolean {
348
+ if (basename(rel) === INDEX_NAME) return false;
349
+ if (!rel.startsWith(".harness/uploads/") || rel.includes("\0")) return false;
350
+ try {
351
+ const abs = resolveUnderCwd(cwd, rel);
352
+ return abs.startsWith(`${dir}/`) && abs !== dir;
353
+ } catch {
354
+ return false;
355
+ }
356
+ }
357
+
246
358
  export function composeUploadMessage(text: string, files: SavedUpload[]): string {
247
359
  return buildUploadMessage(
248
360
  text,
package/src/index.ts CHANGED
@@ -79,6 +79,19 @@ export {
79
79
  runNamedEval,
80
80
  } from "./evals/runner.ts";
81
81
  export { initHost } from "./init.ts";
82
+ export { extractMemories, parseExtractedFacts } from "./memory/extract.ts";
83
+ export { isMemoryEnabled, readMemoryPrefs, writeMemoryPrefs } from "./memory/prefs.ts";
84
+ export { formatMemoryList, formatRetrievedMemory } from "./memory/prompt.ts";
85
+ export {
86
+ addFacts,
87
+ deleteFact,
88
+ listFacts,
89
+ type MemoryFact,
90
+ type MemoryScope,
91
+ pinFact,
92
+ searchFacts,
93
+ unpinFact,
94
+ } from "./memory/store.ts";
82
95
  export {
83
96
  createObservability,
84
97
  createRecordingObservability,
@@ -35,9 +35,20 @@ export interface LinkedMcpSource {
35
35
  accessToken: string;
36
36
  }
37
37
 
38
+ function trimUnderscores(value: string): string {
39
+ let trimmed = value;
40
+ while (trimmed.startsWith("_")) trimmed = trimmed.slice(1);
41
+ while (trimmed.endsWith("_")) trimmed = trimmed.slice(0, -1);
42
+ return trimmed;
43
+ }
44
+
45
+ function slugToken(value: string, pattern: RegExp): string {
46
+ return trimUnderscores(value.replace(pattern, "_"));
47
+ }
48
+
38
49
  export function namespaceRemoteTool(connectorId: string, remoteName: string): string {
39
- const prefix = connectorId.replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "");
40
- const tool = remoteName.replace(/[^a-zA-Z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
50
+ const prefix = slugToken(connectorId, /[^a-zA-Z0-9]+/g);
51
+ const tool = slugToken(remoteName, /\W+/g);
41
52
  return `${prefix}__${tool}`;
42
53
  }
43
54
 
@@ -223,39 +234,58 @@ function ensureObjectSchema(schema: Record<string, unknown>): Record<string, unk
223
234
  return { type: "object", properties: {}, ...(schema as object) };
224
235
  }
225
236
 
226
- function mapCallToolResult(result: unknown): ToolResult {
227
- if (!result || typeof result !== "object") {
228
- return textResult(String(result ?? ""));
237
+ function scalarToolText(value: unknown): string | undefined {
238
+ if (value == null) return "";
239
+ if (typeof value === "string") return value;
240
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
241
+ return `${value}`;
229
242
  }
230
- const r = result as {
231
- content?: unknown;
232
- isError?: boolean;
233
- structuredContent?: Record<string, unknown>;
234
- };
235
- const isError = r.isError === true;
236
- const blocks = Array.isArray(r.content) ? r.content : [];
243
+ return undefined;
244
+ }
245
+
246
+ function contentTexts(content: unknown): string[] {
247
+ if (!Array.isArray(content)) return [];
237
248
  const textParts: string[] = [];
238
- for (const block of blocks) {
249
+ for (const block of content) {
239
250
  if (!block || typeof block !== "object") continue;
240
251
  const b = block as { type?: string; text?: string };
241
252
  if (b.type === "text" && typeof b.text === "string") textParts.push(b.text);
242
253
  else textParts.push(JSON.stringify(block));
243
254
  }
244
- if (textParts.length === 0 && r.structuredContent) {
245
- return jsonResult(r.structuredContent, isError);
246
- }
247
- if (textParts.length === 0) {
248
- return jsonResult(result as Record<string, unknown>, isError);
249
- }
250
- const text = textParts.join("\n");
255
+ return textParts;
256
+ }
257
+
258
+ function jsonObjectOrNull(text: string): Record<string, unknown> | null {
251
259
  try {
252
260
  const parsed: unknown = JSON.parse(text);
253
261
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
254
- return jsonResult(parsed, isError);
262
+ return parsed as Record<string, unknown>;
255
263
  }
256
264
  } catch {
257
265
  /* plain text */
258
266
  }
267
+ return null;
268
+ }
269
+
270
+ function mapCallToolResult(result: unknown): ToolResult {
271
+ const scalar = scalarToolText(result);
272
+ if (scalar !== undefined) return textResult(scalar);
273
+ const r = result as {
274
+ content?: unknown;
275
+ isError?: boolean;
276
+ structuredContent?: Record<string, unknown>;
277
+ };
278
+ const isError = r.isError === true;
279
+ const textParts = contentTexts(r.content);
280
+ if (textParts.length === 0 && r.structuredContent) {
281
+ return jsonResult(r.structuredContent, isError);
282
+ }
283
+ if (textParts.length === 0) {
284
+ return jsonResult(result as Record<string, unknown>, isError);
285
+ }
286
+ const text = textParts.join("\n");
287
+ const parsed = jsonObjectOrNull(text);
288
+ if (parsed) return jsonResult(parsed, isError);
259
289
  return textResult(text, isError);
260
290
  }
261
291
 
@@ -0,0 +1,81 @@
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 type { MainModelProvider } from "../core/events.ts";
6
+ import { createMemorySessionStore } from "../core/session.ts";
7
+ import { extractMemories, parseExtractedFacts, turnMemorySource } from "./extract.ts";
8
+ import { listFacts } from "./store.ts";
9
+
10
+ describe("memory extract", () => {
11
+ test("parses a JSON array and ignores chatter", () => {
12
+ expect(
13
+ parseExtractedFacts(
14
+ 'Here you go:\n[{"text":"Prefer bun","scope":"user"},{"text":"Bridge is loopback","scope":"project"}]\n',
15
+ ),
16
+ ).toEqual([
17
+ { text: "Prefer bun", scope: "user" },
18
+ { text: "Bridge is loopback", scope: "project" },
19
+ ]);
20
+ expect(parseExtractedFacts("nothing durable")).toEqual([]);
21
+ expect(parseExtractedFacts("[]")).toEqual([]);
22
+ });
23
+
24
+ test("builds a source from the last user, assistant, and tools", async () => {
25
+ const store = createMemorySessionStore();
26
+ let session = await store.create("sys");
27
+ session = await store.append(session, { kind: "turn", role: "user", content: "use bun" });
28
+ session = await store.append(session, {
29
+ kind: "tool",
30
+ name: "read_file",
31
+ callId: "c1",
32
+ status: "ok",
33
+ preview: "package.json",
34
+ });
35
+ session = await store.append(session, {
36
+ kind: "turn",
37
+ role: "assistant",
38
+ content: "I will keep using bun.",
39
+ });
40
+ const source = turnMemorySource(session);
41
+ expect(source).toContain("use bun");
42
+ expect(source).toContain("I will keep using bun.");
43
+ expect(source).toContain("read_file: package.json");
44
+ });
45
+
46
+ test("stores extracted facts from the provider", async () => {
47
+ const cwd = await mkdtemp(join(tmpdir(), "harness-mem-ex-"));
48
+ const home = await mkdtemp(join(tmpdir(), "harness-mem-ex-home-"));
49
+ const env = { HARNESS_HOME: home };
50
+ const provider: MainModelProvider = {
51
+ kind: "fake",
52
+ modelId: "fake",
53
+ async *stream() {
54
+ yield {
55
+ type: "text_delta",
56
+ text: '[{"text":"Prefer bun over npm for installs","scope":"user"}]',
57
+ };
58
+ yield { type: "done" };
59
+ },
60
+ };
61
+ try {
62
+ const store = createMemorySessionStore();
63
+ let session = await store.create("sys");
64
+ session = await store.append(session, {
65
+ kind: "turn",
66
+ role: "user",
67
+ content: "always use bun",
68
+ });
69
+ session = await store.append(session, {
70
+ kind: "turn",
71
+ role: "assistant",
72
+ content: "I will use bun.",
73
+ });
74
+ expect(await extractMemories({ cwd, session, provider, env })).toBe(1);
75
+ expect(listFacts(cwd, env)[0]?.text).toContain("Prefer bun");
76
+ } finally {
77
+ await rm(cwd, { recursive: true, force: true });
78
+ await rm(home, { recursive: true, force: true });
79
+ }
80
+ });
81
+ });
@@ -0,0 +1,88 @@
1
+ import type { MainModelProvider } from "../core/events.ts";
2
+ import type { Session } from "../core/session.ts";
3
+ import { addFacts, type MemoryScope } from "./store.ts";
4
+
5
+ export const MEMORY_EXTRACT_SYSTEM = [
6
+ "Extract durable facts worth remembering in later chats with this coding agent.",
7
+ "Keep: user preferences, stack and tool choices, project decisions, stable conventions.",
8
+ "Write each pref as a short factual sentence the user might ask about later.",
9
+ "Drop: secrets, keys, one-off task details, file contents, compliments, transient errors, anything already obvious from the repo.",
10
+ 'Reply with a JSON array only. Each item is {"text":"short sentence","scope":"user"|"project"}.',
11
+ "scope is user for personal style or prefs, project for this repository.",
12
+ "If nothing is durable, reply [].",
13
+ ].join(" ");
14
+
15
+ export interface ExtractedFact {
16
+ text: string;
17
+ scope: MemoryScope;
18
+ }
19
+
20
+ export function parseExtractedFacts(raw: string): ExtractedFact[] {
21
+ const text = raw.trim();
22
+ if (!text) return [];
23
+ const start = text.indexOf("[");
24
+ const end = text.lastIndexOf("]");
25
+ if (start < 0 || end <= start) return [];
26
+ try {
27
+ const parsed = JSON.parse(text.slice(start, end + 1)) as unknown;
28
+ if (!Array.isArray(parsed)) return [];
29
+ const out: ExtractedFact[] = [];
30
+ for (const item of parsed) {
31
+ if (!item || typeof item !== "object") continue;
32
+ const row = item as { text?: unknown; scope?: unknown };
33
+ if (typeof row.text !== "string") continue;
34
+ out.push({
35
+ text: row.text,
36
+ scope: row.scope === "user" ? "user" : "project",
37
+ });
38
+ }
39
+ return out;
40
+ } catch {
41
+ return [];
42
+ }
43
+ }
44
+
45
+ export function turnMemorySource(session: Session): string {
46
+ let user = "";
47
+ let assistant = "";
48
+ const tools: string[] = [];
49
+ for (const message of session.messages) {
50
+ if (message.kind === "turn" && message.role === "user") user = message.content;
51
+ if (message.kind === "turn" && message.role === "assistant") assistant = message.content;
52
+ if (message.kind === "tool" && message.status === "ok" && message.preview) {
53
+ tools.push(`${message.name}: ${message.preview}`);
54
+ }
55
+ }
56
+ if (!user.trim() && !assistant.trim()) return "";
57
+ const clip = (value: string) => (value.length > 4000 ? `${value.slice(0, 4000)}\n…` : value);
58
+ const parts = [`User:\n${clip(user)}`, `Assistant:\n${clip(assistant)}`];
59
+ if (tools.length > 0) parts.push(`Tools:\n${clip(tools.slice(-6).join("\n"))}`);
60
+ return parts.join("\n\n");
61
+ }
62
+
63
+ export async function extractMemories(input: {
64
+ cwd: string;
65
+ session: Session;
66
+ provider: MainModelProvider;
67
+ env?: Record<string, string | undefined>;
68
+ }): Promise<number> {
69
+ const source = turnMemorySource(input.session);
70
+ if (!source.trim()) return 0;
71
+ let raw = "";
72
+ for await (const event of input.provider.stream({
73
+ system: MEMORY_EXTRACT_SYSTEM,
74
+ messages: [{ role: "user", content: source }],
75
+ maxTokens: 300,
76
+ })) {
77
+ if (event.type === "text_delta") raw += event.text;
78
+ if (event.type === "error") return 0;
79
+ }
80
+ return addFacts(
81
+ input.cwd,
82
+ parseExtractedFacts(raw).map((fact) => ({
83
+ ...fact,
84
+ sessionId: input.session.id,
85
+ })),
86
+ input.env,
87
+ ).length;
88
+ }
@@ -0,0 +1,53 @@
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 { isMemoryEnabled, writeMemoryPrefs } from "./prefs.ts";
6
+ import { formatMemoryList, formatRetrievedMemory } from "./prompt.ts";
7
+
8
+ describe("memory prefs", () => {
9
+ test("is off unless the user or config turns it on", async () => {
10
+ const home = await mkdtemp(join(tmpdir(), "harness-mem-pref-"));
11
+ const env = { HARNESS_HOME: home };
12
+ try {
13
+ expect(isMemoryEnabled({ env })).toBe(false);
14
+ expect(isMemoryEnabled({ configEnabled: true, env })).toBe(true);
15
+ writeMemoryPrefs({ enabled: false }, env);
16
+ expect(isMemoryEnabled({ configEnabled: true, env })).toBe(false);
17
+ writeMemoryPrefs({ enabled: true }, env);
18
+ expect(isMemoryEnabled({ env })).toBe(true);
19
+ } finally {
20
+ await rm(home, { recursive: true, force: true });
21
+ }
22
+ });
23
+
24
+ test("formats a retrieved block and a slash list", () => {
25
+ expect(formatRetrievedMemory([])).toBe("");
26
+ const retrieved = formatRetrievedMemory([
27
+ {
28
+ id: "mem_1",
29
+ hash: "a",
30
+ text: "Prefer bun",
31
+ scope: "user",
32
+ createdAt: "2026-01-01T00:00:00.000Z",
33
+ },
34
+ ]);
35
+ expect(retrieved).toContain("stored prefs");
36
+ expect(retrieved).toContain("- Prefer bun");
37
+ expect(formatMemoryList({ enabled: false, facts: [] })).toContain("Memory is off");
38
+ expect(
39
+ formatMemoryList({
40
+ enabled: true,
41
+ facts: [
42
+ {
43
+ id: "mem_1",
44
+ hash: "a",
45
+ text: "Prefer bun",
46
+ scope: "user",
47
+ createdAt: "2026-01-01T00:00:00.000Z",
48
+ },
49
+ ],
50
+ }),
51
+ ).toContain("1 user Prefer bun");
52
+ });
53
+ });