dsh-plugin-agent-memory 0.0.0-stage → 0.1.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/index.js ADDED
@@ -0,0 +1,714 @@
1
+ /**
2
+ * Host half of the Tencent agent-memory integration.
3
+ *
4
+ * Responsibilities:
5
+ * - talk to the Memory Hub (`hubUrl`) with the configured instance id and user key
6
+ * - cache the team / agent lists so the composer selector can render them
7
+ * - keep the selected "expert" (team + agent) per session
8
+ * - recall that expert's memories for each user message and append them to the step
9
+ *
10
+ * The Client half only renders the selector; every Hub call happens here so the user
11
+ * key never reaches the browser.
12
+ */
13
+
14
+ import { randomUUID } from 'node:crypto';
15
+ import { appendFileSync, rmSync, statSync } from 'node:fs';
16
+ import { homedir } from 'node:os';
17
+ import z from '@deepseek-ai/schemastery';
18
+
19
+ const CACHE_TTL_MS = 5 * 60 * 1000;
20
+ const LAYERS = ['L3', 'L2', 'L1', 'L0'];
21
+ const DEBUG_LOG_LIMIT = 256 * 1024;
22
+
23
+ /**
24
+ * Configuration schema shown on this plugin's detail page and validated at activation.
25
+ * `userKey` carries `role('secret')` so the GUI redacts it instead of echoing it back.
26
+ */
27
+ export const Config = z.object({
28
+ hubUrl: z
29
+ .string()
30
+ .default('')
31
+ .description('Memory Hub 地址,例如 http://memhub.example.com:8125;留空则插件保持空闲'),
32
+ instanceId: z.string().min(1).default('default').description('Memory Hub 实例 id(请求头 X-Tdai-Service-Id)'),
33
+ userKey: z.string().role('secret').default('').description('Memory Hub userkey(请求头 X-Tdai-User-Key)'),
34
+ defaultAgentId: z.string().default('').description('未选择专家时默认使用的 agent id;留空则等用户在面板里选择'),
35
+ injectMemory: z.boolean().default(true).description('每轮对话前召回该专家的记忆并注入上下文'),
36
+ writeMemory: z.boolean().default(false).description('每轮对话结束后把用户消息写回记忆库'),
37
+ topK: z.number().min(1).max(10).step(1).default(4).description('每次召回的记忆条数'),
38
+ timeoutMs: z.number().min(1000).step(500).default(6000).description('单次 Hub 请求超时(毫秒)'),
39
+ debug: z.boolean().default(false).description('把召回/写回诊断写入 ~/.dsh/agent-memory-debug.log'),
40
+ });
41
+
42
+ function textOf(value) {
43
+ if (typeof value === 'string') return value;
44
+ if (!Array.isArray(value)) return '';
45
+ return value
46
+ .filter((block) => block && block.type === 'text' && typeof block.text === 'string')
47
+ .map((block) => block.text)
48
+ .join('\n');
49
+ }
50
+
51
+ function lastUserText(messages) {
52
+ let fallback = '';
53
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
54
+ const message = messages[index];
55
+ if (!message || message.role !== 'user') continue;
56
+ if (message.source?.kind === 'agent-memory') continue;
57
+ const text = textOf(message.content).trim();
58
+ if (text === '') continue;
59
+ if (message.source === undefined || message.source.kind === 'user') return text;
60
+ if (fallback === '') fallback = text;
61
+ }
62
+ return fallback;
63
+ }
64
+
65
+ const WRITE_NOISE = [
66
+ /^Background subagent /,
67
+ /^The user changed the approval policy/,
68
+ /^\[Scheduled message\]/,
69
+ /^<skill_content>/,
70
+ ];
71
+
72
+ function writeBackText(text) {
73
+ const trimmed = text.trim();
74
+ if (trimmed === '') return '';
75
+ if (WRITE_NOISE.some((pattern) => pattern.test(trimmed))) return '';
76
+ return trimmed
77
+ .replace(/\n+Your final answer is delivered automatically[\s\S]*$/, '')
78
+ .replace(/\n+If your last action is a message to your parent[\s\S]*$/, '')
79
+ .trim();
80
+ }
81
+
82
+ function normalizeConfig(config) {
83
+ const value = config ?? {};
84
+ return {
85
+ hubUrl: String(value.hubUrl ?? '').replace(/\/+$/, ''),
86
+ instanceId: String(value.instanceId ?? 'default'),
87
+ userKey: String(value.userKey ?? ''),
88
+ defaultAgentId: typeof value.defaultAgentId === 'string' ? value.defaultAgentId : '',
89
+ injectMemory: value.injectMemory !== false,
90
+ writeMemory: value.writeMemory === true,
91
+ topK: Number.isFinite(value.topK) ? Math.max(1, Math.min(10, value.topK)) : 4,
92
+ timeoutMs: Number.isFinite(value.timeoutMs) ? Math.max(1000, value.timeoutMs) : 6000,
93
+ debug: value.debug === true,
94
+ };
95
+ }
96
+
97
+ export function apply(ctx, config) {
98
+ const settings = normalizeConfig(config);
99
+ // A published bundle ships no Hub address or key, so an unconfigured install must still
100
+ // start: the routes below answer `/state` and `/config` so the settings form can be reached.
101
+ const configured = settings.hubUrl !== '' && settings.userKey !== '';
102
+ if (!configured) ctx.logger?.warn?.('[agent-memory] hubUrl/userKey missing; integration stays idle until configured');
103
+
104
+ const headers = {
105
+ 'X-Tdai-Service-Id': settings.instanceId,
106
+ 'X-Tdai-User-Key': settings.userKey,
107
+ 'Content-Type': 'application/json',
108
+ };
109
+
110
+ const state = {
111
+ teams: [],
112
+ teamsAt: 0,
113
+ agentsByTeam: new Map(),
114
+ identity: null,
115
+ selections: new Map(),
116
+ blocks: new Map(),
117
+ lastInjection: new Map(),
118
+ lastUser: new Map(),
119
+ };
120
+
121
+ function debug(entry) {
122
+ if (settings.debug === false) return;
123
+ const file = `${homedir()}/.dsh/agent-memory-debug.log`;
124
+ try {
125
+ const size = statSync(file, { throwIfNoEntry: false })?.size ?? 0;
126
+ if (size > DEBUG_LOG_LIMIT) rmSync(file, { force: true });
127
+ appendFileSync(file, `${new Date().toISOString()} ${JSON.stringify(entry)}\n`);
128
+ } catch {
129
+ /* diagnostics must never break recall */
130
+ }
131
+ }
132
+
133
+ async function hub(rpc, body) {
134
+ if (settings.hubUrl === '') throw new Error('Memory Hub 地址未配置:请先在插件设置里填 hubUrl');
135
+ if (settings.userKey === '') throw new Error('Memory Hub userkey 未配置:请先在插件设置里填 userKey');
136
+ const response = await fetch(`${settings.hubUrl}/api/v1/meta/${rpc}`, {
137
+ method: 'POST',
138
+ headers,
139
+ body: JSON.stringify(body ?? {}),
140
+ signal: AbortSignal.timeout(settings.timeoutMs),
141
+ });
142
+ const payload = await response.json().catch(() => null);
143
+ if (payload === null || typeof payload !== 'object') throw new Error(`hub ${rpc}: unreadable response`);
144
+ if (payload.code !== 0) throw new Error(`hub ${rpc}: ${payload.message ?? `code ${payload.code}`}`);
145
+ return payload.data ?? {};
146
+ }
147
+
148
+ async function chatMemory(method, body) {
149
+ const response = await fetch(`${settings.hubUrl}/api/v1/chat-memory/${method}`, {
150
+ method: 'POST',
151
+ headers,
152
+ body: JSON.stringify(body ?? {}),
153
+ signal: AbortSignal.timeout(settings.timeoutMs),
154
+ });
155
+ const payload = await response.json().catch(() => null);
156
+ if (payload === null || typeof payload !== 'object') throw new Error(`chat-memory ${method}: unreadable response`);
157
+ if (payload.code !== 0) throw new Error(`chat-memory ${method}: ${payload.message ?? `code ${payload.code}`}`);
158
+ return payload.data ?? {};
159
+ }
160
+
161
+ async function identity() {
162
+ if (state.identity !== null) return state.identity;
163
+ const verified = await hub('auth/verify', { user_key: settings.userKey });
164
+ const userId = verified?.user?.user_id;
165
+ if (typeof userId !== 'string' || userId === '') throw new Error('auth/verify returned no user_id');
166
+ state.identity = { userId, username: verified.user.username ?? '' };
167
+ return state.identity;
168
+ }
169
+
170
+ async function teams() {
171
+ if (state.teams.length > 0 && Date.now() - state.teamsAt < CACHE_TTL_MS) return state.teams;
172
+ const me = await identity();
173
+ const data = await hub('team/list', { user_id: me.userId });
174
+ state.teams = Array.isArray(data.items) ? data.items : [];
175
+ state.teamsAt = Date.now();
176
+ return state.teams;
177
+ }
178
+
179
+ async function agents(teamId) {
180
+ const cached = state.agentsByTeam.get(teamId);
181
+ if (cached !== undefined && Date.now() - cached.at < CACHE_TTL_MS) return cached.items;
182
+ const data = await hub('agent/list', { team_id: teamId, limit: 100 });
183
+ const items = Array.isArray(data.items) ? data.items : [];
184
+ state.agentsByTeam.set(teamId, { at: Date.now(), items });
185
+ return items;
186
+ }
187
+
188
+ async function resolveAgent(teamId, agentId) {
189
+ const still = await agents(teamId);
190
+ return still.find((agent) => agent.agent_id === agentId);
191
+ }
192
+
193
+ async function selectionFor(sessionId) {
194
+ const existing = state.selections.get(sessionId);
195
+ if (existing !== undefined) return existing;
196
+ if (settings.defaultAgentId === '') return null;
197
+ const known = await teams();
198
+ for (const team of known) {
199
+ const found = await resolveAgent(team.team_id, settings.defaultAgentId);
200
+ if (found === undefined) continue;
201
+ const selection = {
202
+ teamId: team.team_id,
203
+ teamName: team.name,
204
+ agentId: found.agent_id,
205
+ agentName: found.name,
206
+ };
207
+ state.selections.set(sessionId, selection);
208
+ return selection;
209
+ }
210
+ return null;
211
+ }
212
+
213
+ async function blockId(teamId, agentId) {
214
+ const key = `${teamId}:${agentId}`;
215
+ const cached = state.blocks.get(key);
216
+ if (cached !== undefined) return cached;
217
+ const data = await chatMemory('agent-fixed', { agent_id: agentId });
218
+ const items = Array.isArray(data.items) ? data.items : [];
219
+ const match = items.find((item) => item.agent_id === agentId) ?? items[0];
220
+ if (match === undefined) throw new Error('agent has no memory block');
221
+ state.blocks.set(key, match.id);
222
+ return match.id;
223
+ }
224
+
225
+ async function recall(selection, query) {
226
+ const block = await blockId(selection.teamId, selection.agentId);
227
+ const collected = [];
228
+ const seen = new Set();
229
+ for (const layer of LAYERS) {
230
+ let data;
231
+ try {
232
+ data = await chatMemory('search', {
233
+ block_id: block,
234
+ layer,
235
+ query,
236
+ limit: settings.topK,
237
+ });
238
+ } catch {
239
+ continue;
240
+ }
241
+ const items = Array.isArray(data.items) ? data.items : [];
242
+ for (const item of items) {
243
+ const body = typeof item.body === 'string' ? item.body.trim() : '';
244
+ if (body === '' || seen.has(body)) continue;
245
+ seen.add(body);
246
+ collected.push({ layer, body });
247
+ if (collected.length >= settings.topK * 2) break;
248
+ }
249
+ if (collected.length >= settings.topK) break;
250
+ }
251
+ return collected;
252
+ }
253
+
254
+ function memoryBlock(selection, hits) {
255
+ const lines = [
256
+ `<agent-memory expert="${selection.agentName}" team="${selection.teamName}">`,
257
+ '以下内容来自该专家的长期记忆库,仅在与当前问题相关时使用;若无关请忽略。',
258
+ ];
259
+ hits.forEach((hit, index) => {
260
+ lines.push(`${index + 1}. (${hit.layer}) ${hit.body}`);
261
+ });
262
+ lines.push('</agent-memory>');
263
+ return lines.join('\n');
264
+ }
265
+
266
+ ctx.effect(() => {
267
+ const listener = async function (payload, next) {
268
+ debug({ at: 'pre-step-enter', agent: String(payload?.agent?.id ?? '') });
269
+ const decision = await next();
270
+ if (decision?.kind !== 'enter' || settings.injectMemory !== true || !configured) {
271
+ debug({ at: 'skip-decision', kind: decision?.kind ?? null });
272
+ return decision;
273
+ }
274
+ const messages = Array.isArray(decision.messages) ? decision.messages : [];
275
+ const query = lastUserText(messages);
276
+ if (query === '') return decision;
277
+ const sessionId = String(payload?.agent?.id ?? '');
278
+ if (sessionId === '') return decision;
279
+ state.lastUser.set(sessionId, query);
280
+ try {
281
+ const selection = await selectionFor(sessionId);
282
+ if (selection === null) {
283
+ debug({ at: 'skip-no-selection', sessionId });
284
+ return decision;
285
+ }
286
+ const dedupeKey = `${sessionId}:${query}`;
287
+ if (state.lastInjection.get(sessionId) === dedupeKey) return decision;
288
+ const hits = await recall(selection, query);
289
+ debug({ at: 'recall', sessionId, agent: selection.agentId, query: query.slice(0, 60), hits: hits.length });
290
+ if (hits.length === 0) return decision;
291
+ state.lastInjection.set(sessionId, dedupeKey);
292
+ return {
293
+ ...decision,
294
+ messages: [
295
+ ...messages,
296
+ {
297
+ id: randomUUID(),
298
+ role: 'user',
299
+ content: [{ type: 'text', text: memoryBlock(selection, hits) }],
300
+ source: { kind: 'agent-memory' },
301
+ },
302
+ ],
303
+ };
304
+ } catch (error) {
305
+ debug({ at: 'error', message: String(error?.message ?? error) });
306
+ ctx.logger?.warn?.(`[agent-memory] recall skipped: ${error?.message ?? error}`);
307
+ return decision;
308
+ }
309
+ };
310
+ const off = ctx.on('agent/pre-step', listener, { global: true, prepend: true });
311
+ return () => off();
312
+ }, 'agent-memory: recall injection');
313
+
314
+ ctx.effect(() => {
315
+ const onTurnStopping = async function (payload) {
316
+ if (settings.writeMemory !== true) return;
317
+ const sessionId = String(payload?.agent?.id ?? '');
318
+ if (sessionId === '') return;
319
+ const text = writeBackText(state.lastUser.get(sessionId) ?? '');
320
+ state.lastUser.delete(sessionId);
321
+ if (text.length < 20) {
322
+ debug({ at: 'write-skip', sessionId, reason: 'too-short', chars: text.length });
323
+ return;
324
+ }
325
+ try {
326
+ const selection = await selectionFor(sessionId);
327
+ if (selection === null) return;
328
+ const data = await chatMemory('import', {
329
+ team_id: selection.teamId,
330
+ agent_id: selection.agentId,
331
+ session_id: sessionId,
332
+ messages: [{ role: 'user', content: text }],
333
+ });
334
+ debug({
335
+ at: 'write',
336
+ sessionId,
337
+ agent: selection.agentId,
338
+ chars: text.length,
339
+ accepted: data.accepted_count ?? null,
340
+ });
341
+ } catch (error) {
342
+ debug({ at: 'write-error', sessionId, message: String(error?.message ?? error) });
343
+ }
344
+ };
345
+ const off = ctx.on('agent/turn-stopping', onTurnStopping, { global: true });
346
+ return () => off();
347
+ }, 'agent-memory: memory write-back');
348
+
349
+ const webServer = ctx.get('webServer');
350
+ if (webServer === undefined) {
351
+ ctx.logger?.warn?.('[agent-memory] webServer service unavailable; the composer selector stays hidden');
352
+ return;
353
+ }
354
+
355
+ const origin = (() => {
356
+ try {
357
+ return webServer.getOrigin();
358
+ } catch {
359
+ return '';
360
+ }
361
+ })();
362
+
363
+ /**
364
+ * These routes are same-origin browser calls, so only the transport address is a hard
365
+ * requirement; the fetch metadata headers merely veto a cross-site page. Electron's
366
+ * renderer sends neither `Sec-Fetch-Site` nor `Origin`, so a missing header must pass.
367
+ */
368
+ function sameSite(request) {
369
+ const address = request.socket?.remoteAddress ?? '';
370
+ const loopback =
371
+ address === '127.0.0.1' ||
372
+ address === '::1' ||
373
+ address === '::ffff:127.0.0.1' ||
374
+ address.startsWith('127.');
375
+ if (!loopback) return false;
376
+ const fetchSite = request.headers['sec-fetch-site'];
377
+ if (
378
+ typeof fetchSite === 'string' &&
379
+ fetchSite !== '' &&
380
+ fetchSite !== 'same-origin' &&
381
+ fetchSite !== 'same-site' &&
382
+ fetchSite !== 'none'
383
+ ) {
384
+ debug({ at: 'denied-fetch-site', fetchSite, url: String(request.url ?? '') });
385
+ return false;
386
+ }
387
+ // Only a web origin can drive a cross-site request, so only a differing http(s)
388
+ // origin is rejected; a custom-scheme or opaque origin from the desktop shell passes.
389
+ const requestOrigin = request.headers.origin;
390
+ const webOrigin =
391
+ typeof requestOrigin === 'string' ? /^https?:\/\//i.test(requestOrigin) : false;
392
+ if (webOrigin && requestOrigin !== origin) {
393
+ debug({ at: 'denied-origin', requestOrigin, origin, url: String(request.url ?? '') });
394
+ return false;
395
+ }
396
+ return true;
397
+ }
398
+
399
+ function reply(response, status, body) {
400
+ const text = JSON.stringify(body);
401
+ response.writeHead(status, {
402
+ 'Content-Type': 'application/json; charset=utf-8',
403
+ 'Cache-Control': 'no-store',
404
+ 'Content-Length': Buffer.byteLength(text),
405
+ });
406
+ response.end(text);
407
+ }
408
+
409
+ async function readJson(request) {
410
+ const chunks = [];
411
+ let size = 0;
412
+ for await (const chunk of request) {
413
+ size += chunk.length;
414
+ if (size > 64 * 1024) throw new Error('request body too large');
415
+ chunks.push(chunk);
416
+ }
417
+ if (chunks.length === 0) return {};
418
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
419
+ }
420
+
421
+ ctx.effect(
422
+ () =>
423
+ webServer.register({
424
+ kind: 'exact',
425
+ path: '/plugins/agent-memory/state',
426
+ handler: async (request, response) => {
427
+ if (!sameSite(request)) {
428
+ reply(response, 403, { error: 'forbidden' });
429
+ return;
430
+ }
431
+ const url = new URL(request.url ?? '/', 'http://localhost');
432
+ const sessionId = url.searchParams.get('session') ?? '';
433
+ try {
434
+ let knownTeams = [];
435
+ let loadError = '';
436
+ try {
437
+ knownTeams = await teams();
438
+ } catch (error) {
439
+ loadError = String(error?.message ?? error);
440
+ }
441
+ const selection = sessionId === '' ? null : await selectionFor(sessionId);
442
+ reply(response, 200, {
443
+ configured,
444
+ teams: knownTeams.map((team) => ({ teamId: team.team_id, name: team.name })),
445
+ selection,
446
+ error: loadError,
447
+ defaultAgentId: settings.defaultAgentId,
448
+ config: {
449
+ hubUrl: settings.hubUrl,
450
+ instanceId: settings.instanceId,
451
+ userKeySet: settings.userKey !== '',
452
+ userKeyHint:
453
+ settings.userKey === '' ? '' : `****${settings.userKey.slice(-4)}`,
454
+ injectMemory: settings.injectMemory,
455
+ writeMemory: settings.writeMemory,
456
+ topK: settings.topK,
457
+ debug: settings.debug,
458
+ },
459
+ });
460
+ } catch (error) {
461
+ reply(response, 502, { error: String(error?.message ?? error) });
462
+ }
463
+ },
464
+ }),
465
+ 'agent-memory: state route',
466
+ );
467
+
468
+ /** Connectivity probe used by the selector's settings panel and by the detail page. */
469
+ ctx.effect(
470
+ () =>
471
+ webServer.register({
472
+ kind: 'exact',
473
+ path: '/plugins/agent-memory/health',
474
+ handler: async (request, response) => {
475
+ if (!sameSite(request)) {
476
+ reply(response, 403, { error: 'forbidden' });
477
+ return;
478
+ }
479
+ const startedAt = Date.now();
480
+ try {
481
+ const me = await identity();
482
+ const knownTeams = await teams();
483
+ let agentCount = 0;
484
+ const teamDetails = [];
485
+ for (const team of knownTeams) {
486
+ const list = await agents(team.team_id);
487
+ const owned = list.filter((agent) => agent.owner_user_id === me.userId).length;
488
+ agentCount += list.length;
489
+ teamDetails.push({
490
+ teamId: team.team_id,
491
+ name: team.name,
492
+ agents: list.length,
493
+ owned,
494
+ });
495
+ }
496
+ reply(response, 200, {
497
+ ok: true,
498
+ hubUrl: settings.hubUrl,
499
+ latencyMs: Date.now() - startedAt,
500
+ user: { userId: me.userId, username: me.username },
501
+ agents: agentCount,
502
+ teams: teamDetails,
503
+ });
504
+ } catch (error) {
505
+ reply(response, 502, { ok: false, error: String(error?.message ?? error) });
506
+ }
507
+ },
508
+ }),
509
+ 'agent-memory: health route',
510
+ );
511
+
512
+ /**
513
+ * Saves the connection settings from the UI. The `configEditor` service owns the profile
514
+ * patch file; editing an ordinary field restarts this plugin so `apply` rebuilds state.
515
+ */
516
+ ctx.effect(
517
+ () =>
518
+ webServer.register({
519
+ kind: 'exact',
520
+ path: '/plugins/agent-memory/config',
521
+ handler: async (request, response) => {
522
+ if (request.method !== 'POST') {
523
+ reply(response, 405, { error: 'POST required' });
524
+ return;
525
+ }
526
+ if (!sameSite(request)) {
527
+ reply(response, 403, { error: 'forbidden' });
528
+ return;
529
+ }
530
+ let body;
531
+ try {
532
+ body = await readJson(request);
533
+ } catch (error) {
534
+ reply(response, 400, { error: String(error?.message ?? error) });
535
+ return;
536
+ }
537
+ const patch = {};
538
+ if (typeof body.hubUrl === 'string' && body.hubUrl.trim() !== '') {
539
+ patch.hubUrl = body.hubUrl.trim().replace(/\/+$/, '');
540
+ }
541
+ if (typeof body.instanceId === 'string' && body.instanceId.trim() !== '') {
542
+ patch.instanceId = body.instanceId.trim();
543
+ }
544
+ if (typeof body.userKey === 'string' && body.userKey.trim() !== '') {
545
+ patch.userKey = body.userKey.trim();
546
+ }
547
+ if (typeof body.defaultAgentId === 'string' && body.defaultAgentId.trim() !== '') {
548
+ patch.defaultAgentId = body.defaultAgentId.trim();
549
+ }
550
+ if (typeof body.injectMemory === 'boolean') patch.injectMemory = body.injectMemory;
551
+ if (typeof body.writeMemory === 'boolean') patch.writeMemory = body.writeMemory;
552
+ if (Number.isFinite(body.topK)) patch.topK = Math.max(1, Math.min(10, body.topK));
553
+ if (Number.isFinite(body.timeoutMs)) patch.timeoutMs = Math.max(1000, body.timeoutMs);
554
+ if (typeof body.debug === 'boolean') patch.debug = body.debug;
555
+ if (Object.keys(patch).length === 0) {
556
+ reply(response, 400, { error: 'no editable field in request' });
557
+ return;
558
+ }
559
+ const editor = ctx.get('configEditor');
560
+ const entry = ctx.fiber?.entry;
561
+ if (editor === undefined || entry === undefined) {
562
+ reply(response, 501, {
563
+ error: 'configEditor unavailable in this profile; edit cordis.patch.yml instead',
564
+ });
565
+ return;
566
+ }
567
+ debug({ at: 'config-save', fields: Object.keys(patch) });
568
+ try {
569
+ await editor.edit(entry, (current) => ({ ...current, ...patch }));
570
+ } catch (error) {
571
+ reply(response, 409, { error: String(error?.message ?? error) });
572
+ return;
573
+ }
574
+ reply(response, 200, { saved: Object.keys(patch) });
575
+ },
576
+ }),
577
+ 'agent-memory: config route',
578
+ );
579
+
580
+ ctx.effect(
581
+ () =>
582
+ webServer.register({
583
+ kind: 'exact',
584
+ path: '/plugins/agent-memory/agents',
585
+ handler: async (request, response) => {
586
+ if (!sameSite(request)) {
587
+ reply(response, 403, { error: 'forbidden' });
588
+ return;
589
+ }
590
+ const url = new URL(request.url ?? '/', 'http://localhost');
591
+ const teamId = url.searchParams.get('team') ?? '';
592
+ if (teamId === '') {
593
+ reply(response, 400, { error: 'team query parameter is required' });
594
+ return;
595
+ }
596
+ try {
597
+ const items = await agents(teamId);
598
+ const me = await identity();
599
+ reply(response, 200, {
600
+ agents: items.map((agent) => ({
601
+ agentId: agent.agent_id,
602
+ name: agent.name,
603
+ description: agent.description ?? '',
604
+ status: agent.status ?? 'active',
605
+ owned: agent.owner_user_id === me.userId,
606
+ })),
607
+ });
608
+ } catch (error) {
609
+ reply(response, 502, { error: String(error?.message ?? error) });
610
+ }
611
+ },
612
+ }),
613
+ 'agent-memory: agents route',
614
+ );
615
+
616
+ ctx.effect(
617
+ () =>
618
+ webServer.register({
619
+ kind: 'exact',
620
+ path: '/plugins/agent-memory/select',
621
+ handler: async (request, response) => {
622
+ if (request.method !== 'POST') {
623
+ reply(response, 405, { error: 'POST required' });
624
+ return;
625
+ }
626
+ if (!sameSite(request)) {
627
+ reply(response, 403, { error: 'forbidden' });
628
+ return;
629
+ }
630
+ try {
631
+ const body = await readJson(request);
632
+ const sessionId = String(body.sessionId ?? '');
633
+ const teamId = String(body.teamId ?? '');
634
+ const agentId = String(body.agentId ?? '');
635
+ if (sessionId === '') {
636
+ reply(response, 400, { error: 'sessionId is required' });
637
+ return;
638
+ }
639
+ if (teamId === '' || agentId === '') {
640
+ state.selections.delete(sessionId);
641
+ state.lastInjection.delete(sessionId);
642
+ reply(response, 200, { selection: null });
643
+ return;
644
+ }
645
+ const knownTeams = await teams();
646
+ const team = knownTeams.find((item) => item.team_id === teamId);
647
+ if (team === undefined) {
648
+ reply(response, 404, { error: 'unknown team' });
649
+ return;
650
+ }
651
+ const agent = await resolveAgent(teamId, agentId);
652
+ if (agent === undefined) {
653
+ reply(response, 404, { error: 'unknown agent for that team' });
654
+ return;
655
+ }
656
+ const me = await identity();
657
+ if (agent.owner_user_id !== me.userId) {
658
+ reply(response, 403, { error: 'NOT_YOUR_AGENT' });
659
+ return;
660
+ }
661
+ const selection = {
662
+ teamId,
663
+ teamName: team.name,
664
+ agentId,
665
+ agentName: agent.name,
666
+ };
667
+ state.selections.set(sessionId, selection);
668
+ state.lastInjection.delete(sessionId);
669
+ reply(response, 200, { selection });
670
+ } catch (error) {
671
+ reply(response, 400, { error: String(error?.message ?? error) });
672
+ }
673
+ },
674
+ }),
675
+ 'agent-memory: select route',
676
+ );
677
+
678
+ ctx.effect(
679
+ () =>
680
+ webServer.register({
681
+ kind: 'exact',
682
+ path: '/plugins/agent-memory/preview',
683
+ handler: async (request, response) => {
684
+ if (!sameSite(request)) {
685
+ reply(response, 403, { error: 'forbidden' });
686
+ return;
687
+ }
688
+ const url = new URL(request.url ?? '/', 'http://localhost');
689
+ const sessionId = url.searchParams.get('session') ?? '';
690
+ const query = url.searchParams.get('q') ?? '';
691
+ if (sessionId === '' || query === '') {
692
+ reply(response, 400, { error: 'session and q are required' });
693
+ return;
694
+ }
695
+ try {
696
+ const selection = await selectionFor(sessionId);
697
+ if (selection === null) {
698
+ reply(response, 200, { selection: null, block: '' });
699
+ return;
700
+ }
701
+ const hits = await recall(selection, query);
702
+ reply(response, 200, {
703
+ selection,
704
+ hits,
705
+ block: hits.length === 0 ? '' : memoryBlock(selection, hits),
706
+ });
707
+ } catch (error) {
708
+ reply(response, 502, { error: String(error?.message ?? error) });
709
+ }
710
+ },
711
+ }),
712
+ 'agent-memory: preview route',
713
+ );
714
+ }