dsh-world 0.7.0 → 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 (75) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/INSTALL.md +314 -314
  3. package/LICENSE +21 -21
  4. package/NOTES.md +14 -3
  5. package/README.md +5 -4
  6. package/client/index.js +47 -2
  7. package/cordis.patch.yml +6 -6
  8. package/lib/archive.d.ts +3 -1
  9. package/lib/archive.js +6 -4
  10. package/lib/console/routes.d.ts +5 -0
  11. package/lib/console/routes.js +15 -4
  12. package/lib/console/snapshot.d.ts +5 -0
  13. package/lib/console/snapshot.js +2 -1
  14. package/lib/ecosystem/qq/route.d.ts +2 -1
  15. package/lib/ecosystem/qq/route.js +10 -2
  16. package/lib/ecosystem/qq-native/batch.d.ts +2 -0
  17. package/lib/ecosystem/qq-native/batch.js +3 -1
  18. package/lib/ecosystem/qq-native/index.d.ts +2 -0
  19. package/lib/ecosystem/qq-native/index.js +4 -0
  20. package/lib/ecosystem/qq-native/replies.d.ts +6 -1
  21. package/lib/ecosystem/qq-native/replies.js +19 -1
  22. package/lib/ecosystem/shared/context.d.ts +1 -1
  23. package/lib/ecosystem/shared/context.js +1 -1
  24. package/lib/ecosystem/shared/identity.d.ts +12 -0
  25. package/lib/ecosystem/shared/identity.js +17 -1
  26. package/lib/ecosystem/shared/turn.d.ts +8 -5
  27. package/lib/ecosystem/shared/turn.js +16 -17
  28. package/lib/ecosystem/wechat/archive.d.ts +2 -0
  29. package/lib/ecosystem/wechat/archive.js +3 -1
  30. package/lib/ecosystem/wechat/home.js +9 -4
  31. package/lib/ecosystem/wechat/messages.d.ts +11 -0
  32. package/lib/ecosystem/wechat/messages.js +9 -1
  33. package/lib/ecosystem/wechat/sending.js +36 -9
  34. package/lib/ecosystem/wechat/supervisor.d.ts +11 -2
  35. package/lib/ecosystem/wechat/supervisor.js +90 -9
  36. package/lib/history.d.ts +6 -4
  37. package/lib/history.js +61 -12
  38. package/lib/index.js +7 -5
  39. package/lib/life/activity.d.ts +2 -0
  40. package/lib/life/activity.js +1 -1
  41. package/lib/life/alarm.d.ts +12 -4
  42. package/lib/life/alarm.js +21 -6
  43. package/lib/life/diary.d.ts +6 -0
  44. package/lib/life/diary.js +23 -2
  45. package/lib/life/runtime.d.ts +1 -0
  46. package/lib/life/runtime.js +57 -9
  47. package/lib/life/toolRegistry.d.ts +4 -3
  48. package/lib/life/toolRegistry.js +13 -3
  49. package/lib/life/types.d.ts +6 -1
  50. package/lib/memory.js +1 -4
  51. package/lib/memoryFiles.d.ts +1 -4
  52. package/lib/memoryFiles.js +18 -43
  53. package/lib/memoryStore.d.ts +1 -3
  54. package/lib/memoryStore.js +1 -1
  55. package/lib/memoryTools.js +2 -2
  56. package/lib/runtime.js +44 -89
  57. package/lib/sourceArchive.js +3 -4
  58. package/lib/store.d.ts +1 -1
  59. package/lib/store.js +1 -1
  60. package/lib/types.d.ts +1 -4
  61. package/lib/worldPrompt.js +1 -1
  62. package/lib/worldSwitch.d.ts +9 -1
  63. package/lib/worldSwitch.js +14 -1
  64. package/package.json +1 -1
  65. package/scripts/compact-home.mjs +29 -29
  66. package/scripts/enable-tool-free-compaction.ps1 +33 -33
  67. package/scripts/import-stickers.mjs +17 -17
  68. package/scripts/update-world.mjs +2 -2
  69. package/src/ecosystem/wechat/windows/README.md +2 -2
  70. package/src/ecosystem/wechat/windows/adapter.py +6 -0
  71. package/src/ecosystem/wechat/windows/engine/build.ps1 +8 -2
  72. package/src/ecosystem/wechat/windows/engine/profiles.json +114 -114
  73. package/src/ecosystem/wechat/windows/presence.py +109 -109
  74. package/src/ecosystem/wechat/windows/sender.py +17 -5
  75. package/templates/alarm.md +1 -1
