dsh-world 0.7.2 → 0.7.4

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 (78) hide show
  1. package/CHANGELOG.md +403 -379
  2. package/INSTALL.md +314 -314
  3. package/LICENSE +21 -21
  4. package/NOTES.md +23 -13
  5. package/README.md +22 -7
  6. package/client/index.js +74 -27
  7. package/cordis.patch.yml +6 -6
  8. package/lib/archiveSelection.d.ts +6 -2
  9. package/lib/archiveSelection.js +21 -12
  10. package/lib/compaction.d.ts +7 -0
  11. package/lib/compaction.js +18 -9
  12. package/lib/compactionSwap.d.ts +17 -0
  13. package/lib/compactionSwap.js +68 -6
  14. package/lib/console/routes.d.ts +2 -3
  15. package/lib/console/routes.js +7 -8
  16. package/lib/console/snapshot.d.ts +1 -3
  17. package/lib/console/snapshot.js +0 -3
  18. package/lib/ecosystem/bridge/bridge.d.ts +5 -0
  19. package/lib/ecosystem/bridge/bridge.js +2 -1
  20. package/lib/ecosystem/bridge/route.d.ts +4 -6
  21. package/lib/ecosystem/bridge/route.js +34 -58
  22. package/lib/ecosystem/qq/panel.d.ts +0 -1
  23. package/lib/ecosystem/qq/route.d.ts +6 -7
  24. package/lib/ecosystem/qq/route.js +10 -10
  25. package/lib/ecosystem/qq/snowluma-start.d.ts +1 -0
  26. package/lib/ecosystem/qq/snowluma-start.js +41 -8
  27. package/lib/ecosystem/qq/supervisor.d.ts +1 -2
  28. package/lib/ecosystem/qq/supervisor.js +4 -2
  29. package/lib/ecosystem/qq-native/index.js +2 -0
  30. package/lib/ecosystem/qq-native/native-bridge.d.ts +0 -1
  31. package/lib/ecosystem/qq-native/native-bridge.js +0 -2
  32. package/lib/ecosystem/qq-native/snowluma.js +11 -2
  33. package/lib/ecosystem/shared/turn.d.ts +3 -0
  34. package/lib/ecosystem/shared/turn.js +9 -2
  35. package/lib/ecosystem/wechat/home.d.ts +3 -0
  36. package/lib/ecosystem/wechat/home.js +12 -4
  37. package/lib/ecosystem/wechat/index.d.ts +0 -1
  38. package/lib/ecosystem/wechat/index.js +9 -6
  39. package/lib/hostContract.d.ts +19 -0
  40. package/lib/index.js +117 -49
  41. package/lib/life/toolRegistry.js +2 -2
  42. package/lib/memoryFiles.d.ts +0 -1
  43. package/lib/memoryStore.d.ts +0 -1
  44. package/lib/memoryStore.js +0 -1
  45. package/lib/memoryTools.d.ts +0 -1
  46. package/lib/memoryTools.js +2 -3
  47. package/lib/mood.d.ts +28 -0
  48. package/lib/mood.js +69 -0
  49. package/lib/promptSection.d.ts +7 -5
  50. package/lib/promptSection.js +74 -28
  51. package/lib/runtime.d.ts +6 -2
  52. package/lib/runtime.js +163 -26
  53. package/lib/self.d.ts +1 -1
  54. package/lib/self.js +1 -1
  55. package/lib/sourceArchive.d.ts +4 -2
  56. package/lib/sourceArchive.js +18 -4
  57. package/lib/store.js +2 -1
  58. package/lib/types.d.ts +3 -1
  59. package/lib/worldPrompt.d.ts +2 -3
  60. package/lib/worldPrompt.js +2 -3
  61. package/lib/worldRoutes.d.ts +9 -0
  62. package/lib/worldRoutes.js +29 -0
  63. package/lib/worldScope.d.ts +5 -5
  64. package/lib/worldScope.js +16 -7
  65. package/lib/worldSwitch.d.ts +1 -2
  66. package/lib/worldSwitch.js +1 -1
  67. package/package.json +17 -16
  68. package/scripts/compact-home.mjs +29 -29
  69. package/scripts/enable-tool-free-compaction.ps1 +33 -33
  70. package/scripts/import-stickers.mjs +17 -17
  71. package/scripts/update-world.mjs +2 -2
  72. package/src/ecosystem/README.md +1 -1
  73. package/src/ecosystem/wechat/windows/README.md +3 -3
  74. package/src/ecosystem/wechat/windows/adapter.py +21 -3
  75. package/src/ecosystem/wechat/windows/engine/profiles.json +142 -142
  76. package/src/ecosystem/wechat/windows/presence.py +109 -109
  77. package/templates/alarm.md +2 -2
  78. package/templates/world-prompt.md +11 -2
@@ -42,9 +42,8 @@ export function renderTemplate(template, flags, values) {
42
42
  return text.replace(/\{\{(\w+)\}\}/g, (tag, name) => values[name] ?? tag).replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim();
43
43
  }
