dsh-world 0.6.4 → 0.6.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/CONTRIBUTING.md +161 -161
  3. package/INSTALL.md +314 -311
  4. package/NOTES.md +152 -0
  5. package/README.md +45 -48
  6. package/client/index.js +22 -3
  7. package/lib/compaction.d.ts +19 -0
  8. package/lib/compaction.js +26 -10
  9. package/lib/compactionSwap.d.ts +29 -0
  10. package/lib/compactionSwap.js +56 -0
  11. package/lib/console/routes.d.ts +2 -0
  12. package/lib/console/routes.js +6 -0
  13. package/lib/console/snapshot.d.ts +1 -0
  14. package/lib/console/snapshot.js +1 -0
  15. package/lib/ecosystem/qq-native/home.js +2 -2
  16. package/lib/ecosystem/shared/context.d.ts +2 -1
  17. package/lib/ecosystem/shared/context.js +8 -1
  18. package/lib/ecosystem/wechat/home.js +4 -4
  19. package/lib/ecosystem/wechat/index.js +13 -4
  20. package/lib/ecosystem/wechat/messages.js +1 -1
  21. package/lib/ecosystem/wechat/reading.d.ts +9 -0
  22. package/lib/ecosystem/wechat/reading.js +61 -12
  23. package/lib/ecosystem/wechat/sending.d.ts +1 -0
  24. package/lib/ecosystem/wechat/sending.js +3 -0
  25. package/lib/ecosystem/wechat/stickerLibrary.d.ts +50 -0
  26. package/lib/ecosystem/wechat/stickerLibrary.js +167 -0
  27. package/lib/ecosystem/wechat/stickerTools.d.ts +18 -0
  28. package/lib/ecosystem/wechat/stickerTools.js +69 -0
  29. package/lib/index.d.ts +3 -1
  30. package/lib/index.js +9 -2
  31. package/lib/life/activity.js +5 -0
  32. package/lib/life/runtime.d.ts +2 -0
  33. package/lib/life/runtime.js +4 -2
  34. package/lib/promptSection.d.ts +3 -5
  35. package/lib/promptSection.js +12 -12
  36. package/lib/runtime.js +61 -39
  37. package/lib/types.d.ts +2 -0
  38. package/lib/worldSwitch.d.ts +10 -3
  39. package/lib/worldSwitch.js +19 -7
  40. package/package.json +117 -114
  41. package/scripts/import-stickers.mjs +17 -0
  42. package/src/ecosystem/wechat/windows/README.md +22 -5
  43. package/src/ecosystem/wechat/windows/adapter.py +24 -5
  44. package/src/ecosystem/wechat/windows/groups.py +2 -2
  45. package/src/ecosystem/wechat/windows/native.py +4 -3
  46. package/src/ecosystem/wechat/windows/outgoing.py +14 -7
  47. package/src/ecosystem/wechat/windows/reading.py +58 -1
  48. package/src/ecosystem/wechat/windows/snapshot.py +8 -0
  49. package/src/ecosystem/wechat/windows/stickers.py +69 -60
