@dsh-ray/assistant-delivery 0.2.4 → 0.3.1

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 (79) hide show
  1. package/README.md +15 -2
  2. package/cordis.patch.yml +0 -2
  3. package/lib/agent-runtime.d.ts +15 -0
  4. package/lib/agent-runtime.d.ts.map +1 -1
  5. package/lib/agent-runtime.js +446 -51
  6. package/lib/agent-runtime.js.map +1 -1
  7. package/lib/attention-audit-store.d.ts +2 -1
  8. package/lib/attention-audit-store.d.ts.map +1 -1
  9. package/lib/attention-audit-store.js +3 -0
  10. package/lib/attention-audit-store.js.map +1 -1
  11. package/lib/coordinator.d.ts +21 -1
  12. package/lib/coordinator.d.ts.map +1 -1
  13. package/lib/coordinator.js +255 -68
  14. package/lib/coordinator.js.map +1 -1
  15. package/lib/feedback-command.d.ts +1 -0
  16. package/lib/feedback-command.d.ts.map +1 -1
  17. package/lib/feedback-command.js +1 -1
  18. package/lib/feedback-command.js.map +1 -1
  19. package/lib/index.d.ts +2 -1
  20. package/lib/index.d.ts.map +1 -1
  21. package/lib/index.js +1 -0
  22. package/lib/index.js.map +1 -1
  23. package/lib/interrupted-notices.d.ts +20 -5
  24. package/lib/interrupted-notices.d.ts.map +1 -1
  25. package/lib/interrupted-notices.js +238 -24
  26. package/lib/interrupted-notices.js.map +1 -1
  27. package/lib/learning-command.d.ts +2 -0
  28. package/lib/learning-command.d.ts.map +1 -1
  29. package/lib/learning-command.js +2 -0
  30. package/lib/learning-command.js.map +1 -1
  31. package/lib/native-web-owner.d.ts +12 -0
  32. package/lib/native-web-owner.d.ts.map +1 -1
  33. package/lib/native-web-owner.js +653 -80
  34. package/lib/native-web-owner.js.map +1 -1
  35. package/lib/operator-snapshot.d.ts +1 -1
  36. package/lib/operator-snapshot.d.ts.map +1 -1
  37. package/lib/operator-snapshot.js +6 -5
  38. package/lib/operator-snapshot.js.map +1 -1
  39. package/lib/ray-worker-runtime.d.ts +192 -0
  40. package/lib/ray-worker-runtime.d.ts.map +1 -0
  41. package/lib/ray-worker-runtime.js +1300 -0
  42. package/lib/ray-worker-runtime.js.map +1 -0
  43. package/lib/service.d.ts +286 -3
  44. package/lib/service.d.ts.map +1 -1
  45. package/lib/service.js +1608 -72
  46. package/lib/service.js.map +1 -1
  47. package/lib/session-commands.d.ts +6 -0
  48. package/lib/session-commands.d.ts.map +1 -1
  49. package/lib/session-commands.js +14 -0
  50. package/lib/session-commands.js.map +1 -1
  51. package/lib/session-lease-runtime.d.ts +31 -6
  52. package/lib/session-lease-runtime.d.ts.map +1 -1
  53. package/lib/session-lease-runtime.js +553 -43
  54. package/lib/session-lease-runtime.js.map +1 -1
  55. package/lib/sqlite.d.ts +1 -1
  56. package/lib/sqlite.d.ts.map +1 -1
  57. package/lib/sqlite.js +83 -3
  58. package/lib/sqlite.js.map +1 -1
  59. package/lib/store.d.ts +93 -2
  60. package/lib/store.d.ts.map +1 -1
  61. package/lib/store.js +695 -24
  62. package/lib/store.js.map +1 -1
  63. package/lib/tools.d.ts.map +1 -1
  64. package/lib/tools.js +319 -0
  65. package/lib/tools.js.map +1 -1
  66. package/lib/version-query.d.ts.map +1 -1
  67. package/lib/version-query.js +109 -20
  68. package/lib/version-query.js.map +1 -1
  69. package/lib/version.d.ts +1 -1
  70. package/lib/version.js +1 -1
  71. package/lib/work-item-feedback-store.d.ts +2 -1
  72. package/lib/work-item-feedback-store.d.ts.map +1 -1
  73. package/lib/work-item-feedback-store.js +1 -0
  74. package/lib/work-item-feedback-store.js.map +1 -1
  75. package/lib/work-item-replies-store.d.ts +2 -1
  76. package/lib/work-item-replies-store.d.ts.map +1 -1
  77. package/lib/work-item-replies-store.js +3 -0
  78. package/lib/work-item-replies-store.js.map +1 -1
  79. package/package.json +11 -11
@@ -17,8 +17,9 @@ import { learningCommandUsage, parseLearningCommand, serializeLearningExport, }
17
17
  import { attachRestartRun, restartDigest, restartContinuationText } from './restart-runtime.js';
18
18
  import { admitRestartContinuation, createRestartContinuation } from './restart-native.js';
19
19
  import { renderOwnerApprovalStatus } from './approval-status-context.js';
20
- import { isExactDeliveryCommand, isOwnerUpdateSlashAttempt, learningDispatchRecoveryCode, OWNER_UPDATE_USAGE, parseDeliveryCommand, parseOwnerSelfIterationCommand, parseOwnerVersionQuery, permissionDispatchRecoveryCode, } from './session-commands.js';
21
- import { classifyMidTurnFailure } from './interrupted-notices.js';
20
+ import { isExactDeliveryCommand, isOwnerUpdateSlashAttempt, learningDispatchRecoveryCode, OWNER_UPDATE_USAGE, parseDeliveryCommand, parseOwnerSelfIterationCommand, parseOwnerVersionQuery, parseOwnerVetoArgs, permissionDispatchRecoveryCode, } from './session-commands.js';
21
+ import { classifyMidTurnFailure, summarizeTurnToolMutations, } from './interrupted-notices.js';
22
+ import { ReloadInterruptedError } from './coordinator.js';
22
23
  import { collectDeliveryVersionReport, formatAssistantVersionSummary, } from './version-query.js';
23
24
  import { DeliveryStoreError } from './store.js';
24
25
  import { SessionLeaseUnavailable } from './session-lease-runtime.js';
@@ -1309,49 +1310,165 @@ export class DshDeliveryRuntime {
1309
1310
  throw new Error('assistant-delivery: restart continuation authority changed');
1310
1311
  }, record);
1311
1312
  }
