dsh-cross-memory 0.2.13 → 0.2.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -47,7 +47,7 @@ import { planRetention, retentionKey } from './retention.js';
47
47
  import { MemoryLog, createFileSink, createLogExporter, pluginLogger } from './log.js';
48
48
  import { collectExtractionWindow, collectWindow, resolveLlmRoute, runExtraction, selectKnownTitles } from './extract.js';
49
49
  import { collectExcerpts, collectRagExcerpts } from './raw-recall.js';
50
- import { decodeSessionLog, findSessionLogs, parseSessionLog, planWindows, zstdAvailable } from './backfill.js';
50
+ import { decodeSessionLogAsync, findSessionLogs, parseSessionLog, planWindows, zstdAvailable } from './backfill.js';
51
51
  import { backgroundDelayMs, cappedBackoffMs, extractionDelayMs, formatDelay, parsePeakHours, peakDelayMs } from './schedule.js';
52
52
  import { CONSOLIDATE_PRESET_ID, adjudicateDisputes, applyPlan, applyVerdicts, classifyPlan, clearPendingPlan, conflictDisputes, denyToolsFor, hasApplicableFragment, mergePendingPlan, pinExistingScopes, proposalIsFresh, readPendingPlan, runConsolidation, runConsolidationDirect, selectForConsolidation, writePendingPlan } from './consolidate.js';
53
53
  import { discardDraft, listDrafts, promote, writeDraft } from './skills.js';