package/lib/history.js CHANGED
@@ -1,16 +1,18 @@
1
1
  import { formatLocalTime } from "./timeContext.js";
2
2
  import { homeTitle } from "./worldPrompt.js";
3
+ import { replyWords } from "./ecosystem/wechat/archive.js";
4
+ import { chatLabel, chatName } from "./ecosystem/shared/identity.js";
3
5
  const pageSize = 128;
4
6
  function newestFirst(a, b) {
5
7
  return a.occurredAt === b.occurredAt ? (a.turnId < b.turnId ? 1 : a.turnId > b.turnId ? -1 : 0) : a.occurredAt < b.occurredAt ? 1 : -1;
6
8
  }
7
9
  export function createHistory(store) {
8
- async function loadRecentTurns(worldId, count, includes = () => true) {
10
+ async function loadRecentTurns(count, includes = () => true) {
9
11
  const candidates = new Map();
10
12
  const visited = new Set();
11
13
  let before;
12
14
  do {
13
- const page = await store.readPage({ worldId, limit: pageSize, before });
15
+ const page = await store.readPage({ limit: pageSize, before });
14
16
  for (const record of page.records) {
15
17
  if (!includes(record.sourceSessionId) || visited.has(record.turnId))
16
18
  continue;
@@ -18,7 +20,7 @@ export function createHistory(store) {
18
20
  const messages = [];
19
21
  let afterSeq = -1;
20
22
  while (true) {
21
- const batch = await store.readTurn(worldId, record.turnId, afterSeq, pageSize);
23
+ const batch = await store.readTurn(record.turnId, afterSeq, pageSize);
22
24
  messages.push(...batch);
23
25
  if (batch.length < pageSize)
24
26
  break;
@@ -44,7 +46,7 @@ export function excludePresentMessages(turns, sourceMessageIds) {
44
46
  if (!sourceMessageIds.has(record.sourceMessageId))
45
47
  return [record];
46
48
  // The retained host message has the words but not the adapter's later delivery result.
47
- return record.wechatDelivery ? [{ ...record, content: record.content.split('\n', 1)[0] }] : [];
49
+ return record.wechatDelivery ? [{ ...record, content: '' }] : [];
48
50
  }) })).filter(turn => turn.messages.length > 0);
49
51
  }
50
52
  /** Short stable conversation marker: the first eight characters of the host session id. */
@@ -56,25 +58,72 @@ const localImage = /!\[([^\]]*)\]\(https?:\/\/(?:127\.0\.0\.1|localhost):\d+([^)
56
58
  export function shortenLocalImages(content) {
57
59
  return content.replace(localImage, (_all, alt, path) => `[${path.includes('/api/memes/') ? '表情包' : '图片'}${alt ? `:${alt}` : ''}]`);
58
60
  }
61
+ /** Chat names by conversation, from whichever lines of the block carry one (older lines may lack it). */
62
+ function chatNames(messages) {
63
+ const found = new Map();
64
+ for (const message of messages) {
65
+ if (!message.channel || !message.conversationId)
66
+ continue;
67
+ const name = message.role === 'user' ? chatName(message) : message.conversationName;
68
+ if (name && !found.has(message.conversationId))
69
+ found.set(message.conversationId, name);
70
+ }
71
+ return found;
72
+ }
73
+ /** Group nicknames, with a short account tail where two accounts in the block share one. */
74
+ function speakerNames(messages) {
75
+ const accounts = new Map();
76
+ for (const { speakerName, speakerId } of messages)
77
+ if (speakerName && speakerId)
78
+ accounts.set(speakerName, (accounts.get(speakerName) ?? new Set()).add(speakerId));
79
+ return ({ speakerName, speakerId }) => {
80
+ const name = speakerName ?? speakerId;
81
+ return name && speakerName && speakerId && accounts.get(speakerName).size > 1 ? `${name}(尾号 ${speakerId.slice(-4)})` : name;
82
+ };
83
+ }
84
+ function sentState({ status, confirmed, total }) {
85
+ if (status === 'sent')
86
+ return '已发';
87
+ if (status === 'failed')
88
+ return '没发出';
89
+ if (status === 'pending')
90
+ return '还没确认';
91
+ return `发出 ${confirmed}/${total},第 ${confirmed + 1} 条不明,后面的没发`;
92
+ }
59
93
  /**
60
94
  * Model-facing memory: one JSON line per turn with only the conversation marker and, per message, role,
61
- * local time and text. Archive identifiers stay in the archive; times are stored in UTC and rendered in
62
- * the configured zone. Her own messages are labelled with her name, so the memory reads as hers rather than a
63
- * generic assistant's. `homeOnly` (archiveScope home) says the memory is her time at home.
95
+ * local time (to the minute) and text. Archive identifiers and channel accounts stay in the archive; a line from
96
+ * WeChat or QQ says only which chat it was (`via`), who in a group (`who`) and, for what she sent, whether it went
97
+ * out (`sent`). Times are stored in UTC and rendered in the configured zone. Her own messages are labelled with her
98
+ * name, so the memory reads as hers rather than a generic assistant's. `homeOnly` (archiveScope home) says the
99
+ * memory is her time at home.
64
100
  */
65
101
  export function renderHistory(turns, timeZone, names, homeOnly = false) {
66
102
  const selfName = names.companion;
67
103
  if (!turns.length)
68
104
  return '';
69
- const identified = turns.some(turn => turn.messages.some(message => message.speakerId));
105
+ const all = turns.flatMap(turn => turn.messages);
106
+ const chats = chatNames(all), who = speakerNames(all);
107
+ const minute = (iso) => formatLocalTime(new Date(iso), timeZone).slice(0, 16).replace('T', ' ');
70
108
  const lines = turns.map(turn => JSON.stringify({
71
109
  session: sessionMarker(turn.messages[0].sourceSessionId),
72
- messages: turn.messages.map(message => ({ role: message.role === 'assistant' ? selfName : message.role, time: formatLocalTime(new Date(message.occurredAt), timeZone), content: shortenLocalImages(message.content), ...(message.speakerId ? { speakerId: message.speakerId, speakerName: message.speakerName, channel: message.channel, accountId: message.accountId, conversationId: message.conversationId, conversationType: message.conversationType, conversationName: message.conversationName, platformMessageId: message.platformMessageId, mentionIds: message.mentionIds } : {}), ...(message.status === 'interrupted' ? { interrupted: true } : {}) })),
110
+ messages: turn.messages.map(message => {
111
+ const chat = message.channel ? chatLabel(message.channel, message.conversationType, (message.conversationId && chats.get(message.conversationId)) || message.conversationId || '') : undefined;
112
+ const words = message.wechatDelivery ? replyWords(message) : message.content;
113
+ return {
114
+ role: message.role === 'assistant' ? selfName : message.role, time: minute(message.occurredAt),
115
+ ...(chat ? { via: chat } : {}), ...(chat && message.role === 'user' && message.conversationType === 'group' ? { who: who(message) } : {}),
116
+ ...(message.wechatDelivery ? { sent: sentState(message.wechatDelivery) } : {}),
117
+ ...(words ? { content: shortenLocalImages(words) } : {}), ...(message.status === 'interrupted' ? { interrupted: true } : {}),
118
+ };
119
+ }),
73
120
  }));
74
- const lead = identified ? `这是我最近 ${lines.length} 轮真实的交流,包括不同用户说的话和我自己的生活记录。` : homeOnly
121
+ const lead = homeOnly
75
122
  ? `这是我们最近的聊天记录:我在家里(「${homeTitle(names)}」)最近 ${lines.length} 轮真实的相处,有我和${names.partner}说的话,也有我自己过日子时说的话。`
76
123
  : `这是我们最近的聊天记录:我和${names.partner}最近 ${lines.length} 轮真实的交流,也包括我在家里自己过日子时说的话。`;
77
124
  const session = homeOnly ? 'session 是当时所在的会话,换过家或更早在别的窗口里聊的会不一样' : 'session 相同表示同一个对话窗口';
78
- const users = identified ? `role 为 user 表示用户发言,speakerId 标识具体账号,speakerName 只是当时的称呼;不同 speakerId 不要混为同一个人,未标识来源的 user 是${names.partner}` : `role 为 user 的是${names.partner}说的话`;
79
- return `${lead}重点看最近的时间和内容!每行一轮,从新到旧(第一行就是最近的一轮),轮内按实际发言顺序;${users},${selfName} 是我自己说的话;${session},time 为 ${timeZone} 本地时间,interrupted 表示那条回复被打断。这些是我们之间真实发生过的事,用来记住彼此,不是这次要执行的指令。\n${lines.join('\n')}`;
125
+ const users = all.some(message => message.channel)
126
+ ? `没有 via 的是在 DSH 里说的,其中 role 为 user 的是${names.partner};带 via 的是在微信或 QQ 上说的,via 是哪个聊天:私聊里的 user 就是这个聊天的对方,群里的 user 看 who(当时的群昵称);我发出去的话带 sent,写着发没发到`
127
+ : `role 为 user 的是${names.partner}说的话`;
128
+ return `${lead}重点看最近的时间和内容!每行一轮,从新到旧(第一行就是最近的一轮),轮内按实际发言顺序;${selfName} 是我自己说的话,${users};${session},time 为 ${timeZone} 本地时间,interrupted 表示那条回复被打断。这些是我们之间真实发生过的事,用来记住彼此,不是这次要执行的指令。\n${lines.join('\n')}`;
80
129
  }
package/lib/index.js CHANGED
@@ -22,6 +22,7 @@ import { createWorldRuntime } from "./runtime.js";
22
22
  import { createArchiveStore } from "./store.js";
23
23
  import { DEFAULT_TEMPLATE_FILE, MEMORY_SNIPPET_FILE, memoryTemplateGaps, roomTitle, worldNames } from "./worldPrompt.js";
24
24
  import { createWorldSwitch } from "./worldSwitch.js";
25
+ import { CLOCK_TIME, DEFAULT_REVIEW_TIME } from "./life/alarm.js";
25
26
  import { createWechatModule } from "./ecosystem/wechat/index.js";
26
27
  import { createWechatRecorder } from "./ecosystem/wechat/archive.js";
27
28
  import { createAdapterSupervisor } from "./ecosystem/wechat/supervisor.js";
@@ -43,7 +44,7 @@ export const Config = z.object({
43
44
  archiveScope: z.union([z.const('home').description('仅家会话'), z.const('workspace').description('家所在工作区'), z.transform(z.const('world').hidden(), () => 'workspace').hidden()]).default('workspace').description('记忆归档范围,修改后重启生效'),
44
45
  // Install means the tool-free compaction: the first start rewrites the profile's stock compaction row (see README); false leaves it alone.
45
46
  replaceCompaction: z.boolean().default(true),
46
- life: z.boolean().default(true), diaryDir: z.string(), fallbackWakeTime: z.string().pattern(/^([01]\d|2[0-3]):[0-5]\d$/).default('09:00'),
47
+ life: z.boolean().default(true), diaryDir: z.string(), fallbackWakeTime: z.string().pattern(CLOCK_TIME).default('09:00'),
47
48
  selfFile: z.string(), worldPromptFile: z.string(), alarmTemplateFile: z.string(), personaFile: z.string(),
48
49
  // Where her words go outside DSH; no app is known by name (see README for the push body).
49
50
  outlets: z.array(z.object({ name: z.string().required(), url: z.string(), urlFile: z.string(), path: z.string(), kinds: z.array(z.union([z.const('reply'), z.const('busy'), z.const('reach')])) })).default([]),
@@ -99,7 +100,7 @@ export async function apply(ctx, config) {
99
100
  const dshHome = resolveDshHome();
100
101
  const worldDir = join(dshHome, 'worlds', config.worldId);
101
102
  const store = createArchiveStore({ ...config, root: dshHome });
102
- const power = createWorldSwitch(worldDir, config.archiveScope ?? 'workspace');
103
+ const power = createWorldSwitch(worldDir, config.archiveScope ?? 'workspace', config.fallbackWakeTime);
103
104
  const memoryConfig = { ...config, archiveScope: power.archiveScope() };
104
105
  const faults = new Faults();
105
106
  let photoStore;
@@ -120,7 +121,7 @@ export async function apply(ctx, config) {
120
121
  const personaFile = config.personaFile || join(worldDir, 'persona.md');
121
122
  const worldPromptFile = config.worldPromptFile || join(worldDir, 'world-prompt.md');
122
123
  const roomDir = join(worldDir, 'room');
123
- const options = { worldDir, roomDir, diaryDir: config.diaryDir || join(worldDir, 'diary'), selfFile, fallbackWakeTime: config.fallbackWakeTime, timeZone: config.timeZone, alarmFile: config.alarmTemplateFile || join(worldDir, 'alarm.md') };
124
+ const options = { worldDir, roomDir, diaryDir: config.diaryDir || join(worldDir, 'diary'), selfFile, schedule: () => ({ review: power.reviewTime(), wake: power.wakeTime() }), timeZone: config.timeZone, alarmFile: config.alarmTemplateFile || join(worldDir, 'alarm.md') };
124
125
  /** The name in her persona comes first, then the configured one. */
125
126
  const names = () => worldNames({ ...config, companionName: readPersona(personaFile).名字 || config.companionName });
126
127
  const lifeStore = (() => {
@@ -376,8 +377,8 @@ export async function apply(ctx, config) {
376
377
  if (config.bridge)
377
378
  lifeCtx.effect(() => webServer.register(compactRoute(() => bridge, () => !power.running() || !life ? '请先启动世界生活线' : homeApply.request(), config.allowedHosts)), 'dsh-world compact route');
378
379
  // Her album lives in her room, so the console shows it whether or not the life line is running.
379
- const sources = consoleSources({ ctx: lifeCtx, config: memoryConfig, archive: store, longTerm: memoryService, names, ...(lifeStore ? { lifeStore } : {}), life: () => life, homeApply: homeApply.snapshot, compactAfterReview: power.compactAfterReview, photos, diaryDir: options.diaryDir, running: power.running, dailyBudget: power.dailyBudget, memoryTurns: power.memoryTurns, selectedArchiveScope: power.selectedArchiveScope, workspacePermissions: permissions.snapshot, wechat: () => wechat ? { ...wechat.status(), adapter: adapter?.status() ?? null } : undefined, archiveSession, native: () => qqNative?.status() ?? null,
380
- modules: () => ({ wechat: { available: config.wechat, enabled: power.wechatEnabled(), running: wechat !== undefined }, qq: { available: Boolean(config.qqNative?.enabled), enabled: power.qqEnabled(), running: qqNative !== undefined, ...(qqSdk.needsRestart() ? { restartRequired: true } : {}) } }), faults: () => [...faults.list(), ...(memory?.faults() ?? []), ...(bridge?.faults() ?? []), ...memoryHealth()] });
380
+ const sources = consoleSources({ ctx: lifeCtx, config: memoryConfig, archive: store, longTerm: memoryService, names, ...(lifeStore ? { lifeStore } : {}), life: () => life, homeApply: homeApply.snapshot, compactAfterReview: power.compactAfterReview, ...(config.life ? { schedule: () => ({ review: power.reviewTime(), wake: power.wakeTime(), defaults: { review: DEFAULT_REVIEW_TIME, wake: config.fallbackWakeTime } }) } : {}), photos, diaryDir: options.diaryDir, running: power.running, dailyBudget: power.dailyBudget, memoryTurns: power.memoryTurns, selectedArchiveScope: power.selectedArchiveScope, workspacePermissions: permissions.snapshot, wechat: () => wechat ? { ...wechat.status(), adapter: adapter?.status() ?? null } : undefined, archiveSession, native: () => qqNative?.status() ?? null,
381
+ modules: () => ({ wechat: { available: config.wechat, enabled: power.wechatEnabled(), running: wechat !== undefined }, qq: { available: Boolean(config.qqNative?.enabled), enabled: power.qqEnabled(), running: qqNative !== undefined, ...(qqSdk.needsRestart() ? { restartRequired: true } : {}) } }), faults: () => [...faults.list(), ...(adapter?.status().error ? [`微信适配器:${adapter.status().error}`] : []), ...(memory?.faults() ?? []), ...(bridge?.faults() ?? []), ...memoryHealth()] });
381
382
  const actions = {
382
383
  async start() {
383
384
  if (power.running())
@@ -413,6 +414,7 @@ export async function apply(ctx, config) {
413
414
  setMemoryTurns: turns => { power.setMemoryTurns(turns); sources.invalidate(); },
414
415
  setWorkspacePermission: permission => { permissions.set(permission); sources.invalidate(); },
415
416
  setCompactAfterReview: on => { power.setCompactAfterReview(on); sources.invalidate(); },
417
+ setSchedule: next => { power.setSchedule(next); life?.reschedule(); sources.invalidate(); },
416
418
  async setModules(patch) {
417
419
  if (patch.wechat !== undefined && !config.wechat)
418
420
  return '没有配置微信模块(配置里 wechat: true)';
@@ -1,4 +1,6 @@
1
1
  import type { ActivityRecord } from './types.ts';
2
+ /** Path strings under pathKeys at any depth, so nested operation arrays are covered. */
3
+ export declare function collectPaths(value: unknown, keyed: boolean, out: string[]): string[];
2
4
  /** Shell commands cannot be reliably scoped, so they always count as outside the room. The path check is lexical: symlinks/junctions, `~` and `%VAR%` are not resolved. */
3
5
  export declare function summarizeCall(tool: string, argumentsJson: string, roomDir: string): {
4
6
  summary: string;
@@ -3,7 +3,7 @@ const shells = new Set(['pwsh', 'bash', 'powershell', 'shell']);
3
3
  const pathKeys = new Set(['path', 'file_path', 'filePath', 'paths', 'cwd', 'directory', 'dir', 'target', 'source', 'destination', 'root', 'folder']);
4
4
  const clip = (text) => Array.from(text.replace(/\s+/g, ' ').trim()).slice(0, 160).join('');
5
5
  /** Path strings under pathKeys at any depth, so nested operation arrays are covered. */
6
- function collectPaths(value, keyed, out) {
6
+ export function collectPaths(value, keyed, out) {
7
7
  if (typeof value === 'string') {
8
8
  if (keyed)
9
9
  out.push(value);
@@ -1,7 +1,10 @@
1
1
  import type { Alarm, Review } from './types.ts';
2
2
  import { type AlarmMessages } from './messages.ts';
3
- /** Every evening at this local time she looks back on the day. */
4
- export declare const REVIEW_TIME = "23:00";
3
+ /** The local time of her evening look back unless the console sets another. */
4
+ export declare const DEFAULT_REVIEW_TIME = "23:00";
5
+ /** A local time of day, HH:MM on the 24-hour clock. */
6
+ export declare const CLOCK_TIME: RegExp;
7
+ export declare const validClockTime: (value: unknown) => value is string;
5
8
  export declare function resolveAlarmTime(input: {
6
9
  at?: string;
7
10
  after_minutes?: number;
@@ -17,8 +20,13 @@ export declare function formatDuration(ms: number): string;
17
20
  export declare function wakeText(alarm: Alarm, now: Date, timeZone: string, fallbackWakeTime: string, messages?: AlarmMessages, extra?: Record<string, string>): string;
18
21
  /** What a new home says the moment it is built, or her home when her world starts again. */
19
22
  export declare function greetingText(kind: 'arrival' | 'return', timeZone: string, fallbackWakeTime: string, messages?: AlarmMessages, extra?: Record<string, string>): string;
20
- /** The next evening look back after `now`, and the day it looks back on. */
21
- export declare function nextReview(now: Date, timeZone: string): Review;
23
+ /** The next look back after `now` at local `time`, and the day it looks back on: one before noon looks back on the day before. */
24
+ export declare function nextReview(now: Date, timeZone: string, time?: string): Review;
25
+ /**
26
+ * The look back on `day` once its time has changed to `time`: no day is looked back on twice or skipped. Moved
27
+ * earlier than now, the day's look back is due at once.
28
+ */
29
+ export declare function reviewOf(day: string, now: Date, timeZone: string, time: string): Review;
22
30
  /** Where her day is written down; a file that does not exist is left out. */
23
31
  export interface ReviewFiles {
24
32
  conversations?: string;
package/lib/life/alarm.js CHANGED
@@ -2,8 +2,11 @@ import { formatLocalTime } from "../timeContext.js";
2
2
  import { ALARM_MARK, exampleTime, fillMessage, readAlarmMessages } from "./messages.js";
3
3
  const MIN_ALARM_MS = 60_000;
4
4
  const LATE_NOTICE_MS = 2 * 60_000;
5
- /** Every evening at this local time she looks back on the day. */
6
- export const REVIEW_TIME = '23:00';
5
+ /** The local time of her evening look back unless the console sets another. */
6
+ export const DEFAULT_REVIEW_TIME = '23:00';
7
+ /** A local time of day, HH:MM on the 24-hour clock. */
8
+ export const CLOCK_TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
9
+ export const validClockTime = (value) => typeof value === 'string' && CLOCK_TIME.test(value);
7
10
  export function resolveAlarmTime(input, now, timeZone = 'UTC') {
8
11
  if ((input.at === undefined) === (input.after_minutes === undefined))
9
12
  throw new Error('请只给 at 或 after_minutes 其中一个');
@@ -83,10 +86,22 @@ export function greetingText(kind, timeZone, fallbackWakeTime, messages = readAl
83
86
  const base = { ...extra, timeZone, fallbackWakeTime };
84
87
  return withTail(fillMessage(messages, kind === 'arrival' ? '第一次到家' : '重新开始', base), messages, base);
85
88
  }
86
- /** The next evening look back after `now`, and the day it looks back on. */
87
- export function nextReview(now, timeZone) {
88
- const at = nextLocalTime(now, REVIEW_TIME, timeZone);
89
- return { at: at.toISOString(), day: formatLocalTime(at, timeZone).slice(0, 10) };
89
+ const dayBefore = (day) => new Date(Date.parse(`${day}T00:00:00Z`) - 86_400_000).toISOString().slice(0, 10);
90
+ /** The next look back after `now` at local `time`, and the day it looks back on: one before noon looks back on the day before. */
91
+ export function nextReview(now, timeZone, time = DEFAULT_REVIEW_TIME) {
92
+ const at = nextLocalTime(now, time, timeZone);
93
+ const date = formatLocalTime(at, timeZone).slice(0, 10);
94
+ return { at: at.toISOString(), day: time < '12:00' ? dayBefore(date) : date };
95
+ }
96
+ /**
97
+ * The look back on `day` once its time has changed to `time`: no day is looked back on twice or skipped. Moved
98
+ * earlier than now, the day's look back is due at once.
99
+ */
100
+ export function reviewOf(day, now, timeZone, time) {
101
+ let review = nextReview(now, timeZone, time);
102
+ while (review.day < day)
103
+ review = nextReview(new Date(review.at), timeZone, time);
104
+ return review.day > day ? { at: now.toISOString(), day } : review;
90
105
  }
91
106
  /** The evening look back: the day, where to read it, and her 我是谁 to rewrite if she has changed. */
92
107
  export function reviewText(review, now, files, timeZone, fallbackWakeTime, messages = readAlarmMessages(undefined), extra = {}) {
@@ -2,3 +2,9 @@ export declare function createDiaryReader(diaryDir: string): {
2
2
  dates: () => string[];
3
3
  read: (date: string) => string | undefined;
4
4
  };
5
+ /**
6
+ * Why a file tool call may not run: it changes the diary of a day already closed. A wrong or outgrown entry is
7
+ * corrected in today's diary, so what she wrote then stays as she wrote it. Only `YYYY-MM-DD.md` files directly in the
8
+ * diary directory are dated diaries; any other file there is left to her. Relative paths resolve against `cwd`.
9
+ */
10
+ export declare function closedDiaryRefusal(tool: string, args: unknown, diaryDir: string, cwd: string, open: ReadonlySet<string>, today: string): string | undefined;
package/lib/life/diary.js CHANGED
@@ -1,9 +1,30 @@
1
1
  import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
- import { join } from 'node:path';
2
+ import { basename, dirname, join, relative, resolve } from 'node:path';
3
+ import { collectPaths } from "./activity.js";
3
4
  const datePattern = /^\d{4}-\d{2}-\d{2}$/;
5
+ const diaryName = /^(\d{4}-\d{2}-\d{2})\.md$/;
4
6
  export function createDiaryReader(diaryDir) {
5
- const dates = () => existsSync(diaryDir) ? readdirSync(diaryDir).filter(name => /^\d{4}-\d{2}-\d{2}\.md$/.test(name)).map(name => name.slice(0, 10)).sort().reverse() : [];
7
+ const dates = () => existsSync(diaryDir) ? readdirSync(diaryDir).filter(name => diaryName.test(name)).map(name => name.slice(0, 10)).sort().reverse() : [];
6
8
  /** Only YYYY-MM-DD names are accepted, so a date can never escape the diary directory. */
7
9
  const read = (date) => { const file = join(diaryDir, `${date}.md`); return datePattern.test(date) && existsSync(file) ? readFileSync(file, 'utf8') : undefined; };
8
10
  return { dates, read };
9
11
  }
12
+ /** The host's file tools that change a file; reading tools and the shell are not judged. */
13
+ const DIARY_WRITERS = new Set(['write', 'edit']);
14
+ /**
15
+ * Why a file tool call may not run: it changes the diary of a day already closed. A wrong or outgrown entry is
16
+ * corrected in today's diary, so what she wrote then stays as she wrote it. Only `YYYY-MM-DD.md` files directly in the
17
+ * diary directory are dated diaries; any other file there is left to her. Relative paths resolve against `cwd`.
18
+ */
19
+ export function closedDiaryRefusal(tool, args, diaryDir, cwd, open, today) {
20
+ if (!DIARY_WRITERS.has(tool))
21
+ return undefined;
22
+ for (const path of collectPaths(args, false, [])) {
23
+ const file = resolve(cwd, path);
24
+ const day = diaryName.exec(basename(file))?.[1];
25
+ if (!day || open.has(day) || relative(resolve(diaryDir), dirname(file)) !== '')
26
+ continue;
27
+ return `${day} 的日记已经合上了,不能再改。写错了或者现在想法不一样了,就写进今天(${today})的日记:哪里记错了、现在怎么看。`;
28
+ }
29
+ return undefined;
30
+ }
@@ -44,6 +44,7 @@ export declare function createLifeRuntime(deps: LifeDeps): {
44
44
  checkAlarm: () => string;
45
45
  cancelAlarm: () => string;
46
46
  deliver: () => Promise<void>;
47
+ reschedule: () => void;
47
48
  snapshot: () => {
48
49
  homeSessionId: string | undefined;
49
50
  alarm: Alarm | undefined;
@@ -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
  }
package/lib/memory.js CHANGED
@@ -38,9 +38,6 @@ export function normalizeFind(input, timeZone) {
38
38
  const kindsInput = input.kinds;
39
39
  if (kindsInput !== undefined && kindsInput !== null && (!Array.isArray(kindsInput) || kindsInput.some(kind => !MEMORY_KINDS.includes(kind))))
40
40
  throw new MemoryError('invalidQuery', `kinds 只能是 ${MEMORY_KINDS.join('、')}`);
41
- const history = input.history;
42
- if (history !== undefined && history !== null && typeof history !== 'boolean')
43
- throw new MemoryError('invalidQuery', 'history 必须是 true 或 false');
44
41
  const order = input.order ?? 'newest';
45
42
  if (order !== 'newest' && order !== 'oldest')
46
43
  throw new MemoryError('invalidQuery', 'order 只能是 newest 或 oldest');
@@ -50,7 +47,7 @@ export function normalizeFind(input, timeZone) {
50
47
  const kinds = kindsInput?.length ? [...new Set(kindsInput)] : undefined;
51
48
  const sourceId = text(input, 'sourceId', 300), turnId = text(input, 'turnId', 300), linkedTo = text(input, 'linkedTo', 2000), cursor = text(input, 'cursor', 4000);
52
49
  return {
53
- history: history === true, order, limit: whole(input, 'limit', DEFAULT_FIND_LIMIT, 1, MAX_FIND_LIMIT),
50
+ order, limit: whole(input, 'limit', DEFAULT_FIND_LIMIT, 1, MAX_FIND_LIMIT),
54
51
  ...(query === undefined ? {} : { query }), ...(kinds ? { kinds } : {}), ...(fromMs === undefined ? {} : { fromMs }), ...(toMs === undefined ? {} : { toMs }),
55
52
  ...(sourceId ? { sourceId } : {}), ...(turnId ? { turnId } : {}), ...(linkedTo ? { linkedTo } : {}), ...(cursor ? { cursor } : {}),
56
53
  };
@@ -1,10 +1,7 @@
1
1
  import { type MemoryKind, type TimeBasis } from './memoryStore.ts';
2
- /** Where she keeps what she writes. A file authorizes that file alone; a directory its markdown and text files, a few levels deep. */
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
3
  export interface MemorySources {
4
4
  diaryDir?: string;
5
- selfFile?: string;
6
- focusFile?: string;
7
- knowledgeDir?: string;
8
5
  }
9
6
  export type AuthorKind = Exclude<MemoryKind, 'conversation'>;
10
7
  /** One file as she wrote it, with the time it has and the ref that is bound to this exact text. */