@@ -0,0 +1,69 @@
1
+ import { readFile, rm } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { defineTool } from '@deepseek-ai/dsh-tools';
4
+ import { wechatTextOutput } from "./messages.js";
5
+ const messageIdPattern = /^[A-Za-z0-9_.-]{1,64}:\d{1,20}$/;
6
+ const labels = (tags) => tags.join('/');
7
+ /**
8
+ * The model's side of the world's own sticker library. Kept deliberately small: nothing here puts a catalog or a
9
+ * picture in front of the model unless it asked, and sending is the ordinary `wechat_send`.
10
+ */
11
+ export function createStickerTools(deps) {
12
+ const { library } = deps;
13
+ return [
14
+ defineTool({
15
+ name: 'sticker_search',
16
+ description: '按关键词查表情库(匹配名称、标签),返回 id|名称|标签;不带词看最近收的,limit 默认 8、最多 20。发送用 wechat_send 的 {type:"sticker", stickerId}。',
17
+ parameters: { query: { type: 'string' }, limit: { type: 'integer' } },
18
+ output: wechatTextOutput,
19
+ execute: async ({ query, limit }) => {
20
+ const { total, items } = await library.search({ ...(query === undefined ? {} : { query }), ...(limit === undefined ? {} : { limit }) });
21
+ if (!total)
22
+ return '表情库还是空的,可以用 sticker_save 收别人发来的表情包。';
23
+ if (!items.length)
24
+ return `没有匹配「${query ?? ''}」的表情(库里共 ${total} 张)。换个词,或不带关键词看最近收的。`;
25
+ return `共 ${total} 张,显示 ${items.length} 张:\n` + items.map(sticker => `${sticker.id}|${sticker.name}|${labels(sticker.tags)}`).join('\n');
26
+ },
27
+ }),
28
+ defineTool({
29
+ name: 'sticker_save',
30
+ description: '把聊天里别人发来的表情包收进库。chatId、messageId 取自那条消息;tags 1–8 个短词(每个≤16 字)概括情绪和用法;name 可省。同一张图不重复收。',
31
+ parameters: { chatId: { type: 'string', required: true }, messageId: { type: 'string', required: true }, tags: { type: 'array', items: { type: 'string' }, required: true }, name: { type: 'string' } },
32
+ output: wechatTextOutput,
33
+ execute: async ({ chatId, messageId, tags, name }, context) => {
34
+ if (!messageIdPattern.test(messageId))
35
+ throw new Error('messageId 必须是那条表情消息的 id');
36
+ const identity = deps.target(chatId);
37
+ const staged = JSON.parse(await deps.ask(identity, { chatId, limit: 1, stickerId: messageId }, context));
38
+ const file = join(deps.stagingDir, staged.file);
39
+ try {
40
+ context.signal.throwIfAborted();
41
+ const { sticker, existing } = await library.add(await readFile(file), { tags, ...(name === undefined ? {} : { name }) }, { expectedMd5: staged.md5 });
42
+ return existing ? `库里已经有这张:${sticker.id}「${sticker.name}」(标签 ${labels(sticker.tags)},没有改动)。` : `已收进表情库:${sticker.id}「${sticker.name}」(标签 ${labels(sticker.tags)})。`;
43
+ }
44
+ finally {
45
+ await rm(file, { force: true });
46
+ }
47
+ },
48
+ }),
49
+ defineTool({
50
+ name: 'sticker_edit',
51
+ description: '改表情的名称或标签(tags 整个替换)。',
52
+ parameters: { id: { type: 'string', required: true }, name: { type: 'string' }, tags: { type: 'array', items: { type: 'string' } } },
53
+ output: wechatTextOutput,
54
+ execute: async ({ id, name, tags }) => {
55
+ if (name === undefined && tags === undefined)
56
+ throw new Error('需要给出新的 name 或 tags');
57
+ const sticker = await library.edit(id, { ...(name === undefined ? {} : { name }), ...(tags === undefined ? {} : { tags }) });
58
+ return `已更新 ${sticker.id}「${sticker.name}」:${labels(sticker.tags)}`;
59
+ },
60
+ }),
61
+ defineTool({
62
+ name: 'sticker_remove',
63
+ description: '删除表情及其图片文件。',
64
+ parameters: { id: { type: 'string', required: true } },
65
+ output: wechatTextOutput,
66
+ execute: async ({ id }) => { await library.remove(id); return `已移出 ${id}。`; },
67
+ }),
68
+ ];
69
+ }
package/lib/index.d.ts CHANGED
@@ -6,7 +6,7 @@ export type { WorldConfig, ConversationRecord, ConversationTurn, ArchiveCursor }
6
6
  export declare const name = "dsh-world";
7
7
  export declare const inject: string[];
8
8
  /** What `apply` receives: the schema below fills these defaults. */
