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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -66,6 +66,8 @@ export default {
66
66
  | `AGENTS.md` | Project instructions |
67
67
  | `~/.harness/AGENTS.md` | User instructions for every project |
68
68
  | `.harness/sessions/` | Session logs |
69
+ | `~/.harness/memory/` | User memory facts, if enabled |
70
+ | `.harness/memory/` | Project memory facts, if enabled |
69
71
  | `~/.harness/integrations.json` | Connected hosted MCP servers |
70
72
 
71
73
  The desktop stores the OpenRouter key in `~/.harness`. The terminal UI reads `OPENROUTER_API_KEY`, and optionally `OPENROUTER_MODEL` and `OPENROUTER_BASE_URL`.
@@ -112,6 +114,7 @@ In the desktop and the terminal UI, `/` opens slash commands, and Tab completes
112
114
  /model pick a model
113
115
  /mode ask, plan, or agent
114
116
  /compact summarize earlier turns
117
+ /memory remember across chats
115
118
  /image [prompt] generate an image
116
119
  /video [prompt] generate a clip
117
120
  /transcribe speech to text model
@@ -164,6 +167,10 @@ Each connection is stored in `~/.harness/integrations.json`, and disconnecting r
164
167
 
165
168
  Start in `ask`, `plan`, or `agent` with `/mode`, which changes which tools are available. `exec` and `git_commit` prompt for approval by default (`prompt`), and `auto` still refuses destructive commands. Local exec is the host machine rather than a sandbox.
166
169
 
170
+ ## Memory
171
+
172
+ Turn it on from the Memory tab or `/memory on` if you want later chats to keep prefs and project decisions. After a turn the model adds a few of those to `~/.harness/memory` and `.harness/memory`, and the next session only sees the ones that fit what you asked. `/memory` lists them, `/memory delete 1` removes a line, and `/memory pin 1` copies it into `AGENTS.md`.
173
+
167
174
  ## Library
168
175
 
169
176
  The desktop, the terminal UI, and `caelence chat -m` all call `createHarness`, so you can drive the same runtime from a bot, a script, or another host UI.
@@ -1,4 +1,4 @@
1
- import { looksLikeWebUrl } from "./rich-text.ts";
1
+ import { looksLikeWebUrl } from "./rich-text";
2
2
 
3
3
  const VOID_TAGS = new Set([
4
4
  "area",
@@ -87,27 +87,23 @@ export function rewritePreviewAssets(
87
87
  });
88
88
  }
89
89
 
90
+ const JS_URL_ATTRS = ["href", "src", "srcset", "xlink:href"] as const;
91
+
90
92
  export function sanitizePreviewHtml(html: string): string {
91
- return html
92
- .replace(/<script\b[\s\S]*?<\/script>/gi, "")
93
- .replace(/<style\b[\s\S]*?<\/style>/gi, "")
94
- .replace(/<(iframe|object|embed|link|meta)\b[\s\S]*?>/gi, "")
95
- .replace(/\s+on[a-z]+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi, "")
96
- .replace(/\s(href|src|srcset|xlink:href)\s*=\s*(['"])\s*javascript:[\s\S]*?\2/gi, "");
93
+ let out = stripEnclosedTag(html, "script");
94
+ out = stripEnclosedTag(out, "style");
95
+ for (const tag of ["iframe", "object", "embed", "link", "meta"]) {
96
+ out = stripOpenTag(out, tag);
97
+ }
98
+ return stripJavascriptUrls(stripEventHandlers(out));
97
99
  }
98
100
 
99
101
  export function renderMarkdown(src: string): string {
100
102
  const fences: string[] = [];
101
103
  const htmlBlocks: string[] = [];
102
- let text = src.replace(/\r\n/g, "\n");
103
- text = text.replace(/^```([\w-]*)\n([\s\S]*?)^```/gm, (_all, _lang: string, code: string) => {
104
- const id = fences.length;
105
- fences.push(`<pre><code>${escapeHtml(code.replace(/\n$/, ""))}</code></pre>`);
106
- return `\n%%FENCE${id}%%\n`;
107
- });
104
+ let text = extractFences(src.replaceAll("\r\n", "\n"), fences);
108
105
  text = extractHtmlBlocks(text, htmlBlocks);
109
- return text
110
- .split(/\n{2,}/)
106
+ return splitBlocks(text)
111
107
  .map((block) => {
112
108
  const trimmed = block.trim();
113
109
  if (!trimmed) return "";
@@ -135,23 +131,17 @@ function extractHtmlBlocks(src: string, store: string[]): string {
135
131
  const tag = start?.[1]?.toLowerCase();
136
132
  if (tag && !INLINE_TAGS.has(tag)) {
137
133
  const chunk: string[] = [];
138
- if (
139
- VOID_TAGS.has(tag) ||
140
- /\/>\s*$/.test(line) ||
141
- new RegExp(`</${tag}\\s*>`, "i").test(line)
142
- ) {
134
+ if (VOID_TAGS.has(tag) || lineEndsWithSelfClose(line) || lineHasCloseTag(line, tag)) {
143
135
  chunk.push(line);
144
136
  i += 1;
145
137
  } else {
146
138
  let depth = 1;
147
139
  chunk.push(line);
148
140
  i += 1;
149
- const openRe = new RegExp(`<${tag}\\b`, "gi");
150
- const closeRe = new RegExp(`</${tag}\\s*>`, "gi");
151
141
  while (i < lines.length && depth > 0) {
152
142
  const next = lines[i] ?? "";
153
- depth += (next.match(openRe) ?? []).length;
154
- depth -= (next.match(closeRe) ?? []).length;
143
+ depth += countTagOpens(next, tag);
144
+ depth -= countTagCloses(next, tag);
155
145
  chunk.push(next);
156
146
  i += 1;
157
147
  }
@@ -168,12 +158,9 @@ function extractHtmlBlocks(src: string, store: string[]): string {
168
158
  }
169
159
 
170
160
  function renderBlock(block: string): string {
171
- if (/^#{1,6}\s/.test(block)) {
172
- const match = /^(#{1,6})\s+([\s\S]+)$/.exec(block);
173
- if (match) {
174
- const level = match[1]?.length ?? 1;
175
- return `<h${level}>${renderInline(match[2] ?? "")}</h${level}>`;
176
- }
161
+ const heading = parseHeading(block);
162
+ if (heading) {
163
+ return `<h${heading.level}>${renderInline(heading.body)}</h${heading.level}>`;
177
164
  }
178
165
  if (/^[-*_]{3,}$/.test(block)) return "<hr />";
179
166
  if (
@@ -241,14 +228,313 @@ function renderInline(src: string): string {
241
228
  codes.push(`<code>${code}</code>`);
242
229
  return `%%CODE${id}%%`;
243
230
  });
244
- text = text.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (_all, alt: string, href: string) => {
245
- return `<img src="${href}" alt="${alt}" />`;
246
- });
247
- text = text.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_all, label: string, href: string) => {
248
- return `<a href="${href}">${label}</a>`;
249
- });
231
+ text = rewriteMdMedia(text, true);
232
+ text = rewriteMdMedia(text, false);
250
233
  text = text.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
251
234
  text = text.replace(/__([^_]+)__/g, "<strong>$1</strong>");
252
235
  text = text.replace(/(^|[^\w*])\*([^*\n]+)\*(?!\*)/g, "$1<em>$2</em>");
253
236
  return text.replace(/%%CODE(\d+)%%/g, (_all, id: string) => codes[Number(id)] ?? "");
254
237
  }
238
+
239
+ function isSpace(ch: string | undefined): boolean {
240
+ return ch === " " || ch === "\t" || ch === "\n" || ch === "\r";
241
+ }
242
+
243
+ function codeAt(ch: string | undefined): number {
244
+ return ch?.codePointAt(0) ?? -1;
245
+ }
246
+
247
+ function isWordChar(ch: string | undefined): boolean {
248
+ const code = codeAt(ch);
249
+ return (
250
+ (code >= 48 && code <= 57) ||
251
+ (code >= 65 && code <= 90) ||
252
+ (code >= 97 && code <= 122) ||
253
+ code === 95
254
+ );
255
+ }
256
+
257
+ function isAlpha(ch: string | undefined): boolean {
258
+ const code = codeAt(ch);
259
+ return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
260
+ }
261
+
262
+ function skipSpaces(text: string, i: number): number {
263
+ while (i < text.length && isSpace(text[i])) i += 1;
264
+ return i;
265
+ }
266
+
267
+ function skipQuoted(text: string, i: number, quote: string): number {
268
+ let p = i + 1;
269
+ while (p < text.length && text[p] !== quote) p += 1;
270
+ return p < text.length ? p + 1 : p;
271
+ }
272
+
273
+ function skipUnquotedValue(text: string, i: number): number {
274
+ let p = i;
275
+ while (p < text.length && !isSpace(text[p]) && text[p] !== ">") p += 1;
276
+ return p;
277
+ }
278
+
279
+ function findTagOpen(html: string, tag: string, from: number): number {
280
+ const needle = `<${tag}`;
281
+ const lower = html.toLowerCase();
282
+ let start = from;
283
+ while (start < html.length) {
284
+ const i = lower.indexOf(needle, start);
285
+ if (i < 0) return -1;
286
+ if (!isWordChar(html[i + needle.length])) return i;
287
+ start = i + 1;
288
+ }
289
+ return -1;
290
+ }
291
+
292
+ function stripEnclosedTag(html: string, tag: string): string {
293
+ let out = html;
294
+ while (true) {
295
+ const start = findTagOpen(out, tag, 0);
296
+ if (start < 0) return out;
297
+ const closeNeedle = `</${tag}`;
298
+ const close = out.toLowerCase().indexOf(closeNeedle, start + tag.length + 1);
299
+ if (close < 0) return out.slice(0, start);
300
+ const gt = out.indexOf(">", close + closeNeedle.length);
301
+ if (gt < 0) return out.slice(0, start);
302
+ out = out.slice(0, start) + out.slice(gt + 1);
303
+ }
304
+ }
305
+
306
+ function stripOpenTag(html: string, tag: string): string {
307
+ let out = html;
308
+ while (true) {
309
+ const start = findTagOpen(out, tag, 0);
310
+ if (start < 0) return out;
311
+ const gt = out.indexOf(">", start);
312
+ if (gt < 0) return out.slice(0, start);
313
+ out = out.slice(0, start) + out.slice(gt + 1);
314
+ }
315
+ }
316
+
317
+ function eventHandlerEnd(html: string, spaceStart: number): number | null {
318
+ const nameStart = skipSpaces(html, spaceStart);
319
+ const first = html[nameStart];
320
+ const second = html[nameStart + 1];
321
+ if ((first !== "o" && first !== "O") || (second !== "n" && second !== "N")) return null;
322
+ let k = nameStart + 2;
323
+ while (k < html.length && isAlpha(html[k])) k += 1;
324
+ if (k === nameStart + 2) return null;
325
+ let p = skipSpaces(html, k);
326
+ if (html[p] !== "=") return null;
327
+ p = skipSpaces(html, p + 1);
328
+ const quote = html[p];
329
+ if (quote === '"' || quote === "'") return skipQuoted(html, p, quote);
330
+ return skipUnquotedValue(html, p);
331
+ }
332
+
333
+ function stripEventHandlers(html: string): string {
334
+ let out = "";
335
+ let i = 0;
336
+ while (i < html.length) {
337
+ const end = isSpace(html[i]) ? eventHandlerEnd(html, i) : null;
338
+ if (end !== null) {
339
+ i = end;
340
+ continue;
341
+ }
342
+ out += html[i];
343
+ i += 1;
344
+ }
345
+ return out;
346
+ }
347
+
348
+ function attrNameAt(html: string, afterSpace: number): string | undefined {
349
+ const rest = html.slice(afterSpace).toLowerCase();
350
+ return JS_URL_ATTRS.find((name) => {
351
+ if (!rest.startsWith(name)) return false;
352
+ const next = rest[name.length];
353
+ return !next || next === "=" || isSpace(next);
354
+ });
355
+ }
356
+
357
+ function javascriptUrlEnd(html: string, spaceStart: number): number | null {
358
+ const attr = attrNameAt(html, spaceStart + 1);
359
+ if (!attr) return null;
360
+ let p = skipSpaces(html, spaceStart + 1 + attr.length);
361
+ if (html[p] !== "=") return null;
362
+ p = skipSpaces(html, p + 1);
363
+ const quote = html[p];
364
+ if (quote !== '"' && quote !== "'") return null;
365
+ const valueStart = skipSpaces(html, p + 1);
366
+ if (html.slice(valueStart, valueStart + 11).toLowerCase() !== "javascript:") return null;
367
+ return skipQuoted(html, p, quote);
368
+ }
369
+
370
+ function stripJavascriptUrls(html: string): string {
371
+ let out = "";
372
+ let i = 0;
373
+ while (i < html.length) {
374
+ const end = isSpace(html[i]) ? javascriptUrlEnd(html, i) : null;
375
+ if (end !== null) {
376
+ i = end;
377
+ continue;
378
+ }
379
+ out += html[i];
380
+ i += 1;
381
+ }
382
+ return out;
383
+ }
384
+
385
+ function extractFences(src: string, fences: string[]): string {
386
+ const lines = src.split("\n");
387
+ const out: string[] = [];
388
+ let i = 0;
389
+ while (i < lines.length) {
390
+ const line = lines[i] ?? "";
391
+ if (line.startsWith("```")) {
392
+ const chunk: string[] = [];
393
+ let j = i + 1;
394
+ while (j < lines.length && !(lines[j] ?? "").startsWith("```")) {
395
+ chunk.push(lines[j] ?? "");
396
+ j += 1;
397
+ }
398
+ if (j < lines.length) {
399
+ const id = fences.length;
400
+ fences.push(`<pre><code>${escapeHtml(chunk.join("\n"))}</code></pre>`);
401
+ out.push("", `%%FENCE${id}%%`, "");
402
+ i = j + 1;
403
+ continue;
404
+ }
405
+ }
406
+ out.push(line);
407
+ i += 1;
408
+ }
409
+ return out.join("\n");
410
+ }
411
+
412
+ function splitBlocks(text: string): string[] {
413
+ const blocks: string[] = [];
414
+ let start = 0;
415
+ let i = 0;
416
+ while (i < text.length) {
417
+ if (text[i] === "\n" && text[i + 1] === "\n") {
418
+ blocks.push(text.slice(start, i));
419
+ while (text[i] === "\n") i += 1;
420
+ start = i;
421
+ continue;
422
+ }
423
+ i += 1;
424
+ }
425
+ blocks.push(text.slice(start));
426
+ return blocks;
427
+ }
428
+
429
+ function lineEndsWithSelfClose(line: string): boolean {
430
+ let i = line.length - 1;
431
+ while (i >= 0 && isSpace(line[i])) i -= 1;
432
+ return i >= 1 && line[i] === ">" && line[i - 1] === "/";
433
+ }
434
+
435
+ function lineHasCloseTag(line: string, tag: string): boolean {
436
+ const needle = `</${tag}`;
437
+ const lower = line.toLowerCase();
438
+ let from = 0;
439
+ while (from < line.length) {
440
+ const i = lower.indexOf(needle, from);
441
+ if (i < 0) return false;
442
+ let p = i + needle.length;
443
+ while (p < line.length && isSpace(line[p])) p += 1;
444
+ if (line[p] === ">") return true;
445
+ from = i + 1;
446
+ }
447
+ return false;
448
+ }
449
+
450
+ function countTagOpens(line: string, tag: string): number {
451
+ const needle = `<${tag}`;
452
+ const lower = line.toLowerCase();
453
+ let n = 0;
454
+ let from = 0;
455
+ while (from < line.length) {
456
+ const i = lower.indexOf(needle, from);
457
+ if (i < 0) return n;
458
+ if (!isWordChar(line[i + needle.length])) n += 1;
459
+ from = i + 1;
460
+ }
461
+ return n;
462
+ }
463
+
464
+ function countTagCloses(line: string, tag: string): number {
465
+ const needle = `</${tag}`;
466
+ const lower = line.toLowerCase();
467
+ let n = 0;
468
+ let from = 0;
469
+ while (from < line.length) {
470
+ const i = lower.indexOf(needle, from);
471
+ if (i < 0) return n;
472
+ let p = i + needle.length;
473
+ while (p < line.length && isSpace(line[p])) p += 1;
474
+ if (line[p] === ">") n += 1;
475
+ from = i + 1;
476
+ }
477
+ return n;
478
+ }
479
+
480
+ function parseHeading(block: string): { level: number; body: string } | null {
481
+ let level = 0;
482
+ while (level < 6 && block[level] === "#") level += 1;
483
+ if (level === 0) return null;
484
+ let i = level;
485
+ if (!isSpace(block[i])) return null;
486
+ while (isSpace(block[i])) i += 1;
487
+ const body = block.slice(i);
488
+ if (!body) return null;
489
+ return { level, body };
490
+ }
491
+
492
+ function hrefEndAt(text: string, start: number): number | null {
493
+ let i = start;
494
+ while (i < text.length && text[i] !== ")") {
495
+ const ch = text[i];
496
+ if (ch === " " || ch === "\t" || ch === "\n") return null;
497
+ i += 1;
498
+ }
499
+ return text[i] === ")" ? i : null;
500
+ }
501
+
502
+ function mediaAt(
503
+ text: string,
504
+ start: number,
505
+ image: boolean,
506
+ ): { html: string; next: number } | null {
507
+ const labelStart = start + (image ? 2 : 1);
508
+ const labelEnd = text.indexOf("]", labelStart);
509
+ if (labelEnd < 0 || text[labelEnd + 1] !== "(") return null;
510
+ const hrefEnd = hrefEndAt(text, labelEnd + 2);
511
+ if (hrefEnd === null) return null;
512
+ const label = text.slice(labelStart, labelEnd);
513
+ if (!image && !label) return null;
514
+ const href = text.slice(labelEnd + 2, hrefEnd);
515
+ const html = image ? `<img src="${href}" alt="${label}" />` : `<a href="${href}">${label}</a>`;
516
+ return { html, next: hrefEnd + 1 };
517
+ }
518
+
519
+ function rewriteMdMedia(text: string, image: boolean): string {
520
+ const marker = image ? "![" : "[";
521
+ let out = "";
522
+ let i = 0;
523
+ while (i < text.length) {
524
+ const start = text.indexOf(marker, i);
525
+ if (start < 0) {
526
+ out += text.slice(i);
527
+ break;
528
+ }
529
+ out += text.slice(i, start);
530
+ const media = mediaAt(text, start, image);
531
+ if (!media) {
532
+ out += text[start];
533
+ i = start + 1;
534
+ continue;
535
+ }
536
+ out += media.html;
537
+ i = media.next;
538
+ }
539
+ return out;
540
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@useavalon/caelence-agent",
3
- "version": "0.2.3-canary.0",
3
+ "version": "0.2.3-canary.1",
4
4
  "description": "Caelence agent: Strands turn loop, local tools, skills, evals, and a themable terminal UI.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -39,7 +39,7 @@
39
39
  ],
40
40
  "scripts": {
41
41
  "start": "bun bin/harness.ts",
42
- "test": "bun test src/core src/tools src/skills src/evals src/cli src/observability src/desktop src/integrations src/media src/init.test.ts src/runtime.test.ts desktop/src/rich-text.test.ts desktop/src/stream.test.ts desktop/src/dictation.test.ts desktop/src/thought.test.ts desktop/src/queue.test.ts desktop/src/composer-files.test.ts desktop/src/tool-label.test.ts desktop/src/reply-sources.test.ts desktop/src/pipeline.test.ts desktop/src/preview-render.test.ts",
42
+ "test": "bun test src/core src/tools src/skills src/evals src/cli src/observability src/desktop src/integrations src/media src/memory src/init.test.ts src/runtime.test.ts desktop/src/rich-text.test.ts desktop/src/stream.test.ts desktop/src/dictation.test.ts desktop/src/thought.test.ts desktop/src/queue.test.ts desktop/src/composer-files.test.ts desktop/src/tool-label.test.ts desktop/src/reply-sources.test.ts desktop/src/pipeline.test.ts desktop/src/preview-render.test.ts",
43
43
  "typecheck": "bunx tsc --noEmit -p tsconfig.json",
44
44
  "lint": "biome ci .",
45
45
  "format": "biome format --write .",
@@ -1,4 +1,4 @@
1
- import { OPENROUTER_DEFAULT_BASE_URL } from "../config.ts";
1
+ import { OPENROUTER_DEFAULT_BASE_URL, stripTrailingSlashes } from "../config.ts";
2
2
 
3
3
  const LIVE_TTL_MS = 10 * 60 * 1000;
4
4
  const EMPTY = new Map<string, string>();
@@ -13,11 +13,34 @@ function displayName(id: string, rawName: string): string {
13
13
  return prettyLiveModelName(name);
14
14
  }
15
15
 
16
+ function liveNameFromRow(item: unknown): { id: string; name: string } | undefined {
17
+ if (typeof item !== "object" || item === null) return undefined;
18
+ const row = item as Record<string, unknown>;
19
+ const id = typeof row.id === "string" ? row.id : "";
20
+ if (!id) return undefined;
21
+ const target = row.alias_target;
22
+ if (typeof target === "object" && target !== null) {
23
+ const name = (target as { name?: unknown }).name;
24
+ const slug = (target as { slug?: unknown }).slug;
25
+ if (typeof name === "string" && name.trim()) {
26
+ return { id, name: displayName(typeof slug === "string" ? slug : id, name) };
27
+ }
28
+ }
29
+ if (typeof row.name === "string" && row.name.trim()) {
30
+ return { id, name: displayName(id, row.name) };
31
+ }
32
+ return undefined;
33
+ }
34
+
35
+ function wordsOf(name: string): string[] {
36
+ return name.toLowerCase().replaceAll("_", " ").replaceAll("-", " ").split(" ").filter(Boolean);
37
+ }
38
+
16
39
  /** OpenRouter calls Auto "Auto Router". Product copy is Auto / Auto beta. */
17
40
  export function prettyLiveModelName(name: string): string {
18
- const lower = name.toLowerCase().replace(/[_-]+/g, " ").replace(/\s+/g, " ").trim();
19
- if (!/\bauto\b/.test(lower) || !/\brouter\b/.test(lower)) return name;
20
- return /\bbeta\b/.test(lower) ? "Auto beta" : "Auto";
41
+ const words = wordsOf(name);
42
+ if (!words.includes("auto") || !words.includes("router")) return name;
43
+ return words.includes("beta") ? "Auto beta" : "Auto";
21
44
  }
22
45
 
23
46
  /** Human name of the concrete model a `~latest` alias currently resolves to. */
@@ -27,22 +50,8 @@ export function parseLiveTargetNames(json: unknown): Map<string, string> {
27
50
  const data = (json as { data?: unknown }).data;
28
51
  if (!Array.isArray(data)) return names;
29
52
  for (const item of data) {
30
- if (typeof item !== "object" || item === null) continue;
31
- const row = item as Record<string, unknown>;
32
- const id = typeof row.id === "string" ? row.id : "";
33
- if (!id) continue;
34
- const target = row.alias_target;
35
- if (typeof target === "object" && target !== null) {
36
- const name = (target as { name?: unknown }).name;
37
- const slug = (target as { slug?: unknown }).slug;
38
- if (typeof name === "string" && name.trim()) {
39
- names.set(id, displayName(typeof slug === "string" ? slug : id, name));
40
- continue;
41
- }
42
- }
43
- if (typeof row.name === "string" && row.name.trim()) {
44
- names.set(id, displayName(id, row.name));
45
- }
53
+ const mapped = liveNameFromRow(item);
54
+ if (mapped) names.set(mapped.id, mapped.name);
46
55
  }
47
56
  return names;
48
57
  }
@@ -61,7 +70,7 @@ export async function loadLiveTargetNames(options: {
61
70
  const useCache = fetchImpl === globalThis.fetch;
62
71
  if (useCache && cache && cache.expires > Date.now()) return cache.names;
63
72
  try {
64
- const base = (options.baseUrl ?? OPENROUTER_DEFAULT_BASE_URL).replace(/\/+$/, "");
73
+ const base = stripTrailingSlashes(options.baseUrl ?? OPENROUTER_DEFAULT_BASE_URL);
65
74
  const res = await fetchImpl(`${base}/models`, {
66
75
  headers: {
67
76
  Authorization: `Bearer ${options.apiKey}`,
@@ -250,6 +250,31 @@ describe("dispatchSlash", () => {
250
250
  expect(await runSlashLine(fakeHarness(), "/asdf")).toEqual({ kind: "hold" });
251
251
  });
252
252
 
253
+ test("memory lists facts and can turn on", async () => {
254
+ const home = await mkdtemp(join(tmpdir(), "harness-mem-slash-"));
255
+ const cwd = await mkdtemp(join(tmpdir(), "harness-mem-slash-cwd-"));
256
+ const prevHome = process.env.HARNESS_HOME;
257
+ process.env.HARNESS_HOME = home;
258
+ try {
259
+ const { addFacts } = await import("../memory/store.ts");
260
+ addFacts(cwd, [{ text: "Prefer bun over npm for installs", scope: "user" }]);
261
+ const off = await dispatchSlash(fakeHarness({ cwd }), "/memory");
262
+ expect(off.kind).toBe("text");
263
+ if (off.kind === "text") {
264
+ expect(off.text).toContain("off");
265
+ expect(off.text).toContain("Prefer bun");
266
+ }
267
+ const on = await dispatchSlash(fakeHarness({ cwd }), "/memory on");
268
+ expect(on.kind).toBe("text");
269
+ if (on.kind === "text") expect(on.text).toContain("Memory on");
270
+ } finally {
271
+ if (prevHome === undefined) delete process.env.HARNESS_HOME;
272
+ else process.env.HARNESS_HOME = prevHome;
273
+ await rm(home, { recursive: true, force: true });
274
+ await rm(cwd, { recursive: true, force: true });
275
+ }
276
+ });
277
+
253
278
  test("settings reports a missing key without opening a picker", async () => {
254
279
  const result = await dispatchSlash(fakeHarness({ hasApiKey: false }), "/settings");
255
280
  expect(result.kind).toBe("text");
@@ -13,6 +13,9 @@ import {
13
13
  } from "../integrations/store.ts";
14
14
  import { type GeneratedMedia, generateImage, generateVideo } from "../media/openrouter-generate.ts";
15
15
  import { readMediaPrefs, writeMediaPrefs } from "../media/prefs.ts";
16
+ import { isMemoryEnabled, writeMemoryPrefs } from "../memory/prefs.ts";
17
+ import { formatMemoryList } from "../memory/prompt.ts";
18
+ import { deleteFact, listFacts, matchFact, pinFact, unpinFact } from "../memory/store.ts";
16
19
  import type { HarnessRuntime } from "../runtime.ts";
17
20
  import { browseSkillCatalog } from "../skills/catalog.ts";
18
21
  import {
@@ -366,6 +369,43 @@ async function handleEval(harness: HarnessRuntime, arg: string): Promise<SlashOu
366
369
  }
367
370
  }
368
371
 
372
+ function memoryState(harness: HarnessRuntime) {
373
+ return {
374
+ enabled: isMemoryEnabled({ configEnabled: harness.config.memory?.enabled }),
375
+ facts: listFacts(harness.cwd),
376
+ };
377
+ }
378
+
379
+ async function handleMemory(harness: HarnessRuntime, arg: string): Promise<SlashOutcome> {
380
+ const body = arg.trim();
381
+ if (!body) return { kind: "text", text: formatMemoryList(memoryState(harness)) };
382
+ if (body === "on" || body === "off") {
383
+ writeMemoryPrefs({ enabled: body === "on" });
384
+ return { kind: "text", text: formatMemoryList(memoryState(harness)) };
385
+ }
386
+ const [action, ...rest] = body.split(/\s+/);
387
+ const target = rest.join(" ").trim();
388
+ if ((action === "delete" || action === "pin") && !target) {
389
+ return { kind: "text", text: `/memory ${action} <n>` };
390
+ }
391
+ if (action === "delete") {
392
+ const fact = matchFact(listFacts(harness.cwd), target);
393
+ if (!fact) return { kind: "text", text: `No memory matches ${target}.` };
394
+ deleteFact(harness.cwd, fact.id);
395
+ const unpinned = unpinFact(harness.cwd, fact, harness.config.instructionsFile);
396
+ if ("error" in unpinned) return { kind: "text", text: unpinned.error };
397
+ return { kind: "text", text: `Deleted ${fact.text}` };
398
+ }
399
+ if (action === "pin") {
400
+ const fact = matchFact(listFacts(harness.cwd), target);
401
+ if (!fact) return { kind: "text", text: `No memory matches ${target}.` };
402
+ const pinned = pinFact(harness.cwd, fact, harness.config.instructionsFile);
403
+ if ("error" in pinned) return { kind: "text", text: pinned.error };
404
+ return { kind: "text", text: `Pinned to ${pinned.path}` };
405
+ }
406
+ return { kind: "text", text: "/memory on · /memory off · /memory delete 1 · /memory pin 1" };
407
+ }
408
+
369
409
  async function handleSettings(harness: HarnessRuntime, arg: string): Promise<SlashOutcome> {
370
410
  const body = arg.trim();
371
411
  if (!body || body === "key") {
@@ -406,6 +446,7 @@ const SLASH_HANDLERS: Record<string, SlashHandler> = {
406
446
  transcribe: handleTranscribe,
407
447
  resume: handleResume,
408
448
  eval: handleEval,
449
+ memory: handleMemory,
409
450
  settings: handleSettings,
410
451
  exit: async () => ({ kind: "exit" }),
411
452
  quit: async () => ({ kind: "exit" }),
package/src/cli/slash.ts CHANGED
@@ -20,6 +20,7 @@ export const SLASH_COMMANDS: SlashCommand[] = [
20
20
  { name: "model", hint: "pick a model" },
21
21
  { name: "mode", hint: "ask, plan, or agent" },
22
22
  { name: "compact", hint: "summarize earlier turns" },
23
+ { name: "memory", hint: "remember across chats", arg: true },
23
24
  { name: "image", hint: "generate an image", arg: true, slot: "[prompt]" },
24
25
  { name: "video", hint: "generate a clip", arg: true, slot: "[prompt]" },
25
26
  { name: "transcribe", hint: "speech to text model" },
package/src/config.ts CHANGED
@@ -24,6 +24,8 @@ export interface HarnessConfig {
24
24
  openrouterBaseUrl?: string;
25
25
  subagents?: { enabled?: boolean };
26
26
  observability?: { enabled?: boolean };
27
+ /** Cross-session memory. Off unless this is true or ~/.harness/memory.json enables it. */
28
+ memory?: { enabled?: boolean };
27
29
  /** Default agent. ask = read only. plan = read + todos. */
28
30
  mode?: AgentMode;
29
31
  hooks?: HookConfig[];
@@ -66,11 +68,18 @@ export async function loadConfig(cwd: string): Promise<HarnessConfig> {
66
68
  },
67
69
  mcp: partial.mcp ?? [],
68
70
  observability: partial.observability,
71
+ memory: partial.memory,
69
72
  mode: partial.mode,
70
73
  hooks: partial.hooks,
71
74
  };
72
75
  }
73
76
 
77
+ export function stripTrailingSlashes(value: string): string {
78
+ let trimmed = value;
79
+ while (trimmed.endsWith("/")) trimmed = trimmed.slice(0, -1);
80
+ return trimmed;
81
+ }
82
+
74
83
  export function resolveOpenRouter(config: HarnessConfig): {
75
84
  apiKey: string;
76
85
  baseUrl: string;
@@ -82,5 +91,5 @@ export function resolveOpenRouter(config: HarnessConfig): {
82
91
  config.openrouterBaseUrl ||
83
92
  OPENROUTER_DEFAULT_BASE_URL;
84
93
  const model = process.env.OPENROUTER_MODEL?.trim() || config.model;
85
- return { apiKey, baseUrl: baseUrl.replace(/\/+$/, ""), model };
94
+ return { apiKey, baseUrl: stripTrailingSlashes(baseUrl), model };
86
95
  }
@@ -202,12 +202,15 @@ describe("runTurn", () => {
202
202
  cwd: "/tmp/proj",
203
203
  userInstructions: "prefer bun",
204
204
  projectInstructions: "no secrets",
205
+ memory: "Use these only when they are relevant.\n- Prefer bun",
205
206
  mode: "ask",
206
207
  });
207
208
  expect(prompt).toContain("## User instructions");
208
209
  expect(prompt).toContain("prefer bun");
209
210
  expect(prompt).toContain("## Project instructions");
210
211
  expect(prompt).toContain("no secrets");
212
+ expect(prompt).toContain("## Memory");
213
+ expect(prompt).toContain("Prefer bun");
211
214
  expect(prompt).toContain("## Mode: ask");
212
215
  expect(prompt).toContain("You are a coding agent in this project.");
213
216
  expect(prompt).not.toContain("You are harness, a coding agent working in /tmp/proj");