44
44
  /**
45
- * The one world prompt every world session carries in its system prompt. `template` and `self` are read at
46
- * session start, after compaction or on explicit console application, so ordinary saves keep the cached prefix. The world
47
- * line's tools live in the home alone; the template tells other sessions where to find them.
45
+ * The one world prompt every world session carries in its system prompt. The world line's tools live in the home alone;
46
+ * the template tells other sessions where to find them.
48
47
  */
49
48
  export function renderWorldPrompt(prompt, template, self, home) {
50
49
  const { life, names } = prompt;
@@ -0,0 +1,9 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ export declare const WORLDS_PATH = "/dsh-world/worlds";
3
+ export declare const validWorldId: (id: string) => boolean;
4
+ export declare const worldPath: (id: string) => string;
5
+ export declare function worldListRoute(worlds: ReadonlyMap<string, readonly string[]>): {
6
+ kind: "exact";
7
+ path: string;
8
+ handler(req: IncomingMessage, res: ServerResponse): void;
9
+ };
@@ -0,0 +1,29 @@
1
+ import { knownHost, sendJson } from "./http.js";
2
+ export const WORLDS_PATH = '/dsh-world/worlds';
3
+ export const validWorldId = (id) => /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(id);
4
+ export const worldPath = (id) => `${WORLDS_PATH}/${id}`;
5
+ export function worldListRoute(worlds) {
6
+ return {
7
+ kind: 'exact', path: WORLDS_PATH,
8
+ handler(req, res) {
9
+ const ids = [...worlds].filter(([, hosts]) => knownHost(req.headers.host, hosts)).map(([id]) => id).sort();
10
+ if (!ids.length || req.headers['sec-fetch-site'] === 'cross-site') {
11
+ sendJson(res, { status: 403, body: { error: 'forbidden' } });
12
+ return;
13
+ }
14
+ if (req.method !== 'GET') {
15
+ sendJson(res, { status: 405, body: { error: 'method not allowed' }, headers: { allow: 'GET' } });
16
+ return;
17
+ }
18
+ const { searchParams } = new URL(req.url ?? WORLDS_PATH, 'http://localhost');
19
+ const limit = Number(searchParams.get('limit') ?? 20), offset = Number(searchParams.get('offset') ?? 0);
20
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100 || !Number.isSafeInteger(offset) || offset < 0) {
21
+ sendJson(res, { status: 400, body: { error: '世界列表分页参数无效' } });
22
+ return;
23
+ }
24
+ const worldIds = ids.slice(offset, offset + limit);
25
+ const nextOffset = offset + worldIds.length < ids.length ? offset + worldIds.length : null;
26
+ sendJson(res, { status: 200, body: { worldIds, nextOffset } });
27
+ },
28
+ };
29
+ }
@@ -3,7 +3,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent';
3
3
  import type { Session } from '@deepseek-ai/dsh-session';
4
4
  import type { ToolDefinition } from '@deepseek-ai/dsh-tools';
5
5
  /**
6
- * Her world reaches only the sessions of her room's workspace (plus her persona, which follows the preset). A
6
+ * Her world and persona reach only her preset's sessions in her room's workspace. A
7
7
  * session can join or leave the workspace at any time, so every way in checks again where it matters: before an
8
8
  * injection, after every wait, and when a tool runs.
9
9
  */
@@ -13,10 +13,10 @@ export declare class OutsideWorldError extends Error {
13
13
  }
14
14
  /** The agent, if it is (still) in her world; without a predicate every agent is. */
15
15
  export declare function admit(inWorld: InWorld | undefined, agent: Agent): Agent;
16
- /** The tool, refusing to run once its agent has left her world; `left` lets the owner take it away. */
17
- export declare function scopedTool(tool: ToolDefinition, inside: () => boolean, left?: () => void): ToolDefinition;
16
+ /** The same scope check controls step admission and execution; older hosts ignore the registration condition. */
17
+ export declare function registerScopedTool(agent: Agent, tool: ToolDefinition, inside: () => boolean, left?: () => void): () => void;
18
18
  /**
19
- * Membership can change after `agent/created`, so whatever a session's world providers depend on is synced as its
20
- * system prompt is assembled; when `sync` changed something, the prompt is assembled again to include it.
19
+ * DSH 0.2.2 selects tools before prompt assembly, so synchronize at turn start and between steps as well.
20
+ * The assembly check still catches membership changes while a request is being prepared.
21
21
  */
22
22
  export declare function reassembleOnChange(ctx: Context, sync: (agent: Agent) => boolean): () => void;
package/lib/worldScope.js CHANGED
@@ -7,20 +7,29 @@ export function admit(inWorld, agent) {
7
7
  throw new OutsideWorldError();
8
8
  return agent;
9
9
  }
