dsh-world 0.6.6 → 0.7.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.
Files changed (90) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/CONTRIBUTING.md +163 -161
  3. package/NOTES.md +184 -152
  4. package/README.md +237 -227
  5. package/client/index.js +894 -738
  6. package/lib/archive.d.ts +3 -1
  7. package/lib/archive.js +6 -4
  8. package/lib/compaction.js +8 -0
  9. package/lib/compactionSwap.d.ts +29 -2
  10. package/lib/compactionSwap.js +62 -7
  11. package/lib/console/homeApply.d.ts +11 -2
  12. package/lib/console/homeApply.js +36 -7
  13. package/lib/console/routes.d.ts +13 -0
  14. package/lib/console/routes.js +43 -0
  15. package/lib/console/snapshot.d.ts +8 -0
  16. package/lib/console/snapshot.js +4 -2
  17. package/lib/ecosystem/bridge/route.d.ts +7 -0
  18. package/lib/ecosystem/bridge/route.js +30 -0
  19. package/lib/ecosystem/qq/route.d.ts +2 -1
  20. package/lib/ecosystem/qq/route.js +10 -2
  21. package/lib/ecosystem/qq-native/batch.d.ts +2 -0
  22. package/lib/ecosystem/qq-native/batch.js +3 -1
  23. package/lib/ecosystem/qq-native/index.d.ts +2 -0
  24. package/lib/ecosystem/qq-native/index.js +4 -0
  25. package/lib/ecosystem/qq-native/replies.d.ts +6 -1
  26. package/lib/ecosystem/qq-native/replies.js +19 -1
  27. package/lib/ecosystem/shared/context.d.ts +1 -1
  28. package/lib/ecosystem/shared/context.js +1 -1
  29. package/lib/ecosystem/shared/identity.d.ts +12 -0
  30. package/lib/ecosystem/shared/identity.js +17 -1
  31. package/lib/ecosystem/shared/turn.d.ts +8 -5
  32. package/lib/ecosystem/shared/turn.js +16 -17
  33. package/lib/ecosystem/wechat/archive.d.ts +2 -0
  34. package/lib/ecosystem/wechat/archive.js +3 -1
  35. package/lib/ecosystem/wechat/home.js +9 -4
  36. package/lib/ecosystem/wechat/messages.d.ts +11 -0
  37. package/lib/ecosystem/wechat/messages.js +9 -1
  38. package/lib/ecosystem/wechat/sending.js +36 -9
  39. package/lib/ecosystem/wechat/supervisor.d.ts +11 -2
  40. package/lib/ecosystem/wechat/supervisor.js +90 -9
  41. package/lib/history.d.ts +6 -4
  42. package/lib/history.js +61 -12
  43. package/lib/hostContract.d.ts +1 -0
  44. package/lib/index.js +41 -14
  45. package/lib/life/activity.d.ts +2 -0
  46. package/lib/life/activity.js +1 -1
  47. package/lib/life/alarm.d.ts +12 -4
  48. package/lib/life/alarm.js +21 -6
  49. package/lib/life/diary.d.ts +6 -0
  50. package/lib/life/diary.js +23 -2
  51. package/lib/life/runtime.d.ts +1 -0
  52. package/lib/life/runtime.js +57 -9
  53. package/lib/life/toolRegistry.d.ts +4 -3
  54. package/lib/life/toolRegistry.js +13 -3
  55. package/lib/life/types.d.ts +6 -1
  56. package/lib/memory.d.ts +57 -0
  57. package/lib/memory.js +207 -0
  58. package/lib/memoryFiles.d.ts +50 -0
  59. package/lib/memoryFiles.js +168 -0
  60. package/lib/memoryStore.d.ts +112 -0
  61. package/lib/memoryStore.js +159 -0
  62. package/lib/memoryTools.d.ts +31 -0
  63. package/lib/memoryTools.js +106 -0
  64. package/lib/promptSection.d.ts +2 -0
  65. package/lib/runtime.d.ts +1 -1
  66. package/lib/runtime.js +62 -75
  67. package/lib/sourceArchive.d.ts +1 -0
  68. package/lib/sourceArchive.js +4 -5
  69. package/lib/store.d.ts +15 -1
  70. package/lib/store.js +12 -2
  71. package/lib/types.d.ts +1 -4
  72. package/lib/worldPrompt.d.ts +6 -0
  73. package/lib/worldPrompt.js +8 -2
  74. package/lib/worldSwitch.d.ts +9 -1
  75. package/lib/worldSwitch.js +14 -1
  76. package/package.json +128 -117
  77. package/scripts/compact-home.mjs +29 -0
  78. package/scripts/update-world.mjs +6 -4
  79. package/src/ecosystem/wechat/windows/README.md +7 -5
  80. package/src/ecosystem/wechat/windows/adapter.py +86 -31
  81. package/src/ecosystem/wechat/windows/engine/NOTICE.md +1 -1
  82. package/src/ecosystem/wechat/windows/engine/bridge.cpp +9 -1
  83. package/src/ecosystem/wechat/windows/engine/build.ps1 +8 -2
  84. package/src/ecosystem/wechat/windows/engine/profiles.json +56 -0
  85. package/src/ecosystem/wechat/windows/native.py +4 -1
  86. package/src/ecosystem/wechat/windows/outgoing.py +21 -0
  87. package/src/ecosystem/wechat/windows/sender.py +26 -6
  88. package/templates/alarm.md +3 -4
  89. package/templates/world-prompt-memory.md +10 -0
  90. package/templates/world-prompt.md +7 -2
