forked from nexu-io/open-design
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory.ts
More file actions
694 lines (660 loc) · 26.2 KB
/
Copy pathmemory.ts
File metadata and controls
694 lines (660 loc) · 26.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
import type { Express } from 'express';
import { MEMORY_TYPES } from '@open-design/contracts';
import type { RouteDeps } from '../server-context.js';
import {
buildMemoryTree,
composeMemoryBody,
deleteMemoryEntry,
extractFromMessage,
listMemoryEntries,
maskMemoryExtractionConfig,
memoryDir,
memoryEvents,
readMemoryConfig,
readMemoryEntry,
readMemoryIndex,
updateMemoryTreeNode,
upsertMemoryEntry,
writeMemoryConfig,
writeMemoryIndex,
} from '../memory.js';
import {
clearExtractions as clearMemoryExtractions,
listExtractions as listMemoryExtractions,
removeExtraction as removeMemoryExtraction,
} from '../memory-extractions.js';
import {
clearVerifications as clearMemoryVerifications,
listVerifications as listMemoryVerifications,
removeVerification as removeMemoryVerification,
} from '../memory-verify.js';
import { distillRulesFromAnnotations } from '../memory-rules.js';
import {
extractMemoryFromConnectors,
suggestMemoryFromConnectors,
} from '../memory-connectors.js';
export interface RegisterMemoryRoutesDeps extends RouteDeps<'http' | 'paths' | 'appConfig'> {}
type UnknownRecord = Record<string, unknown>;
type MemoryType =
| 'user'
| 'feedback'
| 'project'
| 'reference'
| 'profile'
| 'rule';
type MemoryExtractionProvider = 'anthropic' | 'openai' | 'azure' | 'google' | 'ollama';
interface MemoryExtractionPatch {
provider: MemoryExtractionProvider;
model?: string;
baseUrl?: string;
apiKey?: string;
apiVersion?: string;
}
interface MemoryConfigPatch {
enabled?: boolean;
chatExtractionEnabled?: boolean;
/** Two-loop memory per-hook toggles (default-on; omit to leave unchanged). */
profileEnabled?: boolean;
rewriteEnabled?: boolean;
verifyEnabled?: boolean;
extraction?: MemoryExtractionPatch | null;
}
interface MemoryEntryInput {
id?: string;
name: string;
description?: string;
type: MemoryType;
body?: string;
}
interface MemoryAppConfigLike {
agentId?: string;
agentModels?: Record<string, { model?: string }>;
}
function asRecord(value: unknown): UnknownRecord {
return value && typeof value === 'object' ? (value as UnknownRecord) : {};
}
function errorMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
function isMemoryType(value: unknown): value is MemoryType {
// Sourced from the shared contract so the new `profile` / `rule` buckets
// can't be rejected here while the type union already allows them.
return (
typeof value === 'string'
&& (MEMORY_TYPES as readonly string[]).includes(value)
);
}
function isExtractionProvider(value: unknown): value is MemoryExtractionProvider {
return (
value === 'anthropic'
|| value === 'openai'
|| value === 'azure'
|| value === 'google'
|| value === 'ollama'
);
}
export function registerMemoryRoutes(app: Express, ctx: RegisterMemoryRoutesDeps) {
const { RUNTIME_DATA_DIR, PROJECT_ROOT, PROJECTS_DIR } = ctx.paths;
const { createSseResponse, requireLocalDaemonRequest } = ctx.http;
const { readAppConfig } = ctx.appConfig;
// ----- Memory store -----------------------------------------------------
// Markdown-on-disk memory under <dataDir>/memory/. The daemon folds these
// into every system prompt (gated by `enabled`) and the chat run loop
// calls `/api/memory/extract` after each turn to sediment new facts.
app.get('/api/memory', async (_req, res) => {
try {
const [config, index, entries] = await Promise.all([
readMemoryConfig(RUNTIME_DATA_DIR),
readMemoryIndex(RUNTIME_DATA_DIR),
listMemoryEntries(RUNTIME_DATA_DIR),
]);
res.json({
enabled: config.enabled,
chatExtractionEnabled: config.chatExtractionEnabled,
profileEnabled: config.profileEnabled,
rewriteEnabled: config.rewriteEnabled,
verifyEnabled: config.verifyEnabled,
rootDir: memoryDir(RUNTIME_DATA_DIR),
index,
entries,
extraction: maskMemoryExtractionConfig(config.extraction),
});
} catch (err) {
res.status(500).json({ error: String(err) });
}
});
// Static sub-resources (`/index`, `/config`, `/extract`) registered
// BEFORE the `:id` catch-alls so an `index` / `config` / `extract` slug
// can't shadow the real handlers.
app.get('/api/memory/tree', async (_req, res) => {
try {
const [config, tree] = await Promise.all([
readMemoryConfig(RUNTIME_DATA_DIR),
buildMemoryTree(RUNTIME_DATA_DIR),
]);
res.json({
enabled: config.enabled,
rootDir: memoryDir(RUNTIME_DATA_DIR),
tree,
});
} catch (err) {
res.status(500).json({ error: errorMessage(err) });
}
});
app.patch('/api/memory/tree/:id', async (req, res) => {
try {
const body = asRecord(req.body);
const entry = await updateMemoryTreeNode(
RUNTIME_DATA_DIR,
req.params.id,
body,
);
const tree = await buildMemoryTree(RUNTIME_DATA_DIR);
res.json({ entry, tree });
} catch (err) {
const message = errorMessage(err);
res.status(message === 'memory not found' ? 404 : 400).json({ error: message });
}
});
app.put('/api/memory/index', async (req, res) => {
try {
const body = asRecord(req.body);
const index = typeof body.index === 'string' ? body.index : '';
await writeMemoryIndex(RUNTIME_DATA_DIR, index, undefined);
res.json({ index });
} catch (err) {
res.status(400).json({ error: errorMessage(err) });
}
});
app.patch('/api/memory/config', async (req, res) => {
try {
const body = asRecord(req.body);
const patch: MemoryConfigPatch = {};
if (typeof body.enabled === 'boolean') patch.enabled = body.enabled;
if (typeof body.chatExtractionEnabled === 'boolean') {
patch.chatExtractionEnabled = body.chatExtractionEnabled;
}
if (typeof body.profileEnabled === 'boolean') {
patch.profileEnabled = body.profileEnabled;
}
if (typeof body.rewriteEnabled === 'boolean') {
patch.rewriteEnabled = body.rewriteEnabled;
}
if (typeof body.verifyEnabled === 'boolean') {
patch.verifyEnabled = body.verifyEnabled;
}
// Three-state extraction handling so the UI can: (a) leave the
// override alone (omit `extraction`), (b) clear it back to
// auto-pick (`extraction: null`), or (c) commit a custom override
// (`extraction: { provider, ... }`). For the apiKey field we
// need *four* states because the masked GET surfaces only an
// `apiKeyTail` (the secret never round-trips):
// - field absent → preserve the stored key (UI re-saves
// a settings form without re-typing
// the secret).
// - field === '' → CLEAR the stored key (the picker's
// drift-resync effect fires this when
// the user clears their BYOK chat
// API key — keeping the old daemon-
// side credential would silently keep
// calling the provider after the user
// intentionally removed it from the
// chat picker, which the reviewer
// flagged as a credential-sync bug).
// - field === 'sk-…' → replace with the new key.
// - provider differs → ignore stored key entirely.
if (Object.prototype.hasOwnProperty.call(body, 'extraction')) {
if (body.extraction === null) {
patch.extraction = null;
} else if (body.extraction && typeof body.extraction === 'object') {
const incoming = body.extraction as UnknownRecord;
const current = await readMemoryConfig(RUNTIME_DATA_DIR);
const currentExtraction = current.extraction as MemoryExtractionPatch | null;
const apiKeyOmitted = !Object.prototype.hasOwnProperty.call(
incoming,
'apiKey',
);
const sameProvider =
!!currentExtraction
&& currentExtraction.provider === incoming.provider;
let nextApiKey = '';
if (typeof incoming.apiKey === 'string' && incoming.apiKey) {
nextApiKey = incoming.apiKey;
} else if (apiKeyOmitted && sameProvider) {
nextApiKey = currentExtraction?.apiKey ?? '';
}
if (!isExtractionProvider(incoming.provider)) {
throw new Error('invalid extraction provider');
}
const nextExtraction: MemoryExtractionPatch = {
provider: incoming.provider,
apiKey: nextApiKey,
};
if (typeof incoming.model === 'string') nextExtraction.model = incoming.model;
if (typeof incoming.baseUrl === 'string') nextExtraction.baseUrl = incoming.baseUrl;
// Azure-only; ignored by the validator for the other providers.
// We forward whatever the UI sent (or the previously-stored
// value when the UI omits the field) so re-saving an azure
// override without re-typing the api-version doesn't blank it.
const apiVersion =
typeof incoming.apiVersion === 'string'
? incoming.apiVersion
: currentExtraction?.apiVersion;
if (typeof apiVersion === 'string') nextExtraction.apiVersion = apiVersion;
patch.extraction = nextExtraction;
}
}
const next = await writeMemoryConfig(RUNTIME_DATA_DIR, patch);
res.json({
enabled: next.enabled,
chatExtractionEnabled: next.chatExtractionEnabled,
profileEnabled: next.profileEnabled,
rewriteEnabled: next.rewriteEnabled,
verifyEnabled: next.verifyEnabled,
extraction: maskMemoryExtractionConfig(next.extraction),
});
} catch (err) {
res.status(400).json({ error: errorMessage(err) });
}
});
// SSE feed of memory mutations. The web settings panel subscribes to
// this and re-fetches on every event; toast UIs can listen for
// `kind === 'extract'` and surface a small "Memory updated (N new)"
// notification. Payload shape: MemoryChangeEvent (see ./memory.ts).
//
// The same connection also forwards `extraction` events — one per LLM
// extraction phase transition — so the settings panel can render a
// live "recent extractions" list. We multiplex on a single SSE stream
// so the browser opens one connection instead of two.
app.get('/api/memory/events', async (_req, res) => {
const sse = createSseResponse(res);
sse.send('connected', { at: Date.now() });
const onChange = (event: unknown) => {
sse.send('change', event);
};
const onExtraction = (event: unknown) => {
sse.send('extraction', event);
};
// `verify` events carry POST self-verify enforcement outcomes (THREAD 2),
// one per enforced turn. Multiplexed on the same connection as `change`
// and `extraction` so the settings panel opens a single stream.
const onVerify = (event: unknown) => {
sse.send('verify', event);
};
memoryEvents.on('change', onChange);
memoryEvents.on('extraction', onExtraction);
memoryEvents.on('verify', onVerify);
res.on('close', () => {
memoryEvents.off('change', onChange);
memoryEvents.off('extraction', onExtraction);
memoryEvents.off('verify', onVerify);
});
});
// Recent LLM-extraction attempts (newest first; capped server-side).
// Surfaces skip reasons, in-flight calls, success counts, and errors
// so the settings panel can show "why didn't memory update?" at a
// glance instead of leaving the user to guess.
app.get('/api/memory/extractions', async (_req, res) => {
try {
res.json({ extractions: listMemoryExtractions() });
} catch (err) {
res.status(500).json({ error: String(err) });
}
});
// Drop the entire extraction history. Registered BEFORE the `:id`
// catch-all so a literal "/api/memory/extractions" can still be
// cleared with `curl -X DELETE`.
app.delete('/api/memory/extractions', async (_req, res) => {
try {
const removed = clearMemoryExtractions();
res.json({ removed });
} catch (err) {
res.status(400).json({ error: errorMessage(err) });
}
});
app.delete('/api/memory/extractions/:id', async (req, res) => {
try {
const removed = removeMemoryExtraction(req.params.id);
res.json({ removed });
} catch (err) {
res.status(400).json({ error: errorMessage(err) });
}
});
// Recent POST self-verify enforcement outcomes (THREAD 2; newest first,
// capped server-side). Surfaces `missing` (model skipped the scorecard) and
// `fail` (a rule failed or was left uncovered) so the user can see that
// verification is actually enforced, not honour-system.
app.get('/api/memory/verifications', async (_req, res) => {
try {
res.json({ verifications: listMemoryVerifications() });
} catch (err) {
res.status(500).json({ error: String(err) });
}
});
// Drop the entire verification history. Registered BEFORE the `:id`
// catch-all so a literal "/api/memory/verifications" can be cleared.
app.delete('/api/memory/verifications', async (_req, res) => {
try {
const removed = clearMemoryVerifications();
res.json({ removed });
} catch (err) {
res.status(400).json({ error: errorMessage(err) });
}
});
app.delete('/api/memory/verifications/:id', async (req, res) => {
try {
const removed = removeMemoryVerification(req.params.id);
res.json({ removed });
} catch (err) {
res.status(400).json({ error: errorMessage(err) });
}
});
// Distil a batch of in-canvas/in-deck annotations into candidate rule
// proposals (THREAD 1). Display-only: the response feeds the existing
// rule-proposal Keep gate; nothing is written until the user confirms a
// proposal through `POST /api/memory` (`type: 'rule'`). Runs a heuristic
// pass always, and an LLM pass when an extraction provider is configured.
app.post('/api/memory/rules/suggest', async (req, res) => {
try {
const body = asRecord(req.body);
const rawAnnotations = Array.isArray(body.annotations) ? body.annotations : [];
const annotations = rawAnnotations
.map((item: unknown) => {
const a = asRecord(item);
const note = typeof a.note === 'string' ? a.note : '';
if (!note.trim()) return null;
return {
note,
...(typeof a.targetLabel === 'string' ? { targetLabel: a.targetLabel } : {}),
...(typeof a.filePath === 'string' ? { filePath: a.filePath } : {}),
...(typeof a.currentText === 'string' ? { currentText: a.currentText } : {}),
...(typeof a.selectionKind === 'string' ? { selectionKind: a.selectionKind } : {}),
...(typeof a.htmlHint === 'string' ? { htmlHint: a.htmlHint } : {}),
};
})
.filter((a): a is { note: string } => a !== null);
const appConfig = (await readAppConfig(RUNTIME_DATA_DIR).catch(() => ({}))) as MemoryAppConfigLike;
const chatAgentId =
typeof body.chatAgentId === 'string' && body.chatAgentId.trim()
? body.chatAgentId.trim()
: typeof appConfig.agentId === 'string' && appConfig.agentId.trim()
? appConfig.agentId.trim()
: null;
const chatModel =
typeof body.chatModel === 'string' && body.chatModel.trim()
? body.chatModel.trim()
: (chatAgentId && appConfig.agentModels?.[chatAgentId]?.model
? appConfig.agentModels[chatAgentId].model ?? null
: null);
const result = await distillRulesFromAnnotations(
RUNTIME_DATA_DIR,
{ annotations },
{
projectRoot: PROJECT_ROOT,
...(chatAgentId ? { chatAgentId } : {}),
...(chatModel ? { chatModel } : {}),
...(body.chatProvider && typeof body.chatProvider === 'object'
? { chatProvider: body.chatProvider }
: {}),
},
);
res.json(result);
} catch (err) {
res.status(400).json({ error: errorMessage(err) });
}
});
app.post('/api/memory/connectors/suggest', requireLocalDaemonRequest, async (req, res) => {
try {
const body = asRecord(req.body);
const connectorIds = Array.isArray(body.connectorIds)
? body.connectorIds
.filter((id: unknown): id is string => typeof id === 'string')
.map((id: string) => id.trim())
.filter(Boolean)
.slice(0, 12)
: undefined;
const query =
typeof body.query === 'string' ? body.query.trim().slice(0, 240) : '';
const projectId =
typeof body.projectId === 'string' && body.projectId.trim()
? body.projectId.trim()
: null;
const appConfig = (await readAppConfig(RUNTIME_DATA_DIR).catch(() => ({}))) as MemoryAppConfigLike;
const chatAgentId =
typeof body.chatAgentId === 'string' && body.chatAgentId.trim()
? body.chatAgentId.trim()
: typeof appConfig.agentId === 'string' && appConfig.agentId.trim()
? appConfig.agentId.trim()
: null;
const requestChatModel =
typeof body.chatModel === 'string' && body.chatModel.trim()
? body.chatModel.trim()
: null;
const chatModel =
requestChatModel
|| (chatAgentId && appConfig.agentModels?.[chatAgentId]?.model
? appConfig.agentModels[chatAgentId].model ?? null
: null);
const options = {
projectsRoot: PROJECTS_DIR,
projectRoot: PROJECT_ROOT,
...(projectId ? { projectId } : {}),
...(connectorIds ? { connectorIds } : {}),
...(query ? { query } : {}),
...(chatAgentId ? { chatAgentId } : {}),
...(chatModel ? { chatModel } : {}),
};
const result = await suggestMemoryFromConnectors(RUNTIME_DATA_DIR, options);
res.json(result);
} catch (err) {
res.status(400).json({ error: errorMessage(err) });
}
});
app.post('/api/memory/connectors/extract', requireLocalDaemonRequest, async (req, res) => {
try {
const body = asRecord(req.body);
const connectorIds = Array.isArray(body.connectorIds)
? body.connectorIds
.filter((id: unknown): id is string => typeof id === 'string')
.map((id: string) => id.trim())
.filter(Boolean)
.slice(0, 12)
: undefined;
const query =
typeof body.query === 'string' ? body.query.trim().slice(0, 240) : '';
const projectId =
typeof body.projectId === 'string' && body.projectId.trim()
? body.projectId.trim()
: null;
const appConfig = (await readAppConfig(RUNTIME_DATA_DIR).catch(() => ({}))) as MemoryAppConfigLike;
const chatAgentId =
typeof body.chatAgentId === 'string' && body.chatAgentId.trim()
? body.chatAgentId.trim()
: typeof appConfig.agentId === 'string' && appConfig.agentId.trim()
? appConfig.agentId.trim()
: null;
const requestChatModel =
typeof body.chatModel === 'string' && body.chatModel.trim()
? body.chatModel.trim()
: null;
const chatModel =
requestChatModel
|| (chatAgentId && appConfig.agentModels?.[chatAgentId]?.model
? appConfig.agentModels[chatAgentId].model ?? null
: null);
const options = {
projectsRoot: PROJECTS_DIR,
projectRoot: PROJECT_ROOT,
...(projectId ? { projectId } : {}),
...(connectorIds ? { connectorIds } : {}),
...(query ? { query } : {}),
...(chatAgentId ? { chatAgentId } : {}),
...(chatModel ? { chatModel } : {}),
};
const result = await extractMemoryFromConnectors(RUNTIME_DATA_DIR, options);
res.json(result);
} catch (err) {
res.status(400).json({ error: errorMessage(err) });
}
});
// Imperative extract — used by CLI chats internally and by BYOK /
// API-mode chats from the web app, which never reach the chat-run
// path on the daemon. Mirrors the two-phase hook the daemon's chat
// route applies inline:
//
// - Pre-turn (only `userMessage` supplied): run the synchronous
// heuristic regex pack so explicit "remember: X" / "我是 X"
// markers land in memory before the prompt is composed, and the
// same turn's assistant reply already reflects them.
// - Post-turn (`userMessage` + `assistantMessage` supplied): queue
// the LLM extractor in the background — it speaks SSE /
// extraction-history on its own and may take several seconds, so
// we don't block the HTTP response on it. The heuristic is
// skipped on this branch because the caller already ran it
// pre-turn; running it twice would double the
// `recordHeuristic({...})` rows in the extraction history for
// every turn.
//
// External callers (curl, replay tools) that pass only
// `userMessage` keep the legacy behaviour: heuristic-only.
app.post('/api/memory/extract', async (req, res) => {
try {
const body = asRecord(req.body);
const userMessage =
typeof body.userMessage === 'string' ? body.userMessage : '';
const assistantMessage =
typeof body.assistantMessage === 'string' ? body.assistantMessage : '';
const hasAssistant = assistantMessage.trim().length > 0;
const memoryConfig = await readMemoryConfig(RUNTIME_DATA_DIR);
if (memoryConfig.chatExtractionEnabled === false) {
return res.json({ changed: [], attemptedLLM: false });
}
const changed = hasAssistant
? []
: await extractFromMessage(RUNTIME_DATA_DIR, userMessage);
// BYOK chat config — only forwarded by the web app for API-mode
// chats. We strip the surface to the five fields pickProvider()
// actually consumes and validate the provider against the four
// shapes the extractor speaks; an unknown / missing provider
// means "let the legacy chain decide" so a malformed payload
// can't override the env / media-config fallbacks.
const rawChat = body.chatProvider;
let chatProvider = null;
if (rawChat && typeof rawChat === 'object') {
const chatConfig = rawChat as UnknownRecord;
const provider = chatConfig.provider;
if (
provider === 'anthropic'
|| provider === 'openai'
|| provider === 'azure'
|| provider === 'google'
|| provider === 'ollama'
) {
chatProvider = {
provider,
apiKey: typeof chatConfig.apiKey === 'string' ? chatConfig.apiKey : '',
baseUrl: typeof chatConfig.baseUrl === 'string' ? chatConfig.baseUrl : '',
apiVersion:
typeof chatConfig.apiVersion === 'string' ? chatConfig.apiVersion : '',
model: typeof chatConfig.model === 'string' ? chatConfig.model : '',
};
}
}
const chatModel =
typeof body.chatModel === 'string' && body.chatModel.trim()
? body.chatModel.trim()
: '';
let attemptedLLM = false;
if (userMessage.trim().length > 0 && hasAssistant) {
attemptedLLM = true;
void import('../memory-llm.js')
.then(({ extractWithLLM }) =>
extractWithLLM(
RUNTIME_DATA_DIR,
{ userMessage, assistantMessage },
{
projectRoot: PROJECT_ROOT,
chatAgentId: null,
chatProvider,
...(chatModel ? { chatModel } : {}),
},
),
)
.catch((err) =>
console.warn('[memory-llm] background failed (http extract)', err),
);
}
res.json({ changed, attemptedLLM });
} catch (err) {
res.status(400).json({ error: errorMessage(err) });
}
});
// Composed memory body for the system prompt. Daemon-side chat runs
// call `composeMemoryBody()` directly; the web app (BYOK / API mode)
// can't import daemon internals, so this endpoint exposes the same
// string the daemon would have folded into the system prompt for a
// CLI run. `ProjectView.composedSystemPrompt()` calls it before each
// BYOK turn and passes the result into `composeSystemPrompt`'s
// `memoryBody` field — without this, the Memory tab is a no-op for
// BYOK users even though the UI saves model/index/entries for them.
app.get('/api/memory/system-prompt', async (_req, res) => {
try {
const body = await composeMemoryBody(RUNTIME_DATA_DIR);
res.json({ body });
} catch (err) {
res.status(500).json({ error: errorMessage(err) });
}
});
app.post('/api/memory', async (req, res) => {
try {
const body = asRecord(req.body);
if (!isMemoryType(body.type) || typeof body.name !== 'string') {
throw new Error('memory entry requires `name` and a valid `type`');
}
const entry = await upsertMemoryEntry(
RUNTIME_DATA_DIR,
body as unknown as MemoryEntryInput,
undefined,
);
res.json({ entry });
} catch (err) {
res.status(400).json({ error: errorMessage(err) });
}
});
app.get('/api/memory/:id', async (req, res) => {
try {
const entry = await readMemoryEntry(RUNTIME_DATA_DIR, req.params.id);
if (!entry) return res.status(404).json({ error: 'memory not found' });
res.json({ entry });
} catch (err) {
res.status(400).json({ error: errorMessage(err) });
}
});
app.put('/api/memory/:id', async (req, res) => {
try {
const body = asRecord(req.body);
if (!isMemoryType(body.type) || typeof body.name !== 'string') {
throw new Error('memory entry requires `name` and a valid `type`');
}
const entry = await upsertMemoryEntry(
RUNTIME_DATA_DIR,
{
...(body as unknown as MemoryEntryInput),
id: req.params.id,
},
undefined,
);
res.json({ entry });
} catch (err) {
res.status(400).json({ error: errorMessage(err) });
}
});
app.delete('/api/memory/:id', async (req, res) => {
try {
await deleteMemoryEntry(RUNTIME_DATA_DIR, req.params.id);
res.json({ ok: true });
} catch (err) {
res.status(400).json({ error: errorMessage(err) });
}
});
}