dsh-world 0.7.5 → 0.8.0

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 (115) hide show
  1. package/CHANGELOG.md +541 -446
  2. package/CONTRIBUTING.md +174 -163
  3. package/INSTALL.md +314 -314
  4. package/NOTES.md +98 -5
  5. package/README.md +332 -258
  6. package/client/index.js +1126 -986
  7. package/lib/compaction.d.ts +7 -1
  8. package/lib/compaction.js +8 -3
  9. package/lib/console/routes.d.ts +11 -3
  10. package/lib/console/routes.js +12 -7
  11. package/lib/console/snapshot.d.ts +2 -0
  12. package/lib/console/snapshot.js +1 -0
  13. package/lib/ecosystem/computer/browser/browser.d.ts +34 -0
  14. package/lib/ecosystem/computer/browser/browser.js +101 -0
  15. package/lib/ecosystem/computer/browser/cdp.d.ts +22 -0
  16. package/lib/ecosystem/computer/browser/cdp.js +91 -0
  17. package/lib/ecosystem/computer/browser/edge.d.ts +15 -0
  18. package/lib/ecosystem/computer/browser/edge.js +80 -0
  19. package/lib/ecosystem/computer/browser/page.d.ts +41 -0
  20. package/lib/ecosystem/computer/browser/page.js +140 -0
  21. package/lib/ecosystem/computer/browser/pageLib.d.ts +7 -0
  22. package/lib/ecosystem/computer/browser/pageLib.js +106 -0
  23. package/lib/ecosystem/computer/desktop/desktop.d.ts +91 -0
  24. package/lib/ecosystem/computer/desktop/desktop.js +322 -0
  25. package/lib/ecosystem/computer/desktop/driver.d.ts +34 -0
  26. package/lib/ecosystem/computer/desktop/driver.js +197 -0
  27. package/lib/ecosystem/computer/desktop/processes.d.ts +5 -0
  28. package/lib/ecosystem/computer/desktop/processes.js +15 -0
  29. package/lib/ecosystem/computer/desktop/recording.d.ts +77 -0
  30. package/lib/ecosystem/computer/desktop/recording.js +187 -0
  31. package/lib/ecosystem/computer/desktop/screen.d.ts +33 -0
  32. package/lib/ecosystem/computer/desktop/screen.js +182 -0
  33. package/lib/ecosystem/computer/desktop/turns.d.ts +58 -0
  34. package/lib/ecosystem/computer/desktop/turns.js +94 -0
  35. package/lib/ecosystem/computer/desktop/watching.d.ts +25 -0
  36. package/lib/ecosystem/computer/desktop/watching.js +81 -0
  37. package/lib/ecosystem/computer/inbox/inbox.d.ts +32 -0
  38. package/lib/ecosystem/computer/inbox/inbox.js +142 -0
  39. package/lib/ecosystem/computer/index.d.ts +82 -0
  40. package/lib/ecosystem/computer/index.js +133 -0
  41. package/lib/ecosystem/computer/procedures/alarm.d.ts +13 -0
  42. package/lib/ecosystem/computer/procedures/alarm.js +46 -0
  43. package/lib/ecosystem/computer/procedures/archive.d.ts +32 -0
  44. package/lib/ecosystem/computer/procedures/archive.js +68 -0
  45. package/lib/ecosystem/computer/procedures/catalog.d.ts +7 -0
  46. package/lib/ecosystem/computer/procedures/catalog.js +75 -0
  47. package/lib/ecosystem/computer/procedures/format.d.ts +167 -0
  48. package/lib/ecosystem/computer/procedures/format.js +332 -0
  49. package/lib/ecosystem/computer/procedures/library.d.ts +53 -0
  50. package/lib/ecosystem/computer/procedures/library.js +178 -0
  51. package/lib/ecosystem/computer/procedures/run.d.ts +80 -0
  52. package/lib/ecosystem/computer/procedures/run.js +245 -0
  53. package/lib/ecosystem/computer/tools.d.ts +21 -0
  54. package/lib/ecosystem/computer/tools.js +197 -0
  55. package/lib/ecosystem/qq-native/images.d.ts +8 -1
  56. package/lib/ecosystem/qq-native/images.js +34 -15
  57. package/lib/ecosystem/qq-native/index.js +5 -5
  58. package/lib/ecosystem/shared/turn.d.ts +3 -0
  59. package/lib/ecosystem/shared/turn.js +13 -3
  60. package/lib/ecosystem/wechat/home.d.ts +1 -0
  61. package/lib/ecosystem/wechat/home.js +9 -3
  62. package/lib/ecosystem/wechat/images.js +3 -5
  63. package/lib/ecosystem/wechat/index.d.ts +6 -0
  64. package/lib/ecosystem/wechat/index.js +3 -1
  65. package/lib/ecosystem/wechat/presence.d.ts +5 -1
  66. package/lib/ecosystem/wechat/presence.js +22 -13
  67. package/lib/ecosystem/wechat/reading.d.ts +1 -1
  68. package/lib/ecosystem/wechat/reading.js +2 -2
  69. package/lib/elsewhere.d.ts +34 -0
  70. package/lib/elsewhere.js +40 -0
  71. package/lib/history.d.ts +5 -0
  72. package/lib/history.js +7 -1
  73. package/lib/hostContract.d.ts +6 -0
  74. package/lib/images.d.ts +30 -0
  75. package/lib/images.js +101 -0
  76. package/lib/index.d.ts +4 -0
  77. package/lib/index.js +98 -6
  78. package/lib/life/photoTools.js +4 -15
  79. package/lib/life/runtime.d.ts +12 -2
  80. package/lib/life/runtime.js +93 -12
  81. package/lib/life/toolRegistry.d.ts +9 -3
  82. package/lib/life/toolRegistry.js +46 -27
  83. package/lib/life/turnCost.d.ts +16 -0
  84. package/lib/life/turnCost.js +44 -0
  85. package/lib/life/types.d.ts +17 -0
  86. package/lib/memoryTools.d.ts +4 -2
  87. package/lib/memoryTools.js +25 -5
  88. package/lib/mood.d.ts +5 -1
  89. package/lib/mood.js +25 -8
  90. package/lib/promptSection.d.ts +3 -0
  91. package/lib/promptSection.js +29 -42
  92. package/lib/runtime.js +44 -17
  93. package/lib/sessionNews.d.ts +17 -0
  94. package/lib/sessionNews.js +55 -0
  95. package/lib/store.d.ts +6 -0
  96. package/lib/store.js +17 -3
  97. package/lib/types.d.ts +4 -0
  98. package/lib/worldAdd.d.ts +9 -0
  99. package/lib/worldAdd.js +39 -0
  100. package/lib/worldPrompt.d.ts +3 -2
  101. package/lib/worldPrompt.js +3 -2
  102. package/lib/worldRoutes.d.ts +5 -2
  103. package/lib/worldRoutes.js +29 -4
  104. package/lib/worldSwitch.d.ts +8 -2
  105. package/lib/worldSwitch.js +11 -5
  106. package/package.json +132 -129
  107. package/src/ecosystem/README.md +2 -1
  108. package/src/ecosystem/computer/NOTICE.md +27 -0
  109. package/src/ecosystem/computer/README.md +244 -0
  110. package/src/ecosystem/computer/desktop/win32.ps1 +858 -0
  111. package/src/ecosystem/wechat/windows/README.md +4 -2
  112. package/src/ecosystem/wechat/windows/engine/NOTICE.md +6 -0
  113. package/src/ecosystem/wechat/windows/engine/profiles.json +28 -0
  114. package/templates/world-prompt-memory.md +10 -10
  115. package/templates/world-prompt.md +65 -65