9
- export type Config = WorldConfig & Required<Pick<WorldConfig, 'life' | 'fallbackWakeTime' | 'outlets' | 'bridge' | 'toast' | 'allowedHosts'>>;
9
+ export type Config = WorldConfig & Required<Pick<WorldConfig, 'life' | 'replaceCompaction' | 'fallbackWakeTime' | 'outlets' | 'bridge' | 'toast' | 'allowedHosts'>>;
10
10
  export declare const Config: z<Schemastery.ObjectS<NoInfer<{
11
11
  worldId: z<string, string, "defined">;
12
12
  agentPreset: z<string, string, "defined">;
@@ -14,6 +14,7 @@ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
14
14
  companionName: z<string, string, "plain">;
15
15
  partnerName: z<string, string, "plain">;
16
16
  archiveScope: z<"home" | "workspace" | "world", "home" | "workspace", "defined">;
17
+ replaceCompaction: z<boolean, boolean, "defined">;
17
18
  life: z<boolean, boolean, "defined">;
18
19
  diaryDir: z<string, string, "plain">;
19
20
  fallbackWakeTime: z<string, string, "defined">;
@@ -108,6 +109,7 @@ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
108
109
  companionName: z<string, string, "plain">;
109
110
  partnerName: z<string, string, "plain">;
110
111
  archiveScope: z<"home" | "workspace" | "world", "home" | "workspace", "defined">;
112
+ replaceCompaction: z<boolean, boolean, "defined">;
111
113
  life: z<boolean, boolean, "defined">;
112
114
  diaryDir: z<string, string, "plain">;
113
115
  fallbackWakeTime: z<string, string, "defined">;
package/lib/index.js CHANGED
@@ -8,6 +8,7 @@ import { consoleRoute } from "./console/routes.js";
8
8
  import { consoleSources } from "./console/snapshot.js";
9
9
  import { createHomeApply } from "./console/homeApply.js";
10
10
  import { errorText, Faults } from "./faults.js";
11
+ import { swapCompactionOnce } from "./compactionSwap.js";
11
12
  import { hostLife } from "./life/host.js";
12
13
  import { createLifeStore, durableWrite } from "./life/lifeStore.js";
13
14
  import { toastSupported, windowsToast } from "./life/notify.js";
@@ -39,6 +40,8 @@ export const Config = z.object({
39
40
  worldId: z.string().default('default'), agentPreset: z.string().default('standard'), timeZone: z.string().default(systemTimeZone),
40
41
  companionName: z.string(), partnerName: z.string(),
41
42
  archiveScope: z.union([z.const('home').description('仅家会话'), z.const('workspace').description('家所在工作区'), z.transform(z.const('world').hidden(), () => 'workspace').hidden()]).default('workspace').description('记忆归档范围,修改后重启生效'),
43
+ // Install means the tool-free compaction: the first start rewrites the profile's stock compaction row (see README); false leaves it alone.
44
+ replaceCompaction: z.boolean().default(true),
42
45
  life: z.boolean().default(true), diaryDir: z.string(), fallbackWakeTime: z.string().pattern(/^([01]\d|2[0-3]):[0-5]\d$/).default('09:00'),
43
46
  selfFile: z.string(), worldPromptFile: z.string(), alarmTemplateFile: z.string(), personaFile: z.string(),
44
47
  // Where her words go outside DSH; no app is known by name (see README for the push body).
@@ -169,6 +172,8 @@ export async function apply(ctx, config) {
169
172
  ctx.inject(['sessionController', 'permissionPresets', 'webServer'], async (lifeCtx) => {
170
173
  const webServer = lifeCtx.webServer;
171
174
  const host = hostLife(lifeCtx);
175
+ swapCompactionOnce({ enabled: config.replaceCompaction, profileDir: lifeCtx.get('profileContext')?.dir, done: power.compactionSwapped, markDone: power.markCompactionSwapped,
176
+ report: message => { faults.set('compaction-swap', message); lifeCtx.logger.warn(`dsh-world: ${message}`); } });
172
177
  const permissions = createWorkspacePermissions(lifeCtx, options.roomDir, power);
173
178
  // QQ 的两扇门:她自己那条 OneBot 通道的状态与开关,以及 SnowLuma 的控制台。**无条件注册** —— 通道
174
179
  // 关着的时候 /native 回 null,而 SnowLuma 那扇门跟通道没关系。(这里原来还有一半是给外面那个
@@ -308,7 +313,8 @@ export async function apply(ctx, config) {
308
313
  await lifeStop;
309
314
  const outlets = config.outlets.map(outlet => createOutlet(outlet, () => host.origin()));
310
315
  const notifier = { ...(config.toast && toastSupported() ? { toast: windowsToast(config.toastAppId || undefined) } : {}), outlets };
311
- const current = createLifeRuntime({ ctx: lifeCtx, config: { ...config, companionName: names().companion }, options, store: lifeStore, host, notifier, dailyBudget: power.dailyBudget, inWorkspace, photos, alarmContext: now => wechat?.presence(now) });
316
+ const current = createLifeRuntime({ ctx: lifeCtx, config: { ...config, companionName: names().companion }, options, store: lifeStore, host, notifier, dailyBudget: power.dailyBudget, inWorkspace, photos, alarmContext: now => wechat?.presence(now), afterReview: () => { if (power.compactAfterReview())
317
+ homeApply.request(); } });
312
318
  life = current;
313
319
  isHome = current.isHome;
314
320
  if (config.bridge) {
@@ -345,7 +351,7 @@ export async function apply(ctx, config) {
345
351
  if (config.bridge)
346
352
  lifeCtx.effect(() => webServer.register(bridgeRoute(() => bridge, config.allowedHosts)), 'dsh-world bridge route');
347
353
  // Her album lives in her room, so the console shows it whether or not the life line is running.
348
- const sources = consoleSources({ ctx: lifeCtx, config: memoryConfig, archive: store, names, ...(lifeStore ? { lifeStore } : {}), life: () => life, homeApply: homeApply.snapshot, 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,
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,
349
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() ?? [])] });
350
356
  const actions = {
351
357
  async start() {
@@ -381,6 +387,7 @@ export async function apply(ctx, config) {
381
387
  setDailyBudget: yuan => { power.setDailyBudget(yuan); sources.invalidate(); },
382
388
  setMemoryTurns: turns => { power.setMemoryTurns(turns); sources.invalidate(); },
383
389
  setWorkspacePermission: permission => { permissions.set(permission); sources.invalidate(); },
390
+ setCompactAfterReview: on => { power.setCompactAfterReview(on); sources.invalidate(); },
384
391
  async setModules(patch) {
385
392
  if (patch.wechat !== undefined && !config.wechat)
386
393
  return '没有配置微信模块(配置里 wechat: true)';
@@ -28,6 +28,11 @@ const spoken = {
28
28
  wechat_chats: () => '看了看微信能发给谁',
29
29
  wechat_delivery: () => '查了一条微信送到没有',
30
30
  wechat_history: () => '翻了翻微信的聊天记录',
31
+ wechat_image: () => '看了一张微信群里的图片',
32
+ sticker_search: () => '翻了翻表情库',
33
+ sticker_save: () => '把一个表情包收进了表情库',
34
+ sticker_edit: () => '改了改表情库里的表情',
35
+ sticker_remove: () => '整理了一下表情库',
31
36
  send_sticker: () => '发了个表情',
32
37
  web_search: (args) => {
33
38
  const queries = args.queries;
@@ -19,6 +19,8 @@ export interface LifeDeps {
19
19
  timers?: LifeTimers;
20
20
  /** CNY her home may spend a day; undefined or absent is no limit. */
21
21
  dailyBudget?: () => number | undefined;
22
+ /** Called once each evening look back has been handed to her home (not for alarms or greetings, and not when delivery failed). */
23
+ afterReview?: () => void;
22
24
  /** Read-only facts appended after the user's alarm template is rendered. */
23
25
  alarmContext?: (now: Date) => string | undefined;
24
26
  photos?: () => PhotoStore;
@@ -229,7 +229,7 @@ export function createLifeRuntime(deps) {
229
229
  * A message of the plugin's own, taken off the schedule while it is sent and put back if it fails: it backs
230
230
  * off like an alarm, and its turn is never asked about as an early stop. It counts once its turn starts a step.
231
231
  */
232
- async function sayOwn(what, source, scheduledAt, job, take, putBack, text) {
232
+ async function sayOwn(what, source, scheduledAt, job, take, putBack, text, delivered) {
233
233
  try {
234
234
  const agent = await home.open();
235
235
  if (stopped)
@@ -240,6 +240,8 @@ export function createLifeRuntime(deps) {
240
240
  expect(agent, message, what, scheduledAt, source, job, now);
241
241
  earlyStop.startsOwnTurn();
242
242
  await say(agent, message);
243
+ if (!stopped)
244
+ delivered?.();
243
245
  }
244
246
  catch (error) {
245
247
  ctx.logger.error(error);
@@ -280,7 +282,7 @@ export function createLifeRuntime(deps) {
280
282
  return sayOwn('每日回顾', 'review', review.at, { review }, take, () => { state.review = review; }, now => reviewText(review, now, {
281
283
  ...withValue('conversations', existing('conversations')), ...withValue('activity', existing('activity')), ...withValue('snapshot', snapshot),
282
284
  diaryDir: options.diaryDir, selfFile: options.selfFile,
283
- }, timeZone, options.fallbackWakeTime, alarmMessages(), templateValues()));
285
+ }, timeZone, options.fallbackWakeTime, alarmMessages(), templateValues()), () => deps.afterReview?.());
284
286
  }
285
287
  async function send(alarm) {
286
288
  try {
@@ -1,6 +1,5 @@
1
1
  import type { Agent } from '@deepseek-ai/dsh-agent';
2
2
  import type { Session } from '@deepseek-ai/dsh-session';
3
- import { type Faults } from './faults.ts';
4
3
  import type { WorldConfig } from './types.ts';
5
4
  import { type WorldNames, type WorldPrompt } from './worldPrompt.ts';
6
5
  export interface WorldPromptSource {
@@ -19,12 +18,11 @@ export interface WorldPromptSource {
19
18
  * the system prompt before pre-step, so the refresh happens on compaction/end) or explicit console application, so the prompt
20
19
  * stays in the provider-cached prefix. Whether the session is her home is asked per request.
21
20
  *
22
- * Her persona takes the place of the host's: registered under the host persona's name for her agent, it shadows
23
- * the deployment default. Where her preset already gave her agent a persona, that name is taken, so hers follows
24
- * it under its own name and the console says so.
21
+ * Her persona takes the place of DeepSeek Harness's stock identity line, but never of a persona someone has set: it is its own
22
+ * section placed right after the host's persona slot, so a system persona the deployment or her preset already has stays
23
+ * where it is and hers follows it.
25
24
  */
26
25
  export declare function createPromptSections(config: WorldConfig, world: WorldPromptSource, deps: {
27
- faults: Faults;
28
26
  logger: {
29
27
  warn(...args: unknown[]): void;
30
28
  };
@@ -1,11 +1,10 @@
1
- import { errorText } from "./faults.js";
2
1
  import { readPersona, renderPersona } from "./persona.js";
3
2
  import { renderSelf } from "./self.js";
4
3
  import { belongsToWorld, inWorld } from "./sourceArchive.js";
5
4
  import { readTemplate, renderWorldPrompt } from "./worldPrompt.js";
6
5
  import { reassembleOnChange } from "./worldScope.js";
7
- /** The host's persona section; a preset may also register it for its own agents. */
8
- const HOST_PERSONA = 'deployment:persona-prefix';
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
+ const HARNESS_IDENTITY = 'harness:identity';
9
8
  /**
10
9
  * Her persona follows the configured preset; the world prompt is limited to the world's workspace.
11
10
  * Both are sections of the session's system prompt so she sees them on every
@@ -13,9 +12,9 @@ const HOST_PERSONA = 'deployment:persona-prefix';
13
12
  * the system prompt before pre-step, so the refresh happens on compaction/end) or explicit console application, so the prompt
14
13
  * stays in the provider-cached prefix. Whether the session is her home is asked per request.
15
14
  *
16
- * Her persona takes the place of the host's: registered under the host persona's name for her agent, it shadows
17
- * the deployment default. Where her preset already gave her agent a persona, that name is taken, so hers follows
18
- * it under its own name and the console says so.
15
+ * 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
+ * section placed right after the host's persona slot, so a system persona the deployment or her preset already has stays
17
+ * where it is and hers follows it.
19
18
  */
20
19
  export function createPromptSections(config, world, deps) {
21
20
  const entries = new Map();
@@ -46,14 +45,15 @@ export function createPromptSections(config, world, deps) {
46
45
  const prompt = agent.ctx.systemPrompt;
47
46
  const order = prompt.getSectionOrder('DEPLOYMENT_PERSONA_PREFIX') ?? 0;
48
47
  const text = () => entry.text.persona;
48
+ const persona = prompt.section({ name: 'dsh-world-persona', order: order + 1, interpolate: false, text });
49
+ // DeepSeek Harness's own identity line gives way to hers; a persona someone set in DSH sits in its own slot and is left alone.
50
+ // If a preset already put its own words on that identity slot for this agent, they stay exactly as written.
51
+ let identity;
49
52
  try {
50
- entry.persona = prompt.section({ name: HOST_PERSONA, order, interpolate: false, text });
51
- deps.faults.clear('persona');
52
- }
53
- catch (error) {
54
- entry.persona = prompt.section({ name: 'dsh-world-persona', order: order + 1, interpolate: false, text });
55
- deps.faults.set('persona', `她的预设自带人设,你写的人设排在它后面(${errorText(error)})`);
53
+ identity = prompt.section({ name: HARNESS_IDENTITY, order: prompt.getSectionOrder('HARNESS_IDENTITY'), interpolate: false, text: () => '' });
56
54
  }
55
+ catch { /* the slot is already taken for this agent */ }
56
+ entry.persona = () => { persona(); identity?.(); };
57
57
  }
58
58
  return {
59
59
  add(agent) {
package/lib/runtime.js CHANGED
@@ -33,7 +33,7 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
33
33
  const names = () => world?.names?.() ?? world?.prompt.names ?? worldNames(config);
34
34
  const included = (session) => inWorld(session, config, world?.inWorkspace);
35
35
  const faults = new Faults();
36
- const prompts = world && createPromptSections(config, world, { faults, logger: ctx.logger });
36
+ const prompts = world && createPromptSections(config, world, { logger: ctx.logger });
37
37
  const memory = new WeakMap();
38
38
  const attaching = new WeakMap();
39
39
  const disposers = [];
@@ -46,11 +46,9 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
46
46
  const event = session.eventAt(seq);
47
47
  return event?.type === 'user/message' && event.data.source.kind === memorySource;
48
48
  });
49
- /** Locate earlier memory blocks; every runtime start rebuilds from the active scope and real times. */
49
+ /** Restore the loop position; recalled blocks are located directly on the current surface. */
50
50
  async function readMemoryState(session) {
51
- const injected = new Map();
52
51
  let position = { turn: 1, step: 1 };
53
- const surface = new Set(session.surface.nodes);
54
52
  const handle = await ctx.sessionPersistence.open(session.id, 'read');
55
53
  try {
56
54
  for (let offset = 0;; offset += 128) {
@@ -60,9 +58,6 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
60
58
  for (const event of events) {
61
59
  if (event.type === 'step/start')
62
60
  position = { turn: event.data.turn, step: event.data.step };
63
- const block = event.type === 'user/message' && event.data.source.kind === memorySource;
64
- if (block && surface.has(event.seq))
65
- injected.set(event.data.id, event.seq);
66
61
  }
67
62
  }
68
63
  }
@@ -70,20 +65,52 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
70
65
  await handle.close();
71
66
  }
72
67
  const inScope = included(session);
73
- return { reload: true, injected, position, inScope, restart: !inScope && belongsToWorld(session, config) };
68
+ return { reload: true, position, retiring: [], inScope, restart: !inScope && belongsToWorld(session, config) };
74
69
  }
75
- /** Empty system nodes retire only our recalled blocks and derive no model message; original logs stay intact. */
70
+ /**
71
+ * Marks our recalled blocks on the surface for retirement. The empty system node that retires one is accepted by
72
+ * the host only inside an open turn and step, which pre-step and attach are not, so `flushRetired` writes it from
73
+ * the step's request hook, after the step has started and before the request is assembled (#22).
74
+ */
76
75
  function retireMemory(session, state) {
77
- for (const [id, seq] of state.injected) {
78
- if (session.surface.nodes.includes(seq)) {
79
- session.append('system/message', { ...state.position, message: createSystemMessage('') }, { surfaceOp: { op: 'replace', startSeq: seq, endSeq: seq }, sourceEventSeqs: [seq] });
80
- state.restart = true;
81
- }
82
- state.injected.delete(id);
83
- }
76
+ state.retiring = session.surface.nodes.filter(seq => {
77
+ const event = session.eventAt(seq);
78
+ return event?.type === 'user/message' && event.data.source.kind === memorySource;
79
+ });
80
+ if (state.retiring.length)
81
+ state.restart = true;
84
82
  state.reload = true;
85
83
  state.pendingId = undefined;
86
84
  }
85
+ /** Where memory blocks sit on a session's surface, for the log: positions and event types only, never message text. */
86
+ function memoryNodesOn(session) {
87
+ const found = [];
88
+ for (const seq of session.surface.nodes) {
89
+ const event = session.eventAt(seq);
90
+ if (!event)
91
+ continue;
92
+ let message;
93
+ try {
94
+ message = session.deriveEventMessage(event);
95
+ }
96
+ catch {
97
+ continue;
98
+ }
99
+ if (message?.source?.kind === memorySource)
100
+ found.push(`#${seq}(${event.type})`);
101
+ }
102
+ return found.length ? found.slice(0, 8).join('、') + (found.length > 8 ? `…共 ${found.length} 个` : '') : '无';
103
+ }
104
+ /** Empty system nodes retire only our recalled blocks and derive no model message; original logs stay intact. */
105
+ function flushRetired(session, state, position) {
106
+ const retiring = state.retiring;
107
+ state.retiring = [];
108
+ for (const seq of retiring) {
109
+ if (!session.surface.nodes.includes(seq))
110
+ continue;
111
+ session.append('system/message', { ...position, message: createSystemMessage('') }, { surfaceOp: { op: 'replace', startSeq: seq, endSeq: seq }, sourceEventSeqs: [seq] });
112
+ }
113
+ }
87
114
  async function attach(agent) {
88
115
  const { session } = agent;
89
116
  if (memory.has(session) || !mayCarryWorld(session))
@@ -98,9 +125,9 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
98
125
  await archive.schedule(session.id);
99
126
  }
100
127
  const state = await readMemoryState(session);
128
+ // Retiring writes a system/message, which the host only accepts inside an open turn and step; attach runs
129
+ // between turns, so an out-of-scope block is retired by the next pre-step (before any request) instead (#22).
101
130
  memory.set(session, state);
102
- if (!included(session))
103
- retireMemory(session, state);
104
131
  });
105
132
  attaching.set(session, job);
106
133
  try {
@@ -110,31 +137,16 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
110
137
  attaching.delete(session);
111
138
  }
112
139
  }
113
- /** Retires the blocks still on the surface (they must be found, or the session would carry two) and builds a fresh one without the messages already present. */
140
+ /** Retire old blocks, then admit fresh memory through the host's normal append path (#21). */
114
141
  async function freshBlock(session, state) {
115
- const messages = session.deriveMessages();
116
142
  const turns = await history.loadRecentTurns(config.worldId, memoryTurns(), archivedByScope);
117
143
  if (!included(session)) {
118
144
  retireMemory(session, state);
119
145
  return undefined;
120
146
  }
121
- const present = new Set(messages.map(message => message.id));
147
+ const present = new Set(session.deriveMessages().map(message => message.id));
122
148
  const text = renderHistory(excludePresentMessages(turns, present), config.timeZone, names(), config.archiveScope === 'home');
123
- const oldBlocks = messages.filter(message => message.source.kind === memorySource);
124
- for (const [index, message] of oldBlocks.entries()) {
125
- if (!included(session)) {
126
- retireMemory(session, state);
127
- return undefined;
128
- }
129
- const seq = state.injected.get(message.id);
130
- if (seq === undefined || !session.surface.nodes.includes(seq))
131
- throw new Error('dsh-world: cannot locate retained injected context in the host surface');
132
- const replacement = createUserMessage({ content: [{ type: 'text', text: index === 0 ? text : '' }], source: { kind: memorySource, form: 'recall' } });
133
- session.append('user/message', replacement, { surfaceOp: { op: 'replace', startSeq: seq, endSeq: seq }, sourceEventSeqs: [seq] });
134
- state.injected.delete(message.id);
135
- }
136
- if (oldBlocks.length)
137
- return undefined;
149
+ retireMemory(session, state);
138
150
  return text ? createUserMessage({ content: [{ type: 'text', text }], source: { kind: memorySource, form: 'recall' } }) : undefined;
139
151
  }
140
152
  /** Reads what the first catch-up had to leave, once the host can say which sessions belong to her. */
@@ -152,8 +164,6 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
152
164
  if (state && event.type === 'step/start')
153
165
  state.position = { turn: event.data.turn, step: event.data.step };
154
166
  const compacted = event.type === 'compaction/end' && event.data.error === undefined;
155
- if (state && event.type === 'user/message' && event.data.source.kind === memorySource)
156
- state.injected.set(event.data.id, event.seq);
157
167
  if (state && event.type === 'user/message' && event.data.id === state.pendingId) {
158
168
  state.reload = false;
159
169
  state.pendingId = undefined;
@@ -205,15 +215,27 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
205
215
  state.pendingId = block.id;
206
216
  return { ...decision, messages: [block, ...decision.messages] };
207
217
  }));
218
+ // The step is open here and its request is not built yet: the one place retired blocks can be written validly.
219
+ disposers.push(ctx.on('agent/request', async function (payload, next) {
220
+ const state = memory.get(payload.agent.session);
221
+ if (state?.retiring.length)
222
+ flushRetired(payload.agent.session, state, { turn: payload.turn, step: payload.step });
223
+ return next();
224
+ }));
208
225
  disposers.push(ctx.on('llm/stream', async function* (request, next) {
209
226
  const agent = isAgentLoopRequest(request) && request.sessionId ? ctx.agents.get(request.sessionId) : undefined;
210
227
  const owned = agent && included(agent.session);
211
- if (agent && !owned && (prompts?.active(agent.session) || request.messages.some(message => message.source?.kind === memorySource))) {
228
+ const inRequest = agent && !owned ? request.messages.filter(message => message.source?.kind === memorySource).length : 0;
229
+ const placed = !!agent && !owned && !!prompts?.active(agent.session);
230
+ if (agent && !owned && (placed || inRequest)) {
212
231
  const state = memory.get(agent.session);
213
232
  if (state) {
214
233
  retireMemory(agent.session, state);
234
+ flushRetired(agent.session, state, state.position);
215
235
  state.restart = true;
216
236
  }
237
+ const reasons = [inRequest ? `请求里还带着 ${inRequest} 条世界记忆块` : '', placed ? '世界提示还挂在会话上' : ''].filter(Boolean).join(';');
238
+ ctx.logger.warn(`dsh-world: 阻止了会话 ${agent.id}(预设 ${agent.session.header.agentPreset ?? '无'})的一次请求,它不在世界工作区里。原因:${reasons}。${state ? '已尝试退役记忆块' : '这个会话没有记忆状态,没法退役'};退役后会话表面上仍有的记忆节点:${memoryNodesOn(agent.session)}。DSH_WORLD_SCOPE_CHANGED`);
217
239
  yield { type: 'finish', reason: { kind: 'error', failure: { code: 'DSH_WORLD_SCOPE_CHANGED', message: 'dsh-world: 会话已离开世界工作区,已阻止携带世界上下文的请求,请重新发送。' } } };
218
240
  return;
219
241
  }
package/lib/types.d.ts CHANGED
@@ -10,6 +10,8 @@ export interface WorldConfig {
10
10
  archiveScope?: MemoryArchiveScope;
11
11
  /** The life line (home session, alarm, tools, console); on by default. */
12
12
  life?: boolean;
13
+ /** On the first start in a profile, switch its stock compaction row to the tool-free one (restart to load it); on by default. */
14
+ replaceCompaction?: boolean;
13
15
  /** Her diary directory; defaults to `<world>/diary`. */
14
16
  diaryDir?: string;
15
17
  /** Local HH:MM of the morning wake when no alarm is pending (she set none, or cancelled hers); 09:00 by default. */
@@ -2,7 +2,7 @@ import { type MemoryArchiveScope } from './archiveSelection.ts';
2
2
  /** How many of the newest turns the memory block carries when nothing else is set. */
3
3
  export declare const DEFAULT_MEMORY_TURNS = 200;
4
4
  /** WeChat group messages read before a mention, and seconds a private image waits for its companions. */
5
- export declare const DEFAULT_WECHAT_CONTEXT = 8, MAX_WECHAT_CONTEXT = 20;
5
+ export declare const DEFAULT_WECHAT_CONTEXT = 5, MAX_WECHAT_CONTEXT = 20;
6
6
  export declare const DEFAULT_WECHAT_BUFFER_SECONDS = 3, MAX_WECHAT_BUFFER_SECONDS = 30;
7
7
  /**
8
8
  * Her world's own settings, changed from the world console and kept in `<world>/world.json` so they outlast a
@@ -17,6 +17,12 @@ export declare function createWorldSwitch(worldDir: string, configuredScope?: Me
17
17
  setArchiveScope(scope: MemoryArchiveScope): void;
18
18
  workspacePermission: () => string;
19
19
  setWorkspacePermission(permission: string): void;
20
+ /** After each evening look back her home is applied and compacted, so the 我是谁 she has just rewritten takes effect; on unless the partner turns it off. */
21
+ compactAfterReview: () => boolean;
22
+ setCompactAfterReview(on: boolean): void;
23
+ /** Whether the profile has been switched to the tool-free compaction (by this plugin or by hand); asked once, so putting the stock one back sticks. */
24
+ compactionSwapped: () => boolean;
25
+ markCompactionSwapped: () => void;
20
26
  running: () => boolean;
21
27
  set: (running: boolean) => void;
22
28
  /** CNY a day for her home; undefined is no limit. */
@@ -26,8 +32,9 @@ export declare function createWorldSwitch(worldDir: string, configuredScope?: Me
26
32
  memoryTurns: () => number;
27
33
  setMemoryTurns(turns: number | undefined): void;
28
34
  /**
29
- * The console's switches for the WeChat and QQ modules. WeChat is on unless turned off; QQ, whose SDK is an
30
- * optional dependency, is off until turned on, so its code is not even loaded before someone asks for it.
35
+ * The console's switches for the WeChat and QQ modules; both are off until someone turns them on. QQ's SDK is an
36
+ * optional dependency, so its code is not even loaded before then. WeChat used to default to on, so a world that
37
+ * never stored a choice but whose WeChat module has already run (it keeps its outbox) stays on after the upgrade.
31
38
  */
32
39
  wechatEnabled: () => boolean;
33
40
  qqEnabled: () => boolean;
@@ -5,7 +5,7 @@ import { validArchiveScope } from "./archiveSelection.js";
5
5
  /** How many of the newest turns the memory block carries when nothing else is set. */
6
6
  export const DEFAULT_MEMORY_TURNS = 200;
7
7
  /** WeChat group messages read before a mention, and seconds a private image waits for its companions. */
8
- export const DEFAULT_WECHAT_CONTEXT = 8, MAX_WECHAT_CONTEXT = 20;
8
+ export const DEFAULT_WECHAT_CONTEXT = 5, MAX_WECHAT_CONTEXT = 20;
9
9
  export const DEFAULT_WECHAT_BUFFER_SECONDS = 3, MAX_WECHAT_BUFFER_SECONDS = 30;
10
10
  /**
11
11
  * Her world's own settings, changed from the world console and kept in `<world>/world.json` so they outlast a
@@ -24,8 +24,10 @@ export function createWorldSwitch(worldDir, configuredScope = 'workspace') {
24
24
  ...(validWorkspacePermission(stored?.workspacePermission) ? { workspacePermission: stored.workspacePermission } : {}),
25
25
  ...(validWechatContext(stored?.wechatContext) ? { wechatContext: stored.wechatContext } : {}),
26
26
  ...(validWechatBuffer(stored?.wechatBufferSeconds) ? { wechatBufferSeconds: stored.wechatBufferSeconds } : {}),
27
- ...(stored?.wechatEnabled === false ? { wechatEnabled: false } : {}),
27
+ ...(typeof stored?.wechatEnabled === 'boolean' ? { wechatEnabled: stored.wechatEnabled } : {}),
28
28
  ...(typeof stored?.qqEnabled === 'boolean' ? { qqEnabled: stored.qqEnabled } : {}),
29
+ ...(stored?.compactAfterReview === false ? { compactAfterReview: false } : {}),
30
+ ...(stored?.compactionSwapped === true ? { compactionSwapped: true } : {}),
29
31
  };
30
32
  const activeScope = settings.archiveScope ?? configuredScope;
31
33
  function save(next) {
@@ -47,6 +49,15 @@ export function createWorldSwitch(worldDir, configuredScope = 'workspace') {
47
49
  throw new Error('工作区权限必须为非空字符串');
48
50
  save({ ...settings, workspacePermission: permission });
49
51
  },
52
+ /** After each evening look back her home is applied and compacted, so the 我是谁 she has just rewritten takes effect; on unless the partner turns it off. */
53
+ compactAfterReview: () => settings.compactAfterReview !== false,
54
+ setCompactAfterReview(on) {
55
+ const { compactAfterReview: _old, ...rest } = settings;
56
+ save(on ? rest : { ...rest, compactAfterReview: false });
57
+ },
58
+ /** Whether the profile has been switched to the tool-free compaction (by this plugin or by hand); asked once, so putting the stock one back sticks. */
59
+ compactionSwapped: () => settings.compactionSwapped === true,
60
+ markCompactionSwapped: () => save({ ...settings, compactionSwapped: true }),
50
61
  running: () => settings.running,
51
62
  set: (running) => save({ ...settings, running }),
52
63
  /** CNY a day for her home; undefined is no limit. */
@@ -62,15 +73,16 @@ export function createWorldSwitch(worldDir, configuredScope = 'workspace') {
62
73
  save(turns === undefined || turns === DEFAULT_MEMORY_TURNS ? rest : { ...rest, memoryTurns: turns });
63
74
  },
64
75
  /**
65
- * The console's switches for the WeChat and QQ modules. WeChat is on unless turned off; QQ, whose SDK is an
66
- * optional dependency, is off until turned on, so its code is not even loaded before someone asks for it.
76
+ * The console's switches for the WeChat and QQ modules; both are off until someone turns them on. QQ's SDK is an
77
+ * optional dependency, so its code is not even loaded before then. WeChat used to default to on, so a world that
78
+ * never stored a choice but whose WeChat module has already run (it keeps its outbox) stays on after the upgrade.
67
79
  */
68
- wechatEnabled: () => settings.wechatEnabled !== false,
80
+ wechatEnabled: () => settings.wechatEnabled ?? existsSync(join(worldDir, 'wechat-outbox.sqlite')),
69
81
  qqEnabled: () => settings.qqEnabled === true,
70
82
  setModules(next) {
71
83
  const { wechatEnabled, qqEnabled, ...rest } = settings;
72
- const wechat = next.wechat ?? wechatEnabled !== false, qq = next.qq ?? qqEnabled === true;
73
- save({ ...rest, ...(wechat ? {} : { wechatEnabled: false }), ...(qq ? { qqEnabled: true } : {}) });
84
+ const wechat = next.wechat ?? wechatEnabled ?? existsSync(join(worldDir, 'wechat-outbox.sqlite')), qq = next.qq ?? qqEnabled === true;
85
+ save({ ...rest, wechatEnabled: wechat, ...(qq ? { qqEnabled: true } : {}) });
74
86
  },
75
87
  /** Read by the WeChat adapter on its next poll; a batch already waiting keeps the value it started with. */
76
88
  wechatContext: () => settings.wechatContext ?? DEFAULT_WECHAT_CONTEXT,