1313
+ async wakeFrontForHandback(binding, ticket, outerSignal) {
1314
+ if (outerSignal.aborted)
1315
+ return;
1316
+ const agents = this.ctx.get('agents');
1317
+ const sessions = this.ctx.get('sessions');
1318
+ if (agents === undefined || sessions === undefined) {
1319
+ throw new Error('assistant-delivery: agent runtime unavailable for handback wakeup');
1320
+ }
1321
+ const persisted = this.options.getModelSelection(binding.conversation);
1322
+ const requestedRoute = toModelRoute(persisted ?? { provider: this.options.provider, model: this.options.model });
1323
+ const resolvedRoute = await this.resolveExecutionRoute(binding.conversation, persisted, requestedRoute, outerSignal);
1324
+ if ('retry' in resolvedRoute) {
1325
+ throw new Error('assistant-delivery: model selection changed before handback wakeup');
1326
+ }
1327
+ const selected = agentSelection(resolvedRoute.route);
1328
+ const agentPresets = this.options.getAgentPresets();
1329
+ const presetId = agentPresets === undefined
1330
+ ? binding.agentPreset
1331
+ : (await agentPresets.resolve(binding.agentPreset)).id;
1332
+ await requireWorkspace(binding.workspace);
1333
+ outerSignal.throwIfAborted();
1334
+ let lease;
1335
+ const maxLeaseAttempts = 20;
1336
+ for (let attempt = 1;; attempt += 1) {
1337
+ outerSignal.throwIfAborted();
1338
+ try {
1339
+ lease = this.sessionLeases.open({ kind: 'bound', binding }, outerSignal, { allowConcurrentOwner: true });
1340
+ break;
1341
+ }
1342
+ catch (error) {
1343
+ const retryable = error instanceof SessionLeaseUnavailable
1344
+ && (error.kind === 'busy' || error.kind === 'unknown');
1345
+ if (!retryable || attempt >= maxLeaseAttempts)
1346
+ throw error;
1347
+ await this.sessionLeases.waitForDrain(binding.sessionId);
1348
+ await new Promise((resolve, reject) => {
1349
+ if (outerSignal.aborted) {
1350
+ reject(outerSignal.reason);
1351
+ return;
1352
+ }
1353
+ const onAbort = () => {
1354
+ clearTimeout(timer);
1355
+ reject(outerSignal.reason);
1356
+ };
1357
+ const timer = setTimeout(() => {
1358
+ outerSignal.removeEventListener('abort', onAbort);
1359
+ resolve();
1360
+ }, 15);
1361
+ timer.unref?.();
1362
+ outerSignal.addEventListener('abort', onAbort, { once: true });
1363
+ });
1364
+ }
1365
+ }
1366
+ let control;
1367
+ let handle;
1368
+ let taskDeadline;
1369
+ try {
1370
+ control = this.beginSessionControl(binding.sessionId, lease.signal, true);
1371
+ taskDeadline = setTimeout(() => {
1372
+ lease.cancel(new AgentTaskTimeoutError());
1373
+ }, this.options.taskTimeoutMs);
1374
+ taskDeadline.unref?.();
1375
+ lease.dispatch();
1376
+ handle = await this.sessionLeases.resume(this.ctx, {
1377
+ resumeSessionId: SessionId(binding.sessionId),
1378
+ signal: control.controller.signal,
1379
+ agentOptions: {
1380
+ provider: selected.provider,
1381
+ model: selected.model,
1382
+ maxTokens: this.options.maxOutputTokens,
1383
+ },
1384
+ setup: async (agentCtx, preparedAgent) => {
1385
+ await this.setupAgent(agentCtx, preparedAgent, binding.workspace, presetId, externalPrincipalId(binding.principal), selected, agentPresets);
1386
+ },
1387
+ });
1388
+ const agent = handle.agent;
1389
+ await this.reconcileNativeFullPermissionReviewer(agent.session);
1390
+ control.controller.signal.throwIfAborted();
1391
+ const wakeupLines = [
1392
+ '持久后台 Worker 工单已交回前台协调(handback):',
1393
+ `- ticketId: ${ticket.ticketId}`,
1394
+ `- title: ${ticket.title}`,
1395
+ '- status: handed_back',
1396
+ `- handbackReason: ${ticket.handbackReason ?? '需要前台协调或主人确认'}`,
1397
+ ...(ticket.resultSummary ? [`- resultSummary: ${ticket.resultSummary}`] : []),
1398
+ '请根据交回原因向主人同步并重路由处理:可直接答复、用 `ticket_followup` 补充指令或用 `ticket_dispatch` 派发后续工单。',
1399
+ ];
1400
+ const msg = createUserMessage({
1401
+ content: [{ type: 'text', text: wakeupLines.join('\n') }],
1402
+ source: { kind: 'ray-worker-handback', ticketId: ticket.ticketId },
1403
+ });
1404
+ await this.followupTurn(agent, msg, undefined, undefined, undefined, control.controller.signal);
1405
+ await sessions.flush(agent.session);
1406
+ }
1407
+ finally {
1408
+ if (taskDeadline !== undefined)
1409
+ clearTimeout(taskDeadline);
1410
+ try {
1411
+ await this.disposeAfterReplyBoundary(binding.sessionId, handle, undefined, false, 10_000, control);
1412
+ }
1413
+ finally {
1414
+ if (control !== undefined)
1415
+ this.endSessionControl(binding.sessionId, control);
1416
+ lease.close();
1417
+ }
1418
+ }
1419
+ }
1312
1420
  dispatchControl = 'explicit';
1313
1421
  activeSessionControls = new Map();
1422
+ configuredAgents = new WeakSet();
1314
1423
  sessionLeases;
1424
+ disposingReloadCode;
1315
1425
  constructor(ctx, policy, options) {
1316
1426
  this.ctx = ctx;
1317
1427
  this.policy = policy;
1318
1428
  this.options = options;
1319
1429
  this.sessionLeases = options.sessionLeases;
1320
1430
  }