@@ -1,54 +1,39 @@
1
- import { statSync } from 'node:fs';
2
1
  import { readPersona, renderPersona } from "./persona.js";
3
2
  import { renderSelf } from "./self.js";
4
3
  import { belongsToWorld, inWorld } from "./sourceArchive.js";
5
- import { DEFAULT_TEMPLATE_FILE, readTemplate, renderWorldPrompt } from "./worldPrompt.js";
4
+ import { readTemplate, renderWorldPrompt } from "./worldPrompt.js";
6
5
  import { syncBetweenSteps } from "./worldScope.js";
7
6
  // The complete prompt uses DSH's section name, so the request guard reads ownership from the assembly context.
8
7
  export const assembledWorlds = new WeakMap();
9
8
  const promptSlots = new WeakMap();
10
- function cachePromptFile(file, read) {
11
- let cached;
12
- return force => {
13
- let version = '';
14
- try {
15
- const stat = file ? statSync(file, { throwIfNoEntry: false }) : undefined;
16
- if (stat)
17
- version = `${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`;
18
- }
19
- catch {
20
- cached = undefined;
21
- return read();
22
- }
23
- if (!force && cached?.version === version)
24
- return cached.value;
25
- const value = read();
26
- cached = { version, value };
27
- return value;
28
- };
29
- }
30
9
  /** Replace the system prompt only for this world's preset and workspace. */