10
- /** The tool, refusing to run once its agent has left her world; `left` lets the owner take it away. */
11
- export function scopedTool(tool, inside, left) {
12
- return { ...tool, execute: (args, exec) => {
10
+ /** The same scope check controls step admission and execution; older hosts ignore the registration condition. */
11
+ export function registerScopedTool(agent, tool, inside, left) {
12
+ const register = agent.ctx.tools.register.bind(agent.ctx.tools);
13
+ return register({ ...tool, execute: (args, exec) => {
13
14
  if (!inside()) {
14
15
  left?.();
15
16
  throw new OutsideWorldError();
16
17
  }
17
18
  return tool.execute(args, exec);
18
- } };
19
+ } }, { when: inside });
19
20
  }
20
21
  /**
21
- * Membership can change after `agent/created`, so whatever a session's world providers depend on is synced as its
22
- * system prompt is assembled; when `sync` changed something, the prompt is assembled again to include it.
22
+ * DSH 0.2.2 selects tools before prompt assembly, so synchronize at turn start and between steps as well.
23
+ * The assembly check still catches membership changes while a request is being prepared.
23
24
  */
24
25
  export function reassembleOnChange(ctx, sync) {
25
- return ctx.on('system-prompt/assemble', (_assembly, context, next) => context.agent && sync(context.agent) ? context.agent.ctx.systemPrompt.assemble(context) : next());
26
+ const beforeStep = ctx.on('session/event', (session, event) => {
27
+ if (event.type !== 'turn/start' && event.type !== 'step/end')
28
+ return;
29
+ const agent = ctx.get('agents')?.get(session.id);
30
+ if (agent)
31
+ sync(agent);
32
+ });
33
+ const assemble = ctx.on('system-prompt/assemble', (_assembly, context, next) => context.agent && sync(context.agent) ? context.agent.ctx.systemPrompt.assemble(context) : next());
34
+ return () => { beforeStep(); assemble(); };
26
35
  }
@@ -19,7 +19,7 @@ export declare function createWorldSwitch(worldDir: string, configuredScope?: Me
19
19
  setArchiveScope(scope: MemoryArchiveScope): void;
20
20
  workspacePermission: () => string;
21
21
  setWorkspacePermission(permission: string): void;
22
- /** 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. */
22
+ /** Compact the home after the evening look back unless the partner turns it off. */
23
23
  compactAfterReview: () => boolean;
24
24
  setCompactAfterReview(on: boolean): void;
25
25
  /** 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. */
@@ -63,7 +63,6 @@ export declare function createWorldSwitch(worldDir: string, configuredScope?: Me
63
63
  bufferSeconds?: number | null;
64
64
  }): void;
65
65
  };
66
- export type WorldSwitch = ReturnType<typeof createWorldSwitch>;
67
66
  export declare const validTurns: (value: unknown) => value is number;
68
67
  export declare const validColdHours: (value: unknown) => value is number;
69
68
  export declare const validWorkspacePermission: (value: unknown) => value is string;
@@ -55,7 +55,7 @@ export function createWorldSwitch(worldDir, configuredScope = 'workspace', confi
55
55
  throw new Error('工作区权限必须为非空字符串');
56
56
  save({ ...settings, workspacePermission: permission });
57
57
  },
58
- /** 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. */
58
+ /** Compact the home after the evening look back unless the partner turns it off. */
59
59
  compactAfterReview: () => settings.compactAfterReview !== false,
60
60
  setCompactAfterReview(on) {
61
61
  const { compactAfterReview: _old, ...rest } = settings;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-world",
3
- "version": "0.7.2",
3
+ "version": "0.7.4",
4
4
  "description": "Cross-session memory, persona and life routines for DSH, with a world console, tool-free compaction, native QQ and Windows WeChat messaging, group history and quoted replies",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -46,7 +46,7 @@
46
46
  ],
47
47
  "engines": {
48
48
  "node": ">=22.16.0",
49
- "dsh": ">=0.2.1-rc.2 <0.3.0-0"
49
+ "dsh": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0"
50
50
  },
51
51
  "scripts": {
52
52
  "build": "node -e \"require('fs').rmSync('lib',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
@@ -69,7 +69,8 @@
69
69
  "dshReleases": {
70
70
  "0.2.1-rc.2": "compatible",
71
71
  "0.2.1-rc.3": "compatible",
72
- "0.2.1-rc.5": "compatible"
72
+ "0.2.1-rc.5": "compatible",
73
+ "0.2.2-rc.1": "compatible"
73
74
  }
74
75
  }
75
76
  },
@@ -78,19 +79,19 @@
78
79
  },
79
80
  "peerDependencies": {
80
81
  "@snowluma/sdk": "^2.2.1",
81
- "@deepseek-ai/dsh-plugin-manager": ">=0.2.1-rc.3 <0.3.0-0",
82
- "@deepseek-ai/dsh-atomic-write": ">=0.2.1-rc.3 <0.3.0-0",
83
- "@deepseek-ai/cordis": "~4.0.5",
84
- "@deepseek-ai/dsh-agent": ">=0.2.1-rc.2 <0.3.0-0",
85
- "@deepseek-ai/dsh-attachment": ">=0.2.1-rc.2 <0.3.0-0",
86
- "@deepseek-ai/dsh-compaction": ">=0.2.1-rc.2 <0.3.0-0",
87
- "@deepseek-ai/dsh-home-paths": ">=0.2.1-rc.2 <0.3.0-0",
88
- "@deepseek-ai/dsh-llm": ">=0.2.1-rc.2 <0.3.0-0",
89
- "@deepseek-ai/dsh-session": ">=0.2.1-rc.2 <0.3.0-0",
90
- "@deepseek-ai/dsh-session-persistence": ">=0.2.1-rc.2 <0.3.0-0",
91
- "@deepseek-ai/dsh-tools": ">=0.2.1-rc.2 <0.3.0-0",
92
- "@deepseek-ai/schemastery": "~3.18.5",
93
- "@deepseek-ai/dsh-commands": ">=0.2.1-rc.2 <0.3.0-0"
82
+ "@deepseek-ai/dsh-plugin-manager": ">=0.2.1-rc.3 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0",
83
+ "@deepseek-ai/dsh-atomic-write": ">=0.2.1-rc.3 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0",
84
+ "@deepseek-ai/cordis": "~4.0.5 || ~4.1.0",
85
+ "@deepseek-ai/dsh-agent": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0",
86
+ "@deepseek-ai/dsh-attachment": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0",
87
+ "@deepseek-ai/dsh-compaction": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0",
88
+ "@deepseek-ai/dsh-home-paths": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0",
89
+ "@deepseek-ai/dsh-llm": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0",
90
+ "@deepseek-ai/dsh-session": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0",
91
+ "@deepseek-ai/dsh-session-persistence": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0",
92
+ "@deepseek-ai/dsh-tools": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0",
93
+ "@deepseek-ai/schemastery": "~3.18.5 || ~3.19.0",
94
+ "@deepseek-ai/dsh-commands": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0"
94
95
  },