@@ -181,6 +181,12 @@ export function isCatchAllDirectory(root, dshHome) {
181
181
  export const inject = ['tools', 'commands'];
182
182
  /** Job key of the single global consolidation job. */
183
183
  const CONSOLIDATE_JOB = 'global';
184
+ /** Whether a session is a subagent rather than an interactive top-level session. */
185
+ export function isSubagentSession(session) {
186
+ if (session.header.origin === 'subagent')
187
+ return true;
188
+ return session.header.delegationDepth !== undefined && session.header.delegationDepth > 0;
189
+ }
184
190
  /**
185
191
  * The memory runtime: one instance per plugin mount, shared by the tool, the
186
192
  * injector, the extractor, and the command handler.
@@ -236,6 +242,8 @@ export class MemoriesRuntime {
236
242
  injected = new WeakSet();
237
243
  /** Recall deltas already injected into each conversation. */
238
244
  recallCounts = new WeakMap();
245
+ /** Latest human user turn id/seq whose full-history RAG excerpts were already injected. */
246
+ lastRagTurn = new WeakMap();
239
247
  /** Late memory blocks already injected into each conversation. */
240
248
  deltaCounts = new WeakMap();
241
249
  /** The user-turn number at which each conversation last emitted a rotation block. */
@@ -374,6 +382,10 @@ export class MemoriesRuntime {
374
382
  dispose() {
375
383
  this.stopPeriodicExtraction();
376
384
  this.storeSync.stop();
385
+ if (this.exitFlushInstalled) {
386
+ process.off('beforeExit', this.exitFlush);
387
+ this.exitFlushInstalled = false;
388
+ }
377
389
  this.lifecycle.abort(new Error('dsh-cross-memory disposed'));
378
390
  this.state.close();
379
391
  }
@@ -1144,11 +1156,8 @@ export class MemoriesRuntime {
1144
1156
  openingQuery(session) {
1145
1157
  try {
1146
1158
  for (const message of session.deriveMessages()) {
1147
- if (message.role !== 'user')
1159
+ if (message.role !== 'user' || message.source.kind !== 'user')
1148
1160
  continue;
1149
- // 0.2.0 起 MessageSource 只剩 'user' | 'model' | 'tool' | 'system-prompt',
1150
- // 不再有 'plugin'(dsh-llm/lib/types/message.d.ts:19/23/28/103)。原先那句
1151
- // `source.kind === 'plugin'` 已成为不可能的窄化,TS2367 报错,故删除。
1152
1161
  const blocks = message.content;
1153
1162
  const text = blocks
1154
1163
  .filter((block) => block.type === 'text' && typeof block.text === 'string')
@@ -1170,6 +1179,7 @@ export class MemoriesRuntime {
1170
1179
  resetInjection(session) {
1171
1180
  this.injected.delete(session);
1172
1181
  this.recallCounts.delete(session);
1182
+ this.lastRagTurn.delete(session);
1173
1183
  this.deltaCounts.delete(session);
1174
1184
  this.rotationAt.delete(session);
1175
1185
  this.surfacedIds.delete(session);
@@ -1327,17 +1337,20 @@ export class MemoriesRuntime {
1327
1337
  return undefined;
1328
1338
  if (this.sessionOff(session))
1329
1339
  return undefined;
1330
- const query = this.latestUserText(session);
1331
- // The full-history channel is computed before the eligibility gate: a turn
1332
- // with no matching memory still has its original conversation in the logs,
1333
- // and the gate returning nothing must not hide that.
1334
- const ragExcerpts = query !== undefined && this.settings.ragRecall && this.settings.ragRecallBytes > 0
1335
- ? await this.ragExcerpts(query, session.id)
1336
- : [];
1340
+ const latestTurn = this.latestUserTurn(session);
1341
+ if (latestTurn === undefined)
1342
+ return undefined;
1343
+ const query = latestTurn.text;
1337
1344
  // A one-word acknowledgement has nothing a memory could be about; skipping it
1338
- // also avoids a full store scan on every "好" the user types.
1339
- if (query === undefined || !isSubstantiveTurn(query))
1345
+ // before scanning session logs also avoids wasted work on every "好".
1346
+ if (!isSubstantiveTurn(query))
1340
1347
  return undefined;
1348
+ // Per-turn dedup for full-history RAG: tool-call steps within the same turn
1349
+ // or a host-runner continuation turn must not re-inject the same 12 KB RAG block.
1350
+ const ragAlreadyInjected = this.lastRagTurn.get(session) === latestTurn.key;
1351
+ const ragExcerpts = !ragAlreadyInjected && this.settings.ragRecall && this.settings.ragRecallBytes > 0
1352
+ ? await this.ragExcerpts(query, session.id)
1353
+ : [];
1341
1354
  const seen = this.seenIds(session);
1342
1355
  const states = await this.allScopes(session);
1343
1356
  // Resolved once for the turn: this loop scores every entry in the store.
@@ -1405,6 +1418,7 @@ export class MemoriesRuntime {
1405
1418
  const text = renderRecall([], this.settings.recallMaxBytes + this.settings.ragRecallBytes, [], ragExcerpts);
1406
1419
  if (text !== undefined) {
1407
1420
  this.recallCounts.set(session, used + 1);
1421
+ this.lastRagTurn.set(session, latestTurn.key);
1408
1422
  this.log.info('dsh-cross-memory: session %s recalled no memory, used %d raw excerpt(s) from the full history', session.id, ragExcerpts.length);
1409
1423
  return createUserMessage({
1410
1424
  content: [{ type: 'text', text }],
@@ -1520,6 +1534,7 @@ export class MemoriesRuntime {
1520
1534
  // still decides what may be recalled, so this cannot admit an entry the
1521
1535
  // lexical gate refused. When the service is unreachable, `denseScores`
1522
1536
  // returns an empty map and the lexical order stands.
1537
+ let rerankedByDense = false;
1523
1538
  if (this.settings.denseEnabled && eligible.length > 1) {
1524
1539
  const dense = await denseScores(eligible.map((item) => item.entry), query, { url: DEFAULT_DENSE_URL, model: DEFAULT_DENSE_MODEL, cacheDir: this.denseCacheDir() });
1525
1540
  if (dense.size > 0) {
@@ -1527,10 +1542,11 @@ export class MemoriesRuntime {
1527
1542
  const semantic = [...dense.entries()].sort((left, right) => right[1] - left[1]).map(([id]) => id);
1528
1543
  const fused = rrf([lexical, semantic]);
1529
1544
  eligible.sort((left, right) => (fused.get(right.entry.id) ?? 0) - (fused.get(left.entry.id) ?? 0));
1545
+ rerankedByDense = true;
1530
1546
  this.log.info('dsh-cross-memory: session %s recall re-ranked by the dense channel (%d candidates)', session.id, eligible.length);
1531
1547
  }
1532
1548
  }
1533
- else {
1549
+ if (!rerankedByDense) {
1534
1550
  eligible.sort(byStrength);
1535
1551
  }
1536
1552
  // The one-hop neighbours go in after the seeds and carry no lexical
@@ -1538,25 +1554,23 @@ export class MemoriesRuntime {
1538
1554
  // case this exists for is a turn that names one fragment of something the
1539
1555
  // store filed in several.
1540
1556
  const related = relatedHits(this.groups(states), eligible.slice(0, EXPAND_SEEDS).map((item) => ({ entry: item.entry, score: item.score })), { exclude: new Set([...seen, ...eligible.map((item) => item.entry.id)]), limit: remaining });
1541
- for (const hit of related) {
1542
- eligible.push({
1543
- entry: hit.entry,
1544
- about: true,
1545
- distinctive: false,
1546
- credited: false,
1547
- relevance: 0,
1548
- score: hit.score,
1549
- best: '',
1550
- bm25: 0,
1551
- evidence: { strongTerms: 0, phrase: false },
1552
- });
1553
- }
1557
+ const relatedCandidates = related.map((hit) => ({
1558
+ entry: hit.entry,
1559
+ about: true,
1560
+ distinctive: false,
1561
+ credited: false,
1562
+ relevance: 0,
1563
+ score: hit.score,
1564
+ best: '',
1565
+ bm25: 0,
1566
+ evidence: { strongTerms: 0, phrase: false },
1567
+ }));
1568
+ relatedCandidates.sort(byStrength);
1569
+ // Append neighbors AFTER direct hits so their relevance-0 ordering never
1570
+ // overwrites the dense RRF ranking of the direct hits.
1571
+ eligible.push(...relatedCandidates);
1554
1572
  /** Which of the candidates arrived over a hop, and from which seed, for the log line below. */
1555
1573
  const relatedVia = new Map(related.map((hit) => [hit.entry.id, hit.via ?? '']));
1556
- // The neighbours carry relevance 0, so this second sort is what keeps them
1557
- // behind every memory the turn actually matched without relying on the order
1558
- // `relatedHits` happened to return.
1559
- eligible.sort(byStrength);
1560
1574
  const picked = [];
1561
1575
  for (const candidate of eligible) {
1562
1576
  if (picked.length >= remaining)
@@ -1601,10 +1615,15 @@ export class MemoriesRuntime {
1601
1615
  const extras = `${window === undefined ? '' : `, window ${window.label}`}`
1602
1616
  + `${hopped.length === 0 ? '' : `, +${hopped.length} related via ${[...new Set(hopped.map((item) => relatedVia.get(item.entry.id)))].join(',')}`}`
1603
1617
  + `${excerpts.length === 0 ? '' : `, raw +${excerpts.length}`}`;
1604
- this.log.info('dsh-cross-memory: session %s recalled %s (relevance %s, score %s%s, via %s)', session.id, picked.map((item) => item.entry.id).join(', '), picked[0].relevance.toFixed(1), picked[0].score.toFixed(1), extras, JSON.stringify((picked[0].best ?? '').slice(0, 80)));
1605
- this.recallCounts.set(session, used + picked.length);
1606
- await this.markSurfaced(session, picked.map((item) => item.entry));
1607
- this.recordInjection(session, picked.map((item) => item.entry.id));
1618
+ const top = picked[0];
1619
+ this.log.info('dsh-cross-memory: session %s recalled %s (relevance %s, score %s%s, via %s)', session.id, picked.length > 0 ? picked.map((item) => item.entry.id).join(', ') : '(raw-only)', top !== undefined ? top.relevance.toFixed(1) : '0.0', top !== undefined ? top.score.toFixed(1) : '0.0', extras, JSON.stringify((top?.best ?? '').slice(0, 80)));
1620
+ this.recallCounts.set(session, used + Math.max(picked.length, ragExcerpts.length > 0 ? 1 : 0));
1621
+ if (ragExcerpts.length > 0)
1622
+ this.lastRagTurn.set(session, latestTurn.key);
1623
+ if (picked.length > 0) {
1624
+ await this.markSurfaced(session, picked.map((item) => item.entry));
1625
+ this.recordInjection(session, picked.map((item) => item.entry.id));
1626
+ }
1608
1627
  return createUserMessage({
1609
1628
  content: [{ type: 'text', text }],
1610
1629
  // The same form as the summary block; `carriesRecall` tells them apart by
@@ -1901,7 +1920,7 @@ export class MemoriesRuntime {
1901
1920
  * @param session - session to read.
1902
1921
  * @returns the text, or `undefined` when no user message is on the surface.
1903
1922
  */
1904
- latestUserText(session) {
1923
+ latestUserTurn(session) {
1905
1924
  try {
1906
1925
  const messages = session.deriveMessages();
1907
1926
  for (let index = messages.length - 1; index >= 0; index -= 1) {
@@ -1918,8 +1937,10 @@ export class MemoriesRuntime {
1918
1937
  .trim();
1919
1938
  if (text.length < this.settings.recallMinQueryChars)
1920
1939
  return undefined;
1921
- if (text.length > 0)
1922
- return text.slice(0, 2_000);
1940
+ if (text.length > 0) {
1941
+ const key = typeof message.id === 'string' && message.id.length > 0 ? message.id : index;
1942
+ return { key, text: text.slice(0, 2_000) };
1943
+ }
1923
1944
  }
1924
1945
  }
1925
1946
  catch {
@@ -1927,6 +1948,13 @@ export class MemoriesRuntime {
1927
1948
  }
1928
1949
  return undefined;
1929
1950
  }
1951
+ latestUserText(session) {
1952
+ return this.latestUserTurn(session)?.text;
1953
+ }
1954
+ /** Clean up per-session maps when an agent disposes. */
1955
+ forgetSession(sessionId) {
1956
+ this.capped.delete(sessionId);
1957
+ }
1930
1958
  /** Whether memory is switched off for one session. */
1931
1959
  sessionOff(session) {
1932
1960
  return this.state.getSessionMode(session.id) === 'off';
@@ -2048,11 +2076,15 @@ export class MemoriesRuntime {
2048
2076
  * @param delayMs - how long to wait.
2049
2077
  */
2050
2078
  armTimer(agent, delayMs) {
2079
+ if (this.lifecycle.signal.aborted)
2080
+ return;
2051
2081
  const existing = this.idleTimers.get(agent);
2052
2082
  if (existing !== undefined)
2053
2083
  clearTimeout(existing);
2054
2084
  const timer = setTimeout(() => {
2055
2085
  this.idleTimers.delete(agent);
2086
+ if (this.lifecycle.signal.aborted)
2087
+ return;
2056
2088
  // Still inside a peak window? Wait for it to end rather than spending now —
2057
2089
  // the settle clock keeps running, so the pass runs as soon as it is cheap.
2058
2090
  const penalty = peakDelayMs(this.settings.peakHours, new Date());
@@ -2117,10 +2149,14 @@ export class MemoriesRuntime {
2117
2149
  // tick. Skipped under the test runner, which tears its temp dirs down faster
2118
2150
  // than this delayed write would fire.
2119
2151
  if (process.env['NODE_TEST_CONTEXT'] === undefined) {
2152
+ if (this.bootNoticeTimer !== undefined)
2153
+ clearTimeout(this.bootNoticeTimer);
2120
2154
  const boot = setTimeout(() => {
2155
+ this.bootNoticeTimer = undefined;
2121
2156
  void this.pumpNotices().catch(() => undefined);
2122
2157
  }, 15_000);
2123
2158
  boot.unref?.();
2159
+ this.bootNoticeTimer = boot;
2124
2160
  }
2125
2161
  const minutes = this.settings.extractIntervalMinutes;
2126
2162
  if (!(minutes > 0))
@@ -2138,6 +2174,9 @@ export class MemoriesRuntime {
2138
2174
  }
2139
2175
  /** Stop the periodic check, if one is running. */
2140
2176
  stopPeriodicExtraction() {
2177
+ if (this.bootNoticeTimer !== undefined)
2178
+ clearTimeout(this.bootNoticeTimer);
2179
+ this.bootNoticeTimer = undefined;
2141
2180
  if (this.periodicTimer !== undefined)
2142
2181
  clearInterval(this.periodicTimer);
2143
2182
  this.periodicTimer = undefined;
@@ -2154,6 +2193,8 @@ export class MemoriesRuntime {
2154
2193
  markStoreChanged() {
2155
2194
  this.storeSync.markChanged();
2156
2195
  }
2196
+ /** The boot notice check's timer, when one is armed. */
2197
+ bootNoticeTimer;
2157
2198
  /** The periodic check's timer, when one is armed. */
2158
2199
  periodicTimer;
2159
2200
  /** The store's git transport; see {@link StoreSyncService}. */
@@ -2459,8 +2500,12 @@ export class MemoriesRuntime {
2459
2500
  this.idleSince.delete(agent);
2460
2501
  }
2461
2502
  /** Remember an agent so a process exit can still mine it. */
2503
+ trackedAgents = new WeakSet();
2462
2504
  track(agent) {
2463
- this.tracked.add(new WeakRef(agent));
2505
+ if (!this.trackedAgents.has(agent)) {
2506
+ this.trackedAgents.add(agent);
2507
+ this.tracked.add(new WeakRef(agent));
2508
+ }
2464
2509
  this.installExitFlush();
2465
2510
  }
2466
2511
  /**
@@ -2844,7 +2889,7 @@ export class MemoriesRuntime {
2844
2889
  let log;
2845
2890
  try {
2846
2891
  const buffer = await readFile(entry.file);
2847
- log = parseSessionLog(decodeSessionLog(buffer), entry.file, entry.modifiedAt);
2892
+ log = parseSessionLog(await decodeSessionLogAsync(buffer), entry.file, entry.modifiedAt);
2848
2893
  }
2849
2894
  catch (error) {
2850
2895
  skippedEmpty += 1;
@@ -3067,6 +3112,8 @@ export class MemoriesRuntime {
3067
3112
  // A paused account skips the pass and leaves the job in place: the cooldown
3068
3113
  // is the right place to retry, not this turn.
3069
3114
  if (this.backgroundPaused()) {
3115
+ const { lease: _lease, ...unleased } = job;
3116
+ this.state.putJob({ ...unleased, leaseUntil: 0 });
3070
3117
  this.consolidateSkip = 'background passes are paused by a provider quota cooldown';
3071
3118
  return undefined;
3072
3119
  }
@@ -3279,6 +3326,7 @@ export class MemoriesRuntime {
3279
3326
  const now = Date.now();
3280
3327
  try {
3281
3328
  let queue = pruneNotices(await readNotices(dir), now);
3329
+ const before = JSON.stringify(queue);
3282
3330
  const policy = {
3283
3331
  now,
3284
3332
  quietHours: this.settings.noticeQuietHours,
@@ -3311,7 +3359,7 @@ export class MemoriesRuntime {
3311
3359
  // 2. Open loops whose deadline has passed. This is the trigger that makes
3312
3360
  // the assistant pro-active rather than reactive: it needs no question to
3313
3361
  // answer, only a promise the user made and has not closed.
3314
- const loopNow = pruneLoops(await readLoops(dir), now);
3362
+ let loopNow = pruneLoops(await readLoops(dir), now);
3315
3363
  const raised = [];
3316
3364
  for (const loop of dueLoops(loopNow, now)) {
3317
3365
  const admitted = admitNotice(queue, {
@@ -3341,6 +3389,7 @@ export class MemoriesRuntime {
3341
3389
  ledger = withLoop(ledger, id, { remindedAt: now, remindCount: (loop.remindCount ?? 0) + 1 });
3342
3390
  }
3343
3391
  await writeLoops(dir, ledger);
3392
+ loopNow = ledger;
3344
3393
  }
3345
3394
  // 4. Judgement notices: a note with no deadline that has been sitting for
3346
3395
  // days. There is no rule that says it is worth an interruption, so the
@@ -3406,14 +3455,13 @@ export class MemoriesRuntime {
3406
3455
  else if (!this.settings.noticeGate && loopNow.loops.some((loop) => loop.state === 'open' && loop.dueAt === undefined)) {
3407
3456
  this.log.decision('dsh-cross-memory: notice gate is off, undated loops stay silent');
3408
3457
  }
3409
- const before = JSON.stringify(queue);
3410
3458
  // 5. Deliver what is due. The only channel is the operating system's
3411
3459
  // notification: this plugin used to hand the sentence to a desktop pet, and
3412
3460
  // that dependency is gone — a notice is worth having only if it arrives
3413
3461
  // without a second plugin being installed and configured correctly.
3414
3462
  let next = queue;
3415
3463
  for (const notice of dueNotices(queue, now)) {
3416
- if (systemNotification('dsh-cross-memory', notice.title)) {
3464
+ if (await systemNotification('dsh-cross-memory', notice.title)) {
3417
3465
  next = withNotice(next, { ...notice, state: 'delivered', deliveredAt: now });
3418
3466
  this.log.info('dsh-cross-memory: notice delivered via system notification: %s', notice.title);
3419
3467
  }
@@ -3523,7 +3571,7 @@ export class MemoriesRuntime {
3523
3571
  * @returns whether the operating system accepted it.
3524
3572
  */
3525
3573
  async probeNotification() {
3526
- const sent = systemNotification('dsh-cross-memory', '测试通知:看到这条说明通知通道正常。');
3574
+ const sent = await systemNotification('dsh-cross-memory', '测试通知:看到这条说明通知通道正常。');
3527
3575
  return sent ? { ok: true } : { ok: false, reason: 'osascript was rejected or unavailable' };
3528
3576
  }
3529
3577
  /** The notice queue as one short block, for the command. */
@@ -3645,7 +3693,7 @@ export class MemoriesRuntime {
3645
3693
  const verdict = byId.get(dispute.id);
3646
3694
  if (verdict === undefined)
3647
3695
  continue;
3648
- this.log.info('dsh-cross-memory: auto-decide %s %s/%s (confidence %.2f): %s', verdict.accept ? 'accepted' : 'rejected', dispute.scope, dispute.id, verdict.confidence, verdict.reason);
3696
+ this.log.info('dsh-cross-memory: auto-decide %s %s/%s (confidence %s): %s', verdict.accept ? 'accepted' : 'rejected', dispute.scope, dispute.id, verdict.confidence.toFixed(2), verdict.reason);
3649
3697
  }
3650
3698
  if (remaining.length > 0) {
3651
3699
  this.log.info('dsh-cross-memory: %d decision(s) still need a person after auto-decide', remaining.length);
@@ -4413,12 +4461,17 @@ export function apply(ctx, config = {}) {
4413
4461
  * actually fails.
4414
4462
  */
4415
4463
  let runtime;
4464
+ let pendingLogSinkError;
4416
4465
  const sink = createFileSink(deployment.logFile, undefined, (reason) => {
4417
4466
  // A failed write is the one failure the log file cannot report about itself:
4418
4467
  // the very channel is broken. Record it on the runtime so `/memories stats`
4419
4468
  // (and the settings card, which reads the same field) can say the file is
4420
4469
  // stale instead of leaving a user to trust something that stopped growing.
4421
- runtime.logSinkError = `write failed: ${reason}`;
4470
+ const message = `write failed: ${reason}`;
4471
+ if (runtime !== undefined)
4472
+ runtime.logSinkError = message;
4473
+ else
4474
+ pendingLogSinkError = message;
4422
4475
  });
4423
4476
  if (sink !== undefined) {
4424
4477
  ctx.logger.exporter(createLogExporter(sink, () => current.logLevel));
@@ -4427,7 +4480,7 @@ export function apply(ctx, config = {}) {
4427
4480
  // Recorded on the runtime rather than only logged: this very message cannot
4428
4481
  // reach the file that failed to open, and the host's own sink is a ring
4429
4482
  // buffer that a stock profile never reads. `stats` is where a user looks.
4430
- runtime.logSinkError = `unwritable: ${deployment.logFile}`;
4483
+ pendingLogSinkError = `unwritable: ${deployment.logFile}`;
4431
4484
  log.warn('dsh-cross-memory: could not open the log file %s', deployment.logFile);
4432
4485
  }
4433
4486
  // The Memories page is this plugin's own, so the settings domain is asked not
@@ -4445,8 +4498,11 @@ export function apply(ctx, config = {}) {
4445
4498
  liveRegistrations();
4446
4499
  onSettingsCommit();
4447
4500
  });
4448
- runtime = new MemoriesRuntime(ctx, config, read);
4449
- ctx.effect(() => () => runtime.dispose(), 'dsh-cross-memory.lifecycle');
4501
+ const activeRuntime = new MemoriesRuntime(ctx, config, read);
4502
+ runtime = activeRuntime;
4503
+ if (pendingLogSinkError !== undefined)
4504
+ activeRuntime.logSinkError = pendingLogSinkError;
4505
+ ctx.effect(() => () => activeRuntime.dispose(), 'dsh-cross-memory.lifecycle');
4450
4506
  // A staged consolidation proposal can also wait as an answer-embedded action
4451
4507
  // card: the model offers it from its skill, and the buttons apply or discard
4452
4508
  // the whole batch. Both services are optional, and an older action-card
@@ -4463,16 +4519,16 @@ export function apply(ctx, config = {}) {
4463
4519
  }
4464
4520
  const seam = {
4465
4521
  pending: async () => {
4466
- const pending = await readPendingPlan(runtime.store.memoriesDir).catch(() => undefined);
4522
+ const pending = await readPendingPlan(activeRuntime.store.memoriesDir).catch(() => undefined);
4467
4523
  return pending === undefined
4468
4524
  ? undefined
4469
4525
  : { label: pending.label, count: pending.disputes.length, stagedAt: pending.at };
4470
4526
  },
4471
4527
  apply: async (agent) => {
4472
- const result = await runtime.applyPendingPlan(agent);
4528
+ const result = await activeRuntime.applyPendingPlan(agent);
4473
4529
  return result === undefined ? undefined : { written: result.written, retired: result.retired };
4474
4530
  },
4475
- reject: () => runtime.rejectPendingPlan(),
4531
+ reject: () => activeRuntime.rejectPendingPlan(),
4476
4532
  };
4477
4533
  child.effect(() => registerProposalCard(actionCards, skills, seam), 'dsh-cross-memory.proposalCard');
4478
4534
  });
@@ -4496,7 +4552,7 @@ export function apply(ctx, config = {}) {
4496
4552
  description: '合并与重整记忆时使用的子代理组成:不含任何工具,只能返回 JSON 方案。',
4497
4553
  plugins: [],
4498
4554
  }).then((unregister) => {
4499
- runtime.markConsolidatePresetReady(true);
4555
+ activeRuntime.markConsolidatePresetReady(true);
4500
4556
  child.effect(() => () => { void unregister(); }, 'dsh-cross-memory.consolidatePreset');
4501
4557
  log.info('dsh-cross-memory: registered the tool-free preset %s for the consolidation child', CONSOLIDATE_PRESET_ID);
4502
4558
  }, (error) => {
@@ -4504,13 +4560,13 @@ export function apply(ctx, config = {}) {
4504
4560
  });
4505
4561
  });
4506
4562
  onSettingsCommit = () => {
4507
- runtime.startPeriodicExtraction();
4508
- runtime.startPeriodicSync();
4509
- runtime.reportSettingsIssues();
4563
+ activeRuntime.startPeriodicExtraction();
4564
+ activeRuntime.startPeriodicSync();
4565
+ activeRuntime.reportSettingsIssues();
4510
4566
  };
4511
- runtime.startPeriodicExtraction();
4512
- runtime.startPeriodicSync();
4513
- runtime.reportSettingsIssues();
4567
+ activeRuntime.startPeriodicExtraction();
4568
+ activeRuntime.startPeriodicSync();
4569
+ activeRuntime.reportSettingsIssues();
4514
4570
  // The Memories page reads and edits memories through the Typert gateway, so
4515
4571
  // registering the invocation manifest and providing the `memories` service
4516
4572
  // are what make `ctx.remote.memories.*` callable from the browser. Both are
@@ -4529,10 +4585,10 @@ export function apply(ctx, config = {}) {
4529
4585
  const withdraw = typert.register(REMOTE_CONTRIBUTION);
4530
4586
  child.effect(() => withdraw, 'dsh-cross-memory.remoteContribution');
4531
4587
  const service = createRemoteService({
4532
- store: runtime.store,
4588
+ store: activeRuntime.store,
4533
4589
  dshHome: deployment.dshHome,
4534
- disputes: () => runtime.disputes(),
4535
- resolveDispute: (id, decision) => runtime.resolveDispute(id, decision),
4590
+ disputes: () => activeRuntime.disputes(),
4591
+ resolveDispute: (id, decision) => activeRuntime.resolveDispute(id, decision),
4536
4592
  });
4537
4593
  // Provided on the plugin's own context, not the child's: the gateway is a
4538
4594
  // sibling scope and resolves the service as a peer.
@@ -4547,7 +4603,7 @@ export function apply(ctx, config = {}) {
4547
4603
  });
4548
4604
  // Import (and remove) a pre-SQLite watermark file once, so upgrading does not
4549
4605
  // re-mine conversations that were already processed.
4550
- void importLegacyState(runtime.state, runtime.store.memoriesDir).then((imported) => {
4606
+ void importLegacyState(activeRuntime.state, activeRuntime.store.memoriesDir).then((imported) => {
4551
4607
  if (imported === undefined)
4552
4608
  return;
4553
4609
  log.info('dsh-cross-memory: imported %d watermarks from the legacy state file', imported);
@@ -4557,18 +4613,18 @@ export function apply(ctx, config = {}) {
4557
4613
  // The first sweep runs here rather than waiting for a session to settle: a
4558
4614
  // process that starts and stops (a script, a one-shot task) then still gets
4559
4615
  // the periodic cleanup it would otherwise never reach.
4560
- void runtime.sweepIfDue().catch((error) => {
4616
+ void activeRuntime.sweepIfDue().catch((error) => {
4561
4617
  log.warn('dsh-cross-memory: startup sweep failed: %o', error);
4562
4618
  });
4563
4619
  // Activation facts belong at `debug`, not at the file's default verbosity: a
4564
4620
  // hot reload writes this line on every edit, and measured over nine days it
4565
4621
  // was a quarter of the whole log while saying nothing a reader could act on.
4566
4622
  // `/memories stats` reports the same facts on demand.
4567
- log.debug('dsh-cross-memory: store at %s autoExtract=%s idle=%d log=%s', runtime.store.memoriesDir, String(runtime.settings.autoExtract), runtime.settings.autoExtractIdleMs, deployment.logFile.length > 0 ? `${deployment.logFile} (${runtime.settings.logLevel})` : 'off');
4623
+ log.debug('dsh-cross-memory: store at %s autoExtract=%s idle=%d log=%s', activeRuntime.store.memoriesDir, String(activeRuntime.settings.autoExtract), activeRuntime.settings.autoExtractIdleMs, deployment.logFile.length > 0 ? `${deployment.logFile} (${activeRuntime.settings.logLevel})` : 'off');
4568
4624
  // `enableTool`/`enableCommand` are live: each registration is torn down and
4569
4625
  // re-created when the toggle flips, so the model's catalog follows the entry
4570
4626
  // config without a restart.
4571
- const registerTool = () => registerMemoryTool(ctx, runtime);
4627
+ const registerTool = () => registerMemoryTool(ctx, activeRuntime);
4572
4628
  const registerCommand = () => ctx.commands.register({
4573
4629
  name: 'memories',
4574
4630
  description: 'Inspect and manage cross-session memories',
@@ -4579,11 +4635,11 @@ export function apply(ctx, config = {}) {
4579
4635
  // Every failure inside this plugin becomes an error RESULT instead.
4580
4636
  handler: async (invocation) => {
4581
4637
  try {
4582
- return await handleCommand(runtime, invocation);
4638
+ return await handleCommand(activeRuntime, invocation);
4583
4639
  }
4584
4640
  catch (error) {
4585
4641
  const message = error instanceof Error ? error.message : String(error);
4586
- runtime.noteCommandFailure(invocation.rawInput.trim().split(/\s+/u)[0] ?? 'memories', error);
4642
+ activeRuntime.noteCommandFailure(invocation.rawInput.trim().split(/\s+/u)[0] ?? 'memories', error);
4587
4643
  return { kind: 'error', text: `dsh-cross-memory: ${message}` };
4588
4644
  }
4589
4645
  },
@@ -4591,14 +4647,14 @@ export function apply(ctx, config = {}) {
4591
4647
  let toolDisposer;
4592
4648
  let commandDisposer;
4593
4649
  const syncRegistrations = () => {
4594
- const wantTool = runtime.settings.enableTool;
4650
+ const wantTool = activeRuntime.settings.enableTool;
4595
4651
  if (wantTool && toolDisposer === undefined)
4596
4652
  toolDisposer = registerTool();
4597
4653
  else if (!wantTool && toolDisposer !== undefined) {
4598
4654
  toolDisposer();
4599
4655
  toolDisposer = undefined;
4600
4656
  }
4601
- const wantCommand = runtime.settings.enableCommand;
4657
+ const wantCommand = activeRuntime.settings.enableCommand;
4602
4658
  if (wantCommand && commandDisposer === undefined)
4603
4659
  commandDisposer = registerCommand();
4604
4660
  else if (!wantCommand && commandDisposer !== undefined) {
@@ -4613,24 +4669,27 @@ export function apply(ctx, config = {}) {
4613
4669
  commandDisposer?.();
4614
4670
  }, 'dsh-cross-memory.registrations');
4615
4671
  ctx.on('agent/status', ({ agent, status }) => {
4672
+ if (isSubagentSession(agent.session))
4673
+ return;
4616
4674
  if (status === 'idle')
4617
- runtime.scheduleExtraction(agent);
4675
+ activeRuntime.scheduleExtraction(agent);
4618
4676
  else
4619
- runtime.cancelExtraction(agent);
4677
+ activeRuntime.cancelExtraction(agent);
4620
4678
  // Record real activity on every transition, so `maxAgeDays` judges a
4621
4679
  // session by when it was last USED rather than by when it was last mined —
4622
4680
  // a session that is never mined would otherwise look infinitely young.
4623
- runtime.recordActivity(agent.session);
4681
+ activeRuntime.recordActivity(agent.session);
4624
4682
  });
4625
4683
  ctx.on('agent/disposed', ({ agent }) => {
4626
- runtime.cancelExtraction(agent);
4684
+ activeRuntime.cancelExtraction(agent);
4685
+ activeRuntime.forgetSession(agent.session.id);
4627
4686
  // A short-lived process may exit before the idle timer ever fires; the
4628
4687
  // disposal boundary is the last moment an extraction can still run.
4629
4688
  // `flushExit` is declared async, but the registry wraps every listener and
4630
4689
  // reports anything it throws as "agent/disposed listener threw". Normalise
4631
4690
  // the return value first: a `.catch` on a non-promise is exactly the failure
4632
4691
  // the host logged in 2026-11-22..26, and disposal must never be the raiser.
4633
- Promise.resolve(runtime.flushExit()).catch(() => undefined);
4692
+ Promise.resolve(activeRuntime.flushExit()).catch(() => undefined);
4634
4693
  });
4635
4694
  // 0.1.7-rc.1 起宿主把 `agent/session-start` 改名为 `agent/created`(公告见 v0.1.7-rc.1
4636
4695
  // release notes)。payload 形状不变,仍是 `{ agent, source }`,`source` 取值同为
@@ -4642,7 +4701,7 @@ export function apply(ctx, config = {}) {
4642
4701
  // is gone: forget it and let the next pre-step re-inject. Fresh and resumed
4643
4702
  // sessions need no work here — the first step of the first turn injects.
4644
4703
  if (source === 'clear' || source === 'compact')
4645
- runtime.resetInjection(agent.session);
4704
+ activeRuntime.resetInjection(agent.session);
4646
4705
  // 返回 undefined(而不是 void):0.2.0 的 'agent/created' 监听器签名要求
4647
4706
  // `Promise<undefined> | undefined`,隐式 void 会报 TS2345。
4648
4707
  return undefined;
@@ -4651,33 +4710,35 @@ export function apply(ctx, config = {}) {
4651
4710
  const decision = await next();
4652
4711
  if (decision.kind === 'reject')
4653
4712
  return decision;
4713
+ if (isSubagentSession(agent.session))
4714
+ return decision;
4654
4715
  // Memory is an enhancement, never a precondition: this seam runs on every
4655
4716
  // step of every turn, and an exception here fails the user's turn. Contain
4656
4717
  // everything and fall through to the unmodified decision instead.
4657
4718
  try {
4658
4719
  const addition = [];
4659
- const summary = await runtime.injectionFor(agent);
4720
+ const summary = await activeRuntime.injectionFor(agent);
4660
4721
  if (summary !== undefined)
4661
4722
  addition.push(summary);
4662
4723
  // Titles of what the summary had no room for: one small block per
4663
4724
  // conversation, so the store becomes discoverable instead of only the
4664
4725
  // same dozen entries ever being shown.
4665
- const rotation = await runtime.rotationFor(agent);
4726
+ const rotation = await activeRuntime.rotationFor(agent);
4666
4727
  if (rotation !== undefined)
4667
4728
  addition.push(rotation);
4668
4729
  // Credit the memories the block already handed over and this turn is now
4669
4730
  // actually about. Without it the only "demand" signal the ranking has is a
4670
4731
  // search hit, which measures lookup-style knowledge and misses the memory
4671
4732
  // that was injected and used.
4672
- await runtime.creditInjectedUse(agent);
4733
+ await activeRuntime.creditInjectedUse(agent);
4673
4734
  // The on-demand delta is a second, independent decision: a conversation can
4674
4735
  // already carry the summary and still meet a memory that only matters now.
4675
- const delta = await runtime.recallFor(agent);
4736
+ const delta = await activeRuntime.recallFor(agent);
4676
4737
  if (delta !== undefined)
4677
4738
  addition.push(delta);
4678
4739
  // A third, independent decision: the conversation already carries the
4679
4740
  // summary and may still have had memories written after it.
4680
- const late = await runtime.deltaFor(agent);
4741
+ const late = await activeRuntime.deltaFor(agent);
4681
4742
  if (late !== undefined)
4682
4743
  addition.push(late);
4683
4744
  const fresh = addition.filter((message) => !decision.messages.some((existing) => existing.id === message.id));
@@ -4691,7 +4752,7 @@ export function apply(ctx, config = {}) {
4691
4752
  return { ...decision, messages: [...decision.messages, ...fresh] };
4692
4753
  }
4693
4754
  catch (error) {
4694
- runtime.notePreStepFailure(agent.session.id, error);
4755
+ activeRuntime.notePreStepFailure(agent.session.id, error);
4695
4756
  return decision;
4696
4757
  }
4697
4758
  });