31
10
  export function createPromptSections(config, world, token, deps) {
32
11
  const entries = new Map();
33
12
  const agents = new WeakMap();
34
- const persona = cachePromptFile(world.prompt.persona, () => ({
35
- persona: world.prompt.persona ? renderPersona(readPersona(world.prompt.persona)) : '',
36
- names: world.names?.() ?? world.prompt.names,
37
- }));
38
- const template = cachePromptFile(world.prompt.file ?? DEFAULT_TEMPLATE_FILE, () => {
13
+ function readSources() {
39
14
  const template = readTemplate(world.prompt.file);
40
15
  if (template.error)
41
16
  deps.logger.warn(`dsh-world: ${template.error}`);
42
- return template.text;
43
- });
44
- const self = cachePromptFile(config.selfFile, () => config.selfFile ? { file: config.selfFile, text: renderSelf(config.selfFile) } : undefined);
45
- let forceRead = false;
46
- function render(agent) {
47
- const force = forceRead;
48
- forceRead = false;
49
- const card = persona(force);
50
- const body = renderWorldPrompt({ ...world.prompt, names: card.names }, template(force), self(force), world.isHome(agent.id));
51
- return [card.persona, body].filter(Boolean).join('\n\n');
17
+ return {
18
+ persona: world.prompt.persona ? renderPersona(readPersona(world.prompt.persona)) : '',
19
+ names: world.names?.() ?? world.prompt.names,
20
+ template: template.text,
21
+ ...(config.selfFile ? { self: { file: config.selfFile, text: renderSelf(config.selfFile) } } : {}),
22
+ };
23
+ }
24
+ /**
25
+ * Her files are read when the session opens or enters her workspace, and again only when `refresh` asks (after a
26
+ * compaction, a cold session's return, or the console's apply). The prompt sits at the head of every request, so
27
+ * re-reading it on each save would make the provider bill the whole conversation again after every edit she makes.
28
+ */
29
+ function render(agent, entry) {
30
+ if (!entry.sources || entry.reload) {
31
+ entry.sources = readSources();
32
+ entry.reload = false;
33
+ }
34
+ const { persona, names, template, self } = entry.sources;
35
+ const body = renderWorldPrompt({ ...world.prompt, names }, template, self, world.isHome(agent.id));
36
+ return [persona, body].filter(Boolean).join('\n\n');
52
37
  }
53
38
  function sync(agent, entry) {
54
39
  const active = inWorld(agent.session, config, world.inWorkspace);
@@ -68,7 +53,7 @@ export function createPromptSections(config, world, token, deps) {
68
53
  complete: true,
69
54
  interpolate: false,
70
55
  text: context => {
71
- const text = render(agent);
56
+ const text = render(agent, entry);
72
57
  assembledWorlds.set(context, { worldId: config.worldId, token, text });
73
58
  if (text !== entry.text) {
74
59
  entry.text = text;
@@ -83,6 +68,7 @@ export function createPromptSections(config, world, token, deps) {
83
68
  entry.restart = true;
84
69
  promptSlots.delete(agent);
85
70
  delete entry.disposePrompt;
71
+ delete entry.sources; // read afresh when the session comes back into her workspace
86
72
  };
87
73
  entry.disposePrompt = release;
88
74
  promptSlots.set(agent, release);
@@ -102,7 +88,7 @@ export function createPromptSections(config, world, token, deps) {
102
88
  if (entries.has(agent) || !belongsToWorld(agent.session, config))
103
89
  return;
104
90
  // The host captures complete sections before assembly listeners and restores them afterwards.
105
- const entry = { restart: false, disposeSync: syncBetweenSteps(agent.ctx, current => {
91
+ const entry = { reload: false, restart: false, disposeSync: syncBetweenSteps(agent.ctx, current => {
106
92
  if (current === agent)
107
93
  sync(agent, entry);
108
94
  }) };
@@ -123,11 +109,12 @@ export function createPromptSections(config, world, token, deps) {
123
109
  entry.restart = false;
124
110
  return true;
125
111
  },
112
+ /** Her files are read again at the next assembly; one that already ran keeps what it read. */
126
113
  refresh(session) {
127
114
  const agent = agents.get(session);
128
- // A compaction can finish after the current step assembled its prompt.
129
- if (agent && entries.get(agent)?.disposePrompt)
130
- forceRead = true;
115
+ const entry = agent && entries.get(agent);
116
+ if (entry?.disposePrompt)
117
+ entry.reload = true;
131
118
  },
132
119
  forget,
133
120
  clear() {
package/lib/runtime.js CHANGED
@@ -1,15 +1,16 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { createSystemMessage, createUserMessage, isAgentLoopRequest, LlmError } from '@deepseek-ai/dsh-llm';
2
+ import { createSystemMessage, createUserMessage, isAgentLoopRequest } from '@deepseek-ai/dsh-llm';
3
3
  import { appendPluginRecord, pluginRecordOf, SessionLogOffset } from '@deepseek-ai/dsh-session';
4
4
  import "./hostContract.js";
5
5
  import { isOrdinarySession } from "./archive.js";
6
- import { compactsWhole } from "./compaction.js";
6
+ import { compactsWhole, llmError } from "./compaction.js";
7
7
  import { compactionFor } from "./console/homeApply.js";
8
8
  import { Faults } from "./faults.js";
9
- import { createHistory, excludePresentMessages, renderHistory } from "./history.js";
10
- import { MOOD_CLEARED, moodText, readMood } from "./mood.js";
9
+ import { createHistory, excludePresentMessages, GROUP_PRIVACY, renderHistory } from "./history.js";
10
+ import { MOOD_CLEARED, moodAge, moodText, moodUpdatedAt, readMood } from "./mood.js";
11
11
  import { createWorldToolRegistry, memoryTools } from "./memoryTools.js";
12
12
  import { moodTools } from "./moodTools.js";
13
+ import { createSessionNews } from "./sessionNews.js";
13
14
  import { assembledWorlds, createPromptSections } from "./promptSection.js";
14
15
  import { belongsToWorld, createSourceArchive, inWorld, sessionPreset } from "./sourceArchive.js";
15
16
  import { worldNames } from "./worldPrompt.js";
@@ -17,6 +18,7 @@ import { reassembleOnChange } from "./worldScope.js";
17
18
  import { DEFAULT_COLD_HOURS, DEFAULT_MEMORY_TURNS } from "./worldSwitch.js";
18
19
  const memorySource = 'dsh-world-history';
19
20
  const moodSource = 'dsh-world-mood';
21
+ const elsewhereSource = 'dsh-world-elsewhere';
20
22
  const isRecall = (source, worldId) => source?.kind === memorySource && (worldId === undefined || source.worldId === undefined || source.worldId === worldId);
21
23
  const promptRecord = 'plugin:dsh-world/system-prompt';
22
24
  const legacyPromptReset = 'plugin:dsh-world/legacy-prompt-reset';
@@ -54,7 +56,7 @@ export function guardWorldContext(ctx, authorize, hasWorldRoom) {
54
56
  }
55
57
  if (!log.reset && event.type === 'user/message') {
56
58
  const kind = event.data.source.kind;
57
- log.sawWorldContext ||= kind === memorySource || kind === moodSource || kind === 'dsh-world-channel-context';
59
+ log.sawWorldContext ||= kind === memorySource || kind === moodSource || kind === elsewhereSource || kind === 'dsh-world-channel-context';
58
60
  }
59
61
  if (event.type === legacyPromptReset && pluginRecordOf(event))
60
62
  log.reset = true;
@@ -90,7 +92,7 @@ export function guardWorldContext(ctx, authorize, hasWorldRoom) {
90
92
  });
91
93
  }
92
94
  const revoked = (source, session) => {
93
- if (source?.kind === memorySource || source?.kind === moodSource)
95
+ if (source?.kind === memorySource || source?.kind === moodSource || source?.kind === elsewhereSource)
94
96
  return !session || !authorize(session, source.worldId);
95
97
  return source?.kind === 'dsh-world-channel-context' && (!session || !authorize(session));
96
98
  };
@@ -155,7 +157,7 @@ export function guardWorldContext(ctx, authorize, hasWorldRoom) {
155
157
  }
156
158
  yield* next();
157
159
  if (compaction && session && scope && authorize(session, prompt?.worldId) !== scope)
158
- throw new LlmError(failure.message, failure.code);
160
+ throw llmError(failure);
159
161
  });
160
162
  }
161
163
  /**
@@ -195,7 +197,11 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
195
197
  const prompts = world && createPromptSections(config, world, scopeToken, { logger: ctx.logger });
196
198
  const memory = new WeakMap();
197
199
  const service = world?.memory;
198
- const worldTools = (inside) => [...service ? memoryTools(service, inside) : [], ...config.moodFile ? moodTools(config.moodFile, inside) : []];
200
+ const sessionNews = world?.elsewhere ? createSessionNews({ store, isHome: id => !!world.isHome(id), partner: () => world.names?.().partner ?? world.prompt.names.partner }) : undefined;
201
+ const worldTools = (inside, agent) => [
202
+ ...service ? memoryTools(service, inside, sourceId => sessionNews?.looked(agent.session, sourceId.slice('chat:'.length)), () => ctx.get('attachments')) : [],
203
+ ...config.moodFile ? moodTools(config.moodFile, inside) : [],
204
+ ];
199
205
  const tools = service || config.moodFile ? createWorldToolRegistry({ tools: worldTools, inWorld: agent => !stopped && included(agent.session), faults, logger: ctx.logger }) : undefined;
200
206
  /** The world tools (memory, mood) follow world membership, whatever the life line does. */
201
207
  const syncTools = (agent) => !tools ? false : included(agent.session) ? tools.attach(agent) : tools.detach(agent);
@@ -264,8 +270,9 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
264
270
  return event?.type === 'user/message' ? event.data.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('') : undefined;
265
271
  }
266
272
  /**
267
- * Her mood rides just before the time block, appended like it: only when it differs from the latest one on the
268
- * surface, never replacing an old one, so the cached prefix stays whole and compaction clears them all.
273
+ * Her mood rides just before the time block on every step, appended like it and never replacing an old one, so the
274
+ * cached prefix stays whole and compaction clears them all. Every step, because one wake can run a hundred steps: a
275
+ * snapshot shown only when it changed sank far behind her work and she stopped noticing it, so it never moved.
269
276
  */
270
277
  function moodMessage(session) {
271
278
  if (!config.moodFile)
@@ -275,9 +282,22 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
275
282
  faults.set('mood', `mood.md 读不出来:${mood.message}`);
276
283
  else
277
284
  faults.clear('mood');
278
- const latest = latestMood(session);
279
- const text = moodText(mood) ?? (latest === undefined ? undefined : MOOD_CLEARED);
280
- return text === undefined || text === latest ? undefined : createUserMessage({ content: [{ type: 'text', text }], source: { kind: moodSource, form: 'snapshot', worldId: config.worldId } });
285
+ const updatedAt = mood.kind === 'mood' ? moodUpdatedAt(config.moodFile) : undefined;
286
+ const shown = moodText(mood, updatedAt === undefined ? undefined : moodAge(updatedAt, now()));
287
+ const latest = shown === undefined ? latestMood(session) : undefined;
288
+ // A removed file is said once, so the old values stop counting.
289
+ const text = shown ?? (latest === undefined || latest === MOOD_CLEARED ? undefined : MOOD_CLEARED);
290
+ return text === undefined ? undefined : createUserMessage({ content: [{ type: 'text', text }], source: { kind: moodSource, form: 'snapshot', worldId: config.worldId } });
291
+ }
292
+ const inGroup = (session) => store.channelType(session.id) === 'group';
293
+ /**
294
+ * News from elsewhere is an event, told once: at a turn's start it comes before the new message (what gathered
295
+ * before it arrived), later in the turn at the step's end, ahead of her mood and the time.
296
+ */
297
+ function elsewhereMessage(session) {
298
+ const news = world?.elsewhere?.take(session, new Date(now()));
299
+ const text = news && inGroup(session) ? `${news}\n${GROUP_PRIVACY}` : news;
300
+ return text === undefined ? undefined : createUserMessage({ content: [{ type: 'text', text }], source: { kind: elsewhereSource, form: 'notice', worldId: config.worldId } });
281
301
  }
282
302
  function flushRetired(session, state, position) {
283
303
  const retiring = state.retiring;
@@ -315,7 +335,8 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
315
335
  async function freshBlock(session, state) {
316
336
  const turns = await history.loadRecentTurns(memoryTurns(), archivedByScope);
317
337
  const present = new Set(session.deriveMessages().map(message => message.id));
318
- const text = renderHistory(excludePresentMessages(turns, present), config.timeZone, names(), config.archiveScope === 'home');
338
+ const rendered = renderHistory(excludePresentMessages(turns, present), config.timeZone, names(), config.archiveScope === 'home');
339
+ const text = rendered && inGroup(session) ? `${rendered}\n\n${GROUP_PRIVACY}` : rendered;
319
340
  // A session entering this workspace can still carry an inherited recall from another world.
320
341
  retireMemory(session, state, included(session));
321
342
  return text ? createUserMessage({ content: [{ type: 'text', text }], source: { kind: memorySource, form: 'recall', worldId: config.worldId } }) : undefined;
@@ -330,6 +351,8 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
330
351
  /** `fresh`: her world was just started from the console, so what was said while it was stopped is not archived. */
331
352
  async function start(options = {}) {
332
353
  try {
354
+ if (sessionNews && world?.elsewhere)
355
+ disposers.push(world.elsewhere.register(sessionNews.source));
333
356
  disposers.push(ctx.on('session/event', (session, event) => {
334
357
  if (event.type === 'agent-preset/selected') {
335
358
  const agent = ctx.agents.get(session.id);
@@ -346,6 +369,7 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
346
369
  }
347
370
  if (state && compacted) {
348
371
  state.reload = true;
372
+ world?.elsewhere?.retell(session);
349
373
  }
350
374
  // The host assembles the system prompt after turn/start, so a cold session's first request already has both.
351
375
  const cold = !!state && event.type === 'turn/start' && state.lastRequestAt !== undefined && now() - state.lastRequestAt >= coldHours() * 60 * 60_000;
@@ -388,6 +412,8 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
388
412
  await attach(agent);
389
413
  const state = memory.get(agent.session);
390
414
  const leave = () => {
415
+ if (state.inScope)
416
+ world?.elsewhere?.retell(agent.session);
391
417
  state.restart ||= state.inScope;
392
418
  state.inScope = false;
393
419
  retireMemory(agent.session, state);
@@ -402,9 +428,10 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
402
428
  signal.throwIfAborted();
403
429
  if (!included(agent.session))
404
430
  return leave();
405
- const mood = moodMessage(agent.session);
406
- if (mood)
407
- decision = { ...decision, messages: [...decision.messages, mood] };
431
+ const news = elsewhereMessage(agent.session), mood = moodMessage(agent.session);
432
+ const head = news && step === 1 ? [news] : [], tail = [...(news && step > 1 ? [news] : []), ...(mood ? [mood] : [])];
433
+ if (head.length || tail.length)
434
+ decision = { ...decision, messages: [...head, ...decision.messages, ...tail] };
408
435
  if (!state.reload)
409
436
  return decision;
410
437
  // A block that cannot be built leaves the old one in place; she talks on, the fault shows, and the next step tries again.
@@ -0,0 +1,17 @@
1
+ import type { Session } from '@deepseek-ai/dsh-session';
2
+ import { type ElsewhereSource } from './elsewhere.ts';
3
+ import type { ArchiveStore } from './store.ts';
4
+ /**
5
+ * Her other sessions as a source of news: what was archived there since this session started hearing, counted per
6
+ * session, never the words. It starts at the archive's end, so an upgrade or a restart tells nothing old; she reads a
7
+ * place with memory_find on its sourceId, and once she has paged its newest lines it is caught up.
8
+ */
9
+ export declare function createSessionNews(deps: {
10
+ store: Pick<ArchiveStore, 'readSince' | 'lastSequence'>;
11
+ isHome(sessionId: string): boolean;
12
+ partner(): string;
13
+ }): {
14
+ source: ElsewhereSource;
15
+ /** She paged the newest lines of that session from this one: it is caught up. */
16
+ looked(session: Session, sessionId: string): void;
17
+ };
@@ -0,0 +1,55 @@
1
+ import { chatLabel, chatName } from "./ecosystem/shared/identity.js";
2
+ import { ago } from "./elsewhere.js";
3
+ import { sessionMarker } from "./history.js";
4
+ /**
5
+ * Her other sessions as a source of news: what was archived there since this session started hearing, counted per
6
+ * session, never the words. It starts at the archive's end, so an upgrade or a restart tells nothing old; she reads a
7
+ * place with memory_find on its sourceId, and once she has paged its newest lines it is caught up.
8
+ */
9
+ export function createSessionNews(deps) {
10
+ const seen = new WeakMap();
11
+ const labelOf = (sessionId, record) => deps.isHome(sessionId) ? '家'
12
+ : record.channel && record.conversationType === 'group' ? chatLabel(record.channel, 'group', chatName(record) ?? record.conversationId ?? '') : undefined;
13
+ /** Reads what was archived since the last look, keeping only other sessions' lines. */
14
+ function catchUp(session) {
15
+ const state = seen.get(session);
16
+ if (!state) {
17
+ const fresh = { scanned: deps.store.lastSequence(), places: new Map() };
18
+ seen.set(session, fresh);
19
+ return fresh;
20
+ }
21
+ for (let batch = deps.store.readSince(state.scanned); batch.length; batch = deps.store.readSince(state.scanned)) {
22
+ for (const { sequence, record } of batch) {
23
+ state.scanned = sequence;
24
+ const id = record.sourceSessionId;
25
+ if (id === session.id)
26
+ continue;
27
+ const place = state.places.get(id) ?? { count: 0, lastSequence: sequence, last: record };
28
+ place.count += 1;
29
+ place.lastSequence = sequence;
30
+ place.last = record;
31
+ place.label ??= labelOf(id, record);
32
+ state.places.set(id, place);
33
+ }
34
+ }
35
+ return state;
36
+ }
37
+ const source = {
38
+ look: '别的会话用 memory_find 带上那一行的 sourceId 翻最新的',
39
+ news(now, session) {
40
+ return [...catchUp(session).places].sort(([, a], [, b]) => b.lastSequence - a.lastSequence).map(([id, place]) => {
41
+ const who = place.last.role === 'assistant' ? '我自己' : place.last.speakerName ?? deps.partner();
42
+ const label = place.label ?? `另一个窗口(${sessionMarker(id)})`;
43
+ return {
44
+ key: `session:${id}`, mark: `${place.count}:${place.lastSequence}`,
45
+ text: `${label}有 ${place.count} 条我在这边没看到,最后是${who}(${ago(now.getTime() - Date.parse(place.last.occurredAt))});sourceId:chat:${id}`,
46
+ };
47
+ });
48
+ },
49
+ };
50
+ return {
51
+ source,
52
+ /** She paged the newest lines of that session from this one: it is caught up. */
53
+ looked(session, sessionId) { catchUp(session).places.delete(sessionId); },
54
+ };
55
+ }
package/lib/store.d.ts CHANGED
@@ -12,6 +12,11 @@ export declare function createArchiveStore(config: WorldConfig & {
12
12
  hasRecord: (recordId: string) => boolean;
13
13
  updateRecord: (recordId: string, revise: (record: ConversationRecord) => Pick<ConversationRecord, "content" | "wechatDelivery"> & Partial<SpeakerIdentity>) => Promise<void>;
14
14
  readPage: (query: PageQuery) => Promise<RecordPage>;
15
+ readSince: (sequence: number, limit?: number) => {
16
+ sequence: number;
17
+ record: ConversationRecord;
18
+ }[];
19
+ lastSequence: () => number;
15
20
  readTurn: (turnId: string, afterSeq?: number, limit?: number) => Promise<ConversationRecord[]>;
16
21
  progress: (sessionId: string) => ExportProgress;
17
22
  forgetProgress: (sessionId: string) => void;
@@ -22,6 +27,7 @@ export declare function createArchiveStore(config: WorldConfig & {
22
27
  };
23
28
  close: () => void;
24
29
  channelSession: (key: string) => string | undefined;
30
+ channelType: (sessionId: string) => "private" | "group" | undefined;
25
31
  bindChannelSession: (key: string, sessionId: string) => void;
26
32
  delivery: (recordId: string) => DeliveryState | undefined;
27
33
  registerDelivery: (recordId: string, total: number) => void;
package/lib/store.js CHANGED
@@ -115,7 +115,7 @@ export function createArchiveStore(config) {
115
115
  async function readPage(query) {
116
116
  flushExports();
117
117
  const before = query.before;
118
- const maxSequence = before?.maxSequence ?? Number(db.prepare('SELECT COALESCE(MAX(sequence),0) AS n FROM records').get()?.n);
118
+ const maxSequence = before?.maxSequence ?? lastSequence();
119
119
  const rows = (before
120
120
  ? db.prepare('SELECT * FROM records WHERE sequence<=? AND (day, occurredAt, recordId)<(?,?,?) ORDER BY day DESC, occurredAt DESC, recordId DESC LIMIT ?').all(maxSequence, before.date, before.occurredAt, before.recordId, query.limit + 1)
121
121
  : db.prepare('SELECT * FROM records WHERE sequence<=? ORDER BY day DESC, occurredAt DESC, recordId DESC LIMIT ?').all(maxSequence, query.limit + 1));
@@ -146,6 +146,13 @@ export function createArchiveStore(config) {
146
146
  });
147
147
  flushExports();
148
148
  }
149
+ function lastSequence() {
150
+ return Number(db.prepare('SELECT COALESCE(MAX(sequence),0) AS n FROM records').get()?.n);
151
+ }
152
+ /** Records in the order they were archived, after a point: what is new since then. */
153
+ function readSince(sequence, limit = pageSize) {
154
+ return db.prepare('SELECT * FROM records WHERE sequence>? ORDER BY sequence LIMIT ?').all(sequence, limit).map(row => ({ sequence: Number(row.sequence), record: decode(row) }));
155
+ }
149
156
  async function readTurn(turnId, afterSeq = -1, limit = pageSize) {
150
157
  flushExports();
151
158
  return db.prepare('SELECT * FROM records WHERE turnId=? AND sourceSeq>? ORDER BY sourceSeq LIMIT ?').all(turnId, afterSeq, limit).map(decode);
@@ -179,6 +186,13 @@ export function createArchiveStore(config) {
179
186
  function channelSession(key) {
180
187
  return db.prepare('SELECT sessionId FROM channelSessions WHERE conversationKey=? LIMIT 1').get(key)?.sessionId;
181
188
  }
189
+ /** Whether a session is one of her channel conversations, and which kind; undefined for home and DSH windows. */
190
+ function channelType(sessionId) {
191
+ const key = db.prepare('SELECT conversationKey FROM channelSessions WHERE sessionId=? LIMIT 1').get(sessionId)?.conversationKey;
192
+ if (typeof key !== 'string')
193
+ return undefined;
194
+ return JSON.parse(key)[2] === 'group' ? 'group' : 'private';
195
+ }
182
196
  function bindChannelSession(key, sessionId) {
183
197
  transaction(() => { db.prepare('INSERT INTO channelSessions VALUES (?,?) ON CONFLICT(conversationKey) DO UPDATE SET sessionId=excluded.sessionId').run(key, sessionId); });
184
198
  }
@@ -197,6 +211,6 @@ export function createArchiveStore(config) {
197
211
  db.prepare('UPDATE channelDeliveries SET body=? WHERE recordId=?').run(JSON.stringify(revise(previous)), recordId);
198
212
  });
199
213
  }
200
- return { commitRecords, hasRecord, updateRecord, readPage, readTurn, progress, forgetProgress, sourcePage, stats, close,
201
- channelSession, bindChannelSession, delivery, registerDelivery, updateDelivery, memory, snapshotTo };
214
+ return { commitRecords, hasRecord, updateRecord, readPage, readSince, lastSequence, readTurn, progress, forgetProgress, sourcePage, stats, close,
215
+ channelSession, channelType, bindChannelSession, delivery, registerDelivery, updateDelivery, memory, snapshotTo };
202
216
  }
package/lib/types.d.ts CHANGED
@@ -36,6 +36,10 @@ export interface WorldConfig {
36
36
  bridge?: boolean;
37
37
  /** The independent local WeChat module; the Windows adapter uses `<world>/wechat.json`. */
38
38
  wechat?: boolean;
39
+ /** Her own browser and the tools she makes with it (home only); see src/ecosystem/computer/README.md. */
40
+ computer?: boolean;
41
+ /** She also uses the partner's computer, in the background (Windows; needs `computer`); see src/ecosystem/computer/README.md. */
42
+ desktop?: boolean;
39
43
  /** QQ straight to OneBot: no qq-bridge process, the plugin owns the sockets, the sessions and the state. */
40
44
  qqNative?: {
41
45
  enabled?: boolean;
@@ -0,0 +1,9 @@
1
+ /** The loader id of a world added from the console; the first world keeps whatever id its partner gave it. */
2
+ export declare const worldEntryId: (worldId: string) => string;
3
+ /**
4
+ * Adds one more world to the profile's patch file, as the row the README has partners write by hand. The host's
5
+ * config editor can only change rows that are already loaded, so the row is appended as text: every line already
6
+ * there, comments included, stays as it is. The host reads the file when it starts, so the world appears after a
7
+ * restart. Refuses, with the reason, anything it cannot add safely.
8
+ */
9
+ export declare function addWorldEntry(patchFile: string, worldId: string, companionName: string): void;
@@ -0,0 +1,39 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { durableWrite } from "./life/lifeStore.js";
3
+ import { validWorldId } from "./worldRoutes.js";
4
+ /** The loader id of a world added from the console; the first world keeps whatever id its partner gave it. */
5
+ export const worldEntryId = (worldId) => `dsh-world-${worldId}`;
6
+ const said = (line) => line.trim() !== '' && !line.trimStart().startsWith('#');
7
+ /**
8
+ * Adds one more world to the profile's patch file, as the row the README has partners write by hand. The host's
9
+ * config editor can only change rows that are already loaded, so the row is appended as text: every line already
10
+ * there, comments included, stays as it is. The host reads the file when it starts, so the world appears after a
11
+ * restart. Refuses, with the reason, anything it cannot add safely.
12
+ */
13
+ export function addWorldEntry(patchFile, worldId, companionName) {
14
+ if (!validWorldId(worldId))
15
+ throw new Error('世界的名字只能用字母、数字、- 和 _,以字母或数字开头,最多 64 个字符');
16
+ const before = existsSync(patchFile) ? readFileSync(patchFile, 'utf8') : '';
17
+ const lines = before.split(/\r?\n/);
18
+ const rows = lines.filter(said);
19
+ // A new profile's patch is the host's comment and an empty list; the list is what the first row replaces.
20
+ const emptyList = rows.length === 1 && rows[0].trim() === '[]';
21
+ // Appending a row is only safe to a block list; any other shape is left for its owner to edit.
22
+ if (rows.length && !emptyList && !rows.some(line => line.startsWith('- ')))
23
+ throw new Error(`配置文件 ${patchFile} 不是逐条列出的格式,请手动添加(见 README「添加第二个世界」)`);
24
+ const taken = new RegExp(String.raw `^\s*(?:-\s+)?(?:worldId:\s*['"]?${worldId}['"]?|id:\s*['"]?${worldEntryId(worldId)}['"]?)\s*(?:#.*)?$`, 'i');
25
+ if (rows.some(line => taken.test(line)))
26
+ throw new Error(`配置里已经有 ${worldId} 这个世界了`);
27
+ const row = [
28
+ '# dsh-world:从世界控制台新增的世界。',
29
+ '- insert:',
30
+ ` - id: ${worldEntryId(worldId)}`,
31
+ ' name: dsh-world',
32
+ ' config:',
33
+ ` worldId: ${worldId}`,
34
+ ...(companionName ? [` companionName: ${JSON.stringify(companionName)}`] : []),
35
+ '',
36
+ ].join('\n');
37
+ const kept = (emptyList ? before.replace(/^[ \t]*\[\][ \t]*\r?\n?/m, '') : before).replace(/\s*$/, '');
38
+ durableWrite(patchFile, kept ? `${kept}\n\n${row}` : row);
39
+ }
@@ -43,8 +43,9 @@ export declare function readTemplate(file: string | undefined): TemplateRead;
43
43
  */
44
44
  export declare function renderTemplate(template: string, flags: Record<string, boolean>, values: Record<string, string>): string;
45
45
  /**
46
- * The one world prompt every world session carries in its system prompt. The world line's tools live in the home alone;
47
- * the template tells other sessions where to find them.
46
+ * The one world prompt every world session carries in its system prompt. `template` and `self` are read when a session
47
+ * opens, after a compaction or a cold return, or on the console's apply, never on save, so the cached prefix stays. The
48
+ * world line's tools live in the home alone; the template tells other sessions where to find them.
48
49
  */
49
50
  export declare function renderWorldPrompt(prompt: WorldPrompt, template: string, self: {
50
51
  file: string;
@@ -42,8 +42,9 @@ 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. The world line's tools live in the home alone;
46
- * the template tells other sessions where to find them.
45
+ * The one world prompt every world session carries in its system prompt. `template` and `self` are read when a session
46
+ * opens, after a compaction or a cold return, or on the console's apply, never on save, so the cached prefix stays. The
47
+ * world line's tools live in the home alone; the template tells other sessions where to find them.
47
48
  */
48
49
  export function renderWorldPrompt(prompt, template, self, home) {
49
50
  const { life, names } = prompt;
@@ -2,8 +2,11 @@ import type { IncomingMessage, ServerResponse } from 'node:http';
2
2
  export declare const WORLDS_PATH = "/dsh-world/worlds";
3
3
  export declare const validWorldId: (id: string) => boolean;
4
4
  export declare const worldPath: (id: string) => string;
5
- export declare function worldListRoute(worlds: ReadonlyMap<string, readonly string[]>): {
5
+ /** A write must carry this header; a page on another site cannot add it without a CORS preflight, which is never answered. */
6
+ export declare const WRITE_HEADER = "x-dsh-world";
7
+ /** The worlds this profile has loaded, and one more added on request: `add` throws its refusal in words for the partner. */
8
+ export declare function worldListRoute(worlds: ReadonlyMap<string, readonly string[]>, add?: (worldId: string, companionName: string) => Promise<void>): {
6
9
  kind: "exact";
7
10
  path: string;
8
- handler(req: IncomingMessage, res: ServerResponse): void;
11
+ handler(req: IncomingMessage, res: ServerResponse): Promise<void>;
9
12
  };
@@ -1,18 +1,43 @@
1
- import { knownHost, sendJson } from "./http.js";
1
+ import { errorText } from "./faults.js";
2
+ import { jsonObject, knownHost, readBody, sendJson } from "./http.js";
2
3
  export const WORLDS_PATH = '/dsh-world/worlds';
3
4
  export const validWorldId = (id) => /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(id);
4
5
  export const worldPath = (id) => `${WORLDS_PATH}/${id}`;
5
- export function worldListRoute(worlds) {
6
+ /** A write must carry this header; a page on another site cannot add it without a CORS preflight, which is never answered. */
7
+ export const WRITE_HEADER = 'x-dsh-world';
8
+ const MAX_BODY_BYTES = 4 * 1024;
9
+ const MAX_NAME = 40;
10
+ /** The worlds this profile has loaded, and one more added on request: `add` throws its refusal in words for the partner. */
11
+ export function worldListRoute(worlds, add) {
12
+ async function addOne(req, res) {
13
+ const written = req.headers[WRITE_HEADER] === '1' && String(req.headers['content-type'] ?? '').startsWith('application/json');
14
+ const body = written ? jsonObject(await readBody(req, MAX_BODY_BYTES)) : undefined;
15
+ const worldId = body?.worldId, companionName = body?.companionName ?? '';
16
+ if (typeof worldId !== 'string' || typeof companionName !== 'string' || [...companionName].length > MAX_NAME) {
17
+ sendJson(res, { status: 400, body: { error: '请填世界的名字' } });
18
+ return;
19
+ }
20
+ try {
21
+ await add(worldId.trim(), companionName.trim());
22
+ }
23
+ catch (error) {
24
+ sendJson(res, { status: 409, body: { error: errorText(error) } });
25
+ return;
26
+ }
27
+ sendJson(res, { status: 200, body: { ok: true, worldId: worldId.trim(), restartRequired: true } });
28
+ }
6
29
  return {
7
30
  kind: 'exact', path: WORLDS_PATH,
8
- handler(req, res) {
31
+ async handler(req, res) {
9
32
  const ids = [...worlds].filter(([, hosts]) => knownHost(req.headers.host, hosts)).map(([id]) => id).sort();
10
33
  if (!ids.length || req.headers['sec-fetch-site'] === 'cross-site') {
11
34
  sendJson(res, { status: 403, body: { error: 'forbidden' } });
12
35
  return;
13
36
  }
37
+ if (req.method === 'POST' && add)
38
+ return addOne(req, res);
14
39
  if (req.method !== 'GET') {
15
- sendJson(res, { status: 405, body: { error: 'method not allowed' }, headers: { allow: 'GET' } });
40
+ sendJson(res, { status: 405, body: { error: 'method not allowed' }, headers: { allow: add ? 'GET, POST' : 'GET' } });
16
41
  return;
17
42
  }
18
43
  const { searchParams } = new URL(req.url ?? WORLDS_PATH, 'http://localhost');
@@ -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
- /** Compact the home after the evening look back unless the partner turns it off. */
22
+ /** After each evening look back her home is compacted, which is when the 我是谁 she has just rewritten takes effect; on 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. */
@@ -37,15 +37,21 @@ export declare function createWorldSwitch(worldDir: string, configuredScope?: Me
37
37
  coldHours: () => number;
38
38
  setColdHours(hours: number | undefined): void;
39
39
  /**
40
- * The console's switches for the WeChat and QQ modules; both are off until someone turns them on. QQ's SDK is an
40
+ * The console's switches for the WeChat, QQ and computer modules; all are off until someone turns them on. QQ's SDK is an
41
41
  * optional dependency, so its code is not even loaded before then. WeChat used to default to on, so a world that
42
42
  * never stored a choice but whose WeChat module has already run (it keeps its outbox) stays on after the upgrade.
43
43
  */
44
44
  wechatEnabled: () => boolean;
45
45
  qqEnabled: () => boolean;
46
+ /** Her own browser: off until someone turns it on. */
47
+ computerEnabled: () => boolean;
48
+ /** Her use of the partner's computer: off until someone turns it on. */
49
+ desktopEnabled: () => boolean;
46
50
  setModules(next: {
47
51
  wechat?: boolean;
48
52
  qq?: boolean;
53
+ computer?: boolean;
54
+ desktop?: boolean;
49
55
  }): void;
50
56
  /** Her evening look back and her morning wake when nothing is pending; the configured `fallbackWakeTime` is the morning's default. */
51
57
  reviewTime: () => string;