dsh-world 0.7.0 → 0.7.2
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 +379 -347
- package/INSTALL.md +314 -314
- package/LICENSE +21 -21
- package/NOTES.md +32 -10
- package/README.md +7 -6
- package/client/index.js +58 -3
- package/cordis.patch.yml +6 -6
- package/lib/archive.d.ts +3 -1
- package/lib/archive.js +6 -4
- package/lib/console/routes.d.ts +7 -0
- package/lib/console/routes.js +26 -8
- package/lib/console/snapshot.d.ts +7 -0
- package/lib/console/snapshot.js +3 -2
- 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/home.d.ts +1 -0
- package/lib/ecosystem/qq-native/home.js +10 -3
- package/lib/ecosystem/qq-native/index.d.ts +2 -0
- package/lib/ecosystem/qq-native/index.js +21 -4
- package/lib/ecosystem/qq-native/native-bridge.js +5 -2
- package/lib/ecosystem/qq-native/replies.d.ts +7 -1
- package/lib/ecosystem/qq-native/replies.js +30 -1
- package/lib/ecosystem/shared/context.d.ts +6 -1
- package/lib/ecosystem/shared/context.js +6 -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 +4 -1
- package/lib/index.d.ts +1 -0
- package/lib/index.js +27 -7
- 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.js +1 -4
- package/lib/memoryFiles.d.ts +1 -4
- package/lib/memoryFiles.js +18 -43
- package/lib/memoryStore.d.ts +1 -3
- package/lib/memoryStore.js +1 -1
- package/lib/memoryTools.js +2 -2
- package/lib/promptSection.d.ts +5 -4
- package/lib/promptSection.js +9 -8
- package/lib/runtime.d.ts +8 -3
- package/lib/runtime.js +60 -94
- package/lib/sourceArchive.js +4 -5
- package/lib/store.d.ts +1 -1
- package/lib/store.js +1 -1
- package/lib/types.d.ts +1 -4
- package/lib/worldPrompt.js +1 -1
- package/lib/worldSwitch.d.ts +15 -1
- package/lib/worldSwitch.js +24 -1
- package/package.json +1 -1
- package/scripts/compact-home.mjs +29 -29
- package/scripts/enable-tool-free-compaction.ps1 +33 -33
- package/scripts/import-stickers.mjs +17 -17
- package/scripts/update-world.mjs +2 -2
- package/src/ecosystem/wechat/windows/README.md +5 -3
- package/src/ecosystem/wechat/windows/adapter.py +6 -0
- package/src/ecosystem/wechat/windows/engine/NOTICE.md +6 -0
- package/src/ecosystem/wechat/windows/engine/build.ps1 +8 -2
- package/src/ecosystem/wechat/windows/engine/profiles.json +142 -114
- package/src/ecosystem/wechat/windows/presence.py +109 -109
- package/src/ecosystem/wechat/windows/sender.py +17 -5
- package/templates/alarm.md +1 -1
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
import { spawn, type ChildProcess } from 'node:child_process';
|
|
2
2
|
/** The adapter script ships next to the sources; this resolves from both `src/` and the built `lib/`. */
|
|
3
3
|
export declare const ADAPTER_SCRIPT: string;
|
|
4
|
+
/** The native bridge's build script, beside the bridge source the adapter checks its build against. */
|
|
5
|
+
export declare const BUILD_SCRIPT: string;
|
|
4
6
|
/** The adapter exits with this when a person must check WeChat and run `acknowledge`; restarting cannot help. */
|
|
5
7
|
export declare const EXIT_NEEDS_HUMAN = 2;
|
|
8
|
+
/** The adapter exits with this when no build of the native bridge matches its source (an upgrade changed it). */
|
|
9
|
+
export declare const EXIT_NEEDS_BUILD = 3;
|
|
6
10
|
export interface AdapterStatus {
|
|
7
11
|
running: boolean;
|
|
8
12
|
pid: number | null;
|
|
@@ -10,12 +14,14 @@ export interface AdapterStatus {
|
|
|
10
14
|
lastExit: string | null;
|
|
11
15
|
error: string | null;
|
|
12
16
|
needsHuman: boolean;
|
|
17
|
+
building: boolean;
|
|
13
18
|
}
|
|
14
19
|
export interface AdapterSupervisorDeps {
|
|
15
20
|
python: string;
|
|
16
21
|
config: string;
|
|
17
22
|
logFile: string;
|
|
18
23
|
script?: string;
|
|
24
|
+
buildScript?: string;
|
|
19
25
|
/** Delay before the first restart and the cap it doubles up to. */
|
|
20
26
|
minDelayMs?: number;
|
|
21
27
|
maxDelayMs?: number;
|
|
@@ -26,8 +32,11 @@ export interface AdapterSupervisorDeps {
|
|
|
26
32
|
/**
|
|
27
33
|
* Runs the Windows WeChat adapter for as long as the world's WeChat module lives: started with the module,
|
|
28
34
|
* restarted with a growing delay when it exits or cannot start (a file missing during an upgrade comes back),
|
|
29
|
-
* and stopped (its whole process tree) with the module. An exit that says a person must act is not retried.
|
|
30
|
-
*
|
|
35
|
+
* and stopped (its whole process tree) with the module. An exit that says a person must act is not retried. An exit
|
|
36
|
+
* that says the native bridge needs building is answered by building it once into the `engine` folder beside the
|
|
37
|
+
* adapter's config (where the adapter looks) and starting it again; a build that fails, or still does not match,
|
|
38
|
+
* stops with what to do. The adapter itself waits for the same WeChat account to log in again, so a WeChat
|
|
39
|
+
* restart needs nothing from here.
|
|
31
40
|
*/
|
|
32
41
|
export declare function createAdapterSupervisor(deps: AdapterSupervisorDeps): {
|
|
33
42
|
start(): void;
|
|
@@ -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
|
@@ -10,7 +10,6 @@ declare module '@deepseek-ai/dsh-llm' {
|
|
|
10
10
|
'dsh-world-life': {
|
|
11
11
|
kind: 'dsh-world-life';
|
|
12
12
|
};
|
|
13
|
-
/** 她图谱里的卡片:消息里提到她记过的名字时追加,压缩后重来,不进归档。 */
|
|
14
13
|
'dsh-world-channel-context': {
|
|
15
14
|
kind: 'dsh-world-channel-context';
|
|
16
15
|
form: 'recall';
|
|
@@ -21,6 +20,10 @@ declare module '@deepseek-ai/dsh-llm' {
|
|
|
21
20
|
kind: 'dsh-world-outside';
|
|
22
21
|
form: 'ring';
|
|
23
22
|
};
|
|
23
|
+
/** QQ 的一轮完成了却没说出能发的话:提醒她对方还在等,不是谁发来的话,不进归档。 */
|
|
24
|
+
'dsh-world-reply-nudge': {
|
|
25
|
+
kind: 'dsh-world-reply-nudge';
|
|
26
|
+
};
|
|
24
27
|
}
|
|
25
28
|
}
|
|
26
29
|
export {};
|
package/lib/index.d.ts
CHANGED
package/lib/index.js
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import { existsSync, readFileSync, rmSync } from 'node:fs';
|
|
2
2
|
import { join } from 'node:path';
|
|
3
|
+
// DSH's HMR reconciles the profile once at every start and drops, as failed imports, the profile modules whose import
|
|
4
|
+
// has not finished (dsh-hmr `reconcileProfile`). The QQ module is imported later and is the only way to `ws`, a CommonJS
|
|
5
|
+
// package: dropped halfway, Node fails it with ERR_INTERNAL_ASSERTION and QQ switched on at boot never starts. Loaded
|
|
6
|
+
// with the plugin, `ws` is complete before that reconciliation runs.
|
|
7
|
+
import 'ws';
|
|
3
8
|
import z from '@deepseek-ai/schemastery';
|
|
4
9
|
import { resolveDshHome } from '@deepseek-ai/dsh-home-paths';
|
|
5
10
|
import { createBridge } from "./ecosystem/bridge/bridge.js";
|
|
@@ -22,6 +27,7 @@ import { createWorldRuntime } from "./runtime.js";
|
|
|
22
27
|
import { createArchiveStore } from "./store.js";
|
|
23
28
|
import { DEFAULT_TEMPLATE_FILE, MEMORY_SNIPPET_FILE, memoryTemplateGaps, roomTitle, worldNames } from "./worldPrompt.js";
|
|
24
29
|
import { createWorldSwitch } from "./worldSwitch.js";
|
|
30
|
+
import { CLOCK_TIME, DEFAULT_REVIEW_TIME } from "./life/alarm.js";
|
|
25
31
|
import { createWechatModule } from "./ecosystem/wechat/index.js";
|
|
26
32
|
import { createWechatRecorder } from "./ecosystem/wechat/archive.js";
|
|
27
33
|
import { createAdapterSupervisor } from "./ecosystem/wechat/supervisor.js";
|
|
@@ -43,7 +49,7 @@ export const Config = z.object({
|
|
|
43
49
|
archiveScope: z.union([z.const('home').description('仅家会话'), z.const('workspace').description('家所在工作区'), z.transform(z.const('world').hidden(), () => 'workspace').hidden()]).default('workspace').description('记忆归档范围,修改后重启生效'),
|
|
44
50
|
// Install means the tool-free compaction: the first start rewrites the profile's stock compaction row (see README); false leaves it alone.
|
|
45
51
|
replaceCompaction: z.boolean().default(true),
|
|
46
|
-
life: z.boolean().default(true), diaryDir: z.string(), fallbackWakeTime: z.string().pattern(
|
|
52
|
+
life: z.boolean().default(true), diaryDir: z.string(), fallbackWakeTime: z.string().pattern(CLOCK_TIME).default('09:00'),
|
|
47
53
|
selfFile: z.string(), worldPromptFile: z.string(), alarmTemplateFile: z.string(), personaFile: z.string(),
|
|
48
54
|
// Where her words go outside DSH; no app is known by name (see README for the push body).
|
|
49
55
|
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 +105,7 @@ export async function apply(ctx, config) {
|
|
|
99
105
|
const dshHome = resolveDshHome();
|
|
100
106
|
const worldDir = join(dshHome, 'worlds', config.worldId);
|
|
101
107
|
const store = createArchiveStore({ ...config, root: dshHome });
|
|
102
|
-
const power = createWorldSwitch(worldDir, config.archiveScope ?? 'workspace');
|
|
108
|
+
const power = createWorldSwitch(worldDir, config.archiveScope ?? 'workspace', config.fallbackWakeTime);
|
|
103
109
|
const memoryConfig = { ...config, archiveScope: power.archiveScope() };
|
|
104
110
|
const faults = new Faults();
|
|
105
111
|
let photoStore;
|
|
@@ -120,7 +126,7 @@ export async function apply(ctx, config) {
|
|
|
120
126
|
const personaFile = config.personaFile || join(worldDir, 'persona.md');
|
|
121
127
|
const worldPromptFile = config.worldPromptFile || join(worldDir, 'world-prompt.md');
|
|
122
128
|
const roomDir = join(worldDir, 'room');
|
|
123
|
-
const options = { worldDir, roomDir, diaryDir: config.diaryDir || join(worldDir, 'diary'), selfFile,
|
|
129
|
+
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
130
|
/** The name in her persona comes first, then the configured one. */
|
|
125
131
|
const names = () => worldNames({ ...config, companionName: readPersona(personaFile).名字 || config.companionName });
|
|
126
132
|
const lifeStore = (() => {
|
|
@@ -150,12 +156,24 @@ export async function apply(ctx, config) {
|
|
|
150
156
|
const memoryHealth = () => memoryService.status().failures.map(failure => `记忆来源 ${failure.sourceId}:${failure.message}`);
|
|
151
157
|
let memory;
|
|
152
158
|
let stopLifeLine;
|
|
159
|
+
/**
|
|
160
|
+
* A memory line that cannot start is a fault, never a failed plugin: the console must still open to say so, and
|
|
161
|
+
* the life line and channels run on. Stopping and starting the world from the console tries again.
|
|
162
|
+
*/
|
|
153
163
|
async function startMemory(fresh) {
|
|
154
164
|
if (memory)
|
|
155
165
|
return;
|
|
156
166
|
const prompt = { file: worldPromptFile, persona: personaFile, conversationsDir: join(worldDir, 'conversations'), names: names(), memoryTools: true, ...(config.life ? { life: options } : {}) };
|
|
157
|
-
|
|
158
|
-
|
|
167
|
+
const runtime = createWorldRuntime(ctx, { ...memoryConfig, selfFile }, store, { prompt, names, isHome: id => isHome(id), archiveSession, inWorkspace, memory: memoryService }, power.memoryTurns, power.coldHours);
|
|
168
|
+
try {
|
|
169
|
+
await runtime.start({ fresh });
|
|
170
|
+
memory = runtime;
|
|
171
|
+
faults.clear('memory');
|
|
172
|
+
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
faults.set('memory', `记忆线没能启动:${errorText(error)}`);
|
|
175
|
+
ctx.logger.error(error);
|
|
176
|
+
}
|
|
159
177
|
}
|
|
160
178
|
async function stopMemory() {
|
|
161
179
|
const running = memory;
|
|
@@ -376,8 +394,8 @@ export async function apply(ctx, config) {
|
|
|
376
394
|
if (config.bridge)
|
|
377
395
|
lifeCtx.effect(() => webServer.register(compactRoute(() => bridge, () => !power.running() || !life ? '请先启动世界生活线' : homeApply.request(), config.allowedHosts)), 'dsh-world compact route');
|
|
378
396
|
// 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()] });
|
|
397
|
+
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, coldHours: power.coldHours, selectedArchiveScope: power.selectedArchiveScope, workspacePermissions: permissions.snapshot, wechat: () => wechat ? { ...wechat.status(), adapter: adapter?.status() ?? null } : undefined, archiveSession, native: () => qqNative?.status() ?? null,
|
|
398
|
+
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
399
|
const actions = {
|
|
382
400
|
async start() {
|
|
383
401
|
if (power.running())
|
|
@@ -411,8 +429,10 @@ export async function apply(ctx, config) {
|
|
|
411
429
|
savePersona: persona => { writePersona(personaFile, { ...readPersona(personaFile), ...persona }); sources.invalidate(); },
|
|
412
430
|
setDailyBudget: yuan => { power.setDailyBudget(yuan); sources.invalidate(); },
|
|
413
431
|
setMemoryTurns: turns => { power.setMemoryTurns(turns); sources.invalidate(); },
|
|
432
|
+
setColdHours: hours => { power.setColdHours(hours); sources.invalidate(); },
|
|
414
433
|
setWorkspacePermission: permission => { permissions.set(permission); sources.invalidate(); },
|
|
415
434
|
setCompactAfterReview: on => { power.setCompactAfterReview(on); sources.invalidate(); },
|
|
435
|
+
setSchedule: next => { power.setSchedule(next); life?.reschedule(); sources.invalidate(); },
|
|
416
436
|
async setModules(patch) {
|
|
417
437
|
if (patch.wechat !== undefined && !config.wechat)
|
|
418
438
|
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;
|