1321
- async resumeAgent(options) {
1431
+ markDisposing(code) {
1432
+ this.disposingReloadCode ??= code;
1433
+ }
1434
+ async resumeAgent(options, internalOptions) {
1322
1435
  const id = String(options.resumeSessionId);
1323
1436
  this.sessionLeases.assert(id);
1324
- return this.sessionLeases.resume(this.ctx, options);
1437
+ return this.sessionLeases.resume(this.ctx, options, internalOptions);
1325
1438
  }
1326
1439
  async cancelActive(binding, command) {
1327
1440
  const sessionId = binding.sessionId;
1328
- const control = this.activeSessionControls.get(sessionId);
1441
+ const controls = this.activeSessionControls.get(sessionId);
1329
1442
  const agents = this.ctx.get('agents');
1330
1443
  const agent = agents?.get(SessionId(sessionId));
1331
1444
  const activeAgent = agent !== undefined && agent.status !== 'idle';
1332
- if (control === undefined && !activeAgent)
1445
+ if ((controls === undefined || controls.size === 0) && !activeAgent)
1333
1446
  return false;
1334
- if (control !== undefined) {
1335
- // A generation boundary is stronger than a stop acknowledgement. Never
1336
- // let a later `/stop` downgrade an in-flight `/new` cancellation.
1337
- control.command = control.command === 'new' || command === 'new' ? 'new' : 'stop';
1338
- control.resolveCancelRequested();
1339
- if (!control.controller.signal.aborted) {
1340
- control.controller.abort(new UserSessionCancellation(control.command));
1447
+ if (controls !== undefined) {
1448
+ for (const control of controls) {
1449
+ // A generation boundary is stronger than a stop acknowledgement. Never
1450
+ // let a later `/stop` downgrade an in-flight `/new` cancellation.
1451
+ control.command = control.command === 'new' || command === 'new' ? 'new' : 'stop';
1452
+ control.resolveCancelRequested();
1453
+ if (!control.controller.signal.aborted) {
1454
+ control.controller.abort(new UserSessionCancellation(control.command));
1455
+ }
1341
1456
  }
1342
- this.sessionLeases.cancel(sessionId, new UserSessionCancellation(control.command));
1457
+ const rootCommand = [...controls].some(c => c.command === 'new') ? 'new' : command;
1458
+ this.sessionLeases.cancel(sessionId, new UserSessionCancellation(rootCommand));
1343
1459
  }
1344
1460
  // `whenIdle()` follows every later wakeup. Waiting on it here lets an
1345
1461
  // unrelated followup keep `/stop` or `/new` alive forever. Clear pending
1346
1462
  // input and wait only for Delivery's exact reply-scheduling boundary.
1347
1463
  if (activeAgent)
1348
1464
  agent.cancel({ kind: 'user' });
1349
- if (control !== undefined)
1350
- await control.replySafe;
1465
+ if (controls !== undefined && controls.size > 0)
1466
+ await Promise.all([...controls].map(c => c.replySafe));
1351
1467
  return true;
1352
1468
  }
1353
- beginSessionControl(sessionId, outer) {
1354
- if (this.activeSessionControls.has(sessionId)) {
1469
+ beginSessionControl(sessionId, outer, allowConcurrent = false) {
1470
+ let controls = this.activeSessionControls.get(sessionId);
1471
+ if (!allowConcurrent && controls !== undefined && controls.size > 0) {
1355
1472
  throw new Error(`assistant-delivery: session ${sessionFingerprint(sessionId)} is already processing an inbound`);
1356
1473
  }
1357
1474
  const controller = new AbortController();
@@ -1371,13 +1488,21 @@ export class DshDeliveryRuntime {
1371
1488
  resolveCancelRequested,
1372
1489
  resolveReplySafe,
1373
1490
  };
1374
- this.activeSessionControls.set(sessionId, control);
1491
+ if (controls === undefined) {
1492
+ controls = new Set();
1493
+ this.activeSessionControls.set(sessionId, controls);
1494
+ }
1495
+ controls.add(control);
1375
1496
  return control;
1376
1497
  }
1377
1498
  endSessionControl(sessionId, control) {
1378
1499
  control.removeOuterAbort();
1379
1500
  control.resolveReplySafe();
1380
- if (this.activeSessionControls.get(sessionId) === control)
1501
+ const controls = this.activeSessionControls.get(sessionId);
1502
+ if (controls === undefined)
1503
+ return;
1504
+ controls.delete(control);
1505
+ if (controls.size === 0)
1381
1506
  this.activeSessionControls.delete(sessionId);
1382
1507
  }
1383
1508
  /**
@@ -1676,9 +1801,14 @@ export class DshDeliveryRuntime {
1676
1801
  },
1677
1802
  };
1678
1803
  }
1679
- async disposeAfterReplyBoundary(sessionId, handle, afterDisposed, abandonDisposal = false, timeoutMs) {
1680
- const control = this.activeSessionControls.get(sessionId);
1681
- control?.resolveReplySafe();
1804
+ async disposeAfterReplyBoundary(sessionId, handle, afterDisposed, abandonDisposal = false, timeoutMs, control) {
1805
+ if (control !== undefined)
1806
+ control.resolveReplySafe();
1807
+ else {
1808
+ for (const activeControl of this.activeSessionControls.get(sessionId) ?? []) {
1809
+ activeControl.resolveReplySafe();
1810
+ }
1811
+ }
1682
1812
  if (handle === undefined) {
1683
1813
  afterDisposed?.();
1684
1814
  return true;
@@ -1788,13 +1918,14 @@ export class DshDeliveryRuntime {
1788
1918
  ?? new Error('assistant-delivery: execution aborted')), 1_000);
1789
1919
  abortDeadline.unref?.();
1790
1920
  };
1791
- const removeClaimed = this.ctx.on('agent/inbox/claimed', event => {
1921
+ const eventCtx = typeof agent.ctx?.on === 'function' ? agent.ctx : this.ctx;
1922
+ const removeClaimed = eventCtx.on('agent/inbox/claimed', event => {
1792
1923
  if (event.agent === agent && event.message.id === message.id) {
1793
1924
  claimedTurn = event.turn;
1794
1925
  onClaimed?.(event.turn);
1795
1926
  }
1796
1927
  });
1797
- const removeDiscarded = this.ctx.on('agent/inbox/discarded', event => {
1928
+ const removeDiscarded = eventCtx.on('agent/inbox/discarded', event => {
1798
1929
  if (event.agent !== agent || event.message.id !== message.id)
1799
1930
  return;
1800
1931
  try {
@@ -1806,7 +1937,7 @@ export class DshDeliveryRuntime {
1806
1937
  }
1807
1938
  settle(undefined);
1808
1939
  });
1809
- const removeSessionEvent = this.ctx.on('session/event', (session, event) => {
1940
+ const removeSessionEvent = eventCtx.on('session/event', (session, event) => {
1810
1941
  if (session === agent.session && event.type === 'turn/end' && event.data.turn === claimedTurn) {
1811
1942
  try {
1812
1943
  onSettled?.();
@@ -1969,10 +2100,43 @@ export class DshDeliveryRuntime {
1969
2100
  if (agent.session.header.cwd !== workspace || agent.session.header.agentPreset !== presetId) {
1970
2101
  throw new DurableAgentIdentityError('assistant-delivery: durable Agent identity does not match its conversation binding');
1971
2102
  }
2103
+ if (this.configuredAgents.has(agent)) {
2104
+ agent.model.select(selected);
2105
+ return;
2106
+ }
2107
+ this.configuredAgents.add(agent);
1972
2108
  const unbind = this.policy.bindInitiator(agent, initiator, principal);
1973
2109
  agentCtx.effect(() => unbind, `assistant-delivery.${initiator}-initiator`);
1974
2110
  installModelSelection(agentCtx);
1975
2111
  agent.model.select(selected);
2112
+ const workerTickets = this.options.getWorkerTickets?.();
2113
+ const isOwnerFront = this.options.isOwnerSessionAgent
2114
+ ? this.options.isOwnerSessionAgent(agent)
2115
+ : this.options.ownsSession?.(String(agent.session.id)) ?? true;
2116
+ if (workerTickets !== undefined && isOwnerFront && !workerTickets.ownsWorkerSession(String(agent.session.id))) {
2117
+ let pendingToMark = [];
2118
+ agentCtx.inject(['systemPrompt'], promptCtx => promptCtx.systemPrompt.context({
2119
+ name: 'ray:worker-tickets',
2120
+ order: 242,
2121
+ text: () => {
2122
+ if (this.options.isOwnerSessionAgent && !this.options.isOwnerSessionAgent(agent))
2123
+ return '';
2124
+ if (this.options.ownsSession && !this.options.ownsSession(String(agent.session.id)))
2125
+ return '';
2126
+ pendingToMark = workerTickets.pendingFrontNarrationIds();
2127
+ return workerTickets.renderFrontPromptContext();
2128
+ },
2129
+ }));
2130
+ agentCtx.on('session/event', (eventSession, event) => {
2131
+ if (eventSession !== agent.session || event.type !== 'turn/end')
2132
+ return;
2133
+ const reason = event.data.reason;
2134
+ if (reason?.kind === 'completed' && pendingToMark.length > 0) {
2135
+ workerTickets.markFrontNarrated(pendingToMark);
2136
+ pendingToMark = [];
2137
+ }
2138
+ });
2139
+ }
1976
2140
  // The trusted post-cancellation clarification is installed LAZILY and only
1977
2141
  // for a session whose history actually contains a human-aborted turn with an
1978
2142
  // aborted-before-dispatch tool result. Merely registering a runtime context
@@ -2576,7 +2740,7 @@ export class DshDeliveryRuntime {
2576
2740
  const lease = this.sessionLeases.open({ kind: 'construction', sessionId: String(id),
2577
2741
  conversation: input.envelope.conversation, principal: input.envelope.principal,
2578
2742
  workspace, agentPreset: presetId, generation: input.generation,
2579
- ...(input.previous === undefined ? {} : { previous: input.previous }) }, input.signal);
2743
+ ...(input.previous === undefined ? {} : { previous: input.previous }) }, input.signal, { allowDuringDrain: true });
2580
2744
  let handle;
2581
2745
  let adopted = false;
2582
2746
  try {
@@ -2596,7 +2760,7 @@ export class DshDeliveryRuntime {
2596
2760
  agentOptions,
2597
2761
  signal: lease.signal,
2598
2762
  setup,
2599
- });
2763
+ }, { allowDuringDrain: true });
2600
2764
  adopted = true;
2601
2765
  }
2602
2766
  if (handle === undefined) {
@@ -2606,7 +2770,7 @@ export class DshDeliveryRuntime {
2606
2770
  agentOptions,
2607
2771
  signal: lease.signal,
2608
2772
  setup,
2609
- });
2773
+ }, { allowDuringDrain: true });
2610
2774
  }
2611
2775
  const session = handle.agent.session;
2612
2776
  if (adopted)
@@ -3027,6 +3191,7 @@ export class DshDeliveryRuntime {
3027
3191
  .filter(attachment => attachment.resourceType === 'image').length;
3028
3192
  if (envelope.kind === 'command') {
3029
3193
  return { outcome: 'prepared', message: {
3194
+ inboxId: context.inboxId,
3030
3195
  imageAttachments: [],
3031
3196
  ...(context.permissionDispatchRecovery === undefined
3032
3197
  ? {}
@@ -3036,7 +3201,7 @@ export class DshDeliveryRuntime {
3036
3201
  const selected = toModelRoute(this.options.getModelSelection(envelope.conversation)
3037
3202
  ?? { provider: this.options.provider, model: this.options.model });
3038
3203
  if (imageCount === 0) {
3039
- return { outcome: 'prepared', message: { imageAttachments: [], modelRoute: selected } };
3204
+ return { outcome: 'prepared', message: { inboxId: context.inboxId, imageAttachments: [], modelRoute: selected } };
3040
3205
  }
3041
3206
  if (!this.options.isInboundAuthorized(binding, envelope)) {
3042
3207
  return { outcome: 'not-processed', failureCode: 'image-authorization-revoked', retryable: false };
@@ -3069,7 +3234,7 @@ export class DshDeliveryRuntime {
3069
3234
  signal,
3070
3235
  });
3071
3236
  return result.outcome === 'ready'
3072
- ? { outcome: 'prepared', message: { imageAttachments: result.imageAttachments, modelRoute: selected } }
3237
+ ? { outcome: 'prepared', message: { inboxId: context.inboxId, imageAttachments: result.imageAttachments, modelRoute: selected } }
3073
3238
  : { outcome: 'not-processed', failureCode: result.failureCode, retryable: result.retryable,
3074
3239
  ...(result.retryAfterMs === undefined ? {} : { retryAfterMs: result.retryAfterMs }) };
3075
3240
  }
@@ -3300,6 +3465,24 @@ export class DshDeliveryRuntime {
3300
3465
  signal.throwIfAborted();
3301
3466
  markDispatching();
3302
3467
  signal.throwIfAborted();
3468
+ if (parsed.kind === 'growth') {
3469
+ const report = this.options.raySelfGrowthReport?.();
3470
+ const cog = this.options.rayCognitiveSummary?.();
3471
+ const text = report === undefined
3472
+ ? 'Ray 独立成长度量报告:\n- 当前未启用 Ray Home 身体内核(assistant-policy.raySelf 未挂载)。'
3473
+ : [
3474
+ `Ray 独立成长度量报告(身体内核不可篡改口径 · ${report.energy.dayKey}):`,
3475
+ `【服务 Owner 指标】任务=${report.ownerService.totalOwnerTasks}|纠正=${report.ownerService.correctionCount} (${(report.ownerService.correctionRate * 100).toFixed(1)}%)|重复请求=${report.ownerService.repeatRequestCount} (${(report.ownerService.repeatRequestRate * 100).toFixed(1)}%)|验收通过=${report.ownerService.verifiedPassCount}|平均延迟=${report.ownerService.avgLatencyMs}ms`,
3476
+ `【退化与缺口】新伤退化 (newly_regressed)=${report.ownerService.newlyRegressedCount}|固有缺口 (persistent_gap)=${report.ownerService.persistentGapCount}`,
3477
+ `【主动价值指标】提起=${report.proactiveValue.surfacedCount}|采纳=${report.proactiveValue.acceptedCount} (${(report.proactiveValue.acceptanceRate * 100).toFixed(1)}%)|嫌烦=${report.proactiveValue.annoyedCount} (${(report.proactiveValue.annoyanceRate * 100).toFixed(1)}%)|自创能力调用=${report.proactiveValue.selfCapabilityInvocations}`,
3478
+ `【今日精力账本】Owner=${report.energy.ownerTokensUsed} tokens|自由精力=${report.energy.freeTokensUsed}/${report.energy.freeAllowanceTokens} tokens|每日上限=${report.energy.dailyTokenCap}${report.energy.windDown ? '(已进入休眠降噪 wind-down)' : ''}`,
3479
+ ...(cog ? [`【统一点子池】待处理=${cog.pooledCount}|静默探索=${cog.exploredCount}|顺口提配额上限=${cog.tuning.dailyNaturalMentionCap}/天`] : []),
3480
+ `【自身目标进展|${report.selfGoals.trustLevel} 低信任自评,不等同客观成长证明】`,
3481
+ ...report.selfGoals.stageGoals.map(g => `- [${g.status}] ${g.title}(标准:${g.completionCriteria})`),
3482
+ ].join('\n');
3483
+ this.options.replyCommand(binding, envelope.eventId, { text, format: 'plain' });
3484
+ return { outcome: 'processed' };
3485
+ }
3303
3486
  const action = parsed.kind === 'forget-confirm'
3304
3487
  ? 'forget'
3305
3488
  : parsed.kind === 'rollback-confirm' ? 'rollback' : parsed.kind;
@@ -3482,6 +3665,69 @@ export class DshDeliveryRuntime {
3482
3665
  });
3483
3666
  return { outcome: 'processed' };
3484
3667
  }
3668
+ async runOwnerVetoCommand(command, binding, envelope, signal, markDispatching) {
3669
+ if ((envelope.attachments?.length ?? 0) > 0) {
3670
+ return this.replySessionCommand(binding, envelope, {
3671
+ text: '/veto 命令不接受文件、图片或其他附件;本次未执行。',
3672
+ format: 'plain',
3673
+ }, signal, markDispatching);
3674
+ }
3675
+ let authorized;
3676
+ try {
3677
+ authorized = this.options.isOwnerFeedbackController(binding, envelope);
3678
+ }
3679
+ catch {
3680
+ return { outcome: 'not-processed', failureCode: 'veto-authorization-check-failed', retryable: true };
3681
+ }
3682
+ if (!authorized) {
3683
+ return this.replySessionCommand(binding, envelope, {
3684
+ text: '当前身份不是此会话的 owner;仅 owner 可执行 /veto 否决,本次未执行。',
3685
+ format: 'plain',
3686
+ }, signal, markDispatching);
3687
+ }
3688
+ const policy = this.ctx.get?.('assistantPolicy');
3689
+ if (policy?.raySelf?.vetoByOwner === undefined) {
3690
+ return this.replySessionCommand(binding, envelope, {
3691
+ text: '当前尚未挂载 Ray Home 自我模型(assistant-policy.raySelf 未启用);/veto 未执行。',
3692
+ format: 'plain',
3693
+ }, signal, markDispatching);
3694
+ }
3695
+ if (markDispatching === undefined) {
3696
+ return { outcome: 'not-processed', failureCode: 'dispatch-gate-unavailable', retryable: true };
3697
+ }
3698
+ signal.throwIfAborted();
3699
+ markDispatching();
3700
+ signal.throwIfAborted();
3701
+ const { targetEntryId, targetCapabilityId, reason: reasonText } = parseOwnerVetoArgs(command.rawInput);
3702
+ const ownerProof = `owner:${envelope.conversation.channel}:${externalPrincipalId(binding.principal)}`;
3703
+ try {
3704
+ const result = await policy.raySelf.vetoByOwner({
3705
+ ...(targetEntryId === undefined ? {} : { targetEntryId }),
3706
+ ...(targetCapabilityId === undefined ? {} : { targetCapabilityId }),
3707
+ ...(reasonText === undefined ? {} : { reason: reasonText }),
3708
+ ownerProof,
3709
+ });
3710
+ this.options.replyCommand(binding, envelope.eventId, {
3711
+ text: result.ok
3712
+ ? [
3713
+ '✅ Owner 否决已在当前轮次生效(下一轮即按新状态执行):',
3714
+ `- 回滚记录:${result.autobiographyEntry.summary}`,
3715
+ `- 当前自我模型:${result.selfModel.name}(v${result.selfModel.version})`,
3716
+ ...(result.revertedCapabilityId ? [`- 已回退能力:${result.revertedCapabilityId}`] : []),
3717
+ ].join('\n')
3718
+ : '⚠️ 未找到匹配的近期自主演化或能力记录;已在自传中记录本次 owner 反对意见。',
3719
+ format: 'plain',
3720
+ });
3721
+ return { outcome: 'processed' };
3722
+ }
3723
+ catch (error) {
3724
+ return {
3725
+ outcome: 'not-processed',
3726
+ failureCode: error instanceof Error ? error.message : 'ray-veto-failed',
3727
+ retryable: false,
3728
+ };
3729
+ }
3730
+ }
3485
3731
  sessionHelp(native) {
3486
3732
  const lines = [
3487
3733
  '会话命令:',
@@ -3494,6 +3740,8 @@ export class DshDeliveryRuntime {
3494
3740
  '- /learning:查看、导出、暂停、恢复或清除当前 scope 的偏好学习;不进入模型。',
3495
3741
  '- /autonomy:开启、关闭或升级整体助手自迭代能力;不进入模型。',
3496
3742
  '- /update(/upgrade):在后台升级整体助手并自动重启恢复(仅限 owner);不进入模型。',
3743
+ '- /veto [条目ID] [原因]:立即推翻并回滚最近一次自主演化或能力变更(仅限 owner);下一轮生效。',
3744
+ '- /tickets:查看文鳐持久后台 Worker 工单状态;不进入模型。',
3497
3745
  '- /version:查看当前助手、Host、插件版本与自迭代演进统计;不进入模型。',
3498
3746
  '- /help:显示当前实际可用命令。',
3499
3747
  ];
@@ -3507,7 +3755,7 @@ export class DshDeliveryRuntime {
3507
3755
  }
3508
3756
  async runSessionCommand(command, binding, envelope, signal, markDispatching) {
3509
3757
  const args = command.rawInput.trim();
3510
- const local = new Set(['clear', 'help', 'new', 'session', 'status', 'stop']);
3758
+ const local = new Set(['clear', 'help', 'new', 'session', 'status', 'stop', 'tickets']);
3511
3759
  if (local.has(command.name) && args !== '') {
3512
3760
  return this.replySessionCommand(binding, envelope, {
3513
3761
  text: `/${command.name} 不接受参数。发送 /help 查看用法。`,
@@ -3567,9 +3815,43 @@ export class DshDeliveryRuntime {
3567
3815
  format: 'plain',
3568
3816
  }, signal, markDispatching);
3569
3817
  }
3818
+ if (command.name === 'tickets') {
3819
+ if (this.options.ownsSession?.(binding.sessionId) === false) {
3820
+ return this.replySessionCommand(binding, envelope, {
3821
+ text: '当前会话非 owner 绑定,无权查看 Ray 持久后台 Worker 票据。',
3822
+ format: 'plain',
3823
+ }, signal, markDispatching);
3824
+ }
3825
+ const workerTickets = this.options.getWorkerTickets?.();
3826
+ return this.replySessionCommand(binding, envelope, {
3827
+ text: workerTickets === undefined
3828
+ ? '当前尚未启用 Ray 持久后台 Worker(assistant-policy.raySelf 未配置 rayHome)。'
3829
+ : workerTickets.formatTicketsCommandReply(),
3830
+ format: 'plain',
3831
+ }, signal, markDispatching);
3832
+ }
3570
3833
  if (command.name === 'status' || command.name === 'session') {
3571
3834
  const messages = agent.session.deriveMessages().length;
3572
3835
  const turns = agent.session.snapshotEvents().filter(event => event.type === 'turn/end').length;
3836
+ const ownsRay = this.options.ownsSession?.(binding.sessionId) !== false;
3837
+ const rayPolicy = this.ctx.get?.('assistantPolicy');
3838
+ const raySnap = ownsRay && typeof rayPolicy?.raySelf?.snapshot === 'function' ? rayPolicy.raySelf.snapshot(3) : undefined;
3839
+ const workerTickets = ownsRay ? this.options.getWorkerTickets?.() : undefined;
3840
+ const ticketList = workerTickets === undefined ? [] : workerTickets.listTickets({ limit: 5 });
3841
+ const workerLines = ticketList.length === 0 ? [] : [
3842
+ `- 持久 Worker:运行中 ${ticketList.filter(t => t.status === 'running').length} · 已完成 ${ticketList.filter(t => t.status === 'completed').length} · 交回 ${ticketList.filter(t => t.status === 'handed_back').length}`,
3843
+ ];
3844
+ const rayLines = raySnap === undefined ? workerLines : [
3845
+ '',
3846
+ '自我模型(Ray Home)',
3847
+ `- 身份:${raySnap.selfModel.name}(v${raySnap.selfModel.version})`,
3848
+ `- 家目录:${raySnap.rayHome}`,
3849
+ `- 自述:${raySnap.selfModel.selfSummary}`,
3850
+ `- 阶段目标:${raySnap.selfModel.stageGoals.filter(g => g.status === 'active').map(g => g.title).join(';') || '暂无'}`,
3851
+ `- 长期理想:${raySnap.selfModel.ideals.map(i => i.title).join(';') || '暂无'}`,
3852
+ ...(raySnap.missingCredentials.length > 0 ? [`- 待重授权凭据:${raySnap.missingCredentials.length} 项`] : []),
3853
+ ...workerLines,
3854
+ ];
3573
3855
  return this.replySessionCommand(binding, envelope, {
3574
3856
  text: [
3575
3857
  '当前会话',
@@ -3578,6 +3860,7 @@ export class DshDeliveryRuntime {
3578
3860
  `- 上下文消息:${messages}`,
3579
3861
  `- 已记录轮次:${turns}`,
3580
3862
  `- 模型:${routeLabel(selectedRoute)}`,
3863
+ ...rayLines,
3581
3864
  '',
3582
3865
  '/new 会开始空白新 session 并保留旧会话;/stop 只停止当前任务,不清空上下文。',
3583
3866
  ].join('\n'),
@@ -3705,9 +3988,18 @@ export class DshDeliveryRuntime {
3705
3988
  format: 'plain',
3706
3989
  }, outerSignal, markDispatching);
3707
3990
  }
3991
+ let allowConcurrentOwner = false;
3992
+ if (restartContinuation === undefined && (envelope.kind === 'text' || sessionCommand?.name === 'veto')) {
3993
+ try {
3994
+ allowConcurrentOwner = this.options.ownsSession?.(binding.sessionId) === true;
3995
+ }
3996
+ catch {
3997
+ allowConcurrentOwner = false;
3998
+ }
3999
+ }
3708
4000
  let lease;
3709
4001
  try {
3710
- lease = this.sessionLeases.open({ kind: 'bound', binding }, outerSignal);
4002
+ lease = this.sessionLeases.open({ kind: 'bound', binding }, outerSignal, { allowConcurrentOwner });
3711
4003
  }
3712
4004
  catch (error) {
3713
4005
  if (error instanceof SessionLeaseUnavailable) {
@@ -3731,7 +4023,7 @@ export class DshDeliveryRuntime {
3731
4023
  let control;
3732
4024
  let taskDeadline;
3733
4025
  try {
3734
- control = this.beginSessionControl(binding.sessionId, lease.signal);
4026
+ control = this.beginSessionControl(binding.sessionId, lease.signal, allowConcurrentOwner);
3735
4027
  taskDeadline = setTimeout(() => {
3736
4028
  // Cancel the durable lease as well as the local wait: late tools and
3737
4029
  // model requests must remain fenced until real teardown is observed.
@@ -3743,7 +4035,7 @@ export class DshDeliveryRuntime {
3743
4035
  lease.assert();
3744
4036
  markDispatching();
3745
4037
  lease.assert();
3746
- }, restartContinuation);
4038
+ }, restartContinuation, control);
3747
4039
  }
3748
4040
  catch (error) {
3749
4041
  if (control?.command !== undefined && causedByUserCancellation(error)) {
@@ -3765,7 +4057,7 @@ export class DshDeliveryRuntime {
3765
4057
  lease.close();
3766
4058
  }
3767
4059
  }
3768
- async processControlled(binding, envelope, signal, sessionCommand, prepared, markDispatching, restartContinuation) {
4060
+ async processControlled(binding, envelope, signal, sessionCommand, prepared, markDispatching, restartContinuation, activeControl) {
3769
4061
  if (sessionCommand?.name === 'feedback') {
3770
4062
  return await this.runFeedbackCommand(sessionCommand, binding, envelope, signal, markDispatching);
3771
4063
  }
@@ -3831,6 +4123,9 @@ export class DshDeliveryRuntime {
3831
4123
  return modelCommandFailure(error);
3832
4124
  }
3833
4125
  }
4126
+ if (sessionCommand?.name === 'veto') {
4127
+ return await this.runOwnerVetoCommand(sessionCommand, binding, envelope, signal, markDispatching);
4128
+ }
3834
4129
  if (sessionCommand !== undefined) {
3835
4130
  return await this.runSessionCommand(sessionCommand, binding, envelope, signal, markDispatching);
3836
4131
  }
@@ -3921,18 +4216,19 @@ export class DshDeliveryRuntime {
3921
4216
  let progressQueue = Promise.resolve();
3922
4217
  let progressTerminal = false;
3923
4218
  const drainProgress = async () => {
3924
- const control = this.activeSessionControls.get(binding.sessionId);
4219
+ const control = activeControl ?? [...(this.activeSessionControls.get(binding.sessionId) ?? [])].find(c => c.command !== undefined);
3925
4220
  // `/new` and `/stop` abandon presentation follow-through so user-initiated
3926
4221
  // session resets do not stall on a wedged adapter progress stream.
3927
4222
  if (control?.command !== undefined)
3928
4223
  return;
4224
+ const maxProgressWaitMs = signal.reason instanceof ReloadInterruptedError ? 1_000 : 5_000;
3929
4225
  let timeout;
3930
4226
  try {
3931
4227
  await Promise.race([
3932
4228
  progressQueue,
3933
4229
  ...(control === undefined ? [] : [control.cancelRequested]),
3934
4230
  new Promise(resolve => {
3935
- timeout = setTimeout(resolve, 5_000);
4231
+ timeout = setTimeout(resolve, maxProgressWaitMs);
3936
4232
  timeout.unref?.();
3937
4233
  }),
3938
4234
  ]);
@@ -4007,7 +4303,8 @@ export class DshDeliveryRuntime {
4007
4303
  const automaticCompletionTurns = new Map();
4008
4304
  const automaticCompletionToolViolations = new Set();
4009
4305
  const abort = () => {
4010
- const command = this.activeSessionControls.get(binding.sessionId)?.command;
4306
+ const command = activeControl?.command
4307
+ ?? [...(this.activeSessionControls.get(binding.sessionId) ?? [])].find(c => c.command !== undefined)?.command;
4011
4308
  agent.cancel(command === undefined
4012
4309
  ? { kind: 'hook', reason: 'assistant-delivery-signal' }
4013
4310
  : { kind: 'user' });
@@ -4043,10 +4340,14 @@ export class DshDeliveryRuntime {
4043
4340
  });
4044
4341
  this.restartRuns.set(agent, restartRun);
4045
4342
  }
4343
+ const agentEventCtx = typeof agent.ctx?.on === 'function' ? agent.ctx : this.ctx;
4046
4344
  if (acceptance !== undefined || foregroundExecution !== undefined)
4047
- removeAcceptanceRequest = this.ctx.on('session/event', (session, event) => {
4345
+ removeAcceptanceRequest = agentEventCtx.on('session/event', (session, event) => {
4048
4346
  if (session !== agent.session || event.type !== 'request/header')
4049
4347
  return;
4348
+ const eventTurn = event.data.turn;
4349
+ if (eventTurn !== undefined && foregroundTurn !== undefined && eventTurn !== foregroundTurn)
4350
+ return;
4050
4351
  // `agent/request` exposes the candidate route. The native loop writes
4051
4352
  // this header only after `llm.prepareCall()` has applied adapter
4052
4353
  // defaults such as reasoning effort, which is the route actually sent
@@ -4060,7 +4361,7 @@ export class DshDeliveryRuntime {
4060
4361
  // Once the durable marker exists, even a synchronous followup failure is ambiguous:
4061
4362
  // implementations may enqueue before throwing, so no retry is safe.
4062
4363
  dispatched = true;
4063
- removeProgress = this.ctx.on('session/event', (session, event) => {
4364
+ removeProgress = agentEventCtx.on('session/event', (session, event) => {
4064
4365
  if (session !== agent.session)
4065
4366
  return;
4066
4367
  const eventTurn = 'turn' in event.data && typeof event.data.turn === 'number' ? event.data.turn : undefined;
@@ -4150,7 +4451,8 @@ export class DshDeliveryRuntime {
4150
4451
  return { outcome: 'not-processed', failureCode: 'session-flush-failed', retryable: false };
4151
4452
  }
4152
4453
  signal.throwIfAborted();
4153
- const cancelled = this.activeSessionControls.get(binding.sessionId)?.command;
4454
+ const cancelled = activeControl?.command
4455
+ ?? [...(this.activeSessionControls.get(binding.sessionId) ?? [])].find(c => c.command !== undefined)?.command;
4154
4456
  const automaticToolViolation = deliveryTurn !== undefined
4155
4457
  && automaticCompletionToolViolations.has(deliveryTurn);
4156
4458
  if (cancelled !== undefined || (output.stopped && !automaticToolViolation)) {
@@ -4205,7 +4507,8 @@ export class DshDeliveryRuntime {
4205
4507
  if (!(error instanceof AutomaticCompletionUnavailableError))
4206
4508
  throw error;
4207
4509
  signal.throwIfAborted();
4208
- const cancellation = this.activeSessionControls.get(binding.sessionId)?.command;
4510
+ const cancellation = activeControl?.command
4511
+ ?? [...(this.activeSessionControls.get(binding.sessionId) ?? [])].find(c => c.command !== undefined)?.command;
4209
4512
  if (cancellation !== undefined) {
4210
4513
  terminationCause = cancellation === 'new' ? 'owner-new-session' : 'owner-stop';
4211
4514
  publishProgress({ kind: 'failed', code: cancellation === 'new' ? 'new-session' : 'user-stopped' });
@@ -4274,12 +4577,34 @@ export class DshDeliveryRuntime {
4274
4577
  });
4275
4578
  return { outcome: 'processed' };
4276
4579
  }
4580
+ if (this.disposingReloadCode !== undefined && output.turnEndKind === 'aborted' && !output.stopped && output.failureCode === undefined) {
4581
+ const reloadCode = this.disposingReloadCode;
4582
+ const recordId = prepared?.inboxId ?? foregroundExecution;
4583
+ if (recordId !== undefined) {
4584
+ const summary = summarizeTurnToolMutations(agent.session.snapshotEvents(), turnFrom, deliveryTurn);
4585
+ try {
4586
+ this.options.recordInterruptedTurnSummary?.(recordId, reloadCode, summary);
4587
+ }
4588
+ catch { }
4589
+ }
4590
+ terminationCause = 'host-disposed';
4591
+ publishProgress({ kind: 'failed', code: reloadCode });
4592
+ return { outcome: 'not-processed', failureCode: reloadCode, retryable: false };
4593
+ }
4277
4594
  const classified = classifyMidTurnFailure({
4278
4595
  upstreamCode: output.failureCode,
4279
4596
  upstreamMessage: output.errorMessage,
4280
4597
  turnEndKind: output.turnEndKind,
4281
4598
  userCancelled: output.stopped,
4282
4599
  });
4600
+ const recordId = prepared?.inboxId ?? foregroundExecution;
4601
+ if (recordId !== undefined) {
4602
+ const summary = summarizeTurnToolMutations(agent.session.snapshotEvents(), turnFrom, deliveryTurn);
4603
+ try {
4604
+ this.options.recordInterruptedTurnSummary?.(recordId, classified.code, summary);
4605
+ }
4606
+ catch { }
4607
+ }
4283
4608
  terminationCause = classified.code === 'agent-turn-provider-aborted' ? 'execution-aborted' : 'runtime-error';
4284
4609
  publishProgress({ kind: 'failed', code: classified.code });
4285
4610
  return { outcome: 'not-processed', failureCode: classified.code, retryable: false };
@@ -4331,18 +4656,53 @@ export class DshDeliveryRuntime {
4331
4656
  }
4332
4657
  catch (error) {
4333
4658
  if (causedByUserCancellation(error)) {
4334
- terminationCause = this.activeSessionControls.get(binding.sessionId)?.command === 'new' ? 'owner-new-session' : 'owner-stop';
4659
+ const userCommand = activeControl?.command
4660
+ ?? [...(this.activeSessionControls.get(binding.sessionId) ?? [])].find(c => c.command !== undefined)?.command;
4661
+ terminationCause = userCommand === 'new' ? 'owner-new-session' : 'owner-stop';
4335
4662
  if (handle !== undefined && !await sessions.flush(handle.agent.session)) {
4336
4663
  return { outcome: 'not-processed', failureCode: 'session-flush-failed', retryable: false };
4337
4664
  }
4338
- const command = this.activeSessionControls.get(binding.sessionId)?.command;
4339
- publishProgress({ kind: 'failed', code: command === 'new' ? 'new-session' : 'user-stopped' });
4665
+ publishProgress({ kind: 'failed', code: userCommand === 'new' ? 'new-session' : 'user-stopped' });
4340
4666
  return { outcome: 'processed' };
4341
4667
  }
4668
+ const reloadFailureCode = error instanceof ReloadInterruptedError
4669
+ ? error.code
4670
+ : signal.reason instanceof ReloadInterruptedError
4671
+ ? signal.reason.code
4672
+ : undefined;
4673
+ if (reloadFailureCode !== undefined) {
4674
+ if (!dispatched) {
4675
+ return { outcome: 'not-processed', failureCode: reloadFailureCode, retryable: true };
4676
+ }
4677
+ terminationCause = 'host-disposed';
4678
+ const events = handle !== undefined ? handle.agent.session.snapshotEvents() : [];
4679
+ const summary = summarizeTurnToolMutations(events, turnFrom, deliveryTurn);
4680
+ const recordId = prepared?.inboxId ?? foregroundExecution;
4681
+ if (recordId !== undefined) {
4682
+ try {
4683
+ this.options.recordInterruptedTurnSummary?.(recordId, reloadFailureCode, summary);
4684
+ }
4685
+ catch { }
4686
+ }
4687
+ if (handle !== undefined) {
4688
+ await sessions.flush(handle.agent.session).catch(() => false);
4689
+ }
4690
+ publishProgress({ kind: 'failed', code: reloadFailureCode });
4691
+ return { outcome: 'not-processed', failureCode: reloadFailureCode, retryable: false };
4692
+ }
4342
4693
  if (dispatched) {
4343
4694
  const timedOut = signal.reason instanceof AgentTaskTimeoutError;
4344
4695
  terminationCause = timedOut ? 'execution-timeout' : 'runtime-error';
4345
4696
  if (timedOut) {
4697
+ const events = handle !== undefined ? handle.agent.session.snapshotEvents() : [];
4698
+ const summary = summarizeTurnToolMutations(events, turnFrom, deliveryTurn);
4699
+ const recordId = prepared?.inboxId ?? foregroundExecution;
4700
+ if (recordId !== undefined) {
4701
+ try {
4702
+ this.options.recordInterruptedTurnSummary?.(recordId, 'agent-task-timeout', summary);
4703
+ }
4704
+ catch { }
4705
+ }
4346
4706
  publishProgress({ kind: 'failed', code: 'agent-task-timeout' });
4347
4707
  // Preserve an exact durable diagnosis so the existing interruption
4348
4708
  // Outbox can notify the owner even when progress presentation failed.
@@ -4353,6 +4713,23 @@ export class DshDeliveryRuntime {
4353
4713
  const observedOutput = handle !== undefined
4354
4714
  ? finalAssistant(handle.agent.session.snapshotEvents(), turnFrom, deliveryTurn)
4355
4715
  : undefined;
4716
+ if (this.disposingReloadCode !== undefined
4717
+ && observedOutput?.turnEndKind === 'aborted'
4718
+ && !observedOutput.stopped
4719
+ && observedOutput.failureCode === undefined) {
4720
+ const reloadCode = this.disposingReloadCode;
4721
+ const recordId = prepared?.inboxId ?? foregroundExecution;
4722
+ if (recordId !== undefined && handle !== undefined) {
4723
+ const summary = summarizeTurnToolMutations(handle.agent.session.snapshotEvents(), turnFrom, deliveryTurn);
4724
+ try {
4725
+ this.options.recordInterruptedTurnSummary?.(recordId, reloadCode, summary);
4726
+ }
4727
+ catch { }
4728
+ }
4729
+ terminationCause = 'host-disposed';
4730
+ publishProgress({ kind: 'failed', code: reloadCode });
4731
+ return { outcome: 'not-processed', failureCode: reloadCode, retryable: false };
4732
+ }
4356
4733
  const classified = classifyMidTurnFailure({
4357
4734
  error,
4358
4735
  upstreamCode: observedOutput?.failureCode,
@@ -4363,6 +4740,14 @@ export class DshDeliveryRuntime {
4363
4740
  const turnEndedWithError = observedOutput?.turnEndKind === 'error'
4364
4741
  || (observedOutput?.turnEndKind === 'aborted' && !observedOutput.stopped);
4365
4742
  if (completionKind === undefined || classified.matchedSpecific || turnEndedWithError) {
4743
+ const recordId = prepared?.inboxId ?? foregroundExecution;
4744
+ if (recordId !== undefined && handle !== undefined) {
4745
+ const summary = summarizeTurnToolMutations(handle.agent.session.snapshotEvents(), turnFrom, deliveryTurn);
4746
+ try {
4747
+ this.options.recordInterruptedTurnSummary?.(recordId, classified.code, summary);
4748
+ }
4749
+ catch { }
4750
+ }
4366
4751
  terminationCause = classified.code === 'agent-turn-provider-aborted' ? 'execution-aborted' : 'runtime-error';
4367
4752
  publishProgress({ kind: 'failed', code: classified.code });
4368
4753
  return { outcome: 'not-processed', failureCode: classified.code, retryable: false };
@@ -4422,19 +4807,26 @@ export class DshDeliveryRuntime {
4422
4807
  let disposed = false;
4423
4808
  let maintenanceReady = false;
4424
4809
  try {
4425
- disposed = await this.disposeAfterReplyBoundary(binding.sessionId, handle, () => goalContinuation?.dispose(), !goalContinuationQuiescent, restartCheckpoint === undefined && restartContinuation === undefined
4426
- ? goalContinuation?.teardownTimeoutMs() ?? 10_000 : 10_000);
4810
+ const baseTeardownTimeoutMs = restartCheckpoint === undefined && restartContinuation === undefined
4811
+ ? goalContinuation?.teardownTimeoutMs() ?? 10_000 : 10_000;
4812
+ const teardownTimeoutMs = signal.reason instanceof ReloadInterruptedError
4813
+ ? Math.min(1_500, baseTeardownTimeoutMs)
4814
+ : baseTeardownTimeoutMs;
4815
+ disposed = await this.disposeAfterReplyBoundary(binding.sessionId, handle, () => goalContinuation?.dispose(), !goalContinuationQuiescent, teardownTimeoutMs, activeControl);
4427
4816
  }
4428
4817
  finally {
4429
4818
  acceptanceSucceeded = acceptanceSucceeded && disposed && !signal.aborted
4430
4819
  && (goalContinuation?.isQuiescent() ?? true);
4431
4820
  if (foregroundExecution !== undefined && restartCheckpoint === undefined) {
4432
4821
  try {
4433
- const command = this.activeSessionControls.get(binding.sessionId)?.command;
4822
+ const command = activeControl?.command
4823
+ ?? [...(this.activeSessionControls.get(binding.sessionId) ?? [])].find(c => c.command !== undefined)?.command;
4434
4824
  if (command !== undefined)
4435
4825
  terminationCause = command === 'new' ? 'owner-new-session' : 'owner-stop';
4436
4826
  else if (signal.reason instanceof AgentTaskTimeoutError)
4437
4827
  terminationCause = 'execution-timeout';
4828
+ else if (signal.reason instanceof ReloadInterruptedError)
4829
+ terminationCause = 'host-disposed';
4438
4830
  else if (signal.aborted)
4439
4831
  terminationCause = 'execution-aborted';
4440
4832
  const terminal = foregroundTurn === undefined ? undefined : handle?.agent.session.snapshotEvents().findLast(event => event.type === 'turn/end' && event.data.turn === foregroundTurn);
@@ -4485,12 +4877,15 @@ export class DshDeliveryRuntime {
4485
4877
  }
4486
4878
  // A provider-confirmed success cannot precede the durable execution
4487
4879
  // result: teardown can still fail after the final reply was queued.
4880
+ const unknownCode = signal.reason instanceof ReloadInterruptedError
4881
+ ? signal.reason.code
4882
+ : 'INTERRUPTED_RESULT_UNKNOWN';
4488
4883
  if (restartCheckpoint !== undefined)
4489
4884
  publishProgress(maintenanceReady
4490
- ? { kind: 'paused' } : { kind: 'failed', code: 'INTERRUPTED_RESULT_UNKNOWN' });
4885
+ ? { kind: 'paused' } : { kind: 'failed', code: unknownCode });
4491
4886
  else if (completionPending)
4492
4887
  publishProgress(acceptanceSucceeded
4493
- ? { kind: 'completed' } : { kind: 'failed', code: 'INTERRUPTED_RESULT_UNKNOWN' });
4888
+ ? { kind: 'completed' } : { kind: 'failed', code: unknownCode });
4494
4889
  // Terminal journal admission precedes the bounded provider drain.
4495
4890
  await drainProgress();
4496
4891
  }