@@ -9,10 +9,11 @@ import { formatLocalTime } from "../timeContext.js";
9
9
  import { inWorld } from "../sourceArchive.js";
10
10
  import { homeTitle, roomTitle, worldNames } from "../worldPrompt.js";
11
11
  import { admit, reassembleOnChange } from "../worldScope.js";
12
- import { budgetText, cancelReply, greetingText, checkReply, earlyStopText, nextLocalTime, nextReview, planReply, resolveAlarmTime, reviewText, wakeText } from "./alarm.js";
12
+ import { budgetText, cancelReply, greetingText, checkReply, earlyStopText, nextLocalTime, nextReview, planReply, resolveAlarmTime, reviewOf, reviewText, wakeText } from "./alarm.js";
13
13
  import { summarizeSince } from "./activity.js";
14
14
  import { createAlarmTimer, realTimers } from "./alarmTimer.js";
15
15
  import { createEarlyStopWatch } from "./earlyStop.js";
16
+ import { closedDiaryRefusal } from "./diary.js";
16
17
  import { createHome } from "./home.js";
17
18
  import { createJournal } from "./journal.js";
18
19
  import { stepCost } from "./pricing.js";
@@ -60,7 +61,8 @@ export function createLifeRuntime(deps) {
60
61
  faults.clear('alarm-template');
61
62
  return messages;
62
63
  }
63
- const templateValues = () => ({ name: names.companion, partner: names.partner, homeTitle: homeTitle(names), timeZone, fallbackWakeTime: options.fallbackWakeTime, example: exampleTime(timeZone) });
64
+ const wake = () => options.schedule().wake;
65
+ const templateValues = () => ({ name: names.companion, partner: names.partner, homeTitle: homeTitle(names), timeZone, fallbackWakeTime: wake(), example: exampleTime(timeZone) });
64
66
  /**
65
67
  * What she actually did between setting this alarm and hearing it, in one line.
66
68
  *
@@ -167,7 +169,7 @@ export function createLifeRuntime(deps) {
167
169
  return alarm && { kind: 'alarm', at: alarm.at, alarm };
168
170
  }
169
171
  const timer = createAlarmTimer({ clock, timers, dueAlarm: () => nextJob()?.at, fire: () => void deliver() });
170
- const morning = (now) => ({ at: nextLocalTime(now, options.fallbackWakeTime, timeZone).toISOString(), note: '', setAt: now.toISOString(), source: 'fallback' });
172
+ const morning = (now) => ({ at: nextLocalTime(now, wake(), timeZone).toISOString(), note: '', setAt: now.toISOString(), source: 'fallback' });
171
173
  /** A new alarm replaces a failing one, so its backoff and fault go with it. Saved or not, it is armed. */
