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.
- package/CHANGELOG.md +39 -0
- package/CONTRIBUTING.md +163 -161
- package/NOTES.md +184 -152
- package/README.md +237 -227
- package/client/index.js +894 -738
- package/lib/archive.d.ts +3 -1
- package/lib/archive.js +6 -4
- package/lib/compaction.js +8 -0
- package/lib/compactionSwap.d.ts +29 -2
- package/lib/compactionSwap.js +62 -7
- package/lib/console/homeApply.d.ts +11 -2
- package/lib/console/homeApply.js +36 -7
- package/lib/console/routes.d.ts +13 -0
- package/lib/console/routes.js +43 -0
- package/lib/console/snapshot.d.ts +8 -0
- package/lib/console/snapshot.js +4 -2
- package/lib/ecosystem/bridge/route.d.ts +7 -0
- package/lib/ecosystem/bridge/route.js +30 -0
- package/lib/ecosystem/qq/route.d.ts +2 -1
- package/lib/ecosystem/qq/route.js +10 -2
- package/lib/ecosystem/qq-native/batch.d.ts +2 -0
- package/lib/ecosystem/qq-native/batch.js +3 -1
- package/lib/ecosystem/qq-native/index.d.ts +2 -0
- package/lib/ecosystem/qq-native/index.js +4 -0
- package/lib/ecosystem/qq-native/replies.d.ts +6 -1
- package/lib/ecosystem/qq-native/replies.js +19 -1
- package/lib/ecosystem/shared/context.d.ts +1 -1
- package/lib/ecosystem/shared/context.js +1 -1
- package/lib/ecosystem/shared/identity.d.ts +12 -0
- package/lib/ecosystem/shared/identity.js +17 -1
- package/lib/ecosystem/shared/turn.d.ts +8 -5
- package/lib/ecosystem/shared/turn.js +16 -17
- package/lib/ecosystem/wechat/archive.d.ts +2 -0
- package/lib/ecosystem/wechat/archive.js +3 -1
- package/lib/ecosystem/wechat/home.js +9 -4
- package/lib/ecosystem/wechat/messages.d.ts +11 -0
- package/lib/ecosystem/wechat/messages.js +9 -1
- package/lib/ecosystem/wechat/sending.js +36 -9
- package/lib/ecosystem/wechat/supervisor.d.ts +11 -2
- package/lib/ecosystem/wechat/supervisor.js +90 -9
- package/lib/history.d.ts +6 -4
- package/lib/history.js +61 -12
- package/lib/hostContract.d.ts +1 -0
- package/lib/index.js +41 -14
- package/lib/life/activity.d.ts +2 -0
- package/lib/life/activity.js +1 -1
- package/lib/life/alarm.d.ts +12 -4
- package/lib/life/alarm.js +21 -6
- package/lib/life/diary.d.ts +6 -0
- package/lib/life/diary.js +23 -2
- package/lib/life/runtime.d.ts +1 -0
- package/lib/life/runtime.js +57 -9
- package/lib/life/toolRegistry.d.ts +4 -3
- package/lib/life/toolRegistry.js +13 -3
- package/lib/life/types.d.ts +6 -1
- package/lib/memory.d.ts +57 -0
- package/lib/memory.js +207 -0
- package/lib/memoryFiles.d.ts +50 -0
- package/lib/memoryFiles.js +168 -0
- package/lib/memoryStore.d.ts +112 -0
- package/lib/memoryStore.js +159 -0
- package/lib/memoryTools.d.ts +31 -0
- package/lib/memoryTools.js +106 -0
- package/lib/promptSection.d.ts +2 -0
- package/lib/runtime.d.ts +1 -1
- package/lib/runtime.js +62 -75
- package/lib/sourceArchive.d.ts +1 -0
- package/lib/sourceArchive.js +4 -5
- package/lib/store.d.ts +15 -1
- package/lib/store.js +12 -2
- package/lib/types.d.ts +1 -4
- package/lib/worldPrompt.d.ts +6 -0
- package/lib/worldPrompt.js +8 -2
- package/lib/worldSwitch.d.ts +9 -1
- package/lib/worldSwitch.js +14 -1
- package/package.json +128 -117
- package/scripts/compact-home.mjs +29 -0
- package/scripts/update-world.mjs +6 -4
- package/src/ecosystem/wechat/windows/README.md +7 -5
- package/src/ecosystem/wechat/windows/adapter.py +86 -31
- package/src/ecosystem/wechat/windows/engine/NOTICE.md +1 -1
- package/src/ecosystem/wechat/windows/engine/bridge.cpp +9 -1
- package/src/ecosystem/wechat/windows/engine/build.ps1 +8 -2
- package/src/ecosystem/wechat/windows/engine/profiles.json +56 -0
- package/src/ecosystem/wechat/windows/native.py +4 -1
- package/src/ecosystem/wechat/windows/outgoing.py +21 -0
- package/src/ecosystem/wechat/windows/sender.py +26 -6
- package/templates/alarm.md +3 -4
- package/templates/world-prompt-memory.md +10 -0
- package/templates/world-prompt.md +7 -2
|
@@ -1,26 +1,55 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
|
-
import { closeSync, existsSync, openSync, statSync, truncateSync } from 'node:fs';
|
|
3
|
-
import { dirname } from 'node:path';
|
|
2
|
+
import { closeSync, existsSync, openSync, readSync, statSync, truncateSync } from 'node:fs';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
4
|
import { fileURLToPath } from 'node:url';
|
|
5
5
|
/** The adapter script ships next to the sources; this resolves from both `src/` and the built `lib/`. */
|
|
6
6
|
export const ADAPTER_SCRIPT = fileURLToPath(new URL('../../../src/ecosystem/wechat/windows/adapter.py', import.meta.url));
|
|
7
|
+
/** The native bridge's build script, beside the bridge source the adapter checks its build against. */
|
|
8
|
+
export const BUILD_SCRIPT = fileURLToPath(new URL('../../../src/ecosystem/wechat/windows/engine/build.ps1', import.meta.url));
|
|
7
9
|
/** The adapter exits with this when a person must check WeChat and run `acknowledge`; restarting cannot help. */
|
|
8
10
|
export const EXIT_NEEDS_HUMAN = 2;
|
|
11
|
+
/** The adapter exits with this when no build of the native bridge matches its source (an upgrade changed it). */
|
|
12
|
+
export const EXIT_NEEDS_BUILD = 3;
|
|
9
13
|
const MAX_LOG_BYTES = 1024 * 1024;
|
|
10
14
|
const HEALTHY_MS = 60_000;
|
|
15
|
+
const BUILD_BY_HAND = '请在仓库里运行 wechat.ps1 Build,再在控制台重启适配器';
|
|
16
|
+
/** The last line the adapter wrote to its log after byte `from`: what it said as it stopped. */
|
|
17
|
+
function lastLine(file, from) {
|
|
18
|
+
try {
|
|
19
|
+
const size = statSync(file).size, length = Math.min(size - from, 4096);
|
|
20
|
+
if (length <= 0)
|
|
21
|
+
return undefined;
|
|
22
|
+
const buffer = Buffer.alloc(length), fd = openSync(file, 'r');
|
|
23
|
+
try {
|
|
24
|
+
readSync(fd, buffer, 0, length, size - length);
|
|
25
|
+
}
|
|
26
|
+
finally {
|
|
27
|
+
closeSync(fd);
|
|
28
|
+
}
|
|
29
|
+
return buffer.toString('utf8').split(/\r?\n/).map(line => line.trim()).filter(Boolean).at(-1);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
11
35
|
/**
|
|
12
36
|
* Runs the Windows WeChat adapter for as long as the world's WeChat module lives: started with the module,
|
|
13
37
|
* restarted with a growing delay when it exits or cannot start (a file missing during an upgrade comes back),
|
|
14
|
-
* and stopped (its whole process tree) with the module. An exit that says a person must act is not retried.
|
|
15
|
-
*
|
|
38
|
+
* and stopped (its whole process tree) with the module. An exit that says a person must act is not retried. An exit
|
|
39
|
+
* that says the native bridge needs building is answered by building it once into the `engine` folder beside the
|
|
40
|
+
* adapter's config (where the adapter looks) and starting it again; a build that fails, or still does not match,
|
|
41
|
+
* stops with what to do. The adapter itself waits for the same WeChat account to log in again, so a WeChat
|
|
42
|
+
* restart needs nothing from here.
|
|
16
43
|
*/
|
|
17
44
|
export function createAdapterSupervisor(deps) {
|
|
18
|
-
const script = deps.script ?? ADAPTER_SCRIPT;
|
|
45
|
+
const script = deps.script ?? ADAPTER_SCRIPT, buildScript = deps.buildScript ?? BUILD_SCRIPT;
|
|
19
46
|
const spawnProcess = deps.spawnProcess ?? spawn;
|
|
20
47
|
const minDelay = deps.minDelayMs ?? 1000, maxDelay = deps.maxDelayMs ?? 30_000;
|
|
21
48
|
let child;
|
|
22
49
|
let timer;
|
|
23
50
|
let stopped = false, replacing = false, needsHuman = false, started = false, failures = 0, restarts = 0;
|
|
51
|
+
/** `rebuilt`: the last start came right after a build, so needing one again means building cannot help. */
|
|
52
|
+
let building = false, rebuilt = false;
|
|
24
53
|
let lastExit = null, error = null;
|
|
25
54
|
let exited = Promise.resolve();
|
|
26
55
|
const killTree = deps.killTree ?? ((target) => {
|
|
@@ -35,6 +64,50 @@ export function createAdapterSupervisor(deps) {
|
|
|
35
64
|
deps.log(`dsh-world WeChat adapter not started: ${message}`);
|
|
36
65
|
schedule();
|
|
37
66
|
}
|
|
67
|
+
/** Not retried: only a person can fix it, and the console's restart tries again. */
|
|
68
|
+
function halted(message) {
|
|
69
|
+
error = message;
|
|
70
|
+
deps.log(`dsh-world WeChat adapter stopped: ${message}`);
|
|
71
|
+
}
|
|
72
|
+
function rebuild() {
|
|
73
|
+
if (rebuilt)
|
|
74
|
+
return halted(`原生桥刚重新构建过,仍然对不上它的源码;${BUILD_BY_HAND}`);
|
|
75
|
+
let fd;
|
|
76
|
+
try {
|
|
77
|
+
fd = openSync(deps.logFile, 'a');
|
|
78
|
+
}
|
|
79
|
+
catch (cause) {
|
|
80
|
+
return halted(`原生桥需要重新构建,但写不了适配器日志:${String(cause)}`);
|
|
81
|
+
}
|
|
82
|
+
let builder;
|
|
83
|
+
try {
|
|
84
|
+
builder = spawnProcess('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', buildScript, '-OutDir', join(dirname(deps.config), 'engine')], { stdio: ['ignore', fd, fd], windowsHide: true });
|
|
85
|
+
}
|
|
86
|
+
catch (cause) {
|
|
87
|
+
return halted(`原生桥需要重新构建,自动构建没能启动:${String(cause)};${BUILD_BY_HAND}`);
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
closeSync(fd);
|
|
91
|
+
}
|
|
92
|
+
building = true;
|
|
93
|
+
deps.log('dsh-world WeChat adapter: the native bridge no longer matches its source; building it again');
|
|
94
|
+
let done = false;
|
|
95
|
+
const finish = (ok) => {
|
|
96
|
+
if (done)
|
|
97
|
+
return;
|
|
98
|
+
done = true;
|
|
99
|
+
building = false;
|
|
100
|
+
// Stopped meanwhile, or started again by the module, which already launched it.
|
|
101
|
+
if (stopped || child)
|
|
102
|
+
return;
|
|
103
|
+
if (!ok)
|
|
104
|
+
return halted(`原生桥需要重新构建,自动构建没成功(详情在 wechat-adapter.log);${BUILD_BY_HAND}`);
|
|
105
|
+
rebuilt = true;
|
|
106
|
+
launch();
|
|
107
|
+
};
|
|
108
|
+
builder.once('exit', code => finish(code === 0));
|
|
109
|
+
builder.once('error', () => finish(false));
|
|
110
|
+
}
|
|
38
111
|
function launch() {
|
|
39
112
|
if (stopped)
|
|
40
113
|
return;
|
|
@@ -42,11 +115,12 @@ export function createAdapterSupervisor(deps) {
|
|
|
42
115
|
if (!existsSync(path))
|
|
43
116
|
return fail(`${what}不存在:${path}`);
|
|
44
117
|
}
|
|
45
|
-
let fd;
|
|
118
|
+
let fd, logFrom;
|
|
46
119
|
try {
|
|
47
120
|
if (existsSync(deps.logFile) && statSync(deps.logFile).size > MAX_LOG_BYTES)
|
|
48
121
|
truncateSync(deps.logFile, 0);
|
|
49
122
|
fd = openSync(deps.logFile, 'a');
|
|
123
|
+
logFrom = statSync(deps.logFile).size;
|
|
50
124
|
}
|
|
51
125
|
catch (cause) {
|
|
52
126
|
return fail(`无法写适配器日志:${String(cause)}`);
|
|
@@ -75,14 +149,19 @@ export function createAdapterSupervisor(deps) {
|
|
|
75
149
|
done = true;
|
|
76
150
|
if (child === current)
|
|
77
151
|
child = undefined;
|
|
78
|
-
|
|
152
|
+
const said = lastLine(deps.logFile, logFrom);
|
|
153
|
+
lastExit = said ? `${text}:${said}` : text;
|
|
79
154
|
if (Date.now() - startedAt > HEALTHY_MS)
|
|
80
155
|
failures = 0;
|
|
156
|
+
if (code !== EXIT_NEEDS_BUILD)
|
|
157
|
+
rebuilt = false;
|
|
81
158
|
if (!stopped && !replacing) {
|
|
82
159
|
if (code === EXIT_NEEDS_HUMAN) {
|
|
83
160
|
needsHuman = true;
|
|
84
161
|
deps.log('dsh-world WeChat adapter stopped: a message needs checking by a person (run acknowledge, then restart it from the console)');
|
|
85
162
|
}
|
|
163
|
+
else if (code === EXIT_NEEDS_BUILD)
|
|
164
|
+
rebuild();
|
|
86
165
|
else {
|
|
87
166
|
deps.log(`dsh-world WeChat adapter exited (${text}); restarting`);
|
|
88
167
|
schedule();
|
|
@@ -116,7 +195,8 @@ export function createAdapterSupervisor(deps) {
|
|
|
116
195
|
start() { stopped = false; launch(); },
|
|
117
196
|
/** The console's restart: also the way out of "a person must check" once the person has. */
|
|
118
197
|
async restart() {
|
|
119
|
-
|
|
198
|
+
// A build under way starts the adapter itself when it is done.
|
|
199
|
+
if (stopped || building)
|
|
120
200
|
return;
|
|
121
201
|
replacing = true;
|
|
122
202
|
try {
|
|
@@ -127,12 +207,13 @@ export function createAdapterSupervisor(deps) {
|
|
|
127
207
|
}
|
|
128
208
|
needsHuman = false;
|
|
129
209
|
failures = 0;
|
|
210
|
+
rebuilt = false;
|
|
130
211
|
launch();
|
|
131
212
|
},
|
|
132
213
|
async stop() {
|
|
133
214
|
stopped = true;
|
|
134
215
|
await halt();
|
|
135
216
|
},
|
|
136
|
-
status() { return { running: child !== undefined, pid: child?.pid ?? null, restarts, lastExit, error, needsHuman }; },
|
|
217
|
+
status() { return { running: child !== undefined, pid: child?.pid ?? null, restarts, lastExit, error, needsHuman, building }; },
|
|
137
218
|
};
|
|
138
219
|
}
|
package/lib/history.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { ArchiveReader, ConversationTurn } from './types.ts';
|
|
2
2
|
import { type WorldNames } from './worldPrompt.ts';
|
|
3
3
|
export declare function createHistory(store: ArchiveReader): {
|
|
4
|
-
loadRecentTurns: (
|
|
4
|
+
loadRecentTurns: (count: number, includes?: (sessionId: string) => boolean) => Promise<ConversationTurn[]>;
|
|
5
5
|
};
|
|
6
6
|
export declare function excludePresentMessages(turns: readonly ConversationTurn[], sourceMessageIds: ReadonlySet<string>): ConversationTurn[];
|
|
7
7
|
/** Short stable conversation marker: the first eight characters of the host session id. */
|
|
@@ -9,8 +9,10 @@ export declare function sessionMarker(sessionId: string): string;
|
|
|
9
9
|
export declare function shortenLocalImages(content: string): string;
|
|
10
10
|
/**
|
|
11
11
|
* Model-facing memory: one JSON line per turn with only the conversation marker and, per message, role,
|
|
12
|
-
* local time and text. Archive identifiers stay in the archive;
|
|
13
|
-
*
|
|
14
|
-
*
|
|
12
|
+
* local time (to the minute) and text. Archive identifiers and channel accounts stay in the archive; a line from
|
|
13
|
+
* WeChat or QQ says only which chat it was (`via`), who in a group (`who`) and, for what she sent, whether it went
|
|
14
|
+
* out (`sent`). Times are stored in UTC and rendered in the configured zone. Her own messages are labelled with her
|
|
15
|
+
* name, so the memory reads as hers rather than a generic assistant's. `homeOnly` (archiveScope home) says the
|
|
16
|
+
* memory is her time at home.
|
|
15
17
|
*/
|
|
16
18
|
export declare function renderHistory(turns: readonly ConversationTurn[], timeZone: string, names: WorldNames, homeOnly?: boolean): string;
|
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(
|
|
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({
|
|
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(
|
|
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:
|
|
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;
|
|
62
|
-
*
|
|
63
|
-
*
|
|
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
|
|
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 =>
|
|
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 =
|
|
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 =
|
|
79
|
-
|
|
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/hostContract.d.ts
CHANGED
package/lib/index.js
CHANGED
|
@@ -3,12 +3,12 @@ import { join } from 'node:path';
|
|
|
3
3
|
import z from '@deepseek-ai/schemastery';
|
|
4
4
|
import { resolveDshHome } from '@deepseek-ai/dsh-home-paths';
|
|
5
5
|
import { createBridge } from "./ecosystem/bridge/bridge.js";
|
|
6
|
-
import { bridgeRoute } from "./ecosystem/bridge/route.js";
|
|
6
|
+
import { bridgeRoute, compactRoute } from "./ecosystem/bridge/route.js";
|
|
7
7
|
import { consoleRoute } from "./console/routes.js";
|
|
8
8
|
import { consoleSources } from "./console/snapshot.js";
|
|
9
|
-
import { createHomeApply } from "./console/homeApply.js";
|
|
9
|
+
import { compactionFor, createHomeApply } from "./console/homeApply.js";
|
|
10
10
|
import { errorText, Faults } from "./faults.js";
|
|
11
|
-
import { swapCompactionOnce } from "./compactionSwap.js";
|
|
11
|
+
import { swapCompactionOnce, swapPresetCompaction, swapStockCompaction } from "./compactionSwap.js";
|
|
12
12
|
import { hostLife } from "./life/host.js";
|
|
13
13
|
import { createLifeStore, durableWrite } from "./life/lifeStore.js";
|
|
14
14
|
import { toastSupported, windowsToast } from "./life/notify.js";
|
|
@@ -17,10 +17,12 @@ import { createOutlet } from "./ecosystem/shared/outlets.js";
|
|
|
17
17
|
import { readPersona, writePersona } from "./persona.js";
|
|
18
18
|
import { qqRoute } from "./ecosystem/qq/route.js";
|
|
19
19
|
import { createConsoleDoors, discoverSnowlumaHome } from "./ecosystem/qq/panel.js";
|
|
20
|
+
import { createMemory } from "./memory.js";
|
|
20
21
|
import { createWorldRuntime } from "./runtime.js";
|
|
21
22
|
import { createArchiveStore } from "./store.js";
|
|
22
|
-
import { DEFAULT_TEMPLATE_FILE, roomTitle, worldNames } from "./worldPrompt.js";
|
|
23
|
+
import { DEFAULT_TEMPLATE_FILE, MEMORY_SNIPPET_FILE, memoryTemplateGaps, roomTitle, worldNames } from "./worldPrompt.js";
|
|
23
24
|
import { createWorldSwitch } from "./worldSwitch.js";
|
|
25
|
+
import { CLOCK_TIME, DEFAULT_REVIEW_TIME } from "./life/alarm.js";
|
|
24
26
|
import { createWechatModule } from "./ecosystem/wechat/index.js";
|
|
25
27
|
import { createWechatRecorder } from "./ecosystem/wechat/archive.js";
|
|
26
28
|
import { createAdapterSupervisor } from "./ecosystem/wechat/supervisor.js";
|
|
@@ -42,7 +44,7 @@ export const Config = z.object({
|
|
|
42
44
|
archiveScope: z.union([z.const('home').description('仅家会话'), z.const('workspace').description('家所在工作区'), z.transform(z.const('world').hidden(), () => 'workspace').hidden()]).default('workspace').description('记忆归档范围,修改后重启生效'),
|
|
43
45
|
// Install means the tool-free compaction: the first start rewrites the profile's stock compaction row (see README); false leaves it alone.
|
|
44
46
|
replaceCompaction: z.boolean().default(true),
|
|
45
|
-
life: z.boolean().default(true), diaryDir: z.string(), fallbackWakeTime: z.string().pattern(
|
|
47
|
+
life: z.boolean().default(true), diaryDir: z.string(), fallbackWakeTime: z.string().pattern(CLOCK_TIME).default('09:00'),
|
|
46
48
|
selfFile: z.string(), worldPromptFile: z.string(), alarmTemplateFile: z.string(), personaFile: z.string(),
|
|
47
49
|
// Where her words go outside DSH; no app is known by name (see README for the push body).
|
|
48
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([]),
|
|
@@ -98,7 +100,7 @@ export async function apply(ctx, config) {
|
|
|
98
100
|
const dshHome = resolveDshHome();
|
|
99
101
|
const worldDir = join(dshHome, 'worlds', config.worldId);
|
|
100
102
|
const store = createArchiveStore({ ...config, root: dshHome });
|
|
101
|
-
const power = createWorldSwitch(worldDir, config.archiveScope ?? 'workspace');
|
|
103
|
+
const power = createWorldSwitch(worldDir, config.archiveScope ?? 'workspace', config.fallbackWakeTime);
|
|
102
104
|
const memoryConfig = { ...config, archiveScope: power.archiveScope() };
|
|
103
105
|
const faults = new Faults();
|
|
104
106
|
let photoStore;
|
|
@@ -118,7 +120,8 @@ export async function apply(ctx, config) {
|
|
|
118
120
|
const selfFile = config.selfFile || join(worldDir, 'room', '我是谁.md');
|
|
119
121
|
const personaFile = config.personaFile || join(worldDir, 'persona.md');
|
|
120
122
|
const worldPromptFile = config.worldPromptFile || join(worldDir, 'world-prompt.md');
|
|
121
|
-
const
|
|
123
|
+
const roomDir = join(worldDir, 'room');
|
|
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') };
|
|
122
125
|
/** The name in her persona comes first, then the configured one. */
|
|
123
126
|
const names = () => worldNames({ ...config, companionName: readPersona(personaFile).名字 || config.companionName });
|
|
124
127
|
const lifeStore = (() => {
|
|
@@ -142,13 +145,17 @@ export async function apply(ctx, config) {
|
|
|
142
145
|
/** Where her world reaches: her room's workspace, and in it the sessions of her preset. */
|
|
143
146
|
const inWorkspace = createWorkspaceMembership(ctx, options.roomDir);
|
|
144
147
|
const inWorldSession = (session) => inWorld(session, config, inWorkspace);
|
|
148
|
+
/** Long-term memory over the archive and her own files; the tools and the console are two doors to it. */
|
|
149
|
+
const memoryService = createMemory({ store: store.memory, timeZone: config.timeZone, sources: { diaryDir: options.diaryDir }, visible: id => archiveSession(id) });
|
|
150
|
+
/** What is wrong with long-term memory, in the console's health list: a source that could not be read. */
|
|
151
|
+
const memoryHealth = () => memoryService.status().failures.map(failure => `记忆来源 ${failure.sourceId}:${failure.message}`);
|
|
145
152
|
let memory;
|
|
146
153
|
let stopLifeLine;
|
|
147
154
|
async function startMemory(fresh) {
|
|
148
155
|
if (memory)
|
|
149
156
|
return;
|
|
150
|
-
const prompt = { file: worldPromptFile, persona: personaFile, conversationsDir: join(worldDir, 'conversations'), names: names(), ...(config.life ? { life: options } : {}) };
|
|
151
|
-
memory = createWorldRuntime(ctx, { ...memoryConfig, selfFile }, store, { prompt, names, isHome: id => isHome(id), archiveSession, inWorkspace }, power.memoryTurns);
|
|
157
|
+
const prompt = { file: worldPromptFile, persona: personaFile, conversationsDir: join(worldDir, 'conversations'), names: names(), memoryTools: true, ...(config.life ? { life: options } : {}) };
|
|
158
|
+
memory = createWorldRuntime(ctx, { ...memoryConfig, selfFile }, store, { prompt, names, isHome: id => isHome(id), archiveSession, inWorkspace, memory: memoryService }, power.memoryTurns);
|
|
152
159
|
await memory.start({ fresh });
|
|
153
160
|
}
|
|
154
161
|
async function stopMemory() {
|
|
@@ -172,8 +179,21 @@ export async function apply(ctx, config) {
|
|
|
172
179
|
ctx.inject(['sessionController', 'permissionPresets', 'webServer'], async (lifeCtx) => {
|
|
173
180
|
const webServer = lifeCtx.webServer;
|
|
174
181
|
const host = hostLife(lifeCtx);
|
|
175
|
-
|
|
182
|
+
const configEditor = lifeCtx.get('configEditor');
|
|
183
|
+
const swapCompaction = () => swapCompactionOnce({ enabled: config.replaceCompaction, profileDir: lifeCtx.get('profileContext')?.dir, done: power.compactionSwapped, markDone: power.markCompactionSwapped,
|
|
184
|
+
swap: async (dir) => { const row = swapStockCompaction(dir); return row.status === 'unchanged' && configEditor ? swapPresetCompaction(configEditor, config.agentPreset, dir) : row; },
|
|
176
185
|
report: message => { faults.set('compaction-swap', message); lifeCtx.logger.warn(`dsh-world: ${message}`); } });
|
|
186
|
+
// The preset row the editor rewrites is active only once the host has finished loading.
|
|
187
|
+
const appReady = lifeCtx.get('appReady');
|
|
188
|
+
if (!appReady)
|
|
189
|
+
void swapCompaction();
|
|
190
|
+
else
|
|
191
|
+
lifeCtx.effect(() => {
|
|
192
|
+
let closed = false;
|
|
193
|
+
const cancel = appReady.onReady(() => { if (!closed)
|
|
194
|
+
void swapCompaction(); });
|
|
195
|
+
return () => { closed = true; cancel(); };
|
|
196
|
+
}, 'dsh-world compaction swap');
|
|
177
197
|
const permissions = createWorkspacePermissions(lifeCtx, options.roomDir, power);
|
|
178
198
|
// QQ 的两扇门:她自己那条 OneBot 通道的状态与开关,以及 SnowLuma 的控制台。**无条件注册** —— 通道
|
|
179
199
|
// 关着的时候 /native 回 null,而 SnowLuma 那扇门跟通道没关系。(这里原来还有一半是给外面那个
|
|
@@ -202,10 +222,14 @@ export async function apply(ctx, config) {
|
|
|
202
222
|
home: async () => { if (!life)
|
|
203
223
|
throw new Error('请先启动世界生活线'); return life.home(); },
|
|
204
224
|
isHome: agent => !!life?.isHome(agent.id) && ctx.agents.get(agent.id) === agent && !host.isArchived(agent.id) && inWorldSession(agent.session),
|
|
205
|
-
compaction:
|
|
225
|
+
compaction: agent => compactionFor(lifeCtx, agent),
|
|
206
226
|
refresh: session => { if (!memory)
|
|
207
227
|
throw new Error('世界记忆线已停止'); memory.refreshPrompt(session); },
|
|
208
228
|
changed: () => sources.invalidate(),
|
|
229
|
+
fault: message => { if (message)
|
|
230
|
+
faults.set('home-apply', message);
|
|
231
|
+
else
|
|
232
|
+
faults.clear('home-apply'); },
|
|
209
233
|
});
|
|
210
234
|
let bridge;
|
|
211
235
|
let wechat;
|
|
@@ -350,9 +374,11 @@ export async function apply(ctx, config) {
|
|
|
350
374
|
// The host matches exact routes before the longest prefix, so this path never reaches the console.
|
|
351
375
|
if (config.bridge)
|
|
352
376
|
lifeCtx.effect(() => webServer.register(bridgeRoute(() => bridge, config.allowedHosts)), 'dsh-world bridge route');
|
|
377
|
+
if (config.bridge)
|
|
378
|
+
lifeCtx.effect(() => webServer.register(compactRoute(() => bridge, () => !power.running() || !life ? '请先启动世界生活线' : homeApply.request(), config.allowedHosts)), 'dsh-world compact route');
|
|
353
379
|
// Her album lives in her room, so the console shows it whether or not the life line is running.
|
|
354
|
-
const sources = consoleSources({ ctx: lifeCtx, config: memoryConfig, archive: store, 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,
|
|
355
|
-
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() ?? [])] });
|
|
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()] });
|
|
356
382
|
const actions = {
|
|
357
383
|
async start() {
|
|
358
384
|
if (power.running())
|
|
@@ -381,13 +407,14 @@ export async function apply(ctx, config) {
|
|
|
381
407
|
applyHome: () => !power.running() || !life ? '请先启动世界生活线' : homeApply.request(),
|
|
382
408
|
prompts: () => ({
|
|
383
409
|
persona: readPersona(personaFile),
|
|
384
|
-
worldPrompt: existsSync(worldPromptFile) ? { text: readFileSync(
|
|
410
|
+
worldPrompt: existsSync(worldPromptFile) ? (text => ({ text, custom: true, memory: { missing: memoryTemplateGaps(text), snippet: readFileSync(MEMORY_SNIPPET_FILE, 'utf8') } }))(readFileSync(worldPromptFile, 'utf8')) : { text: readFileSync(DEFAULT_TEMPLATE_FILE, 'utf8'), custom: false },
|
|
385
411
|
}),
|
|
386
412
|
savePersona: persona => { writePersona(personaFile, { ...readPersona(personaFile), ...persona }); sources.invalidate(); },
|
|
387
413
|
setDailyBudget: yuan => { power.setDailyBudget(yuan); sources.invalidate(); },
|
|
388
414
|
setMemoryTurns: turns => { power.setMemoryTurns(turns); sources.invalidate(); },
|
|
389
415
|
setWorkspacePermission: permission => { permissions.set(permission); sources.invalidate(); },
|
|
390
416
|
setCompactAfterReview: on => { power.setCompactAfterReview(on); sources.invalidate(); },
|
|
417
|
+
setSchedule: next => { power.setSchedule(next); life?.reschedule(); sources.invalidate(); },
|
|
391
418
|
async setModules(patch) {
|
|
392
419
|
if (patch.wechat !== undefined && !config.wechat)
|
|
393
420
|
return '没有配置微信模块(配置里 wechat: true)';
|
package/lib/life/activity.d.ts
CHANGED
|
@@ -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;
|
package/lib/life/activity.js
CHANGED
|
@@ -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);
|
package/lib/life/alarm.d.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import type { Alarm, Review } from './types.ts';
|
|
2
2
|
import { type AlarmMessages } from './messages.ts';
|
|
3
|
-
/**
|
|
4
|
-
export declare const
|
|
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
|
|
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
|
-
/**
|
|
6
|
-
export const
|
|
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
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
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 = {}) {
|
package/lib/life/diary.d.ts
CHANGED
|
@@ -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 =>
|
|
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
|
+
}
|
package/lib/life/runtime.d.ts
CHANGED
|
@@ -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;
|