95
96
  "peerDependenciesMeta": {
96
97
  "@snowluma/sdk": {
@@ -1,29 +1,29 @@
1
- #!/usr/bin/env node
2
- // Asks a running world to compact her home conversation once (held behind her running turn).
3
- // Needs `bridge: true` in the plugin config. Usage: node scripts/compact-home.mjs [world directory]
4
- // The world directory defaults to $DSH_WORLD_DIR, then ~/.dsh/worlds/<the only world there>.
5
- import { existsSync, readFileSync, readdirSync } from 'node:fs';
6
- import { homedir } from 'node:os';
7
- import { join } from 'node:path';
8
-
9
- function worldDir() {
10
- if (process.argv[2]) return process.argv[2];
11
- if (process.env.DSH_WORLD_DIR) return process.env.DSH_WORLD_DIR;
12
- const root = join(homedir(), '.dsh', 'worlds');
13
- const worlds = existsSync(root) ? readdirSync(root, { withFileTypes: true }).filter(entry => entry.isDirectory()).map(entry => entry.name) : [];
14
- if (worlds.length !== 1) throw new Error(`找不到唯一的世界目录,请把路径作为参数传入(在 ${root} 下找到 ${worlds.length} 个)`);
15
- return join(root, worlds[0]);
16
- }
17
-
18
- try {
19
- const file = join(worldDir(), 'bridge.json');
20
- if (!existsSync(file)) throw new Error(`没有 ${file}:世界没有在运行,或者没有开启 bridge`);
21
- const { origin, token } = JSON.parse(readFileSync(file, 'utf8'));
22
- const response = await fetch(new URL('/dsh-world/bridge/compact', origin), { method: 'POST', headers: { 'x-dsh-world-token': token }, signal: AbortSignal.timeout(15000) });
23
- const body = await response.json().catch(() => ({}));
24
- if (response.status === 202) console.log('已请求压缩家会话;她正在忙的话会等这一轮结束后再压缩。');
25
- else { console.error(`没有受理(${response.status}):${body.error ?? '未知原因'}`); process.exitCode = 1; }
26
- } catch (error) {
27
- console.error(error instanceof Error ? error.message : String(error));
28
- process.exitCode = 1;
29
- }
1
+ #!/usr/bin/env node
2
+ // Asks a running world to compact her home conversation once (held behind her running turn).
3
+ // Needs `bridge: true` in the plugin config. Usage: node scripts/compact-home.mjs [world directory]
4
+ // The world directory defaults to $DSH_WORLD_DIR, then ~/.dsh/worlds/<the only world there>.
5
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
6
+ import { homedir } from 'node:os';
7
+ import { join } from 'node:path';
8
+
9
+ function worldDir() {
10
+ if (process.argv[2]) return process.argv[2];
11
+ if (process.env.DSH_WORLD_DIR) return process.env.DSH_WORLD_DIR;
12
+ const root = join(homedir(), '.dsh', 'worlds');
13
+ const worlds = existsSync(root) ? readdirSync(root, { withFileTypes: true }).filter(entry => entry.isDirectory()).map(entry => entry.name) : [];
14
+ if (worlds.length !== 1) throw new Error(`找不到唯一的世界目录,请把路径作为参数传入(在 ${root} 下找到 ${worlds.length} 个)`);
15
+ return join(root, worlds[0]);
16
+ }
17
+
18
+ try {
19
+ const file = join(worldDir(), 'bridge.json');
20
+ if (!existsSync(file)) throw new Error(`没有 ${file}:世界没有在运行,或者没有开启 bridge`);
21
+ const { origin, compactPath, token } = JSON.parse(readFileSync(file, 'utf8'));
22
+ const response = await fetch(new URL(compactPath, origin), { method: 'POST', headers: { 'x-dsh-world-token': token }, signal: AbortSignal.timeout(15000) });
23
+ const body = await response.json().catch(() => ({}));
24
+ if (response.status === 202) console.log('已请求压缩家会话;她正在忙的话会等这一轮结束后再压缩。');
25
+ else { console.error(`没有受理(${response.status}):${body.error ?? '未知原因'}`); process.exitCode = 1; }
26
+ } catch (error) {
27
+ console.error(error instanceof Error ? error.message : String(error));
28
+ process.exitCode = 1;
29
+ }
@@ -1,33 +1,33 @@
1
- param(
2
- [Parameter(Mandatory = $true)]
3
- [string] $profilePath
4
- )
5
-
6
- $ErrorActionPreference = 'Stop'
7
- try {
8
- $resolvedProfile = (Resolve-Path -LiteralPath $profilePath).Path
9
- $packagePath = Join-Path $resolvedProfile 'package.json'
10
- $patchPath = Join-Path $resolvedProfile 'cordis.patch.yml'
11
- $package = Get-Content -LiteralPath $packagePath -Raw | ConvertFrom-Json
12
- if (-not $package.dependencies.'dsh-world') {
13
- throw 'Install the built dsh-world package in this profile before enabling its compaction backend.'
14
- }
15
- $content = [System.IO.File]::ReadAllText($patchPath)
16
- if ($content -match '(?m)^\s*name:\s*[''"'']?dsh-world/compaction[''"'']?\s*$') {
17
- Write-Output 'Tool-free compaction is already configured.'
18
- return
19
- }
20
- $pattern = '(?m)^(\s*name:\s*)([''"'']?)@deepseek-ai/dsh-compaction-basic\2([ \t]*(?:#.*)?\r?)$'
21
- $matchesFound = [regex]::Matches($content, $pattern)
22
- if ($matchesFound.Count -ne 1) {
23
- throw "Expected exactly one explicit compaction-basic entry in cordis.patch.yml; found $($matchesFound.Count). No configuration was changed."
24
- }
25
- $updated = [regex]::Replace($content, $pattern, '${1}''dsh-world/compaction''${3}')
26
- $backupPath = "$patchPath.dsh-world.$([Guid]::NewGuid().ToString('N')).bak"
27
- $temporaryPath = "$patchPath.$([Guid]::NewGuid().ToString('N')).tmp"
28
- [System.IO.File]::WriteAllText($temporaryPath, $updated, [System.Text.UTF8Encoding]::new($false))
29
- [System.IO.File]::Replace($temporaryPath, $patchPath, $backupPath)
30
- Write-Output "Configured tool-free compaction. Restart this DSH profile to load it. Backup: $backupPath"
31
- } catch {
32
- throw "Cannot configure dsh-world compaction: $($_.Exception.Message)"
33
- }
1
+ param(
2
+ [Parameter(Mandatory = $true)]
3
+ [string] $profilePath
4
+ )
5
+
6
+ $ErrorActionPreference = 'Stop'
7
+ try {
8
+ $resolvedProfile = (Resolve-Path -LiteralPath $profilePath).Path
9
+ $packagePath = Join-Path $resolvedProfile 'package.json'
10
+ $patchPath = Join-Path $resolvedProfile 'cordis.patch.yml'
11
+ $package = Get-Content -LiteralPath $packagePath -Raw | ConvertFrom-Json
12
+ if (-not $package.dependencies.'dsh-world') {
13
+ throw 'Install the built dsh-world package in this profile before enabling its compaction backend.'
14
+ }
15
+ $content = [System.IO.File]::ReadAllText($patchPath)
16
+ if ($content -match '(?m)^\s*name:\s*[''"'']?dsh-world/compaction[''"'']?\s*$') {
17
+ Write-Output 'Tool-free compaction is already configured.'
18
+ return
19
+ }
20
+ $pattern = '(?m)^(\s*name:\s*)([''"'']?)@deepseek-ai/dsh-compaction-basic\2([ \t]*(?:#.*)?\r?)$'
21
+ $matchesFound = [regex]::Matches($content, $pattern)
22
+ if ($matchesFound.Count -ne 1) {
23
+ throw "Expected exactly one explicit compaction-basic entry in cordis.patch.yml; found $($matchesFound.Count). No configuration was changed."
24
+ }
25
+ $updated = [regex]::Replace($content, $pattern, '${1}''dsh-world/compaction''${3}')
26
+ $backupPath = "$patchPath.dsh-world.$([Guid]::NewGuid().ToString('N')).bak"
27
+ $temporaryPath = "$patchPath.$([Guid]::NewGuid().ToString('N')).tmp"
28
+ [System.IO.File]::WriteAllText($temporaryPath, $updated, [System.Text.UTF8Encoding]::new($false))
29
+ [System.IO.File]::Replace($temporaryPath, $patchPath, $backupPath)
30
+ Write-Output "Configured tool-free compaction. Restart this DSH profile to load it. Backup: $backupPath"
31
+ } catch {
32
+ throw "Cannot configure dsh-world compaction: $($_.Exception.Message)"
33
+ }
@@ -1,17 +1,17 @@
1
- // One-time import of the older sticker plugin's library (catalog.json + assets/) into the world's own sticker library.
2
- // Usage: node scripts/import-stickers.mjs <older library folder, e.g. ~/.dsh/memes> <world folder, e.g. ~/.dsh/worlds/<id>>
3
- // Ids, names and tags carry over; packs and long meanings do not. Running it again adds nothing. The older folder is only read.
4
- import { join, resolve } from 'node:path';
5
- import { pathToFileURL, fileURLToPath } from 'node:url';
6
-
7
- const [legacy, world] = process.argv.slice(2);
8
- if (!legacy || !world) {
9
- console.error('用法:node scripts/import-stickers.mjs <旧表情包目录> <世界目录>');
10
- process.exit(2);
11
- }
12
- const modulePath = join(fileURLToPath(new URL('..', import.meta.url)), 'lib', 'ecosystem', 'wechat', 'stickerLibrary.js');
13
- const { createStickerLibrary, importLegacyStickers } = await import(pathToFileURL(modulePath).href);
14
- const library = createStickerLibrary(join(resolve(world), 'stickers'));
15
- const report = await importLegacyStickers(resolve(legacy), library);
16
- console.log(`导入 ${report.imported} 张,已在库里的 ${report.duplicates} 张,跳过 ${report.skipped.length} 张;表情库现有 ${(await library.list()).length} 张。`);
17
- for (const line of report.skipped) console.log(` 跳过 ${line}`);
1
+ // One-time import of the older sticker plugin's library (catalog.json + assets/) into the world's own sticker library.
2
+ // Usage: node scripts/import-stickers.mjs <older library folder, e.g. ~/.dsh/memes> <world folder, e.g. ~/.dsh/worlds/<id>>
3
+ // Ids, names and tags carry over; packs and long meanings do not. Running it again adds nothing. The older folder is only read.
4
+ import { join, resolve } from 'node:path';
5
+ import { pathToFileURL, fileURLToPath } from 'node:url';
6
+
7
+ const [legacy, world] = process.argv.slice(2);
8
+ if (!legacy || !world) {
9
+ console.error('用法:node scripts/import-stickers.mjs <旧表情包目录> <世界目录>');
10
+ process.exit(2);
11
+ }
12
+ const modulePath = join(fileURLToPath(new URL('..', import.meta.url)), 'lib', 'ecosystem', 'wechat', 'stickerLibrary.js');
13
+ const { createStickerLibrary, importLegacyStickers } = await import(pathToFileURL(modulePath).href);
14
+ const library = createStickerLibrary(join(resolve(world), 'stickers'));
15
+ const report = await importLegacyStickers(resolve(legacy), library);
16
+ console.log(`导入 ${report.imported} 张,已在库里的 ${report.duplicates} 张,跳过 ${report.skipped.length} 张;表情库现有 ${(await library.list()).length} 张。`);
17
+ for (const line of report.skipped) console.log(` 跳过 ${line}`);
@@ -7,8 +7,8 @@ import { fileURLToPath } from 'node:url';
7
7
  import { isDeepStrictEqual, parseArgs, promisify } from 'node:util';
8
8
 
9
9
  const execute = promisify(execFile);
10
- const command = (file, args, options = {}) => execute(file, args, { windowsHide: true, maxBuffer: 16 * 1024 * 1024, ...options });
11
- // GNU tar (the one Git Bash puts first) reads the `C:` of an archive path as a remote host; naming the archive from its own folder works with every tar.
10
+ const command = (file, args, options = {}) => execute(file, args, { windowsHide: true, maxBuffer: 16 * 1024 * 1024, ...options });
11
+ // GNU tar (the one Git Bash puts first) reads the `C:` of an archive path as a remote host; naming the archive from its own folder works with every tar.
12
12
  const readArchive = (run, archive, args, options = {}) => run('tar', [args[0], basename(archive), ...args.slice(1)], { ...options, cwd: dirname(archive) });
13
13
  const json = async file => JSON.parse((await readFile(file, 'utf8')).replace(/^\uFEFF/, ''));
14
14
  async function exists(file) {
@@ -5,7 +5,7 @@
5
5
  新增模块的目录约定、公共协议、内核变更说明和提交要求见 [贡献协议](../../CONTRIBUTING.md)。
6
6
 
7
7
  - `wechat/`:微信宿主接口、群消息主动分页读取、回复编排、图片接收和发送回执;读写使用同一账号绑定与适配器轮询。`windows/messages.py` 共用身份与显示格式,`reading.py` 负责只读历史分页,`windows/` 同时放 Python 收发适配器及 `engine/` 原生桥。启动步骤见 [微信模块](wechat/windows/README.md)。
8
- - `qq/`:QQ 的两扇门——插件自己那条通道的接口(`/dsh-world/qq/native` 看状态、拨开关)与 SnowLuma 控制台入口。收发不在这里。(2026-10-27 之前这里管的是一个外部 `qq-bridge` 进程,那个进程已拆掉,配置项一并消失。)
8
+ - `qq/`:QQ 的两扇门——插件自己那条通道的接口(`/dsh-world/worlds/<worldId>/qq/native` 看状态、拨开关)与 SnowLuma 控制台入口。收发不在这里。(2026-10-27 之前这里管的是一个外部 `qq-bridge` 进程,那个进程已拆掉,配置项一并消失。)
9
9
  - `qq-native/`:QQ 的原生通道——直连 OneBot 的 WebSocket(收发、去重、白名单、群里被叫到才接、主动开口引擎),以及「阳台」那条给本机别的程序用的线(`native-bridge.ts`,对面跑的是 `src/qq-line.ts`)。
10
10
  - `shared/`:通用来源身份、群上下文、平台会话路由和消息出口。
11
11
  - `bridge/`:桌宠及其他本地程序向家的通用桥。
@@ -32,7 +32,7 @@ DSH 端代码在 `src/ecosystem/wechat/`,此目录只负责 Windows 微信收
32
32
  - 生成时先记为待发送,适配器逐条核对目标聊天中的本人消息、内容及服务器消息编号,再更新同一条记忆的已确认条数。中断则记录已确认部分与结果不明项;这不是对方已读回执。
33
33
  - 回执先保存在适配器本地,宿主暂时不可用时,重启监听只补报回执,不重发消息。旧版本的待发送记录不会凭空改成已发送。
34
34
  - 宿主队列保存在世界目录 `wechat-outbox.sqlite`。适配器离线时已排队消息会等待恢复;已领取任务按同一 ID 恢复,适配器已有回执时只补报,不再发送。入站处理结果不明时保留 pending,只暂停这一个聊天的接收(其他聊天照常),日志提示人工核对,独立发送任务仍继续轮询;主动发送的待核对消息 ID 为 `outgoing:<发送 ID>`。结果不明的原发送任务不会重发,其余任务按各自 ID 和回执处理。
35
- - 回执、任务领取、账号状态和群读取结果的单键请求遇到 HTTP 502/503/504 或连接错误时最多尝试 5 次,单次网络超时为 5 秒,间隔 1/2/4/8 秒,每次重读 `wechat.json` 的地址和令牌;响应正文读取中断也按此处理,HTTP 错误保留响应正文(最多 1024 字节)。生成回复的请求仍保留 190 秒网络超时,只发送一次,不能因超时或 503 自动再次调用模型。
35
+ - 回执、任务领取、账号状态和群读取结果的单键请求遇到 HTTP 502/503/504 或连接错误时最多尝试 5 次,单次网络超时为 5 秒,间隔 1/2/4/8 秒,每次重读 `wechat.json` 的地址和令牌;响应正文读取中断也按此处理,HTTP 错误保留响应正文(最多 1024 字节)。生成回复的请求仍保留 190 秒网络超时,只发送一次,不能因超时或 503 自动再次调用模型。她在这一轮里用 `wechat_send` 回了这个聊天,请求就此返回,不再等这一轮剩下的事做完。她正忙、插件 3 分钟内没能把消息交给她时,插件回 HTTP 409:消息没有进家里,适配器撤回这批的待确认标记,之后的轮询重新交给她,这个聊天不会因此停下等人核对。
36
36
  - 群会话沿用现有归档范围:`archiveScope: home` 时能读取家的记忆,但群正文不写入共享记忆;群自己的宿主会话日志保留正文,发送状态单独保存,不绕过归档范围。
37
37
  - `archiveScope: workspace` 会归档家所在工作区的普通会话,包括独立群会话;群图片上下文依旧不进入共享归档。控制台修改范围后重启 DSH 生效,回扫范围内历史并按时间重建近期记忆,保留原始日志和旧归档。
38
38
 
@@ -142,8 +142,8 @@ node <dsh-world 包目录>scriptsimport-stickers.mjs C:Usersyou.dshmemes C:Users
142
142
 
143
143
  这不是微信官方 API。版本变更需重新校准,锁屏和群聊等实际条件必须分别验证。`engine/` 基于第三方原生 ABI 研究定制,保留独立的非商业许可与来源说明;该目录不适用仓库根目录的 MIT 许可。
144
144
 
145
- 4.1.15.56 的指纹与 19 个原生地址映射来自 [helper 的版本表](https://github.com/Prometheus-first/helper/blob/main/native/core_version.h)。两版沿用相同请求 ABI、账号核对和消息对象字段布局;版本表选择、地址编码及未知构建拒绝由离线测试覆盖。上游已实测新版文字收发及桥接加载卸载,媒体未逐项重做真实网络操作,详见其 [验证范围](https://github.com/Prometheus-first/helper/blob/main/native/README.md);本项目实测范围见下方日期记录。本次仅更新 Python 和版本表,无须重新编译未改动的 C++ 桥;新增构建或结构发生变化时仍需校准并实测。
146
-
145
+ 4.1.15.56 的指纹与 19 个原生地址映射来自 [helper 的版本表](https://github.com/Prometheus-first/helper/blob/main/native/core_version.h)。两版沿用相同请求 ABI、账号核对和消息对象字段布局;版本表选择、地址编码及未知构建拒绝由离线测试覆盖。上游已实测新版文字收发及桥接加载卸载,媒体未逐项重做真实网络操作,详见其 [验证范围](https://github.com/Prometheus-first/helper/blob/main/native/README.md);本项目实测范围见下方日期记录。本次仅更新 Python 和版本表,无须重新编译未改动的 C++ 桥;新增构建或结构发生变化时仍需校准并实测。
146
+
147
147
  4.2.0.11 与 4.2.0.12 的指纹和地址取自 helper 的版本表。4.2.0.13 的地址由本项目从腾讯签名的 `Weixin.dll` 独立比对得出,基准是从安装包离线解出的 4.2.0.12 DLL。三个 4.2 构建都沿用静态表情发送方式。适配器取 GIF 第一帧转为 PNG,第一帧完全透明或只有一种颜色时改取最后一帧。4.2.0.13 仅更新版本表,已构建当前原生桥的环境可直接使用。来源见 [NOTICE](engine/NOTICE.md)。
148
148
 
149
149
  2026-11-04 已在 Windows 微信 4.2.0.13 上通过 `Probe`,核对了构建指纹、绑定账号及原生调度。实际文字、图片、表情包投递及 DSH 收发联动待验证。
@@ -3,6 +3,7 @@ import argparse
3
3
  from contextlib import contextmanager
4
4
  from http.client import IncompleteRead
5
5
  import json
6
+ import re
6
7
  import sqlite3
7
8
  import sys
8
9
  import time
@@ -51,6 +52,10 @@ class HomeRequestError(RuntimeError):
51
52
  pass
52
53
 
53
54
 
55
+ class HomeBusy(RuntimeError):
56
+ """The home ran out of time before taking the message in; asking again later cannot repeat it."""
57
+
58
+
54
59
  @contextmanager
55
60
  def exclusiveRun(directory):
56
61
  import msvcrt
@@ -274,6 +279,11 @@ class MessageStore:
274
279
  self.db.execute('UPDATE cursors SET seq=MAX(seq,?) WHERE chatId=?', (int(row['sort_seq']), chatId))
275
280
  print(f'微信消息 {chatId} / {key}:{error}', file=sys.stderr, flush=True)
276
281
 
282
+ def abandonBatch(self, chatId, rows):
283
+ """Undo `beginBatch` for messages the home never took in, so a later poll hands them over again."""
284
+ with self.db:
285
+ self.db.executemany("DELETE FROM messages WHERE chatId=? AND messageId=? AND status='pending'", [(chatId, messageKey(row)) for row in rows])
286
+
277
287
  def finishBatch(self, chatId, rows):
278
288
  with self.db:
279
289
  result = self.db.executemany("UPDATE messages SET status='done' WHERE chatId=? AND messageId=? AND status='pending'", [(chatId, messageKey(row)) for row in rows])
@@ -351,6 +361,8 @@ def postHome(moduleFile, message):
351
361
  try: detail = error.read(1024).decode('utf-8', errors='replace')
352
362
  except (IncompleteRead, URLError, TimeoutError, ConnectionError) as readError:
353
363
  detail = f'响应正文未读完:{readError}'
364
+ if error.code == 409 and not retryable:
365
+ raise HomeBusy(f'DSH HTTP 409: {detail or error.reason}') from error
354
366
  transient = error.code in (502, 503, 504)
355
367
  failure = HomeRequestError if transient else RuntimeError
356
368
  if not retryable or not transient or attempt == 4:
@@ -368,9 +380,10 @@ def postHomeOnce(moduleFile, message, timeout):
368
380
  if message.get('media') and connection.get('protocol', 0) < 3:
369
381
  raise RuntimeError('私聊图片需要新版宿主协议,请更新并重载 DSH 的 dsh-world 插件')
370
382
  origin = urlparse(connection['origin'])
371
- if origin.scheme != 'http' or origin.hostname not in ('127.0.0.1', 'localhost', '::1') or connection.get('path') != '/dsh-world/wechat/ask':
383
+ path = connection.get('path', '')
384
+ if origin.scheme != 'http' or origin.hostname not in ('127.0.0.1', 'localhost', '::1') or not isinstance(path, str) or not re.fullmatch(r'/dsh-world/worlds/[A-Za-z0-9][A-Za-z0-9_-]{0,63}/wechat/ask', path):
372
385
  raise ValueError('微信模块地址必须是本机 DSH 的独立接口')
373
- request = Request(connection['origin'].rstrip('/') + connection['path'],
386
+ request = Request(connection['origin'].rstrip('/') + path,
374
387
  data=json.dumps(message, ensure_ascii=False).encode(),
375
388
  headers={'Content-Type': 'application/json', 'x-dsh-world-token': connection['token']}, method='POST')
376
389
  with urlopen(request, timeout=timeout) as response:
@@ -565,7 +578,12 @@ def watch(config, database, store, send, ask=askHome, report=reportReceipt, poll
565
578
  mergeFollowing(database, chat, config, message, rows[1:])
566
579
  store.beginBatch(chat['id'], rows)
567
580
  if message:
568
- askWhileSending(config, message, database, store, send, ask, report, poll)
581
+ try: askWhileSending(config, message, database, store, send, ask, report, poll)
582
+ except HomeBusy as error:
583
+ # She is still busy and has not seen it: hand the same messages over on a later poll.
584
+ store.abandonBatch(chat['id'], rows)
585
+ print(f'她还在忙,这条稍后再交给她(不会重复):{chat["id"]} / {messageKey(rows[0])}:{error}', file=sys.stderr, flush=True)
586
+ break
569
587
  store.finishBatch(chat['id'], rows)
570
588
  flushOutgoing(config, database, store, send, poll=poll, report=report)
571
589
  config['_presence'] = dict(observedAt=datetime.now(timezone.utc).isoformat(), groups=store.presence.snapshot(config))