172
174
  function setAlarm(alarm) {
173
175
  if (stopped)
@@ -218,6 +220,32 @@ export function createLifeRuntime(deps) {
218
220
  fallbackAlarm();
219
221
  return cancelReply(cancelled, state.alarm, timeZone);
220
222
  }
223
+ /**
224
+ * Moves what is pending to the console's review and morning times when they differ (changed now, or while her
225
+ * world was stopped). The pending look back keeps its day; the plugin's morning alarm moves to the new time after
226
+ * it was set, at once if that has passed. An alarm of hers is left alone. True when anything moved.
227
+ */
228
+ function followSchedule() {
229
+ const now = clock(), { review, wake: morningTime } = options.schedule();
230
+ const timeOf = (at) => formatLocalTime(new Date(at), timeZone).slice(11, 16);
231
+ let moved = false;
232
+ if (state.review && timeOf(state.review.at) !== review) {
233
+ state.review = reviewOf(state.review.day, now, timeZone, review);
234
+ moved = true;
235
+ }
236
+ if (state.alarm?.source === 'fallback' && timeOf(state.alarm.at) !== morningTime) {
237
+ const at = nextLocalTime(new Date(state.alarm.setAt), morningTime, timeZone);
238
+ state.alarm = { ...state.alarm, at: (at > now ? at : now).toISOString() };
239
+ moved = true;
240
+ }
241
+ return moved;
242
+ }
243
+ function reschedule() {
244
+ if (stopped || !followSchedule())
245
+ return;
246
+ record(() => store.write(state));
247
+ timer.reset();
248
+ }
221
249
  // Delivery: one at a time, the next only once the last started a step; a failure backs off, and a newer alarm keeps its own time.
222
250
  function deliver() {
223
251
  const job = nextJob();
@@ -263,11 +291,23 @@ export function createLifeRuntime(deps) {
263
291
  * A new home's first words, so it has a turn (the host lists no session without one) and she knows she moved;
264
292
  * or the word that her world has started again.
265
293
  */
266
- const greet = (greeting) => sayOwn(greeting.kind === 'arrival' ? '新家的第一句话' : '重新开始的那句话', greeting.kind === 'arrival' ? 'first' : 'return', greeting.at, { greeting }, () => { delete state.greeting; }, () => { state.greeting ??= greeting; }, () => greetingText(greeting.kind, timeZone, options.fallbackWakeTime, alarmMessages(), templateValues()));
294
+ const greet = (greeting) => sayOwn(greeting.kind === 'arrival' ? '新家的第一句话' : '重新开始的那句话', greeting.kind === 'arrival' ? 'first' : 'return', greeting.at, { greeting }, () => { delete state.greeting; }, () => { state.greeting ??= greeting; }, () => greetingText(greeting.kind, timeZone, wake(), alarmMessages(), templateValues()));
295
+ /** The day whose look back her home is in now: its diary stays open until that turn ends, even past midnight. */
296
+ let reviewing;
297
+ /** A day's diary is open until its look back has ended: today, and a day whose look back is still to come or under way. */
298
+ function openDiaryDays(today) {
299
+ const days = new Set([today]);
300
+ if (state.review && state.review.day < today)
301
+ days.add(state.review.day);
302
+ if (reviewing)
303
+ days.add(reviewing);
304
+ return days;
305
+ }
267
306
  /** The evening look back on her day; her 我是谁 is kept as it was, so she can rewrite it freely. */
268
307
  function lookBack(review) {
269
308
  let snapshot;
270
309
  const take = () => {
310
+ reviewing = review.day;
271
311
  try {
272
312
  snapshot = keepSelfCopy(options.selfFile, review.day);
273
313
  faults.clear('snapshot');
@@ -276,13 +316,13 @@ export function createLifeRuntime(deps) {
276
316
  faults.set('snapshot', `我是谁没能留底:${errorText(error)}`);
277
317
  ctx.logger.error(error);
278
318
  }
279
- state.review = nextReview(clock(), timeZone);
319
+ state.review = nextReview(clock(), timeZone, options.schedule().review);
280
320
  };
281
321
  const existing = (dir) => { const file = join(options.worldDir, dir, `${review.day}.jsonl`); return existsSync(file) ? file : undefined; };
282
322
  return sayOwn('每日回顾', 'review', review.at, { review }, take, () => { state.review = review; }, now => reviewText(review, now, {
283
323
  ...withValue('conversations', existing('conversations')), ...withValue('activity', existing('activity')), ...withValue('snapshot', snapshot),
284
324
  diaryDir: options.diaryDir, selfFile: options.selfFile,
285
- }, timeZone, options.fallbackWakeTime, alarmMessages(), templateValues()), () => deps.afterReview?.());
325
+ }, timeZone, wake(), alarmMessages(), templateValues()), () => deps.afterReview?.());
286
326
  }
287
327
  async function send(alarm) {
288
328
  try {
@@ -297,7 +337,7 @@ export function createLifeRuntime(deps) {
297
337
  // Cleared before steering, so a turn that ends quickly already sees "no alarm" and gets the fallback.
298
338
  delete state.alarm;
299
339
  const now = clock();
300
- const text = wakeText(alarm, now, timeZone, options.fallbackWakeTime, alarmMessages(), { ...templateValues(), did: alarm.source === 'fallback' ? '' : didSince(alarm, now) });
340
+ const text = wakeText(alarm, now, timeZone, wake(), alarmMessages(), { ...templateValues(), did: alarm.source === 'fallback' ? '' : didSince(alarm, now) });
301
341
  const context = deps.alarmContext?.(now);
302
342
  const message = lifeMessage(context ? `${text}\n\n${context}` : text);
303
343
  expect(agent, message, '闹钟', alarm.at, alarm.source, { alarm }, now);
@@ -370,6 +410,10 @@ export function createLifeRuntime(deps) {
370
410
  faults, logger: ctx.logger,
371
411
  inWorld: agent => !stopped && includes(agent.session),
372
412
  isHome: agent => agent.id === state.homeSessionId,
413
+ guard: ({ name, arguments: args, agent }) => {
414
+ const today = formatLocalTime(clock(), timeZone).slice(0, 10);
415
+ return closedDiaryRefusal(name, args, options.diaryDir, agent?.session.header.cwd ?? options.roomDir, openDiaryDays(today), today);
416
+ },
373
417
  tools: agent => [
374
418
  ...lifeTools({ planNext, checkAlarm, cancelAlarm, notifier, names, origin: () => { try {
375
419
  return host.origin();
@@ -431,6 +475,8 @@ export function createLifeRuntime(deps) {
431
475
  }
432
476
  if (event.type !== 'turn/end')
433
477
  return;
478
+ if (state.delivering?.source !== 'review')
479
+ reviewing = undefined;
434
480
  home.turnEnded(session.id);
435
481
  fallbackAlarm();
436
482
  // A stopped or failed turn is not her deciding she is done.
@@ -439,9 +485,11 @@ export function createLifeRuntime(deps) {
439
485
  for (const agent of ctx.agents.list())
440
486
  attach(agent);
441
487
  if (!state.review) {
442
- state.review = nextReview(clock(), timeZone);
488
+ state.review = nextReview(clock(), timeZone, deps.options.schedule().review);
443
489
  record(() => store.write(state));
444
490
  }
491
+ if (followSchedule())
492
+ record(() => store.write(state));
445
493
  try {
446
494
  const agent = await home.open();
447
495
  faults.clear('home');
@@ -477,7 +525,7 @@ export function createLifeRuntime(deps) {
477
525
  tools.clear();
478
526
  }
479
527
  return {
480
- start, stop, planNext, checkAlarm, cancelAlarm, deliver,
528
+ start, stop, planNext, checkAlarm, cancelAlarm, deliver, reschedule,
481
529
  snapshot: () => ({ homeSessionId: state.homeSessionId, alarm: state.alarm, review: state.review, spend: state.spend, faults: faults.list() }),
482
530
  /** Resolves once no alarm delivery is in flight (its durability flush can outlast the turn it starts). */
483
531
  settled: async () => { while (delivery)
@@ -1,9 +1,9 @@
1
1
  import type { Agent } from '@deepseek-ai/dsh-agent';
2
2
  import { type Faults } from '../faults.ts';
3
- import type { ToolDefinition } from '@deepseek-ai/dsh-tools';
3
+ import type { ToolDefinition, ToolGuard } from '@deepseek-ai/dsh-tools';
4
4
  /**
5
- * The alarm tools are held by every world session (she can set her alarm anywhere; it rings at home);
6
- * reach_out only by the current home. A registration that fails (a name clash) is a fault and never breaks
5
+ * The alarm tools are held by every world session (she can set her alarm anywhere; it rings at home), with `guard`
6
+ * checking each of its tool calls; reach_out only by the current home. A registration that fails (a name clash) is a fault and never breaks
7
7
  * agent creation; it registers all of a group or none. Each tool refuses to run once its session leaves her world.
8
8
  */
9
9
  export declare function createToolRegistry(deps: {
@@ -14,6 +14,7 @@ export declare function createToolRegistry(deps: {
14
14
  tools: (agent: Agent) => readonly ToolDefinition[];
15
15
  isHome(agent: Agent): boolean;
16
16
  inWorld(agent: Agent): boolean;
17
+ guard?: ToolGuard;
17
18
  }): {
18
19
  /** Registers what the agent is missing; true when its tool list changed. */
19
20
  attach(agent: Agent): boolean;
@@ -12,8 +12,8 @@ function undo(list) {
12
12
  }
13
13
  }
14
14
  /**
15
- * The alarm tools are held by every world session (she can set her alarm anywhere; it rings at home);
16
- * reach_out only by the current home. A registration that fails (a name clash) is a fault and never breaks
15
+ * The alarm tools are held by every world session (she can set her alarm anywhere; it rings at home), with `guard`
16
+ * checking each of its tool calls; reach_out only by the current home. A registration that fails (a name clash) is a fault and never breaks
17
17
  * agent creation; it registers all of a group or none. Each tool refuses to run once its session leaves her world.
18
18
  */
19
19
  export function createToolRegistry(deps) {
@@ -43,7 +43,17 @@ export function createToolRegistry(deps) {
43
43
  try {
44
44
  const tools = deps.tools(agent);
45
45
  if (needsAlarm) {
46
- alarm.set(agent, register(agent, tools, ALARM_TOOLS));
46
+ const done = register(agent, tools, ALARM_TOOLS);
47
+ // The world sessions' own policy comes and goes with their alarm tools.
48
+ try {
49
+ if (deps.guard)
50
+ done.push(agent.ctx.tools.guard(execution => deps.inWorld(agent) ? deps.guard(execution) : undefined));
51
+ }
52
+ catch (error) {
53
+ undo(done);
54
+ throw error;
55
+ }
56
+ alarm.set(agent, done);
47
57
  changed = true;
48
58
  }
49
59
  if (needsHome) {
@@ -76,13 +76,18 @@ export interface CompactionRecord {
76
76
  shadowedTokens?: number;
77
77
  error?: string;
78
78
  }
79
+ export interface DailySchedule {
80
+ review: string;
81
+ wake: string;
82
+ }
79
83
  export interface LifeOptions {
80
84
  worldDir: string;
81
85
  roomDir: string;
82
86
  diaryDir: string;
83
87
  selfFile: string;
84
- fallbackWakeTime: string;
85
88
  timeZone: string;
89
+ /** Local HH:MM of the evening look back and of the morning wake when nothing is pending; read each time, since the console can change them. */
90
+ schedule(): DailySchedule;
86
91
  /** Her alarm wording; the shipped `templates/alarm.md` when absent or missing. */
87
92
  alarmFile?: string;
88
93
  }
@@ -0,0 +1,57 @@
1
+ import { type MemorySources } from './memoryFiles.ts';
2
+ import { type FindParams, type MemoryItem, type MemoryKind, type MemoryStatus, type MemoryStore, type ReadResult } from './memoryStore.ts';
3
+ export { MEMORY_KINDS, MemoryError } from './memoryStore.ts';
4
+ export { readStable } from './memoryFiles.ts';
5
+ export type { MemoryErrorCode, MemoryItem, MemoryKind, MemoryStatus } from './memoryStore.ts';
6
+ export type { MemorySources } from './memoryFiles.ts';
7
+ export interface MemoryPage {
8
+ items: MemoryItem[];
9
+ nextCursor?: string;
10
+ coverage: MemoryStatus;
11
+ search: {
12
+ method: 'browse' | 'scan';
13
+ elapsedMs: number;
14
+ };
15
+ }
16
+ export interface MemoryContent {
17
+ ref: string;
18
+ sourceId: string;
19
+ kind: MemoryKind;
20
+ version: string;
21
+ title: string;
22
+ time: string;
23
+ timeBasis: ReadResult['timeBasis'];
24
+ current: boolean;
25
+ content: string;
26
+ offset: number;
27
+ nextOffset?: number;
28
+ totalChars: number;
29
+ turnId?: string;
30
+ origin?: ReadResult['origin'];
31
+ }
32
+ export interface MemoryService {
33
+ find(input: Record<string, unknown>): Promise<MemoryPage>;
34
+ read(input: Record<string, unknown>): Promise<MemoryContent>;
35
+ status(): MemoryStatus;
36
+ }
37
+ export interface MemoryDeps {
38
+ store: MemoryStore;
39
+ timeZone: string;
40
+ sources: MemorySources;
41
+ /** Whether the caller may see this chat session; may throw while the host cannot say yet, which counts as no. */
42
+ visible(sessionId: string): boolean;
43
+ now?: () => Date;
44
+ }
45
+ export declare const DEFAULT_FIND_LIMIT = 20, MAX_FIND_LIMIT = 100, DEFAULT_READ_LIMIT = 4000, MAX_READ_LIMIT = 16000;
46
+ /** The one place a query is checked, for the tools and the console alike. */
47
+ export declare function normalizeFind(input: Record<string, unknown>, timeZone: string): FindParams;
48
+ export declare function normalizeRead(input: Record<string, unknown>): {
49
+ ref: string;
50
+ offset: number;
51
+ limit: number;
52
+ };
53
+ /**
54
+ * The one entry to long-term memory: tools and console call the same `find` and `read`. Nothing is indexed: chat is
55
+ * scanned in the archive and her files are read when asked, so there is no queue to wait for and no index to rebuild.
56
+ */
57
+ export declare function createMemory(deps: MemoryDeps): MemoryService;
package/lib/memory.js ADDED
@@ -0,0 +1,207 @@
1
+ import { createAuthorFiles } from "./memoryFiles.js";
2
+ import { MAX_QUERY_CHARS, MEMORY_KINDS, MemoryError, chatRef, decodeRef, excerptOf, sha, } from "./memoryStore.js";
3
+ import { errorText } from "./faults.js";
4
+ export { MEMORY_KINDS, MemoryError } from "./memoryStore.js";
5
+ export { readStable } from "./memoryFiles.js";
6
+ export const DEFAULT_FIND_LIMIT = 20, MAX_FIND_LIMIT = 100, DEFAULT_READ_LIMIT = 4000, MAX_READ_LIMIT = 16000;
7
+ const iso = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/;
8
+ function text(input, key, max) {
9
+ const value = input[key];
10
+ if (value === undefined || value === null || value === '')
11
+ return undefined;
12
+ if (typeof value !== 'string' || value.length > max)
13
+ throw new MemoryError('invalidQuery', `${key} 必须是不超过 ${max} 个字符的字符串`);
14
+ return value;
15
+ }
16
+ function time(input, key, timeZone) {
17
+ const value = text(input, key, 40);
18
+ if (value === undefined)
19
+ return undefined;
20
+ const ms = iso.test(value) ? Date.parse(value) : NaN;
21
+ if (!Number.isFinite(ms))
22
+ throw new MemoryError('invalidQuery', `${key} 需要带时区的 ISO 时间(如 2026-10-30T00:00:00+08:00);日期请按 ${timeZone} 换算成当天零点`);
23
+ return ms;
24
+ }
25
+ function whole(input, key, fallback, min, max) {
26
+ const value = input[key];
27
+ if (value === undefined || value === null)
28
+ return fallback;
29
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min || value > max)
30
+ throw new MemoryError('invalidQuery', `${key} 必须是 ${min} 到 ${max} 的整数`);
31
+ return value;
32
+ }
33
+ /** The one place a query is checked, for the tools and the console alike. */
34
+ export function normalizeFind(input, timeZone) {
35
+ const query = text(input, 'query', MAX_QUERY_CHARS * 4);
36
+ if (query !== undefined && (Array.from(query).length > MAX_QUERY_CHARS || query.includes('\0')))
37
+ throw new MemoryError('invalidQuery', `query 不能超过 ${MAX_QUERY_CHARS} 个字符,也不能含空字符`);
38
+ const kindsInput = input.kinds;
39
+ if (kindsInput !== undefined && kindsInput !== null && (!Array.isArray(kindsInput) || kindsInput.some(kind => !MEMORY_KINDS.includes(kind))))
40
+ throw new MemoryError('invalidQuery', `kinds 只能是 ${MEMORY_KINDS.join('、')}`);
41
+ const order = input.order ?? 'newest';
42
+ if (order !== 'newest' && order !== 'oldest')
43
+ throw new MemoryError('invalidQuery', 'order 只能是 newest 或 oldest');
44
+ const fromMs = time(input, 'from', timeZone), toMs = time(input, 'to', timeZone);
45
+ if (fromMs !== undefined && toMs !== undefined && fromMs >= toMs)
46
+ throw new MemoryError('invalidQuery', 'from 必须早于 to(区间左闭右开)');
47
+ const kinds = kindsInput?.length ? [...new Set(kindsInput)] : undefined;
48
+ const sourceId = text(input, 'sourceId', 300), turnId = text(input, 'turnId', 300), linkedTo = text(input, 'linkedTo', 2000), cursor = text(input, 'cursor', 4000);
49
+ return {
50
+ order, limit: whole(input, 'limit', DEFAULT_FIND_LIMIT, 1, MAX_FIND_LIMIT),
51
+ ...(query === undefined ? {} : { query }), ...(kinds ? { kinds } : {}), ...(fromMs === undefined ? {} : { fromMs }), ...(toMs === undefined ? {} : { toMs }),
52
+ ...(sourceId ? { sourceId } : {}), ...(turnId ? { turnId } : {}), ...(linkedTo ? { linkedTo } : {}), ...(cursor ? { cursor } : {}),
53
+ };
54
+ }
55
+ export function normalizeRead(input) {
56
+ const ref = text(input, 'ref', 2000);
57
+ if (!ref)
58
+ throw new MemoryError('invalidQuery', 'ref 必须是 memory_find 给出的引用');
59
+ return { ref, offset: whole(input, 'offset', 0, 0, Number.MAX_SAFE_INTEGER), limit: whole(input, 'limit', DEFAULT_READ_LIMIT, 1, MAX_READ_LIMIT) };
60
+ }
61
+ const chatKind = (params) => !params.kinds || params.kinds.includes('conversation');
62
+ const asksForChat = (params) => chatKind(params) && (!params.sourceId || params.sourceId.startsWith('chat:'));
63
+ /** The filters every candidate passes the same way, whichever source it came from. */
64
+ function accepts(candidate, params) {
65
+ const { item } = candidate;
66
+ return (!params.kinds || params.kinds.includes(item.kind)) && (!params.sourceId || item.sourceId === params.sourceId)
67
+ && (params.fromMs === undefined || candidate.timeMs >= params.fromMs) && (params.toMs === undefined || candidate.timeMs < params.toMs)
68
+ && (!params.query || candidate.content.includes(params.query));
69
+ }
70
+ function authorItem(doc, query) {
71
+ return { ref: doc.ref, sourceId: doc.sourceId, kind: doc.kind, title: doc.title, time: doc.time, timeBasis: doc.timeBasis, current: true, excerpt: excerptOf(doc.content, query) };
72
+ }
73
+ const authorCandidate = (doc, query) => ({ item: authorItem(doc, query), content: doc.content, timeMs: doc.timeMs });
74
+ /**
75
+ * The one entry to long-term memory: tools and console call the same `find` and `read`. Nothing is indexed: chat is
76
+ * scanned in the archive and her files are read when asked, so there is no queue to wait for and no index to rebuild.
77
+ */
78
+ export function createMemory(deps) {
79
+ const { store, timeZone } = deps;
80
+ const authors = createAuthorFiles(deps.sources, timeZone);
81
+ const now = deps.now ?? (() => new Date());
82
+ let checkedAt = now().toISOString();
83
+ const scopeFailures = new Map();
84
+ const canSee = (sessionId) => {
85
+ try {
86
+ const yes = deps.visible(sessionId);
87
+ scopeFailures.delete('scope');
88
+ return yes;
89
+ }
90
+ catch (error) {
91
+ scopeFailures.set('scope', `暂时说不清哪些会话在范围内:${errorText(error)}`);
92
+ return false;
93
+ }
94
+ };
95
+ const sessionsInScope = () => store.sessionIds().filter(canSee);
96
+ const docs = async () => { const all = await authors.docs(); checkedAt = now().toISOString(); return all; };
97
+ function status() {
98
+ const failures = [...authors.failures(), ...[...scopeFailures].map(([sourceId, message]) => ({ sourceId, message }))];
99
+ return { state: failures.length ? 'partial' : 'ready', failures, checkedAt };
100
+ }
101
+ function readCursor(cursor, hash, files) {
102
+ let parsed;
103
+ try {
104
+ parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
105
+ }
106
+ catch {
107
+ throw new MemoryError('invalidCursor', '翻页游标无效');
108
+ }
109
+ if (typeof parsed.hash !== 'string' || !Number.isSafeInteger(parsed.upTo) || !Number.isSafeInteger(parsed.revisions) || typeof parsed.files !== 'string' || !Number.isSafeInteger(parsed.offset) || parsed.offset < 0)
110
+ throw new MemoryError('invalidCursor', '翻页游标无效');
111
+ if (parsed.hash !== hash || parsed.revisions !== store.snapshot().revisions || parsed.files !== files)
112
+ throw new MemoryError('cursorExpired', '查询条件、访问范围或资料已经变化,请重新查询(cursorExpired)');
113
+ return parsed;
114
+ }
115
+ const cursorOf = (state) => Buffer.from(JSON.stringify(state)).toString('base64url');
116
+ /** What a link-following query looks at: the files that cite the ref and what the ref's own file cites, never a line she may not see. */
117
+ function linked(ref, all, query) {
118
+ const found = new Map();
119
+ for (const doc of all)
120
+ if (doc.links.includes(ref))
121
+ found.set(doc.ref, authorCandidate(doc, query));
122
+ for (const target of all.find(doc => doc.ref === ref)?.links ?? []) {
123
+ let decoded;
124
+ try {
125
+ decoded = decodeRef(target);
126
+ }
127
+ catch {
128
+ continue;
129
+ }
130
+ const file = decoded.kind === 'a' ? all.find(doc => doc.ref === target) : undefined;
131
+ if (file) {
132
+ found.set(file.ref, authorCandidate(file, query));
133
+ continue;
134
+ }
135
+ const record = decoded.kind === 'c' ? store.byRecordId(decoded.recordId) : undefined;
136
+ if (record && canSee(record.sourceSessionId) && chatRef(record.recordId, record.content) === target)
137
+ found.set(target, { item: store.item(record, query), content: record.content, timeMs: Date.parse(record.occurredAt) });
138
+ }
139
+ return [...found.values()];
140
+ }
141
+ async function find(input) {
142
+ const started = performance.now();
143
+ const params = normalizeFind(input, timeZone);
144
+ const all = await docs();
145
+ const sessions = sessionsInScope();
146
+ if (params.linkedTo) {
147
+ const session = store.refSession(params.linkedTo);
148
+ if (session !== undefined && !canSee(session))
149
+ throw new MemoryError('outOfScope', 'linkedTo 指向的聊天不在当前可读范围内');
150
+ }
151
+ const hash = sha(JSON.stringify([params.query ?? null, params.kinds ?? null, params.fromMs ?? null, params.toMs ?? null, params.sourceId ?? null, params.turnId ?? null, params.linkedTo ?? null, params.order, [...sessions].sort()]));
152
+ const files = sha(all.map(doc => doc.sourceId + doc.ref).sort().join('\n'));
153
+ const resumed = params.cursor ? readCursor(params.cursor, hash, files) : undefined;
154
+ const upTo = resumed?.upTo ?? store.snapshot().head, offset = resumed?.offset ?? 0;
155
+ const want = offset + params.limit + 1;
156
+ let candidates;
157
+ if (params.linkedTo)
158
+ candidates = linked(params.linkedTo, all, params.query).filter(candidate => accepts(candidate, params));
159
+ else {
160
+ const chat = asksForChat(params) ? store.find(params, sessions, upTo, want).map((record) => ({ item: store.item(record, params.query), content: record.content, timeMs: Date.parse(record.occurredAt) })) : [];
161
+ const written = params.turnId ? [] : all.map(doc => authorCandidate(doc, params.query)).filter(candidate => accepts(candidate, params));
162
+ candidates = [...chat, ...written];
163
+ }
164
+ // A turn is read in the order it was said; everything else by time, ties keeping the order the sources gave.
165
+ if (!params.turnId) {
166
+ const way = params.order === 'newest' ? -1 : 1;
167
+ candidates = candidates.map((candidate, index) => ({ candidate, index })).sort((a, b) => way * (a.candidate.timeMs - b.candidate.timeMs) || a.index - b.index).map(entry => entry.candidate);
168
+ }
169
+ const page = candidates.slice(offset, offset + params.limit);
170
+ // Membership is asked again on what is about to be returned: a session that left the scope meanwhile is refused, not trimmed.
171
+ for (const { item } of page)
172
+ if (item.kind === 'conversation' && item.origin?.sessionId && !canSee(item.origin.sessionId))
173
+ throw new MemoryError('scopeChanged', '查询期间可读范围变了,请重新查询');
174
+ const more = candidates.length > offset + params.limit;
175
+ return {
176
+ items: page.map(candidate => candidate.item),
177
+ ...(more ? { nextCursor: cursorOf({ hash, upTo, revisions: store.snapshot().revisions, files, offset: offset + params.limit }) } : {}),
178
+ coverage: status(), search: { method: params.query ? 'scan' : 'browse', elapsedMs: Math.round((performance.now() - started) * 10) / 10 },
179
+ };
180
+ }
181
+ async function read(input) {
182
+ const { ref, offset, limit } = normalizeRead(input);
183
+ const decoded = decodeRef(ref);
184
+ let found;
185
+ if (decoded.kind === 'c') {
186
+ found = store.read(ref, canSee);
187
+ if (found.origin?.sessionId && !canSee(found.origin.sessionId))
188
+ throw new MemoryError('scopeChanged', '读取期间可读范围变了,请重新读取');
189
+ }
190
+ else {
191
+ const doc = (await docs()).find(candidate => candidate.sourceId === decoded.sourceId);
192
+ if (!doc)
193
+ throw new MemoryError('notFound', '这条引用对应的文件不存在');
194
+ if (doc.ref !== ref)
195
+ throw new MemoryError('sourceChanged', '这个文件在引用之后被改过,旧版正文没有保留(sourceChanged)');
196
+ found = { ref, sourceId: doc.sourceId, kind: doc.kind, version: decoded.hash, title: doc.title, time: doc.time, timeBasis: doc.timeBasis, current: true, content: doc.content };
197
+ }
198
+ const chars = Array.from(found.content);
199
+ const end = Math.min(chars.length, offset + limit);
200
+ return {
201
+ ref: found.ref, sourceId: found.sourceId, kind: found.kind, version: found.version, title: found.title, time: found.time, timeBasis: found.timeBasis, current: found.current,
202
+ content: chars.slice(offset, end).join(''), offset, ...(end < chars.length ? { nextOffset: end } : {}), totalChars: chars.length,
203
+ ...(found.turnId ? { turnId: found.turnId } : {}), ...(found.origin ? { origin: found.origin } : {}),
204
+ };
205
+ }
206
+ return { find, read, status };
207
+ }
@@ -0,0 +1,50 @@
1
+ import { type MemoryKind, type TimeBasis } from './memoryStore.ts';
2
+ /** Where she keeps what she writes for memory to find: her diary directory's markdown and text files. 我是谁 is not here; it is placed whole in the world prompt. */
3
+ export interface MemorySources {
4
+ diaryDir?: string;
5
+ }
6
+ export type AuthorKind = Exclude<MemoryKind, 'conversation'>;
7
+ /** One file as she wrote it, with the time it has and the ref that is bound to this exact text. */
8
+ export interface AuthorDoc {
9
+ sourceId: string;
10
+ kind: AuthorKind;
11
+ path: string;
12
+ title: string;
13
+ content: string;
14
+ ref: string;
15
+ links: string[];
16
+ timeMs: number;
17
+ time: string;
18
+ timeBasis: TimeBasis;
19
+ }
20
+ type Read = {
21
+ kind: 'ok';
22
+ content: string;
23
+ stat: string;
24
+ mtimeMs: number;
25
+ } | {
26
+ kind: 'missing';
27
+ } | {
28
+ kind: 'failed';
29
+ message: string;
30
+ };
31
+ /**
32
+ * Reads a file the way its text may be used: stat before and after must agree and the bytes must be valid UTF-8. A
33
+ * file that is changing under us, or cannot be read or decoded, is a failure to retry, never new content and never a
34
+ * deletion. A writer that appends valid text piece by piece cannot be told apart from a finished file.
35
+ */
36
+ export declare function readStable(path: string, between?: () => Promise<void>): Promise<Read>;
37
+ /**
38
+ * What she wrote, read on demand. Files are few and small, so a query looks at the configured places directly; a
39
+ * file whose size and time are unchanged is not read again. A file that cannot be read keeps its last text and is
40
+ * reported; only a file that is really gone leaves the results.
41
+ */
42
+ export declare function createAuthorFiles(sources: MemorySources, timeZone: string): {
43
+ docs: () => Promise<AuthorDoc[]>;
44
+ failures: () => {
45
+ sourceId: string;
46
+ message: string;
47
+ }[];
48
+ };
49
+ export type AuthorFiles = ReturnType<typeof createAuthorFiles>;
50
+ export {};