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
package/lib/life/runtime.js
CHANGED
|
@@ -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
|
|
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,
|
|
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,
|
|
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,
|
|
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,
|
|
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;
|
package/lib/life/toolRegistry.js
CHANGED
|
@@ -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
|
-
|
|
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) {
|
package/lib/life/types.d.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
};
|
package/lib/memoryFiles.d.ts
CHANGED
|
@@ -1,10 +1,7 @@
|
|
|
1
1
|
import { type MemoryKind, type TimeBasis } from './memoryStore.ts';
|
|
2
|
-
/** Where she keeps what she writes
|
|
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. */
|
package/lib/memoryFiles.js
CHANGED
|
@@ -4,7 +4,6 @@ import { errorText } from "./faults.js";
|
|
|
4
4
|
import { formatLocalTime } from "./timeContext.js";
|
|
5
5
|
import { extractLinks, fileRef, localDayStart } from "./memoryStore.js";
|
|
6
6
|
const MAX_FILE_BYTES = 2 * 1024 * 1024, MAX_FILES_PER_DIR = 2000;
|
|
7
|
-
const DIR_DEPTH = { diary: 1, knowledge: 4 };
|
|
8
7
|
const sameFile = (a, b) => a.size === b.size && a.mtimeMs === b.mtimeMs;
|
|
9
8
|
/** Windows compares paths without case. */
|
|
10
9
|
const normalized = (path) => process.platform === 'win32' ? path.toLowerCase() : path;
|
|
@@ -36,8 +35,8 @@ export async function readStable(path, between) {
|
|
|
36
35
|
return { kind: 'failed', message: error instanceof TypeError && /encoded data|decode/i.test(error.message) ? '不是有效的 UTF-8 文本' : errorText(error) };
|
|
37
36
|
}
|
|
38
37
|
}
|
|
39
|
-
/**
|
|
40
|
-
async function listDirectory(root
|
|
38
|
+
/** The diary's own markdown and text files, one level: real paths must stay inside it, so links cannot lead out, and nothing is followed from file contents. */
|
|
39
|
+
async function listDirectory(root) {
|
|
41
40
|
let realRoot;
|
|
42
41
|
try {
|
|
43
42
|
realRoot = await realpath(root);
|
|
@@ -46,16 +45,11 @@ async function listDirectory(root, depth) {
|
|
|
46
45
|
return error.code === 'ENOENT' ? { kind: 'missing' } : { kind: 'failed', message: errorText(error) };
|
|
47
46
|
}
|
|
48
47
|
const files = [];
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
if (!within(realRoot, real) || visited.has(normalized(real)))
|
|
53
|
-
return;
|
|
54
|
-
visited.add(normalized(real));
|
|
55
|
-
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
|
56
|
-
if (entry.name.startsWith('.'))
|
|
48
|
+
try {
|
|
49
|
+
for (const entry of await readdir(root, { withFileTypes: true })) {
|
|
50
|
+
if (entry.name.startsWith('.') || !/\.(md|txt)$/i.test(entry.name))
|
|
57
51
|
continue;
|
|
58
|
-
const path = join(
|
|
52
|
+
const path = join(root, entry.name);
|
|
59
53
|
let target;
|
|
60
54
|
try {
|
|
61
55
|
target = await realpath(path);
|
|
@@ -63,20 +57,12 @@ async function listDirectory(root, depth) {
|
|
|
63
57
|
catch {
|
|
64
58
|
continue;
|
|
65
59
|
}
|
|
66
|
-
if (!within(realRoot, target))
|
|
60
|
+
if (!within(realRoot, target) || !(await stat(path).catch(() => undefined))?.isFile())
|
|
67
61
|
continue;
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
else if (info?.isFile() && /\.(md|txt)$/i.test(entry.name)) {
|
|
72
|
-
if (files.length >= MAX_FILES_PER_DIR)
|
|
73
|
-
throw new Error(`文件超过 ${MAX_FILES_PER_DIR} 个,后面的没有读取`);
|
|
74
|
-
files.push({ path, id: `${prefix}${entry.name}` });
|
|
75
|
-
}
|
|
62
|
+
if (files.length >= MAX_FILES_PER_DIR)
|
|
63
|
+
throw new Error(`文件超过 ${MAX_FILES_PER_DIR} 个,后面的没有读取`);
|
|
64
|
+
files.push({ path, id: entry.name });
|
|
76
65
|
}
|
|
77
|
-
}
|
|
78
|
-
try {
|
|
79
|
-
await walk(root, '', 1);
|
|
80
66
|
return { kind: 'ok', files };
|
|
81
67
|
}
|
|
82
68
|
catch (error) {
|
|
@@ -113,7 +99,7 @@ export function createAuthorFiles(sources, timeZone) {
|
|
|
113
99
|
cache.set(sourceId, { kind, path, stat: result.stat, mtimeMs: result.mtimeMs, content: result.content });
|
|
114
100
|
}
|
|
115
101
|
async function loadDirectory(kind, root) {
|
|
116
|
-
const listing = await listDirectory(root
|
|
102
|
+
const listing = await listDirectory(root);
|
|
117
103
|
const key = `dir:${kind}`;
|
|
118
104
|
if (listing.kind === 'failed') {
|
|
119
105
|
failures.set(key, `${root}:${listing.message}`);
|
|
@@ -133,25 +119,14 @@ export function createAuthorFiles(sources, timeZone) {
|
|
|
133
119
|
}
|
|
134
120
|
}
|
|
135
121
|
async function refreshOnce() {
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
}
|
|
142
|
-
catch (error) {
|
|
143
|
-
failures.set(kind, `${path}:${errorText(error)}`);
|
|
144
|
-
}
|
|
122
|
+
const root = sources.diaryDir;
|
|
123
|
+
if (!root)
|
|
124
|
+
return;
|
|
125
|
+
try {
|
|
126
|
+
await loadDirectory('diary', root);
|
|
145
127
|
}
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
continue;
|
|
149
|
-
try {
|
|
150
|
-
await loadDirectory(kind, root);
|
|
151
|
-
}
|
|
152
|
-
catch (error) {
|
|
153
|
-
failures.set(`dir:${kind}`, `${root}:${errorText(error)}`);
|
|
154
|
-
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
failures.set('dir:diary', `${root}:${errorText(error)}`);
|
|
155
130
|
}
|
|
156
131
|
}
|
|
157
132
|
/** Calls arriving during a refresh join it and make it run once more, so a file saved just now is never missed. */
|
package/lib/memoryStore.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { DatabaseSync } from 'node:sqlite';
|
|
2
2
|
import type { ConversationRecord } from './types.ts';
|
|
3
|
-
export declare const MEMORY_KINDS: readonly ["conversation", "diary"
|
|
3
|
+
export declare const MEMORY_KINDS: readonly ["conversation", "diary"];
|
|
4
4
|
export type MemoryKind = typeof MEMORY_KINDS[number];
|
|
5
5
|
/** `message`: when the line was said. `diaryDate`: the day in a diary's file name. `fileObserved`: when the file last changed. */
|
|
6
6
|
export type TimeBasis = 'message' | 'diaryDate' | 'fileObserved';
|
|
@@ -49,8 +49,6 @@ export interface FindParams {
|
|
|
49
49
|
sourceId?: string;
|
|
50
50
|
turnId?: string;
|
|
51
51
|
linkedTo?: string;
|
|
52
|
-
/** Only the current content of a file exists, so this changes nothing; it is accepted so older callers keep working. */
|
|
53
|
-
history: boolean;
|
|
54
52
|
order: 'newest' | 'oldest';
|
|
55
53
|
limit: number;
|
|
56
54
|
cursor?: string;
|
package/lib/memoryStore.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { formatLocalTime } from "./timeContext.js";
|
|
3
|
-
export const MEMORY_KINDS = ['conversation', 'diary'
|
|
3
|
+
export const MEMORY_KINDS = ['conversation', 'diary'];
|
|
4
4
|
export class MemoryError extends Error {
|
|
5
5
|
code;
|
|
6
6
|
constructor(code, message, options) { super(message, options); this.name = 'MemoryError'; this.code = code; }
|
package/lib/memoryTools.js
CHANGED
|
@@ -33,10 +33,10 @@ export function memoryTools(service, inside) {
|
|
|
33
33
|
return [
|
|
34
34
|
defineTool({
|
|
35
35
|
name: 'memory_find',
|
|
36
|
-
description: `在我自己的长期记忆里按线索查找:原始聊天(conversation)和日记(diary)。query 是要在原文里照字面找的一小段话(区分大小写,不是搜索语法);没有 query 就按时间或来源翻页。kinds 限定种类;from / to 是带时区的 ISO 时间,左闭右开(日期请换成当天零点,如 2026-10-30T00:00:00+08:00);time 的含义看 timeBasis
|
|
36
|
+
description: `在我自己的长期记忆里按线索查找:原始聊天(conversation)和日记(diary)。query 是要在原文里照字面找的一小段话(区分大小写,不是搜索语法);没有 query 就按时间或来源翻页。kinds 限定种类;from / to 是带时区的 ISO 时间,左闭右开(日期请换成当天零点,如 2026-10-30T00:00:00+08:00);time 的含义看 timeBasis:聊天是发言时间,日记是文件名里的日期(文件名没有日期时是它最后改动的时间,不一定是事情发生的时间)。sourceId 限定来源;turnId 取同一轮的全部发言。limit 默认 8、最多 100;返回 nextCursor 就用 cursor 翻下一页,返回 cursorExpired 说明资料变了、要重新查。零命中不等于从没发生过:返回里若带 coverage,说明有来源没能读到。每条结果的 text 只是摘录,要看原文用它的 ref 调 memory_read。`,
|
|
37
37
|
parameters: {
|
|
38
38
|
query: { type: 'string' }, kinds: { type: 'array', items: { type: 'string' } }, from: { type: 'string' }, to: { type: 'string' }, sourceId: { type: 'string' }, turnId: { type: 'string' },
|
|
39
|
-
linkedTo: { type: 'string' },
|
|
39
|
+
linkedTo: { type: 'string' }, order: { type: 'string' }, limit: { type: 'integer' }, cursor: { type: 'string' },
|
|
40
40
|
},
|
|
41
41
|
output,
|
|
42
42
|
execute: async (input) => JSON.stringify(compactFind(await checked(() => service.find({ limit: TOOL_FIND_LIMIT, ...input })))),
|
package/lib/promptSection.d.ts
CHANGED
|
@@ -14,11 +14,12 @@ export interface WorldPromptSource {
|
|
|
14
14
|
memory?: import('./memory.ts').MemoryService;
|
|
15
15
|
}
|
|
16
16
|
/**
|
|
17
|
-
* Her persona
|
|
18
|
-
*
|
|
17
|
+
* Her persona and the world prompt both reach only sessions of her preset inside the world's workspace, and come and
|
|
18
|
+
* go together as a session enters or leaves it: the preset alone is DSH's default `standard` for most setups, so it
|
|
19
|
+
* would turn every unrelated session into her (#37). Both are sections of the session's system prompt so she sees them on every
|
|
19
20
|
* request. They are read when the session opens and again after each successful compaction (the host assembles
|
|
20
|
-
* the system prompt before pre-step, so the refresh happens on compaction/end)
|
|
21
|
-
* stays in the provider-cached prefix. Whether the session is her home is asked per request.
|
|
21
|
+
* the system prompt before pre-step, so the refresh happens on compaction/end), when a cold session speaks again
|
|
22
|
+
* (`coldHours` in `runtime.ts`, on turn/start) or on explicit console application, so the prompt stays in the provider-cached prefix. Whether the session is her home is asked per request.
|
|
22
23
|
*
|
|
23
24
|
* Her persona takes the place of DeepSeek Harness's stock identity line, but never of a persona someone has set: it is its own
|
|
24
25
|
* section placed right after the host's persona slot, so a system persona the deployment or her preset already has stays
|
package/lib/promptSection.js
CHANGED
|
@@ -6,11 +6,12 @@ import { reassembleOnChange } from "./worldScope.js";
|
|
|
6
6
|
/** The stock "You are an AI agent powered by DeepSeek Harness." line; a section of the same name on her agent shadows it. */
|
|
7
7
|
const HARNESS_IDENTITY = 'harness:identity';
|
|
8
8
|
/**
|
|
9
|
-
* Her persona
|
|
10
|
-
*
|
|
9
|
+
* Her persona and the world prompt both reach only sessions of her preset inside the world's workspace, and come and
|
|
10
|
+
* go together as a session enters or leaves it: the preset alone is DSH's default `standard` for most setups, so it
|
|
11
|
+
* would turn every unrelated session into her (#37). Both are sections of the session's system prompt so she sees them on every
|
|
11
12
|
* request. They are read when the session opens and again after each successful compaction (the host assembles
|
|
12
|
-
* the system prompt before pre-step, so the refresh happens on compaction/end)
|
|
13
|
-
* stays in the provider-cached prefix. Whether the session is her home is asked per request.
|
|
13
|
+
* the system prompt before pre-step, so the refresh happens on compaction/end), when a cold session speaks again
|
|
14
|
+
* (`coldHours` in `runtime.ts`, on turn/start) or on explicit console application, so the prompt stays in the provider-cached prefix. Whether the session is her home is asked per request.
|
|
14
15
|
*
|
|
15
16
|
* Her persona takes the place of DeepSeek Harness's stock identity line, but never of a persona someone has set: it is its own
|
|
16
17
|
* section placed right after the host's persona slot, so a system persona the deployment or her preset already has stays
|
|
@@ -33,9 +34,9 @@ export function createPromptSections(config, world, deps) {
|
|
|
33
34
|
persona, names,
|
|
34
35
|
};
|
|
35
36
|
}
|
|
36
|
-
/** Registers her persona
|
|
37
|
+
/** Registers her persona while the session is in her workspace and she has one; drops it otherwise. */
|
|
37
38
|
function placePersona(agent, entry) {
|
|
38
|
-
if (!entry.text.persona) {
|
|
39
|
+
if (!entry.active || !entry.text.persona) {
|
|
39
40
|
entry.persona?.();
|
|
40
41
|
delete entry.persona;
|
|
41
42
|
return;
|
|
@@ -60,7 +61,7 @@ export function createPromptSections(config, world, deps) {
|
|
|
60
61
|
if (entries.has(agent) || !belongsToWorld(agent.session, config))
|
|
61
62
|
return;
|
|
62
63
|
let disposeWorld;
|
|
63
|
-
/** Places or removes the world prompt as the session enters or leaves her workspace; true when it did. */
|
|
64
|
+
/** Places or removes the world prompt and her persona as the session enters or leaves her workspace; true when it did. */
|
|
64
65
|
const sync = () => {
|
|
65
66
|
if (inWorld(agent.session, config, world.inWorkspace) === entry.active)
|
|
66
67
|
return false;
|
|
@@ -68,6 +69,7 @@ export function createPromptSections(config, world, deps) {
|
|
|
68
69
|
if (!entry.active) {
|
|
69
70
|
disposeWorld?.();
|
|
70
71
|
disposeWorld = undefined;
|
|
72
|
+
placePersona(agent, entry);
|
|
71
73
|
return true;
|
|
72
74
|
}
|
|
73
75
|
entry.text = read(true);
|
|
@@ -80,7 +82,6 @@ export function createPromptSections(config, world, deps) {
|
|
|
80
82
|
entries.set(agent, entry);
|
|
81
83
|
agents.set(agent.session, agent);
|
|
82
84
|
sync();
|
|
83
|
-
placePersona(agent, entry);
|
|
84
85
|
},
|
|
85
86
|
active(session) {
|
|
86
87
|
const agent = agents.get(session);
|
package/lib/runtime.d.ts
CHANGED
|
@@ -7,12 +7,17 @@ import type { WorldConfig } from './types.ts';
|
|
|
7
7
|
export type { WorldPromptSource } from './promptSection.ts';
|
|
8
8
|
/**
|
|
9
9
|
* The memory line: her conversations are archived as they happen, and every world session gets a memory
|
|
10
|
-
* block of the newest turns at its start
|
|
11
|
-
* inside the provider-cached prefix. `home` archives the current home; `workspace` uses host membership. The memory block still
|
|
10
|
+
* block of the newest turns at its start, after each successful compaction and when it speaks again after being cold,
|
|
11
|
+
* never in between, so it stays inside the provider-cached prefix. `home` archives the current home; `workspace` uses host membership. The memory block still
|
|
12
12
|
* goes to every world session in her workspace (`inWorkspace`), independently of the archive scope.
|
|
13
13
|
* `memoryTurns` is read each time a block is built (default 200).
|
|
14
|
+
*
|
|
15
|
+
* A session silent for `coldHours` (read at each turn start, default 24) is cold (#36): its provider cache has most
|
|
16
|
+
* likely expired (DeepSeek clears an unused one "usually within a few hours to a few days", best effort), so its next
|
|
17
|
+
* turn re-reads her memory block and prompt as a newly opened session would, at the cost of at most one uncached
|
|
18
|
+
* request. A conversation in progress does not pause that long, so its cached prefix stays whole.
|
|
14
19
|
*/
|
|
15
|
-
export declare function createWorldRuntime(ctx: Context, config: WorldConfig, store: ArchiveStore, world?: WorldPromptSource, memoryTurns?: () => number): {
|
|
20
|
+
export declare function createWorldRuntime(ctx: Context, config: WorldConfig, store: ArchiveStore, world?: WorldPromptSource, memoryTurns?: () => number, coldHours?: () => number, now?: () => number): {
|
|
16
21
|
start: (options?: {
|
|
17
22
|
fresh?: boolean;
|
|
18
23
|
}) => Promise<void>;
|