@dsh-ray/assistant-delivery 0.2.4 → 0.3.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 (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
package/lib/service.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import { engineeringContextData, validateWorkItemEngineeringMaterial, frameWorkItemEngineeringContext, pageWorkItemEngineeringContext } from './work-item-engineering-context.js';
2
2
  import { workItemReplyCanonical, workItemReplyDigest } from './work-item-replies.js';
3
3
  import { chmodSync, mkdirSync, readFileSync } from 'node:fs';
4
- import { isAbsolute } from 'node:path';
4
+ import { homedir } from 'node:os';
5
+ import { isAbsolute, join, resolve } from 'node:path';
5
6
  import { isProxy } from 'node:util/types';
6
7
  import { createHash, randomBytes, randomUUID } from 'node:crypto';
7
8
  import { Context, Service, symbols } from '@deepseek-ai/cordis';
9
+ import { SessionId } from '@deepseek-ai/dsh-session';
8
10
  import Schema from '@deepseek-ai/schemastery';
9
11
  import { RestartStore } from './restart-store.js';
10
12
  import { restartDigest } from './restart-runtime.js';
@@ -16,11 +18,13 @@ import { approvalReviewerOf, } from '@dsh-ray/assistant-policy';
16
18
  // peerDependenciesMeta.optional at module link time). Must stay identical to
17
19
  // TRUSTED_EVALUATION_PRODUCER_PROTOCOL in assistant-evaluation.
18
20
  const TRUSTED_EVALUATION_PRODUCER_PROTOCOL = 'assistant-evaluation/trusted-producer/v1';
19
- import { ASSISTANT_GROWTH_CONTRACT_VERSION, growthObjectDigest, isSourceOwnerContinuation, validateResolvedWorkflowAutomationTemplate, validateWorkflowAutomationTemplate, validateWorkflowScope, validateWorkflowTraceProjectionReceipt, workflowArgumentShapeDigest, } from '@dsh-ray/assistant-growth-contract';
21
+ import { ASSISTANT_GROWTH_CONTRACT_VERSION, defaultRayPluginStatePath, growthObjectDigest, isSourceOwnerContinuation, resolveConfiguredRayHome, validateResolvedWorkflowAutomationTemplate, validateWorkflowAutomationTemplate, validateWorkflowScope, validateWorkflowTraceProjectionReceipt, workflowArgumentShapeDigest, } from '@dsh-ray/assistant-growth-contract';
20
22
  import { DeliveryAdapterRegistry, DeliveryCoordinator, InboundCoordinator, } from './coordinator.js';
21
23
  import { DeliveryStore, DeliveryStoreError, } from './store.js';
22
24
  import { DshDeliveryRuntime, redactOwnerLearningReply } from './agent-runtime.js';
23
- import { DeliverySessionLeases } from './session-lease-runtime.js';
25
+ import { parseOwnerVetoArgs } from './session-commands.js';
26
+ import { RayWorkerTicketRuntime } from './ray-worker-runtime.js';
27
+ import { DeliverySessionLeases, SessionLeaseUnavailable } from './session-lease-runtime.js';
24
28
  import { NativeWebOwner } from './native-web-owner.js';
25
29
  import { validateOwnerGoalOutcomeFeedbackLocator, validateOwnerGoalOutcomeFeedbackProof, } from './goal-wake-types.js';
26
30
  import { IN_PROCESS_RELOAD_DENYLIST, createInProcessReloadRuntime, } from './in-process-reload-runtime.js';
@@ -36,7 +40,7 @@ import { interruptedTurnNoticeForFailureCode, isNotifiableInterruptedFailureCode
36
40
  import { collectDeliveryVersionReport, } from './version-query.js';
37
41
  import { deliveryT1PreferenceKeys, deliveryT1PreferenceValues } from './learning-command.js';
38
42
  import { assertReplyReplayAllowed, blockAgentRepliesForReplay as createReplyReplayBlock, } from './reply-replay.js';
39
- import { feedbackSignalInput, parseFeedbackCommand, parseNaturalObjectiveFeedback, parseNaturalOwnerReply, objectiveStateMessage, classifyNaturalPreferenceDirective, observedResponseLanguage, } from './feedback-command.js';
43
+ import { feedbackSignalInput, naturalOwnerReplyWithoutQuotes, parseFeedbackCommand, parseNaturalObjectiveFeedback, parseNaturalOwnerReply, objectiveStateMessage, classifyNaturalPreferenceDirective, observedResponseLanguage, } from './feedback-command.js';
40
44
  import { DELIVERY_PREFERENCE_PROJECTION_PROTOCOL, TRUSTED_DELIVERY_PRESENTATION_PRODUCER_PROTOCOL, } from './types.js';
41
45
  const trustedDeliveryPreferenceProducers = new WeakSet();
42
46
  const deliveryPreferenceProducerProbe = Symbol('assistant-delivery.preference-producer-probe');
@@ -304,8 +308,8 @@ function isOwnerGoalSnapshotLocator(value) {
304
308
  && typeof locator['goalId'] === 'string' && locator['goalId'] !== '';
305
309
  }
306
310
  const configSchema = Schema.object({
307
- databasePath: Schema.string().required(),
308
- spoolPath: Schema.string().required(),
311
+ databasePath: Schema.string(),
312
+ spoolPath: Schema.string(),
309
313
  inProcessReload: Schema.object({
310
314
  enabled: Schema.boolean().default(true),
311
315
  profilePath: Schema.string().min(1),
@@ -326,6 +330,7 @@ const configSchema = Schema.object({
326
330
  schedulerEnabled: Schema.boolean().default(true),
327
331
  tickIntervalMs: Schema.number().step(1).min(100).default(1_000),
328
332
  agentTaskTimeoutMs: Schema.number().step(1).min(1_000).max(86_400_000).default(1_800_000),
333
+ shutdownGraceMs: Schema.number().step(1).min(0).max(10_000).default(1_500),
329
334
  leaseMs: Schema.number().step(1).min(1_000).default(30_000),
330
335
  maxAttempts: Schema.number().step(1).min(1).max(100).default(5),
331
336
  maxConcurrency: Schema.number().step(1).min(1).max(100).default(4),
@@ -381,6 +386,82 @@ const configSchema = Schema.object({
381
386
  minimumGeneration: Schema.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).required(),
382
387
  })).default([]),
383
388
  });
389
+ /**
390
+ * Narrow structural interface for mirroring worker ticket lifecycle into optional
391
+ * `@dsh-ray/assistant-work-items` and `@dsh-ray/assistant-goals` without importing
392
+ * their public type surfaces (avoiding TS5055 circular emit).
393
+ */
394
+ function isSubagentHeader(header) {
395
+ if (header === undefined)
396
+ return false;
397
+ if (header.origin === 'subagent')
398
+ return true;
399
+ const depth = header.delegationDepth;
400
+ if (depth === undefined)
401
+ return false;
402
+ return typeof depth !== 'number' || !Number.isSafeInteger(depth) || depth !== 0;
403
+ }
404
+ const NON_MIRROR_SOURCE_KINDS = new Set([
405
+ 'delivery',
406
+ 'goal',
407
+ 'assistant-goals',
408
+ 'assistant-delivery',
409
+ 'assistant-delivery-test',
410
+ 'assistant-dreaming',
411
+ 'assistant-proactive',
412
+ 'assistant-growth-driver',
413
+ 'assistant-automations',
414
+ 'assistant-memory-learning',
415
+ 'assistant-verifier',
416
+ 'assistant-evaluation',
417
+ 'assistant-policy',
418
+ 'assistant-evolution',
419
+ 'ray-worker',
420
+ 'ray-worker-handback',
421
+ 'ray-dreaming',
422
+ 'memory',
423
+ 'personal-memory',
424
+ 'ray-episodic',
425
+ 'subagent',
426
+ 'system',
427
+ 'runtime-context',
428
+ 'retry',
429
+ ]);
430
+ const CONTEXT_INJECTION_SOURCE_KINDS = new Set([
431
+ 'personal-memory',
432
+ 'ray-episodic',
433
+ 'model-selection',
434
+ 'user-approval',
435
+ 'skill-catalog',
436
+ 'skill-invocation',
437
+ 'compact-checkpoint',
438
+ 'ptc-mode',
439
+ 'runtime-context',
440
+ ]);
441
+ function extractSessionMessageText(data) {
442
+ if (typeof data !== 'object' || data === null)
443
+ return '';
444
+ const record = data;
445
+ const nested = typeof record.message === 'object' && record.message !== null
446
+ ? record.message.content
447
+ : undefined;
448
+ const content = nested !== undefined ? nested : record.content;
449
+ if (typeof content === 'string')
450
+ return content.trim();
451
+ if (!Array.isArray(content))
452
+ return '';
453
+ return content
454
+ .map(part => {
455
+ if (typeof part !== 'object' || part === null)
456
+ return '';
457
+ if (part.type === 'text' && typeof part.text === 'string') {
458
+ return part.text;
459
+ }
460
+ return '';
461
+ })
462
+ .join('')
463
+ .trim();
464
+ }
384
465
  function policyDenied(decision) {
385
466
  return new AssistantDeliveryError('policy-denied', `assistant-delivery policy denied operation: ${decision.reasonCode}`);
386
467
  }
@@ -722,6 +803,9 @@ export class AssistantDeliveryService extends Service {
722
803
  nativeWebRuntime;
723
804
  ownerId = `assistant-delivery-${randomUUID()}`;
724
805
  bindingFlights = new Map();
806
+ convergeFlights = new Map();
807
+ convergeController = new AbortController();
808
+ convergedEpisodicImports = new WeakMap();
725
809
  conversationTransitions = new Map();
726
810
  agentApprovalBindings = new WeakMap();
727
811
  toolApprovalControllers = new Set();
@@ -782,10 +866,30 @@ export class AssistantDeliveryService extends Service {
782
866
  preferenceProjectionRetryTimer;
783
867
  modelSelectionRetryTimer;
784
868
  runtime;
869
+ drainingRuntime;
870
+ workerTickets;
871
+ workItemsMirror;
872
+ goalsMirror;
873
+ dispatchedHandbackKeys = new Set();
874
+ inFlightHandbackKeys = new Set();
875
+ handbackRetryCounts = new Map();
876
+ pendingHandbackWakes = new Map();
877
+ handbackWakeFlights = new Set();
878
+ handbackWakeController = new AbortController();
785
879
  timer;
786
880
  active = true;
881
+ acceptingAdmissions = true;
882
+ midShutdownCommandTransitions = new Set();
883
+ activeBindingRotations = new Set();
884
+ reloadInterruptionCode;
885
+ runtimeDrainPromise;
886
+ resolveRuntimeDrain;
887
+ sessionLeases;
787
888
  constructor(ctx, input) {
788
889
  super(ctx, 'assistantDelivery');
890
+ this.runtimeDrainPromise = new Promise(resolve => {
891
+ this.resolveRuntimeDrain = resolve;
892
+ });
789
893
  trustedDeliveryPreferenceProducers.add(this);
790
894
  Object.defineProperty(this, deliveryPreferenceProducerProbe, {
791
895
  value: () => this,
@@ -794,6 +898,9 @@ export class AssistantDeliveryService extends Service {
794
898
  writable: false,
795
899
  });
796
900
  this.context = ctx;
901
+ if (input === undefined || input === null || typeof input !== 'object' || Array.isArray(input)) {
902
+ throw new Error('assistant-delivery: invalid configuration: configuration object is required');
903
+ }
797
904
  let config;
798
905
  try {
799
906
  config = AssistantDeliveryService.Config(input);
@@ -801,12 +908,28 @@ export class AssistantDeliveryService extends Service {
801
908
  catch (error) {
802
909
  throw new Error(`assistant-delivery: invalid configuration: ${String(error)}`, { cause: error });
803
910
  }
804
- if (!isAbsolute(config.databasePath) || !isAbsolute(config.spoolPath) || !isAbsolute(config.defaultWorkspace)) {
805
- throw new Error('assistant-delivery: databasePath, spoolPath, and defaultWorkspace must be absolute paths');
806
- }
807
911
  const policy = ctx.get('assistantPolicy');
808
912
  if (policy === undefined)
809
913
  throw new Error('assistant-delivery: assistantPolicy service is required');
914
+ const configuredRayHome = typeof policy.rayHomeDir === 'function' ? policy.rayHomeDir() : resolveConfiguredRayHome(undefined);
915
+ const envDsh = process.env['DSH_HOME'];
916
+ const dshHome = typeof envDsh === 'string' && envDsh.trim() !== '' && isAbsolute(envDsh.trim())
917
+ ? resolve(envDsh.trim())
918
+ : join(homedir(), '.dsh');
919
+ if (config.databasePath === undefined || config.spoolPath === undefined) {
920
+ config = {
921
+ ...config,
922
+ databasePath: config.databasePath ?? (configuredRayHome !== undefined && configuredRayHome.trim() !== ''
923
+ ? defaultRayPluginStatePath(configuredRayHome, 'assistant-delivery', 'state.sqlite')
924
+ : join(dshHome, 'assistant-delivery', 'state.sqlite')),
925
+ spoolPath: config.spoolPath ?? (configuredRayHome !== undefined && configuredRayHome.trim() !== ''
926
+ ? defaultRayPluginStatePath(configuredRayHome, 'assistant-delivery', 'spool')
927
+ : join(dshHome, 'assistant-delivery', 'spool')),
928
+ };
929
+ }
930
+ if (!isAbsolute(config.databasePath) || !isAbsolute(config.spoolPath) || !isAbsolute(config.defaultWorkspace)) {
931
+ throw new Error('assistant-delivery: databasePath, spoolPath, and defaultWorkspace must be absolute paths');
932
+ }
810
933
  mkdirSync(config.spoolPath, { recursive: true, mode: 0o700 });
811
934
  chmodSync(config.spoolPath, 0o700);
812
935
  let ownerRoutes;
@@ -833,6 +956,57 @@ export class AssistantDeliveryService extends Service {
833
956
  };
834
957
  this.ownerRouteGuard = Object.freeze(ownerRouteGuard);
835
958
  this.deliveryStore = new DeliveryStore({ path: config.databasePath, maxTextBytes: config.maxTextBytes });
959
+ const deliveryDbParticipants = [];
960
+ if (policy.raySelf !== undefined && config.databasePath !== ':memory:' && typeof policy.raySelf.registerDatabaseParticipant === 'function') {
961
+ try {
962
+ policy.raySelf.registerDatabase('assistant-delivery', config.databasePath);
963
+ }
964
+ catch { }
965
+ deliveryDbParticipants.push(policy.raySelf.registerDatabaseParticipant({
966
+ id: 'assistant-delivery:store',
967
+ checkpoint: () => this.deliveryStore.checkpoint(),
968
+ beforeCloneImport: () => this.deliveryStore.closeForReload(),
969
+ afterCloneImport: () => this.deliveryStore.reopen(),
970
+ }));
971
+ }
972
+ this.workerTickets = configuredRayHome === undefined || configuredRayHome.trim() === ''
973
+ ? undefined
974
+ : new RayWorkerTicketRuntime({
975
+ rayHome: configuredRayHome,
976
+ policy,
977
+ deliveryStore: this.deliveryStore,
978
+ defaultWorkspace: config.defaultWorkspace,
979
+ defaultAgentPreset: config.defaultAgentPreset,
980
+ defaultProvider: config.agentProvider,
981
+ defaultModel: config.agentModel,
982
+ maxOutputTokens: config.agentMaxOutputTokens,
983
+ getAgentPresets: () => this.context.get('agentPresets'),
984
+ getModelSelection: conversation => this.deliveryStore.getModelSelection(conversation),
985
+ isOwnerSessionAgent: agent => this.isOwnerSessionAgent(agent),
986
+ getRaySelf: () => this.raySelfRuntime(),
987
+ publishNarration: ticket => this.publishWorkerTicketNarration(ticket),
988
+ wakeFrontOnHandback: ticket => this.scheduleHandbackFrontWake(ticket),
989
+ onTicketUpdated: ticket => this.syncWorkerTicketToMirrors(ticket),
990
+ warn: message => this.context.logger.warn(message),
991
+ });
992
+ if (this.workerTickets !== undefined) {
993
+ const ticketsRuntime = this.workerTickets;
994
+ ctx.inject(['assistantPolicy'], policyCtx => {
995
+ if (!this.active)
996
+ return;
997
+ const injectedPolicy = policyCtx.get('assistantPolicy');
998
+ ticketsRuntime.hydratePersistedSessionRoles(injectedPolicy?.raySelf);
999
+ });
1000
+ }
1001
+ if (this.workerTickets !== undefined && policy.raySelf !== undefined && typeof policy.raySelf.registerDatabaseParticipant === 'function') {
1002
+ const ticketsRuntime = this.workerTickets;
1003
+ deliveryDbParticipants.push(policy.raySelf.registerDatabaseParticipant({
1004
+ id: 'assistant-delivery:worker-tickets',
1005
+ checkpoint: () => ticketsRuntime.checkpoint(),
1006
+ beforeCloneImport: () => ticketsRuntime.closeForReload(),
1007
+ afterCloneImport: () => ticketsRuntime.reopen(),
1008
+ }));
1009
+ }
836
1010
  if (config.restart !== undefined && (!isAbsolute(config.restart.databasePath)
837
1011
  || config.restart.databasePath === config.databasePath || !this.ownerRoutes.has(config.restart.ownerRouteId))) {
838
1012
  throw new Error('assistant-delivery: restart requires a separate absolute journal and an exact configured owner route');
@@ -899,6 +1073,43 @@ export class AssistantDeliveryService extends Service {
899
1073
  this.aliasTurns.delete(agent);
900
1074
  }
901
1075
  });
1076
+ ctx.on('session/event', (session, event) => {
1077
+ if (event.type !== 'turn/end')
1078
+ return;
1079
+ this.mirrorCanonicalTurnEndReply(session, event);
1080
+ });
1081
+ ctx.inject(['personalMemory'], () => {
1082
+ if (!this.active || !this.acceptingAdmissions || this.convergeController.signal.aborted)
1083
+ return;
1084
+ void this.convergeOwnerSessions().catch(() => { });
1085
+ });
1086
+ ctx.inject(['sessionPersistence'], () => {
1087
+ if (!this.active || !this.acceptingAdmissions || this.convergeController.signal.aborted)
1088
+ return;
1089
+ void this.convergeOwnerSessions().catch(() => { });
1090
+ });
1091
+ ctx.inject(['assistantWorkItems'], wiCtx => {
1092
+ const mirror = wiCtx.get('assistantWorkItems');
1093
+ if (mirror === undefined || typeof mirror.syncRayWorkerTicket !== 'function')
1094
+ return;
1095
+ this.workItemsMirror = mirror;
1096
+ this.backfillWorkerTicketsToMirror(mirror);
1097
+ return () => {
1098
+ if (this.workItemsMirror === mirror)
1099
+ this.workItemsMirror = undefined;
1100
+ };
1101
+ });
1102
+ ctx.inject(['assistantGoals'], goalsCtx => {
1103
+ const mirror = goalsCtx.get('assistantGoals');
1104
+ if (mirror === undefined || typeof mirror.syncRayWorkerTicket !== 'function')
1105
+ return;
1106
+ this.goalsMirror = mirror;
1107
+ this.backfillWorkerTicketsToMirror(mirror);
1108
+ return () => {
1109
+ if (this.goalsMirror === mirror)
1110
+ this.goalsMirror = undefined;
1111
+ };
1112
+ });
902
1113
  this.registry = new DeliveryAdapterRegistry({
903
1114
  accept: async (envelope) => {
904
1115
  const result = await this.acceptInbound(envelope);
@@ -942,23 +1153,67 @@ export class AssistantDeliveryService extends Service {
942
1153
  notificationGuard: record => this.#notificationGuard(record),
943
1154
  });
944
1155
  this.inbound = new InboundCoordinator({ store: this.deliveryStore, processor: () => this.runtime,
945
- ownerId: this.ownerId, leaseMs: config.leaseMs, maxAttempts: config.maxAttempts,
946
- maxConcurrency: config.maxConcurrency, retryBaseMs: config.retryBaseMs, retryMaxMs: config.retryMaxMs });
1156
+ ownerId: this.ownerId, leaseMs: config.leaseMs, shutdownGraceMs: config.shutdownGraceMs,
1157
+ maxAttempts: config.maxAttempts, maxConcurrency: config.maxConcurrency,
1158
+ retryBaseMs: config.retryBaseMs, retryMaxMs: config.retryMaxMs,
1159
+ blockedSessions: () => {
1160
+ const blocked = new Set();
1161
+ if (this.restartStore === undefined)
1162
+ return blocked;
1163
+ for (const req of this.restartStore.listRequests({ statuses: ['resuming'], limit: 100 })) {
1164
+ const task = this.restartStore.getTask(req.inboxId);
1165
+ if (task?.binding.sessionId)
1166
+ blocked.add(task.binding.sessionId);
1167
+ }
1168
+ return blocked;
1169
+ } });
1170
+ ctx.on('internal/update', (_nextConfig, next) => {
1171
+ this.reloadInterruptionCode = 'config-reload-interrupted';
1172
+ return next();
1173
+ });
947
1174
  ctx.inject(['agents', 'sessions', 'llm'], runtimeCtx => {
1175
+ let deliveryRuntime;
948
1176
  const sessionLeases = new DeliverySessionLeases(runtimeCtx, {
949
1177
  requiresLease: sessionId => this.deliveryStore.requiresSessionLease(sessionId),
1178
+ isActiveOwnerSession: sessionId => this.deliveryStore.isActiveOwnerSession(sessionId),
950
1179
  leaseMs: Math.min(config.leaseMs, 300_000),
951
1180
  claim: (target, holderId, leaseMs) => this.deliveryStore.claimSessionLease(target, holderId, leaseMs),
952
1181
  dispatch: lease => this.deliveryStore.markSessionLeaseDispatched(lease),
953
1182
  valid: lease => this.deliveryStore.hasSessionLease(lease),
954
1183
  renew: (lease, leaseMs) => this.deliveryStore.renewSessionLease(lease, leaseMs),
955
1184
  finish: (lease, input) => this.deliveryStore.finishSessionLease(lease, input),
1185
+ serviceFiber: ctx.fiber,
1186
+ hasActiveInboundDrain: () => this.inbound.hasActive(),
1187
+ onInboundDisposeDrain: async () => {
1188
+ if (!this.acceptingAdmissions) {
1189
+ await this.runtimeDrainPromise;
1190
+ return;
1191
+ }
1192
+ const reloadCode = this.reloadInterruptionCode ?? 'service-reload-interrupted';
1193
+ deliveryRuntime?.markDisposing(reloadCode);
1194
+ await this.inbound.stop(reloadCode, { immediate: true });
1195
+ },
1196
+ hasActiveNativeDrain: () => {
1197
+ const owner = this.nativeWebOwner;
1198
+ return owner?.hasPendingDrain?.() ?? owner?.hasActiveInputs?.() ?? false;
1199
+ },
1200
+ onNativeDisposeDrain: async () => {
1201
+ await this.nativeWebOwner?.dispose();
1202
+ },
956
1203
  });
1204
+ this.sessionLeases = sessionLeases;
957
1205
  const webRuntime = { ctx: runtimeCtx, leases: sessionLeases };
958
1206
  this.nativeWebRuntime = webRuntime;
959
- runtimeCtx.effect(() => () => { if (this.nativeWebRuntime === webRuntime)
960
- this.nativeWebRuntime = undefined; });
961
- const unregister = this.registerInboundRuntime(new DshDeliveryRuntime(runtimeCtx, policy, {
1207
+ this.workerTickets?.attachRuntime(runtimeCtx);
1208
+ runtimeCtx.effect(() => () => {
1209
+ deliveryRuntime?.markDisposing(this.reloadInterruptionCode ?? 'service-reload-interrupted');
1210
+ if (this.nativeWebRuntime === webRuntime)
1211
+ this.nativeWebRuntime = undefined;
1212
+ if (this.sessionLeases === sessionLeases)
1213
+ this.sessionLeases = undefined;
1214
+ this.workerTickets?.detachRuntime(runtimeCtx);
1215
+ });
1216
+ deliveryRuntime = new DshDeliveryRuntime(runtimeCtx, policy, {
962
1217
  ...(this.restartStore === undefined ? {} : { restart: { store: this.restartStore, config: config.restart,
963
1218
  invocationId: this.restartInvocationId,
964
1219
  authorize: (record) => this.restartAuthorized(record),
@@ -970,6 +1225,9 @@ export class AssistantDeliveryService extends Service {
970
1225
  sessionNamespace: this.deliveryStore.instanceId(),
971
1226
  workspace: config.defaultWorkspace, agentPreset: config.defaultAgentPreset, policyRef: config.policyRef,
972
1227
  getAgentPresets: () => runtimeCtx.get('agentPresets'),
1228
+ getWorkerTickets: () => this.workerTickets,
1229
+ ownsSession: sessionId => this.ownsSession(sessionId),
1230
+ isOwnerSessionAgent: agent => this.isOwnerSessionAgent(agent),
973
1231
  readOwnerApprovalStatus: agent => this.readOwnerApprovalStatus(agent),
974
1232
  provider: config.agentProvider, model: config.agentModel, maxOutputTokens: config.agentMaxOutputTokens,
975
1233
  maxAutoContinuationTurns: config.agentMaxAutoContinuationTurns,
@@ -996,6 +1254,7 @@ export class AssistantDeliveryService extends Service {
996
1254
  }
997
1255
  },
998
1256
  completeForegroundTaskExecution: (inboxId, input) => this.completeForegroundTaskExecution(inboxId, input),
1257
+ recordInterruptedTurnSummary: (inboxId, failureCode, summary) => this.deliveryStore.recordInterruptedTurnSummary({ inboxId, failureCode, summary }),
999
1258
  modelPickerTtlMs: config.modelPickerTtlMs,
1000
1259
  permissionPickerTtlMs: config.permissionPickerTtlMs,
1001
1260
  getModelSelection: conversation => this.deliveryStore.getModelSelection(conversation),
@@ -1011,6 +1270,8 @@ export class AssistantDeliveryService extends Service {
1011
1270
  dispatchNaturalObjectiveFeedback: (binding, envelope) => this.dispatchNaturalObjectiveFeedback(binding, envelope),
1012
1271
  dispatchWorkflowCommand: (binding, envelope, command) => this.dispatchWorkflowCommand(binding, envelope, command),
1013
1272
  dispatchLearningCommand: (binding, envelope, action, preferenceKey) => this.dispatchLearningCommand(binding, envelope, action, preferenceKey),
1273
+ raySelfGrowthReport: () => this.raySelfRuntime()?.growthReport?.(),
1274
+ rayCognitiveSummary: () => this.rayCognitiveSummary(),
1014
1275
  dispatchOwnerSelfIterationCommand: (binding, envelope, command) => this.dispatchOwnerSelfIterationCommand(binding, envelope, command),
1015
1276
  dispatchVersionQuery: (binding, envelope, query) => this.dispatchVersionQuery(binding, envelope, query),
1016
1277
  authorizePermissionReply: (binding, envelope) => this.authorizePermissionReply(binding, envelope),
@@ -1043,8 +1304,12 @@ export class AssistantDeliveryService extends Service {
1043
1304
  ...(reply.permissionPicker === undefined ? {} : { permissionPicker: reply.permissionPicker }),
1044
1305
  });
1045
1306
  },
1046
- }));
1307
+ });
1308
+ const unregister = this.registerInboundRuntime(deliveryRuntime);
1047
1309
  void this.drainModelSelectionSettlements().catch(() => { });
1310
+ void this.workerTickets?.recoverUnfinishedTickets().catch(error => {
1311
+ this.context.logger.warn(`assistant-delivery: worker ticket recovery failed: ${String(error)}`);
1312
+ });
1048
1313
  return unregister;
1049
1314
  });
1050
1315
  // Register behind Policy's risk reviewer, but before the generic Web remote.
@@ -1088,14 +1353,46 @@ export class AssistantDeliveryService extends Service {
1088
1353
  if (config.schedulerEnabled)
1089
1354
  this.start();
1090
1355
  ctx.effect(() => async () => {
1091
- this.active = false;
1356
+ const leases = this.sessionLeases;
1357
+ this.acceptingAdmissions = false;
1358
+ this.drainingRuntime ??= this.runtime;
1359
+ leases?.beginShutdown();
1092
1360
  // Disarm the scheduler before the first await: the Web owner drain can
1093
1361
  // take seconds, and an armed tick must not run against a disposed service.
1094
1362
  this.clearSchedulerTimers();
1095
- // The isolated Web owner may already be unwinding concurrently. Await
1096
- // its memoized drain while the delivery Store is still available so a
1097
- // successfully disposed Agent can record its quiescent lease release.
1098
- await this.nativeWebOwner?.dispose();
1363
+ try {
1364
+ // The isolated Web owner may already be unwinding concurrently. Await
1365
+ // its memoized drain while the delivery Store is still available so a
1366
+ // successfully disposed Agent can record its quiescent lease release.
1367
+ await this.nativeWebOwner?.dispose();
1368
+ await this.stopInternal();
1369
+ await Promise.resolve();
1370
+ const pendingCommandWork = [
1371
+ ...this.midShutdownCommandTransitions,
1372
+ ...this.activeBindingRotations,
1373
+ ];
1374
+ if (pendingCommandWork.length > 0) {
1375
+ let transitionTimeout;
1376
+ try {
1377
+ await Promise.race([
1378
+ Promise.allSettled(pendingCommandWork),
1379
+ new Promise(resolve => {
1380
+ transitionTimeout = setTimeout(resolve, 2_500);
1381
+ transitionTimeout.unref?.();
1382
+ }),
1383
+ ]);
1384
+ }
1385
+ finally {
1386
+ if (transitionTimeout !== undefined)
1387
+ clearTimeout(transitionTimeout);
1388
+ }
1389
+ }
1390
+ }
1391
+ finally {
1392
+ this.active = false;
1393
+ this.drainingRuntime = undefined;
1394
+ this.resolveRuntimeDrain?.();
1395
+ }
1099
1396
  trustedDeliveryPreferenceProducers.delete(this);
1100
1397
  this.preferenceFeedbackSink = undefined;
1101
1398
  this.acceptanceSink = undefined;
@@ -1112,7 +1409,14 @@ export class AssistantDeliveryService extends Service {
1112
1409
  for (const controller of this.toolApprovalControllers) {
1113
1410
  controller.abort(new Error('assistant-delivery is stopping'));
1114
1411
  }
1115
- await this.stopInternal();
1412
+ await leases?.finishTeardown();
1413
+ for (const unreg of deliveryDbParticipants.splice(0).reverse()) {
1414
+ try {
1415
+ unreg();
1416
+ }
1417
+ catch { }
1418
+ }
1419
+ await this.workerTickets?.dispose();
1116
1420
  await this.registry.stop();
1117
1421
  this.restartStore?.close();
1118
1422
  this.deliveryStore.close();
@@ -1600,13 +1904,21 @@ export class AssistantDeliveryService extends Service {
1600
1904
  if (this.runtime !== undefined)
1601
1905
  throw new AssistantDeliveryError('runtime-conflict', 'inbound runtime is already registered');
1602
1906
  this.runtime = runtime;
1907
+ this.drainingRuntime = undefined;
1908
+ if (this.acceptingAdmissions) {
1909
+ this.inbound.resume();
1910
+ if (this.config.schedulerEnabled)
1911
+ void this.tick().catch(() => { });
1912
+ }
1603
1913
  let active = true;
1604
1914
  return () => {
1605
1915
  if (!active)
1606
1916
  return;
1607
1917
  active = false;
1608
- if (this.runtime === runtime)
1918
+ if (this.runtime === runtime) {
1919
+ this.drainingRuntime = runtime;
1609
1920
  this.runtime = undefined;
1921
+ }
1610
1922
  };
1611
1923
  }
1612
1924
  /** Versioned capability: idle wake Agents remain alive through exact goal settlement. */
@@ -1888,8 +2200,59 @@ export class AssistantDeliveryService extends Service {
1888
2200
  sessionId: binding.sessionId, scope: Object.freeze({ workspace: binding.workspace, preset: binding.agentPreset }),
1889
2201
  owner: Object.freeze({ principalRecordId: owner.principalRecordId, principalVersion: owner.principalVersion }),
1890
2202
  binding: Object.freeze({ id: binding.id, version: binding.version, generation: binding.generation }), dispatchedAt }));
2203
+ this.recordInboundOwnerSignals(binding, envelope, inbox.id);
1891
2204
  return inbox.id;
1892
2205
  }
2206
+ recordInboundOwnerSignals(binding, envelope, inboxId) {
2207
+ if (envelope.kind !== 'text')
2208
+ return;
2209
+ const trimmed = envelope.text.trim();
2210
+ if (trimmed === '' || trimmed.startsWith('/'))
2211
+ return;
2212
+ const raySelf = this.raySelfRuntime();
2213
+ if (!raySelf?.recordGrowthEvent)
2214
+ return;
2215
+ try {
2216
+ const normalized = trimmed
2217
+ .normalize('NFC')
2218
+ .toLowerCase()
2219
+ .replace(/\s+/gu, ' ')
2220
+ .replace(/[。?!?!.,,;;::]+$/gu, '')
2221
+ .trim();
2222
+ if (normalized.length > 2 && !['ok', 'yes', 'no', '好的', '收到', '谢谢'].includes(normalized)) {
2223
+ const recent = this.deliveryStore.listRecentOwnerInboxTexts({ binding, beforeInboxId: inboxId, limit: 20 });
2224
+ const matchedRepeat = recent.some(item => {
2225
+ const prevNorm = item.text
2226
+ .normalize('NFC')
2227
+ .toLowerCase()
2228
+ .replace(/\s+/gu, ' ')
2229
+ .replace(/[。?!?!.,,;;::]+$/gu, '')
2230
+ .trim();
2231
+ return prevNorm === normalized;
2232
+ });
2233
+ if (matchedRepeat && this.deliveryStore.markGrowthEventEmitted(inboxId, 'repeat-request')) {
2234
+ raySelf.recordGrowthEvent({
2235
+ category: 'repeat-request',
2236
+ metricKey: 'owner-inbound',
2237
+ subjectId: inboxId,
2238
+ });
2239
+ }
2240
+ }
2241
+ const unquoted = naturalOwnerReplyWithoutQuotes(trimmed).trim();
2242
+ const looksLikeNaturalCorrection = (/^(?:不对|错了|不是这样|你理解错了|你搞错了|理解错了|搞错了|我说的是|我让你|我刚才让你|不是让你|重来|重新)|(?:不对[,,。!!]|理解错了|搞错了|不是[^。!!??]{1,20}而是)/iu.test(unquoted)
2243
+ || /(?:^|\b)(?:that'?s\s+wrong|you\s+misunderstood|no,\s*i\s*(?:meant|asked)|not\s+what\s+i\s+asked)\b/iu.test(unquoted)) && !/[??]\s*$/u.test(unquoted);
2244
+ if (looksLikeNaturalCorrection && this.deliveryStore.markGrowthEventEmitted(inboxId, 'owner-correction')) {
2245
+ raySelf.recordGrowthEvent({
2246
+ category: 'owner-correction',
2247
+ metricKey: 'natural-correction',
2248
+ subjectId: inboxId,
2249
+ });
2250
+ }
2251
+ }
2252
+ catch {
2253
+ // Best-effort growth telemetry must never block foreground execution.
2254
+ }
2255
+ }
1893
2256
  registerForegroundTaskObserver(registration) {
1894
2257
  this.assertActive();
1895
2258
  const control = this.context.get('pluginControlPlane', false);
@@ -1936,6 +2299,32 @@ export class AssistantDeliveryService extends Service {
1936
2299
  }
1937
2300
  completeForegroundTaskExecution(inboxId, input) {
1938
2301
  this.deliveryStore.finishForegroundTaskExecution({ inboxId, ...input, completedAt: Date.now() });
2302
+ try {
2303
+ const raySelf = this.raySelfRuntime();
2304
+ const timing = raySelf?.recordGrowthEvent ? this.deliveryStore.getForegroundExecutionTiming(inboxId) : undefined;
2305
+ if (raySelf?.recordGrowthEvent && timing !== undefined) {
2306
+ const elapsedMs = Math.max(1, timing.completedAt - timing.dispatchedAt);
2307
+ if (this.deliveryStore.markGrowthEventEmitted(inboxId, 'owner-task')) {
2308
+ raySelf.recordGrowthEvent({
2309
+ category: 'owner-task',
2310
+ metricKey: 'foreground-turn',
2311
+ subjectId: inboxId,
2312
+ detail: { status: timing.status },
2313
+ });
2314
+ }
2315
+ if (this.deliveryStore.markGrowthEventEmitted(inboxId, 'latency-ms')) {
2316
+ raySelf.recordGrowthEvent({
2317
+ category: 'latency-ms',
2318
+ metricKey: 'foreground-turn',
2319
+ value: elapsedMs,
2320
+ subjectId: inboxId,
2321
+ });
2322
+ }
2323
+ }
2324
+ }
2325
+ catch {
2326
+ // Telemetry must not break foreground completion.
2327
+ }
1939
2328
  try {
1940
2329
  const sink = this.foregroundObserver;
1941
2330
  const observed = sink?.handles.get(inboxId);
@@ -2120,7 +2509,7 @@ export class AssistantDeliveryService extends Service {
2120
2509
  // 0.2.2 removed AgentRegistry.roots(): creation ownership is implicit in the
2121
2510
  // creating fiber, so a subagent child is identified by its durable session
2122
2511
  // lineage instead of a registry ownership query.
2123
- if (agent.session.header.origin === 'subagent' || agent.session.header.delegationDepth !== undefined) {
2512
+ if (isSubagentHeader(agent.session.header)) {
2124
2513
  return { state: 'invalid' };
2125
2514
  }
2126
2515
  }
@@ -2174,36 +2563,118 @@ export class AssistantDeliveryService extends Service {
2174
2563
  } },
2175
2564
  policyRef: this.config.policyRef,
2176
2565
  leaseMs: this.config.leaseMs,
2566
+ shutdownGraceMs: this.config.shutdownGraceMs,
2567
+ getReloadInterruptionCode: () => this.reloadInterruptionCode ?? 'service-reload-interrupted',
2568
+ recordInterruptedTurnSummary: (inboxId, failureCode, summary) => this.deliveryStore.recordInterruptedTurnSummary({ inboxId, failureCode, summary }),
2177
2569
  prepare: (binding, envelope) => this.prepareForegroundTaskAcceptance(binding, envelope),
2178
2570
  complete: (handle, input) => this.completeForegroundTaskAcceptance(handle, input),
2179
2571
  beginExecution: (binding, envelope) => this.beginForegroundTaskExecution(binding, envelope),
2180
2572
  completeExecution: (inboxId, input) => this.completeForegroundTaskExecution(inboxId, input),
2181
2573
  recordExecutionModelSelection: (inboxId, input) => this.deliveryStore.recordForegroundExecutionModelSelection({ inboxId, ...input }),
2182
2574
  claimed: (agent, envelope, turn) => this.capturePreferenceTurn(agent, { kind: 'delivery', channel: envelope.channel, account: envelope.account, eventId: envelope.eventId }, turn),
2183
- notifications: binding => this.deliveryStore.listOutbox({ bindingId: binding.id, limit: 50 }).filter(record => (record.status === 'accepted' || record.status === 'delivered')
2184
- // Acknowledged notices stay listed until read; withdrawal only gates the send attempt.
2185
- && record.intent.metadata?.['dsh.native-notice'] === 'v1' && this.#notificationGuard(record, { withdrawal: false }) === undefined)
2186
- .map(record => ({
2187
- id: record.id,
2188
- text: record.intent.text,
2189
- createdAt: record.createdAt,
2190
- status: record.status === 'delivered' ? 'delivered' : 'accepted',
2191
- ...(record.intent.attachment === undefined ? {} : {
2192
- attachment: Object.freeze({
2193
- kind: record.intent.attachment.kind,
2194
- name: record.intent.attachment.name,
2195
- mediaType: record.intent.attachment.mediaType,
2196
- text: record.intent.attachment.text,
2197
- sha256: record.intent.attachment.sha256,
2575
+ executeOwnerVeto: async (binding, envelope, command) => {
2576
+ const principalRecord = this.deliveryStore.getPrincipal(binding.principal);
2577
+ const ownerRootId = this.deliveryStore.resolveCanonicalOwnerRoot(principalRecord);
2578
+ if (principalRecord?.status !== 'active' || ownerRootId === undefined) {
2579
+ throw new AssistantDeliveryError('policy-denied', 'only active owner principal may execute /veto');
2580
+ }
2581
+ const policyExt = this.policy;
2582
+ if (policyExt.raySelf?.vetoByOwner === undefined) {
2583
+ throw new AssistantDeliveryError('runtime-conflict', 'Ray Home self runtime is unavailable for /veto');
2584
+ }
2585
+ const parsed = parseOwnerVetoArgs(command.rawInput);
2586
+ const vetoResult = await policyExt.raySelf.vetoByOwner({
2587
+ ...(parsed.targetEntryId === undefined ? {} : { targetEntryId: parsed.targetEntryId }),
2588
+ ...(parsed.targetCapabilityId === undefined ? {} : { targetCapabilityId: parsed.targetCapabilityId }),
2589
+ ...(parsed.reason === undefined ? {} : { reason: parsed.reason }),
2590
+ ownerProof: `owner:${envelope.conversation.channel}:${externalPrincipalId(binding.principal)}`,
2591
+ });
2592
+ const replyText = vetoResult.ok
2593
+ ? [
2594
+ '✅ Owner 否决已在当前轮次生效(下一轮即按新状态执行):',
2595
+ `- 回滚记录:${vetoResult.autobiographyEntry.summary}`,
2596
+ `- 当前自我模型:${vetoResult.selfModel.name}(v${vetoResult.selfModel.version})`,
2597
+ ...(vetoResult.revertedCapabilityId ? [`- 已回退能力:${vetoResult.revertedCapabilityId}`] : []),
2598
+ ].join('\n')
2599
+ : '⚠️ 未找到匹配的近期自主演化或能力记录;已在自传中记录本次 owner 反对意见。';
2600
+ const ownerRoute = this.config.ownerRoutes?.find(r => r.workspace === binding.workspace
2601
+ && r.agentPreset === binding.agentPreset
2602
+ && externalPrincipalId(r.principal) === externalPrincipalId(binding.principal));
2603
+ if (ownerRoute !== undefined) {
2604
+ try {
2605
+ this.enqueueOwnerNotification({
2606
+ sourceId: 'proactive-engine',
2607
+ ownerRouteId: ownerRoute.id,
2608
+ scope: {
2609
+ principalId: externalPrincipalId(binding.principal),
2610
+ principalRecordId: principalRecord.id,
2611
+ principalVersion: principalRecord.version,
2612
+ workspace: binding.workspace,
2613
+ preset: binding.agentPreset,
2614
+ },
2615
+ sessionId: binding.sessionId,
2616
+ idempotencyKey: `native-veto:${envelope.eventId}`,
2617
+ text: replyText,
2618
+ expiresAt: Date.now() + 300_000,
2619
+ attention: { purpose: 'result' },
2620
+ });
2621
+ }
2622
+ catch {
2623
+ // Best-effort notice emission when proactive send rule is not configured.
2624
+ }
2625
+ }
2626
+ return { ok: vetoResult.ok, replyText };
2627
+ },
2628
+ onCanonicalSessionCreated: sessionId => {
2629
+ this.pinCanonicalFrontConsciousness(sessionId);
2630
+ const canonical = this.deliveryStore.getCanonicalOwnerSessionBySessionId(sessionId);
2631
+ if (canonical !== undefined) {
2632
+ this.emitCanonicalSessionUpdated(canonical);
2633
+ }
2634
+ },
2635
+ notifications: binding => {
2636
+ const seenIds = new Set();
2637
+ const records = [];
2638
+ for (const candidate of this.webBindingsForSession(binding)) {
2639
+ for (const record of this.deliveryStore.listOutbox({ bindingId: candidate.id, limit: 50 })) {
2640
+ if (seenIds.has(record.id))
2641
+ continue;
2642
+ seenIds.add(record.id);
2643
+ if ((record.status === 'accepted' || record.status === 'delivered')
2644
+ // Acknowledged notices stay listed until read; withdrawal only gates the send attempt.
2645
+ && record.intent.metadata?.['dsh.native-notice'] === 'v1'
2646
+ && this.#notificationGuard(record, { withdrawal: false }) === undefined) {
2647
+ records.push(record);
2648
+ }
2649
+ }
2650
+ }
2651
+ return records.map(record => ({
2652
+ id: record.id,
2653
+ text: record.intent.text,
2654
+ createdAt: record.createdAt,
2655
+ status: record.status === 'delivered' ? 'delivered' : 'accepted',
2656
+ ...(record.intent.attachment === undefined ? {} : {
2657
+ attachment: Object.freeze({
2658
+ kind: record.intent.attachment.kind,
2659
+ name: record.intent.attachment.name,
2660
+ mediaType: record.intent.attachment.mediaType,
2661
+ text: record.intent.attachment.text,
2662
+ sha256: record.intent.attachment.sha256,
2663
+ }),
2198
2664
  }),
2199
- }),
2200
- })),
2665
+ }));
2666
+ },
2201
2667
  acknowledgeNotices: (binding, ids, status) => {
2202
2668
  // Validate the whole batch against this binding and the exact send-path
2203
2669
  // guard before writing anything: one foreign/forged/expired id, drifted
2204
2670
  // owner/binding/route/policy or withdrawn notice rejects the batch with
2205
2671
  // zero receipts.
2206
- const byId = new Map(this.deliveryStore.listOutbox({ bindingId: binding.id, limit: 100 }).map(record => [record.id, record]));
2672
+ const byId = new Map();
2673
+ for (const candidate of this.webBindingsForSession(binding)) {
2674
+ for (const record of this.deliveryStore.listOutbox({ bindingId: candidate.id, limit: 100 })) {
2675
+ byId.set(record.id, record);
2676
+ }
2677
+ }
2207
2678
  const targets = ids.map(id => {
2208
2679
  const record = byId.get(id);
2209
2680
  if (record === undefined || record.intent.metadata?.['dsh.native-notice'] !== 'v1'
@@ -2227,7 +2698,7 @@ export class AssistantDeliveryService extends Service {
2227
2698
  if (rank[status] <= rank[record.status])
2228
2699
  continue;
2229
2700
  try {
2230
- this.deliveryStore.recordReceipt({ channel: binding.conversation.channel, account: binding.conversation.account,
2701
+ this.deliveryStore.recordReceipt({ channel: record.intent.target.conversation.channel, account: record.intent.target.conversation.account,
2231
2702
  providerMessageId: record.providerMessageId, status, occurredAt: Date.now() });
2232
2703
  }
2233
2704
  catch (error) {
@@ -3866,6 +4337,21 @@ export class AssistantDeliveryService extends Service {
3866
4337
  ...(parsed.kind === 'objective-revision' ? { command: parsed } : {}),
3867
4338
  });
3868
4339
  void this.drainWorkflowTraces().catch(() => { });
4340
+ if ((parsed.kind === 'objective-revision' && parsed.action === 'correct')
4341
+ || objectiveStatus === 'not-achieved' || objectiveStatus === 'partial') {
4342
+ try {
4343
+ const raySelf = this.raySelfRuntime();
4344
+ if (raySelf?.recordGrowthEvent && this.deliveryStore.markGrowthEventEmitted(inbox.id, 'owner-correction')) {
4345
+ raySelf.recordGrowthEvent({
4346
+ category: 'owner-correction',
4347
+ metricKey: 'objective-feedback',
4348
+ subjectId: inbox.id,
4349
+ detail: { objectiveStatus },
4350
+ });
4351
+ }
4352
+ }
4353
+ catch { /* ignore */ }
4354
+ }
3869
4355
  return canonical ?? result.ownerFeedbackState ?? 'recorded';
3870
4356
  }
3871
4357
  catch (error) {
@@ -3985,6 +4471,21 @@ export class AssistantDeliveryService extends Service {
3985
4471
  || typeof receipt.idempotencyKey !== 'string') {
3986
4472
  return 'unknown';
3987
4473
  }
4474
+ if ((parsed.kind === 'objective-revision' && parsed.action === 'correct')
4475
+ || objectiveStatus === 'not-achieved' || objectiveStatus === 'partial') {
4476
+ try {
4477
+ const raySelf = this.raySelfRuntime();
4478
+ if (raySelf?.recordGrowthEvent && this.deliveryStore.markGrowthEventEmitted(inbox.id, 'owner-correction')) {
4479
+ raySelf.recordGrowthEvent({
4480
+ category: 'owner-correction',
4481
+ metricKey: 'objective-feedback',
4482
+ subjectId: inbox.id,
4483
+ detail: { objectiveStatus },
4484
+ });
4485
+ }
4486
+ }
4487
+ catch { /* ignore */ }
4488
+ }
3988
4489
  return receipt.ownerFeedbackState ?? 'recorded';
3989
4490
  }
3990
4491
  catch (error) {
@@ -4482,6 +4983,12 @@ export class AssistantDeliveryService extends Service {
4482
4983
  }
4483
4984
  async acceptInbound(envelope, recoverySignal) {
4484
4985
  this.assertActive();
4986
+ if (!this.acceptingAdmissions) {
4987
+ const parsed = parseDeliveryCommand(envelope);
4988
+ if (!isExactDeliveryCommand(parsed, 'stop', 'new', 'clear')) {
4989
+ throw new AssistantDeliveryError('disposed', 'assistant-delivery service is shutting down');
4990
+ }
4991
+ }
4485
4992
  const accepted = this.deliveryStore.acceptInbound(envelope);
4486
4993
  let record = accepted.record;
4487
4994
  if (!['received', 'authorized'].includes(record.status)) {
@@ -4556,15 +5063,25 @@ export class AssistantDeliveryService extends Service {
4556
5063
  });
4557
5064
  this.notifyWorkItemReplyCancellation(fence.replyChildItemIds ?? []);
4558
5065
  this.restartStore?.cancelForBinding(binding.id);
4559
- await this.runtime?.cancelActive?.(binding, 'new');
4560
- await this.inbound.cancelUndispatchedClaims(fence.claimedInboxIds, 'new');
4561
- const rotated = await this.rotateBinding(envelope, binding, record.id, recoverySignal);
4562
- record = this.deliveryStore.getInbox(record.id);
4563
- if (record.status !== 'queued' || record.bindingId !== rotated.id) {
4564
- throw new AssistantDeliveryError('runtime-conflict', 'new-session binding committed without its command Inbox');
5066
+ const activeRuntime = this.runtime ?? (!this.acceptingAdmissions ? this.drainingRuntime : undefined);
5067
+ await activeRuntime?.cancelActive?.(binding, 'new');
5068
+ let resolveTail;
5069
+ const tail = new Promise(resolve => { resolveTail = resolve; });
5070
+ this.midShutdownCommandTransitions.add(tail);
5071
+ try {
5072
+ await this.inbound.cancelUndispatchedClaims(fence.claimedInboxIds, 'new');
5073
+ const rotated = await this.rotateBinding(envelope, binding, record.id, recoverySignal);
5074
+ record = this.deliveryStore.getInbox(record.id);
5075
+ if (record.status !== 'queued' || record.bindingId !== rotated.id) {
5076
+ throw new AssistantDeliveryError('runtime-conflict', 'new-session binding committed without its command Inbox');
5077
+ }
5078
+ return { duplicate: accepted.duplicate, inboxId: record.id, status: record.status };
4565
5079
  }
4566
- return { duplicate: accepted.duplicate, inboxId: record.id, status: record.status };
4567
- });
5080
+ finally {
5081
+ resolveTail();
5082
+ this.midShutdownCommandTransitions.delete(tail);
5083
+ }
5084
+ }, !this.acceptingAdmissions);
4568
5085
  }
4569
5086
  if (isExactDeliveryCommand(sessionCommand, 'stop')) {
4570
5087
  return await this.runConversationTransition(envelope.conversation, async () => {
@@ -4592,11 +5109,21 @@ export class AssistantDeliveryService extends Service {
4592
5109
  // message from overtaking the durable stop acknowledgement.
4593
5110
  this.notifyWorkItemReplyCancellation(fence.replyChildItemIds ?? []);
4594
5111
  this.restartStore?.cancelForBinding(binding.id);
4595
- await this.runtime?.cancelActive?.(binding, 'stop');
4596
- await this.inbound.cancelUndispatchedClaims(fence.claimedInboxIds, 'stop');
4597
- record = this.deliveryStore.queueInbox(record.id, binding.id);
4598
- return { duplicate: accepted.duplicate, inboxId: record.id, status: record.status };
4599
- });
5112
+ const activeRuntime = this.runtime ?? (!this.acceptingAdmissions ? this.drainingRuntime : undefined);
5113
+ await activeRuntime?.cancelActive?.(binding, 'stop');
5114
+ let resolveTail;
5115
+ const tail = new Promise(resolve => { resolveTail = resolve; });
5116
+ this.midShutdownCommandTransitions.add(tail);
5117
+ try {
5118
+ await this.inbound.cancelUndispatchedClaims(fence.claimedInboxIds, 'stop');
5119
+ record = this.deliveryStore.queueInbox(record.id, binding.id);
5120
+ return { duplicate: accepted.duplicate, inboxId: record.id, status: record.status };
5121
+ }
5122
+ finally {
5123
+ resolveTail();
5124
+ this.midShutdownCommandTransitions.delete(tail);
5125
+ }
5126
+ }, !this.acceptingAdmissions);
4600
5127
  }
4601
5128
  // All accept-side binding decisions join this short conversation lock.
4602
5129
  // It serializes only durable admission (not Agent execution), and makes a
@@ -4887,6 +5414,16 @@ export class AssistantDeliveryService extends Service {
4887
5414
  || settled.canonical?.outcomeId !== outcome.id)
4888
5415
  continue;
4889
5416
  this.workItemFeedbackFence(settled);
5417
+ if ((command.kind === 'objective-revision' && command.action === 'correct')
5418
+ || command.objectiveStatus === 'not-achieved' || command.objectiveStatus === 'partial') {
5419
+ try {
5420
+ const raySelf = this.raySelfRuntime();
5421
+ if (raySelf?.recordGrowthEvent && this.deliveryStore.markGrowthEventEmitted(source.inboxId, 'owner-correction')) {
5422
+ raySelf.recordGrowthEvent({ category: 'owner-correction', metricKey: 'work-item-feedback', subjectId: source.inboxId, detail: { objectiveStatus: command.objectiveStatus } });
5423
+ }
5424
+ }
5425
+ catch { }
5426
+ }
4890
5427
  }
4891
5428
  catch (error) {
4892
5429
  if (typeof error === 'object' && error !== null && 'code' in error && ['version-conflict', 'idempotency-conflict'].includes(String(error.code))) {
@@ -5829,7 +6366,8 @@ export class AssistantDeliveryService extends Service {
5829
6366
  const inboxId = key.slice('inbound:'.length, -':interrupted'.length);
5830
6367
  const inbox = this.deliveryStore.getInbox(inboxId);
5831
6368
  const binding = this.deliveryStore.getBinding(record.intent.bindingId);
5832
- const expectedNotice = interruptedTurnNoticeForFailureCode(inbox?.failureCode);
6369
+ const summary = inbox === undefined ? undefined : this.deliveryStore.getInterruptedTurnSummary(inbox.id);
6370
+ const expectedNotice = interruptedTurnNoticeForFailureCode(inbox?.failureCode, summary);
5833
6371
  if (record.intent.text !== expectedNotice || inbox === undefined || binding === undefined
5834
6372
  || !this.deliveryStore.canSendInterruptedInboxNotice(record)
5835
6373
  || !this.isInboundAuthorized(binding, inbox.envelope)) {
@@ -5938,15 +6476,27 @@ export class AssistantDeliveryService extends Service {
5938
6476
  const expiresAt = Number(metadata['dsh.native-notice.expiresAt']);
5939
6477
  const binding = this.deliveryStore.getBinding(intent.bindingId);
5940
6478
  const owner = binding === undefined ? undefined : this.deliveryStore.getPrincipal(binding.principal);
5941
- if (!Number.isSafeInteger(expiresAt) || Date.now() >= expiresAt || binding?.status !== 'active' || owner?.status !== 'active' || owner.role !== 'owner'
6479
+ const isWorkerWebNotice = binding?.conversation.channel === 'web'
6480
+ && metadata['dsh.native-notice.sourceId'] === 'assistant-delivery/worker-tickets';
6481
+ const ownerAuthorized = owner?.status === 'active'
6482
+ && (owner.role === 'owner'
6483
+ || (isWorkerWebNotice && owner.principal.channel === 'web' && owner.role === 'linked'
6484
+ && this.deliveryStore.resolveCanonicalOwnerRoot(owner) !== undefined));
6485
+ if (!Number.isSafeInteger(expiresAt) || Date.now() >= expiresAt || binding?.status !== 'active' || !ownerAuthorized
5942
6486
  || owner.id !== metadata['dsh.native-notice.ownerRecordId'] || String(owner.version) !== metadata['dsh.native-notice.ownerVersion']
5943
6487
  || String(binding.version) !== metadata['dsh.native-notice.bindingVersion'] || String(binding.generation) !== metadata['dsh.native-notice.bindingGeneration'] || binding.sessionId !== metadata['dsh.native-notice.sessionId'])
5944
6488
  return { outcome: 'not-sent', failureCode: 'native-notice-authority-expired', retryable: false };
5945
6489
  try {
5946
6490
  const sourceId = canonicalBackgroundSourceId(metadata['dsh.native-notice.sourceId']);
5947
- const current = this.resolveOwnerRoute(metadata['dsh.native-notice.ownerRouteId']).binding;
5948
- if (current.id !== binding.id || current.version !== binding.version || current.generation !== binding.generation || current.sessionId !== binding.sessionId)
5949
- throw new Error('route changed');
6491
+ const ownerRouteId = metadata['dsh.native-notice.ownerRouteId'];
6492
+ if (ownerRouteId !== undefined) {
6493
+ const current = this.resolveOwnerRoute(ownerRouteId).binding;
6494
+ if (current.id !== binding.id || current.version !== binding.version || current.generation !== binding.generation || current.sessionId !== binding.sessionId)
6495
+ throw new Error('route changed');
6496
+ }
6497
+ else if (!isWorkerWebNotice) {
6498
+ throw new Error('owner route missing');
6499
+ }
5950
6500
  const permission = this.policy.evaluate({ subject: { kind: 'background', id: sourceId, workspace: binding.workspace, principal: externalPrincipalId(binding.principal) }, action: 'send', resource: { kind: 'message', id: binding.id }, context: { initiator: 'background' } });
5951
6501
  if (permission.effect !== 'allow')
5952
6502
  throw new Error('send denied');
@@ -6369,6 +6919,78 @@ export class AssistantDeliveryService extends Service {
6369
6919
  }
6370
6920
  return Object.freeze(scopes);
6371
6921
  }
6922
+ /** Host-only enumeration of active owner binding scopes even without configured ownerRoutes. */
6923
+ listActiveOwnerBindingScopes() {
6924
+ this.assertActive();
6925
+ return Object.freeze(this.deliveryStore.listActiveOwnerBindingScopes());
6926
+ }
6927
+ /** Host-only check whether any delivery bindings or principals exist in the store. */
6928
+ hasAnyBindings() {
6929
+ this.assertActive();
6930
+ return this.deliveryStore.hasAnyBindings();
6931
+ }
6932
+ /** Host-only metadata lookup for a principal record id without exposing external PII. */
6933
+ getPrincipalByRecordId(id) {
6934
+ this.assertActive();
6935
+ const record = this.deliveryStore.getPrincipalByRecordId(id);
6936
+ if (record === undefined)
6937
+ return undefined;
6938
+ return Object.freeze({
6939
+ id: record.id,
6940
+ version: record.version,
6941
+ role: record.role,
6942
+ status: record.status,
6943
+ });
6944
+ }
6945
+ /** Read-only Host hint for out-of-the-box assistant-dreaming provisioning. */
6946
+ defaultDreamingScopeHint() {
6947
+ this.assertActive();
6948
+ const active = this.listActiveOwnerRouteScopes()[0];
6949
+ if (active !== undefined) {
6950
+ return Object.freeze({
6951
+ workspace: active.workspace,
6952
+ preset: active.agentPreset,
6953
+ principalId: active.principalId,
6954
+ ownerRouteId: active.authorityId,
6955
+ activeRoute: true,
6956
+ });
6957
+ }
6958
+ const configured = [...this.ownerRoutes.values()][0];
6959
+ if (configured !== undefined) {
6960
+ return Object.freeze({
6961
+ workspace: configured.workspace,
6962
+ preset: configured.agentPreset,
6963
+ principalId: externalPrincipalId(configured.principal),
6964
+ ownerRouteId: configured.id,
6965
+ activeRoute: false,
6966
+ });
6967
+ }
6968
+ const bound = this.deliveryStore.listActiveOwnerBindingScopes()[0];
6969
+ if (bound !== undefined) {
6970
+ return Object.freeze({
6971
+ workspace: bound.workspace,
6972
+ preset: bound.agentPreset,
6973
+ principalId: bound.principalId,
6974
+ ownerRouteId: 'default-owner-route',
6975
+ activeRoute: false,
6976
+ });
6977
+ }
6978
+ return Object.freeze({
6979
+ workspace: resolve(this.config.defaultWorkspace),
6980
+ preset: this.config.defaultAgentPreset,
6981
+ principalId: 'owner:default',
6982
+ ownerRouteId: 'default-owner-route',
6983
+ activeRoute: false,
6984
+ });
6985
+ }
6986
+ /** Read-only Host default model selection configured on Delivery. */
6987
+ defaultModelSelection() {
6988
+ this.assertActive();
6989
+ return Object.freeze({
6990
+ provider: this.config.agentProvider,
6991
+ model: this.config.agentModel,
6992
+ });
6993
+ }
6372
6994
  /**
6373
6995
  * Read-only Host observation of the configured owner, even after its binding
6374
6996
  * has been revoked. Missing routes and transient failures are not revocation.
@@ -7590,6 +8212,807 @@ export class AssistantDeliveryService extends Service {
7590
8212
  return result;
7591
8213
  }
7592
8214
  get supportsPlannedRestart() { return this.restartStore !== undefined; }
8215
+ isInternalNonOwnerSessionId(sessionId) {
8216
+ const clean = sessionId.trim().toLowerCase();
8217
+ return clean === ''
8218
+ || clean.startsWith('memory-extract-')
8219
+ || clean.startsWith('memory-review-')
8220
+ || clean.startsWith('ray_worker_');
8221
+ }
8222
+ ownsSession(sessionId) {
8223
+ const clean = sessionId.trim();
8224
+ if (!this.active || this.isInternalNonOwnerSessionId(clean))
8225
+ return false;
8226
+ if (this.workerTickets?.ownsWorkerSession(clean) === true)
8227
+ return false;
8228
+ if (this.deliveryStore.isActiveOwnerSession(clean))
8229
+ return true;
8230
+ const binding = this.deliveryStore.getBindingBySession(clean);
8231
+ if (binding?.status !== 'active' || binding.sessionId !== clean)
8232
+ return false;
8233
+ const active = this.deliveryStore.getActiveBinding(binding.conversation);
8234
+ const principal = this.deliveryStore.getPrincipal(binding.principal);
8235
+ return active?.id === binding.id
8236
+ && principal?.status === 'active'
8237
+ && principal.role === 'owner'
8238
+ && JSON.stringify(principal.principal) === JSON.stringify(binding.principal);
8239
+ }
8240
+ hasNonOwnerOrRevokedBinding(sessionId) {
8241
+ const clean = sessionId.trim();
8242
+ if (clean === '' || !this.active)
8243
+ return false;
8244
+ return this.deliveryStore.listBindingsBySession(clean).length > 0 && !this.ownsSession(clean);
8245
+ }
8246
+ canonicalOwnerSession(scope) {
8247
+ if (!this.active)
8248
+ return undefined;
8249
+ const requestedWorkspace = scope?.workspace ?? this.config.defaultWorkspace;
8250
+ const requestedPreset = scope?.agentPreset ?? this.config.defaultAgentPreset;
8251
+ const findForScope = (workspace, agentPreset) => {
8252
+ const owner = this.deliveryStore.activeOwnerPrincipal();
8253
+ if (owner !== undefined) {
8254
+ const exact = this.deliveryStore.getCanonicalOwnerSession({ rootOwnerId: owner.id, workspace, agentPreset });
8255
+ if (exact !== undefined)
8256
+ return exact;
8257
+ }
8258
+ return this.deliveryStore.listCanonicalOwnerSessions().find(row => {
8259
+ if (row.workspace !== workspace || row.agentPreset !== agentPreset)
8260
+ return false;
8261
+ return this.deliveryStore.getPrincipalByRecordId(row.rootOwnerId)?.status === 'active'
8262
+ || this.ownsSession(row.canonicalSessionId);
8263
+ });
8264
+ };
8265
+ return findForScope(requestedWorkspace, requestedPreset)
8266
+ ?? (requestedWorkspace !== this.config.defaultWorkspace || requestedPreset !== this.config.defaultAgentPreset
8267
+ ? findForScope(this.config.defaultWorkspace, this.config.defaultAgentPreset)
8268
+ : undefined);
8269
+ }
8270
+ async convergeOwnerSessions(input) {
8271
+ const signal = this.convergeController.signal;
8272
+ if (!this.active || !this.acceptingAdmissions || signal.aborted)
8273
+ return undefined;
8274
+ let workspace = input?.workspace ?? this.config.defaultWorkspace;
8275
+ let agentPreset = input?.agentPreset ?? this.config.defaultAgentPreset;
8276
+ if (workspace !== this.config.defaultWorkspace || agentPreset !== this.config.defaultAgentPreset) {
8277
+ const owner = this.deliveryStore.activeOwnerPrincipal();
8278
+ const hasBindingsInRequested = owner !== undefined && this.deliveryStore.listActiveBindings().some(b => b.workspace === workspace
8279
+ && b.agentPreset === agentPreset
8280
+ && this.deliveryStore.resolveCanonicalOwnerRoot(this.deliveryStore.getPrincipal(b.principal)) === owner.id);
8281
+ const hasCanonicalInRequested = owner !== undefined
8282
+ && this.deliveryStore.getCanonicalOwnerSession({ rootOwnerId: owner.id, workspace, agentPreset }) !== undefined;
8283
+ if (!hasBindingsInRequested && !hasCanonicalInRequested) {
8284
+ workspace = this.config.defaultWorkspace;
8285
+ agentPreset = this.config.defaultAgentPreset;
8286
+ }
8287
+ }
8288
+ const flightKey = `${workspace}::${agentPreset}`;
8289
+ const prev = this.convergeFlights.get(flightKey);
8290
+ const run = (prev ?? Promise.resolve()).then(() => this.runConvergeOwnerSessions(workspace, agentPreset, input?.extraSessionIds ?? []));
8291
+ const tracked = run.finally(() => {
8292
+ if (this.convergeFlights.get(flightKey) === tracked)
8293
+ this.convergeFlights.delete(flightKey);
8294
+ });
8295
+ this.convergeFlights.set(flightKey, tracked);
8296
+ return tracked;
8297
+ }
8298
+ async runConvergeOwnerSessions(workspace, agentPreset, extraSessionIds) {
8299
+ const signal = this.convergeController.signal;
8300
+ if (!this.active || !this.acceptingAdmissions || signal.aborted)
8301
+ return undefined;
8302
+ const owner = this.deliveryStore.activeOwnerPrincipal();
8303
+ if (owner === undefined)
8304
+ return undefined;
8305
+ const activeOwnerBindings = this.deliveryStore.listActiveBindings().filter(binding => {
8306
+ if (binding.workspace !== workspace || binding.agentPreset !== agentPreset)
8307
+ return false;
8308
+ if (this.isInternalNonOwnerSessionId(binding.sessionId))
8309
+ return false;
8310
+ if (this.workerTickets?.ownsWorkerSession(binding.sessionId) === true)
8311
+ return false;
8312
+ const principal = this.deliveryStore.getPrincipal(binding.principal);
8313
+ return this.deliveryStore.resolveCanonicalOwnerRoot(principal) === owner.id;
8314
+ });
8315
+ let canonical = this.deliveryStore.getCanonicalOwnerSession({ rootOwnerId: owner.id, workspace, agentPreset });
8316
+ if (canonical === undefined) {
8317
+ if (activeOwnerBindings.length === 0)
8318
+ return undefined;
8319
+ const sorted = [...activeOwnerBindings].sort((a, b) => {
8320
+ const aPrincipal = this.deliveryStore.getPrincipal(a.principal);
8321
+ const bPrincipal = this.deliveryStore.getPrincipal(b.principal);
8322
+ const aRank = aPrincipal?.role === 'owner' && a.conversation.channel !== 'web' ? 0
8323
+ : aPrincipal?.role === 'owner' ? 1 : 2;
8324
+ const bRank = bPrincipal?.role === 'owner' && b.conversation.channel !== 'web' ? 0
8325
+ : bPrincipal?.role === 'owner' ? 1 : 2;
8326
+ if (aRank !== bRank)
8327
+ return aRank - bRank;
8328
+ if (a.createdAt !== b.createdAt)
8329
+ return a.createdAt - b.createdAt;
8330
+ return a.id.localeCompare(b.id);
8331
+ });
8332
+ const primary = sorted[0];
8333
+ canonical = this.deliveryStore.ensureCanonicalOwnerSession({
8334
+ rootOwnerId: owner.id,
8335
+ workspace,
8336
+ agentPreset,
8337
+ canonicalSessionId: primary.sessionId,
8338
+ primaryBindingId: primary.id,
8339
+ });
8340
+ }
8341
+ const canonicalSid = canonical.canonicalSessionId;
8342
+ this.pinCanonicalFrontConsciousness(canonicalSid);
8343
+ const sourceChannels = new Map();
8344
+ const convergedBindings = [];
8345
+ for (const binding of activeOwnerBindings) {
8346
+ if (binding.sessionId === canonicalSid) {
8347
+ if (!sourceChannels.has(canonicalSid))
8348
+ sourceChannels.set(canonicalSid, binding.conversation.channel);
8349
+ continue;
8350
+ }
8351
+ const oldSid = binding.sessionId;
8352
+ this.deliveryStore.convergeBindingSessionId(binding.id, canonicalSid);
8353
+ if (!sourceChannels.has(oldSid))
8354
+ sourceChannels.set(oldSid, binding.conversation.channel);
8355
+ convergedBindings.push(oldSid);
8356
+ }
8357
+ const raySelf = this.raySelfRuntime();
8358
+ for (const rawSid of extraSessionIds) {
8359
+ const sid = rawSid.trim();
8360
+ if (sid === '' || sid === canonicalSid || this.isInternalNonOwnerSessionId(sid))
8361
+ continue;
8362
+ if (this.workerTickets?.ownsWorkerSession(sid) === true)
8363
+ continue;
8364
+ if (this.hasNonOwnerOrRevokedBinding(sid))
8365
+ continue;
8366
+ const role = raySelf?.getSessionRole?.(sid);
8367
+ if (role === 'reflection' || role === 'worker' || role === 'worker-free')
8368
+ continue;
8369
+ if (!sourceChannels.has(sid))
8370
+ sourceChannels.set(sid, 'desktop');
8371
+ }
8372
+ if (!sourceChannels.has(canonicalSid))
8373
+ sourceChannels.set(canonicalSid, 'lark');
8374
+ for (const prevSid of canonical.convergedFromSessions) {
8375
+ if (prevSid !== canonicalSid && !sourceChannels.has(prevSid)) {
8376
+ sourceChannels.set(prevSid, prevSid.startsWith('web-') ? 'web' : 'desktop');
8377
+ }
8378
+ }
8379
+ const persistence = this.context.get('sessionPersistence');
8380
+ const sessions = this.context.get('sessions');
8381
+ const personalMemory = this.context.get('personalMemory');
8382
+ const persistedHeaderById = new Map();
8383
+ if (typeof persistence?.list === 'function') {
8384
+ try {
8385
+ for (const snap of await persistence.list({ signal })) {
8386
+ persistedHeaderById.set(String(snap.header.id), snap);
8387
+ }
8388
+ }
8389
+ catch {
8390
+ // Persistence list unavailable; rely on live sessions if present.
8391
+ }
8392
+ }
8393
+ if (!this.active || !this.acceptingAdmissions || signal.aborted)
8394
+ return undefined;
8395
+ let importedForMemory = personalMemory === undefined ? undefined : this.convergedEpisodicImports.get(personalMemory);
8396
+ if (personalMemory !== undefined && importedForMemory === undefined) {
8397
+ importedForMemory = new Set();
8398
+ this.convergedEpisodicImports.set(personalMemory, importedForMemory);
8399
+ }
8400
+ const newlyConverged = new Set(convergedBindings);
8401
+ for (const [sid, channel] of sourceChannels) {
8402
+ if (!this.active || !this.acceptingAdmissions || signal.aborted)
8403
+ return undefined;
8404
+ if (this.isInternalNonOwnerSessionId(sid) || this.workerTickets?.ownsWorkerSession(sid) === true)
8405
+ continue;
8406
+ const role = raySelf?.getSessionRole?.(sid);
8407
+ if (role === 'reflection' || role === 'worker' || role === 'worker-free')
8408
+ continue;
8409
+ const live = sessions?.get?.(SessionId(sid));
8410
+ const persistedMeta = persistedHeaderById.get(sid);
8411
+ const header = live?.header ?? persistedMeta?.header;
8412
+ if (header === undefined)
8413
+ continue;
8414
+ if (header.cwd !== workspace || header.agentPreset !== agentPreset)
8415
+ continue;
8416
+ if (isSubagentHeader(header))
8417
+ continue;
8418
+ if (sid !== canonicalSid)
8419
+ newlyConverged.add(sid);
8420
+ if (typeof personalMemory?.importEpisodicSessionEvents !== 'function')
8421
+ continue;
8422
+ if (importedForMemory?.has(sid) === true)
8423
+ continue;
8424
+ let events = live?.snapshotEvents() ?? persistedMeta?.events;
8425
+ if (events === undefined && typeof persistence?.open === 'function') {
8426
+ if (!this.active || !this.acceptingAdmissions || signal.aborted)
8427
+ return undefined;
8428
+ try {
8429
+ const handle = await persistence.open(SessionId(sid), 'read', { signal });
8430
+ try {
8431
+ const readRes = await handle.read(0, undefined, { signal });
8432
+ events = readRes.events;
8433
+ }
8434
+ finally {
8435
+ await handle.close();
8436
+ }
8437
+ }
8438
+ catch {
8439
+ events = undefined;
8440
+ }
8441
+ }
8442
+ if (!this.active || !this.acceptingAdmissions || signal.aborted)
8443
+ return undefined;
8444
+ if (events === undefined)
8445
+ continue;
8446
+ try {
8447
+ personalMemory.importEpisodicSessionEvents({
8448
+ sessionId: sid,
8449
+ channel,
8450
+ events,
8451
+ ...(header.origin === undefined ? {} : { origin: header.origin }),
8452
+ ...(header.delegationDepth === undefined ? {} : { delegationDepth: header.delegationDepth }),
8453
+ });
8454
+ importedForMemory?.add(sid);
8455
+ }
8456
+ catch {
8457
+ // Best-effort historical import when episodic store is closed/unavailable.
8458
+ }
8459
+ }
8460
+ if (!this.active || !this.acceptingAdmissions || signal.aborted)
8461
+ return undefined;
8462
+ const unrecorded = [...newlyConverged].filter(sid => !canonical.convergedFromSessions.includes(sid));
8463
+ if (unrecorded.length > 0) {
8464
+ const updated = this.deliveryStore.addConvergedCanonicalSessions({
8465
+ rootOwnerId: owner.id,
8466
+ workspace,
8467
+ agentPreset,
8468
+ sessionIds: unrecorded,
8469
+ });
8470
+ if (updated !== undefined) {
8471
+ canonical = updated;
8472
+ this.emitCanonicalSessionUpdated(updated);
8473
+ }
8474
+ }
8475
+ return canonical;
8476
+ }
8477
+ pinCanonicalFrontConsciousness(sessionId) {
8478
+ try {
8479
+ this.raySelfRuntime()?.setSessionRole?.(sessionId, 'front-consciousness');
8480
+ }
8481
+ catch {
8482
+ // Ignore if raySelf is unavailable.
8483
+ }
8484
+ }
8485
+ emitCanonicalSessionUpdated(canonical) {
8486
+ try {
8487
+ this.context.emit('assistant-delivery/canonical-session-updated', canonical);
8488
+ }
8489
+ catch {
8490
+ // Ignore listener errors.
8491
+ }
8492
+ }
8493
+ webBindingsForSession(binding) {
8494
+ const result = [];
8495
+ const seen = new Set();
8496
+ if (binding.conversation.channel === 'web' && binding.status === 'active') {
8497
+ seen.add(binding.id);
8498
+ result.push(binding);
8499
+ }
8500
+ for (const sibling of this.deliveryStore.listBindingsBySession(binding.sessionId)) {
8501
+ if (sibling.status !== 'active' || sibling.conversation.channel !== 'web' || seen.has(sibling.id))
8502
+ continue;
8503
+ const principal = this.deliveryStore.getPrincipal(sibling.principal);
8504
+ if (this.deliveryStore.resolveCanonicalOwnerRoot(principal) === undefined)
8505
+ continue;
8506
+ seen.add(sibling.id);
8507
+ result.push(sibling);
8508
+ }
8509
+ return result;
8510
+ }
8511
+ mirrorCanonicalTurnEndReply(session, event) {
8512
+ if (!this.active || event.data.reason.kind !== 'completed')
8513
+ return;
8514
+ const sessionId = String(session.id);
8515
+ if (!this.ownsSession(sessionId))
8516
+ return;
8517
+ const canonical = this.deliveryStore.getCanonicalOwnerSessionBySessionId(sessionId);
8518
+ if (canonical === undefined)
8519
+ return;
8520
+ const events = session.snapshotEvents();
8521
+ const turn = event.data.turn;
8522
+ let endIdx = -1;
8523
+ for (let i = events.length - 1; i >= 0; i -= 1) {
8524
+ const ev = events[i];
8525
+ if (ev.type === 'turn/end' && ev.data.turn === turn) {
8526
+ endIdx = i;
8527
+ break;
8528
+ }
8529
+ }
8530
+ if (endIdx < 0)
8531
+ return;
8532
+ let startIdx = -1;
8533
+ for (let i = endIdx - 1; i >= 0; i -= 1) {
8534
+ const ev = events[i];
8535
+ if (ev.type === 'turn/start' && ev.data.turn === turn) {
8536
+ startIdx = i;
8537
+ break;
8538
+ }
8539
+ }
8540
+ if (startIdx < 0)
8541
+ return;
8542
+ let triggerSourceKind;
8543
+ let sawContextInjection = false;
8544
+ const assistantTexts = [];
8545
+ for (let i = startIdx + 1; i < endIdx; i += 1) {
8546
+ const ev = events[i];
8547
+ const surfaceOp = ev.surfaceOp;
8548
+ if (surfaceOp !== undefined && surfaceOp !== 'append')
8549
+ continue;
8550
+ if (ev.type === 'user/message' && triggerSourceKind === undefined) {
8551
+ const src = ev.data.source;
8552
+ const kind = typeof src?.kind === 'string' ? src.kind : undefined;
8553
+ if (kind !== undefined) {
8554
+ if (CONTEXT_INJECTION_SOURCE_KINDS.has(kind)) {
8555
+ sawContextInjection = true;
8556
+ }
8557
+ else {
8558
+ triggerSourceKind = kind;
8559
+ }
8560
+ }
8561
+ }
8562
+ if (ev.type === 'assistant/message') {
8563
+ const text = extractSessionMessageText(ev.data);
8564
+ if (text !== '')
8565
+ assistantTexts.push(text);
8566
+ }
8567
+ }
8568
+ if (triggerSourceKind === undefined) {
8569
+ for (let i = startIdx - 1; i >= 0; i -= 1) {
8570
+ const ev = events[i];
8571
+ if (ev.type === 'turn/end')
8572
+ break;
8573
+ const surfaceOp = ev.surfaceOp;
8574
+ if (surfaceOp !== undefined && surfaceOp !== 'append')
8575
+ continue;
8576
+ if (ev.type === 'user/message') {
8577
+ const src = ev.data.source;
8578
+ const kind = typeof src?.kind === 'string' ? src.kind : undefined;
8579
+ if (kind !== undefined) {
8580
+ if (CONTEXT_INJECTION_SOURCE_KINDS.has(kind)) {
8581
+ sawContextInjection = true;
8582
+ }
8583
+ else {
8584
+ triggerSourceKind = kind;
8585
+ break;
8586
+ }
8587
+ }
8588
+ }
8589
+ }
8590
+ }
8591
+ if (triggerSourceKind === undefined && sawContextInjection)
8592
+ return;
8593
+ if (triggerSourceKind !== undefined && NON_MIRROR_SOURCE_KINDS.has(triggerSourceKind))
8594
+ return;
8595
+ const replyText = assistantTexts.join('\n\n').trim();
8596
+ if (replyText === '')
8597
+ return;
8598
+ for (const binding of this.deliveryStore.listCanonicalOwnerBindings(canonical)) {
8599
+ if (binding.status !== 'active' || binding.conversation.channel === 'web')
8600
+ continue;
8601
+ const principal = this.deliveryStore.getPrincipal(binding.principal);
8602
+ if (principal?.status !== 'active' || principal.role !== 'owner')
8603
+ continue;
8604
+ if (this.registry.get(binding.conversation.channel, binding.conversation.account) === undefined)
8605
+ continue;
8606
+ const idempotencyKey = `canonical-reply:${sessionId}:${turn}:${binding.id}`;
8607
+ if (this.deliveryStore.getOutboxByIdempotencyKey(idempotencyKey) !== undefined)
8608
+ continue;
8609
+ try {
8610
+ const decision = this.policy.authorize({
8611
+ subject: {
8612
+ kind: 'agent',
8613
+ id: binding.agentPreset,
8614
+ workspace: binding.workspace,
8615
+ principal: externalPrincipalId(binding.principal),
8616
+ },
8617
+ action: 'reply',
8618
+ resource: { kind: 'message', id: binding.id },
8619
+ context: { initiator: 'external' },
8620
+ }, { idempotencyKey: `message-reply:${idempotencyKey}` });
8621
+ if (decision.effect !== 'allow')
8622
+ continue;
8623
+ if (!this.hasActivePrincipal(binding))
8624
+ continue;
8625
+ this.deliveryStore.enqueue({
8626
+ idempotencyKey,
8627
+ bindingId: binding.id,
8628
+ target: { conversation: binding.conversation, principal: binding.principal },
8629
+ text: replyText,
8630
+ format: this.replyFormat(binding.conversation, 'markdown') ?? 'plain',
8631
+ });
8632
+ }
8633
+ catch {
8634
+ // Best-effort outbound cross-endpoint sync.
8635
+ }
8636
+ }
8637
+ }
8638
+ raySelfRuntime() {
8639
+ try {
8640
+ const policy = this.context.get?.('assistantPolicy');
8641
+ return (policy?.raySelf ?? (this.active ? this.policy?.raySelf : undefined));
8642
+ }
8643
+ catch {
8644
+ return (this.active ? this.policy?.raySelf : undefined);
8645
+ }
8646
+ }
8647
+ rayCognitiveSummary() {
8648
+ try {
8649
+ const proactive = this.context.get?.('assistantProactive');
8650
+ return this.active ? proactive?.rayCognitiveSummary?.() : undefined;
8651
+ }
8652
+ catch {
8653
+ return undefined;
8654
+ }
8655
+ }
8656
+ workerTicketsRuntime() {
8657
+ return this.active ? this.workerTickets : undefined;
8658
+ }
8659
+ listRayWorkerTickets(limit = 20) {
8660
+ return this.active && this.workerTickets !== undefined ? this.workerTickets.listTickets({ limit }) : [];
8661
+ }
8662
+ async recoverRayWorkerTickets() {
8663
+ this.assertActive();
8664
+ return this.workerTickets === undefined ? 0 : await this.workerTickets.recoverUnfinishedTickets();
8665
+ }
8666
+ ownsWorkerSessionAgent(agent) {
8667
+ if (!this.active || this.workerTickets === undefined || agent === undefined || agent.session === undefined)
8668
+ return false;
8669
+ if (isSubagentHeader(agent.session.header))
8670
+ return false;
8671
+ return this.workerTickets.ownsWorkerSession(String(agent.session.id));
8672
+ }
8673
+ sessionChannel(sessionId) {
8674
+ const clean = sessionId.trim();
8675
+ if (!this.active || clean === '')
8676
+ return undefined;
8677
+ const binding = this.deliveryStore.getBindingBySession(clean);
8678
+ if (binding !== undefined)
8679
+ return binding.conversation.channel;
8680
+ if (this.workerTickets?.ownsWorkerSession(clean))
8681
+ return 'worker';
8682
+ return undefined;
8683
+ }
8684
+ backfillWorkerTicketsToMirror(mirror) {
8685
+ if (!this.active || this.workerTickets === undefined || typeof mirror.syncRayWorkerTicket !== 'function')
8686
+ return;
8687
+ for (const ticket of this.workerTickets.iterateTickets(200)) {
8688
+ try {
8689
+ mirror.syncRayWorkerTicket(ticket);
8690
+ }
8691
+ catch {
8692
+ // Best-effort backfill of existing worker tickets.
8693
+ }
8694
+ }
8695
+ }
8696
+ syncWorkerTicketToMirrors(ticket) {
8697
+ if (!this.active)
8698
+ return;
8699
+ for (const mirror of [this.workItemsMirror, this.goalsMirror]) {
8700
+ if (mirror === undefined || typeof mirror.syncRayWorkerTicket !== 'function')
8701
+ continue;
8702
+ try {
8703
+ mirror.syncRayWorkerTicket(ticket);
8704
+ }
8705
+ catch {
8706
+ // Mirror sync failures must never disrupt worker ticket persistence or narration.
8707
+ }
8708
+ }
8709
+ }
8710
+ resolveWakeBindingForTicket(ticket) {
8711
+ const sourceBinding = ticket.sourceBindingId === undefined
8712
+ ? undefined
8713
+ : this.deliveryStore.getBinding(ticket.sourceBindingId);
8714
+ if (sourceBinding === undefined || sourceBinding.status !== 'active' || !this.hasActivePrincipal(sourceBinding)) {
8715
+ return undefined;
8716
+ }
8717
+ const sourcePrincipal = this.deliveryStore.getPrincipal(sourceBinding.principal);
8718
+ const rootOwnerId = this.deliveryStore.resolveCanonicalOwnerRoot(sourcePrincipal);
8719
+ if (rootOwnerId === undefined)
8720
+ return undefined;
8721
+ const canonical = this.deliveryStore.getCanonicalOwnerSession({
8722
+ rootOwnerId,
8723
+ workspace: sourceBinding.workspace,
8724
+ agentPreset: sourceBinding.agentPreset,
8725
+ });
8726
+ const targetSessionId = canonical?.canonicalSessionId ?? sourceBinding.sessionId;
8727
+ if (!this.ownsSession(targetSessionId))
8728
+ return undefined;
8729
+ if (sourceBinding.sessionId === targetSessionId)
8730
+ return sourceBinding;
8731
+ const candidates = canonical === undefined
8732
+ ? this.deliveryStore.listBindingsBySession(targetSessionId)
8733
+ : this.deliveryStore.listCanonicalOwnerBindings(canonical);
8734
+ for (const candidate of candidates) {
8735
+ if (candidate.status !== 'active' || candidate.sessionId !== targetSessionId || !this.hasActivePrincipal(candidate)) {
8736
+ continue;
8737
+ }
8738
+ const principal = this.deliveryStore.getPrincipal(candidate.principal);
8739
+ if (this.deliveryStore.resolveCanonicalOwnerRoot(principal) === rootOwnerId) {
8740
+ return candidate;
8741
+ }
8742
+ }
8743
+ return undefined;
8744
+ }
8745
+ handbackDedupKey(ticket) {
8746
+ return ticket.handbackCount !== undefined
8747
+ ? `${ticket.ticketId}:hb:${ticket.handbackCount}`
8748
+ : `${ticket.ticketId}:${ticket.updatedAt}`;
8749
+ }
8750
+ recordDispatchedHandbackKey(dedupKey) {
8751
+ if (this.dispatchedHandbackKeys.size >= 512) {
8752
+ const oldest = this.dispatchedHandbackKeys.values().next().value;
8753
+ if (oldest !== undefined)
8754
+ this.dispatchedHandbackKeys.delete(oldest);
8755
+ }
8756
+ this.dispatchedHandbackKeys.add(dedupKey);
8757
+ }
8758
+ scheduleHandbackFrontWake(ticket) {
8759
+ if (!this.active || ticket.status !== 'handed_back')
8760
+ return;
8761
+ const dedupKey = this.handbackDedupKey(ticket);
8762
+ if (this.dispatchedHandbackKeys.has(dedupKey)
8763
+ || this.inFlightHandbackKeys.has(dedupKey)
8764
+ || this.pendingHandbackWakes.has(dedupKey)) {
8765
+ return;
8766
+ }
8767
+ if (this.runtime?.wakeFrontForHandback === undefined) {
8768
+ this.pendingHandbackWakes.set(dedupKey, ticket);
8769
+ return;
8770
+ }
8771
+ this.inFlightHandbackKeys.add(dedupKey);
8772
+ this.launchHandbackFrontWake(dedupKey, ticket);
8773
+ }
8774
+ launchHandbackFrontWake(dedupKey, ticket) {
8775
+ const flight = this.runHandbackFrontWake(dedupKey, ticket).finally(() => {
8776
+ this.handbackWakeFlights.delete(flight);
8777
+ });
8778
+ this.handbackWakeFlights.add(flight);
8779
+ }
8780
+ async drainHandbackWakes() {
8781
+ if (!this.active || this.runtime?.wakeFrontForHandback === undefined || this.pendingHandbackWakes.size === 0)
8782
+ return;
8783
+ const queued = [...this.pendingHandbackWakes.entries()];
8784
+ this.pendingHandbackWakes.clear();
8785
+ for (const [dedupKey, ticket] of queued) {
8786
+ if (!this.active)
8787
+ break;
8788
+ if (this.dispatchedHandbackKeys.has(dedupKey) || this.inFlightHandbackKeys.has(dedupKey))
8789
+ continue;
8790
+ this.inFlightHandbackKeys.add(dedupKey);
8791
+ this.launchHandbackFrontWake(dedupKey, ticket);
8792
+ }
8793
+ if (this.handbackWakeFlights.size > 0) {
8794
+ await Promise.all(this.handbackWakeFlights);
8795
+ }
8796
+ }
8797
+ async runHandbackFrontWake(dedupKey, ticket) {
8798
+ try {
8799
+ if (!this.active || this.handbackWakeController.signal.aborted)
8800
+ return;
8801
+ const runtime = this.runtime;
8802
+ if (runtime?.wakeFrontForHandback === undefined) {
8803
+ this.pendingHandbackWakes.set(dedupKey, ticket);
8804
+ return;
8805
+ }
8806
+ const latest = this.workerTickets?.getTicket(ticket.ticketId) ?? ticket;
8807
+ if (latest.status !== 'handed_back')
8808
+ return;
8809
+ const wakeBinding = this.resolveWakeBindingForTicket(latest);
8810
+ if (wakeBinding === undefined)
8811
+ return;
8812
+ try {
8813
+ await runtime.wakeFrontForHandback(wakeBinding, latest, this.handbackWakeController.signal);
8814
+ this.recordDispatchedHandbackKey(dedupKey);
8815
+ this.handbackRetryCounts.delete(dedupKey);
8816
+ }
8817
+ catch (error) {
8818
+ if (!this.active || this.handbackWakeController.signal.aborted)
8819
+ return;
8820
+ const retryable = (error instanceof SessionLeaseUnavailable && (error.kind === 'busy' || error.kind === 'unknown'))
8821
+ || this.runtime?.wakeFrontForHandback === undefined;
8822
+ const retries = this.handbackRetryCounts.get(dedupKey) ?? 0;
8823
+ const current = this.workerTickets?.getTicket(latest.ticketId) ?? latest;
8824
+ if (retryable && current.status === 'handed_back' && retries < 5) {
8825
+ this.handbackRetryCounts.set(dedupKey, retries + 1);
8826
+ await new Promise(resolve => {
8827
+ const signal = this.handbackWakeController.signal;
8828
+ if (signal.aborted) {
8829
+ resolve();
8830
+ return;
8831
+ }
8832
+ const onAbort = () => {
8833
+ clearTimeout(timer);
8834
+ resolve();
8835
+ };
8836
+ const timer = setTimeout(() => {
8837
+ signal.removeEventListener('abort', onAbort);
8838
+ resolve();
8839
+ }, 15);
8840
+ timer.unref?.();
8841
+ signal.addEventListener('abort', onAbort, { once: true });
8842
+ });
8843
+ if (this.active && !this.handbackWakeController.signal.aborted) {
8844
+ this.pendingHandbackWakes.set(dedupKey, current);
8845
+ }
8846
+ return;
8847
+ }
8848
+ this.handbackRetryCounts.delete(dedupKey);
8849
+ this.context.logger.warn(`assistant-delivery: handback front wakeup failed for ${latest.ticketId}: ${error instanceof Error ? error.message : String(error)}`);
8850
+ }
8851
+ }
8852
+ finally {
8853
+ this.inFlightHandbackKeys.delete(dedupKey);
8854
+ }
8855
+ }
8856
+ publishWorkerTicketNarration(ticket) {
8857
+ if (!this.active || !ticket.narrationText)
8858
+ return false;
8859
+ const sourceBinding = ticket.sourceBindingId === undefined
8860
+ ? undefined
8861
+ : this.deliveryStore.getBinding(ticket.sourceBindingId);
8862
+ if (sourceBinding === undefined || sourceBinding.status !== 'active' || !this.hasActivePrincipal(sourceBinding)) {
8863
+ return false;
8864
+ }
8865
+ const sourcePrincipal = this.deliveryStore.getPrincipal(sourceBinding.principal);
8866
+ const rootOwnerId = this.deliveryStore.resolveCanonicalOwnerRoot(sourcePrincipal);
8867
+ if (rootOwnerId === undefined)
8868
+ return false;
8869
+ const canonical = this.deliveryStore.getCanonicalOwnerSession({
8870
+ rootOwnerId,
8871
+ workspace: sourceBinding.workspace,
8872
+ agentPreset: sourceBinding.agentPreset,
8873
+ });
8874
+ const candidates = new Map();
8875
+ candidates.set(sourceBinding.id, sourceBinding);
8876
+ if (canonical !== undefined) {
8877
+ for (const b of this.deliveryStore.listCanonicalOwnerBindings(canonical)) {
8878
+ candidates.set(b.id, b);
8879
+ }
8880
+ }
8881
+ // Ensure linked Web owner surfaces also receive worker narrations even if Web hasn't opened yet.
8882
+ for (const webPrincipal of this.deliveryStore.listActiveCanonicalWebPrincipals(rootOwnerId)) {
8883
+ const hasWebBinding = [...candidates.values()].some(b => b.conversation.channel === 'web'
8884
+ && b.workspace === sourceBinding.workspace
8885
+ && b.agentPreset === sourceBinding.agentPreset
8886
+ && externalPrincipalId(b.principal) === externalPrincipalId(webPrincipal.principal));
8887
+ if (!hasWebBinding) {
8888
+ try {
8889
+ const createdWeb = this.deliveryStore.createBinding({
8890
+ conversation: {
8891
+ channel: 'web',
8892
+ account: webPrincipal.principal.account,
8893
+ tenant: webPrincipal.principal.tenant,
8894
+ kind: 'dm',
8895
+ chat: sourceBinding.sessionId,
8896
+ },
8897
+ principal: webPrincipal.principal,
8898
+ workspace: sourceBinding.workspace,
8899
+ agentPreset: sourceBinding.agentPreset,
8900
+ sessionId: sourceBinding.sessionId,
8901
+ policyRef: this.config.policyRef,
8902
+ });
8903
+ candidates.set(createdWeb.id, createdWeb);
8904
+ }
8905
+ catch {
8906
+ // Ignore binding creation conflicts and proceed with existing targets.
8907
+ }
8908
+ }
8909
+ }
8910
+ const baseIdempotencyKey = `ray-worker:${ticket.ticketId}:${ticket.status}:${ticket.revision ?? ticket.updatedAt}`;
8911
+ const attention = { purpose: 'result' };
8912
+ let emitted = false;
8913
+ for (const target of candidates.values()) {
8914
+ if (target.status !== 'active' || !this.hasActivePrincipal(target))
8915
+ continue;
8916
+ const targetPrincipal = this.deliveryStore.getPrincipal(target.principal);
8917
+ if (targetPrincipal === undefined)
8918
+ continue;
8919
+ const targetKey = target.id === sourceBinding.id ? baseIdempotencyKey : `${baseIdempotencyKey}:${target.id}`;
8920
+ const matchingRoute = [...this.ownerRoutes.values()].find(route => bindingMatchesOwnerRoute(target, route));
8921
+ if (target.conversation.channel === 'web') {
8922
+ if (this.deliveryStore.resolveCanonicalOwnerRoot(targetPrincipal) !== rootOwnerId)
8923
+ continue;
8924
+ try {
8925
+ if (matchingRoute !== undefined && targetPrincipal.role === 'owner') {
8926
+ this.enqueueOwnerNotification({
8927
+ sourceId: 'assistant-delivery/worker-tickets',
8928
+ ownerRouteId: matchingRoute.id,
8929
+ scope: {
8930
+ principalId: externalPrincipalId(target.principal),
8931
+ principalRecordId: targetPrincipal.id,
8932
+ principalVersion: targetPrincipal.version,
8933
+ workspace: target.workspace,
8934
+ preset: target.agentPreset,
8935
+ },
8936
+ sessionId: target.sessionId,
8937
+ idempotencyKey: targetKey,
8938
+ text: ticket.narrationText,
8939
+ expiresAt: Date.now() + 86_400_000,
8940
+ attention,
8941
+ });
8942
+ emitted = true;
8943
+ continue;
8944
+ }
8945
+ const webKey = `${baseIdempotencyKey}:web:${target.id}`;
8946
+ const expiresAt = Date.now() + 86_400_000;
8947
+ this.enqueueBackgroundAuthorized({
8948
+ sourceId: 'assistant-delivery/worker-tickets',
8949
+ workspace: target.workspace,
8950
+ bindingId: target.id,
8951
+ idempotencyKey: webKey,
8952
+ text: ticket.narrationText,
8953
+ format: 'plain',
8954
+ metadata: {
8955
+ 'dsh.native-notice': 'v1',
8956
+ 'dsh.native-notice.sourceId': 'assistant-delivery/worker-tickets',
8957
+ 'dsh.native-notice.expiresAt': String(expiresAt),
8958
+ 'dsh.native-notice.ownerRecordId': targetPrincipal.id,
8959
+ 'dsh.native-notice.ownerVersion': String(targetPrincipal.version),
8960
+ 'dsh.native-notice.bindingVersion': String(target.version),
8961
+ 'dsh.native-notice.bindingGeneration': String(target.generation),
8962
+ 'dsh.native-notice.sessionId': target.sessionId,
8963
+ },
8964
+ }, undefined, { lane: 'owner-notification', envelope: attention });
8965
+ emitted = true;
8966
+ }
8967
+ catch {
8968
+ // Best-effort per-surface narration; policy denial on one endpoint does not block others.
8969
+ }
8970
+ continue;
8971
+ }
8972
+ if (targetPrincipal.role !== 'owner')
8973
+ continue;
8974
+ if (matchingRoute !== undefined) {
8975
+ try {
8976
+ this.enqueueBackgroundRoute({
8977
+ sourceId: 'assistant-delivery/worker-tickets',
8978
+ authorityId: matchingRoute.id,
8979
+ idempotencyKey: targetKey,
8980
+ text: ticket.narrationText,
8981
+ format: 'plain',
8982
+ attention,
8983
+ });
8984
+ emitted = true;
8985
+ continue;
8986
+ }
8987
+ catch {
8988
+ // Fallback to direct background enqueue below.
8989
+ }
8990
+ }
8991
+ try {
8992
+ this.enqueueBackground({
8993
+ sourceId: 'assistant-delivery/worker-tickets',
8994
+ workspace: target.workspace,
8995
+ bindingId: target.id,
8996
+ idempotencyKey: targetKey,
8997
+ text: ticket.narrationText,
8998
+ format: 'plain',
8999
+ attention,
9000
+ });
9001
+ emitted = true;
9002
+ }
9003
+ catch {
9004
+ // Ignore unavailable endpoint/policy.
9005
+ }
9006
+ }
9007
+ return emitted;
9008
+ }
9009
+ isOwnerSessionAgent(agent) {
9010
+ if (!this.active || agent === undefined || agent.session === undefined)
9011
+ return false;
9012
+ if (isSubagentHeader(agent.session.header))
9013
+ return false;
9014
+ return this.ownsSession(String(agent.session.id));
9015
+ }
7593
9016
  /** Host-side registration of an exact, currently mounted read-only definition. */
7594
9017
  registerRestartSafeTool(caller, definition) {
7595
9018
  if (this.restartStore === undefined)
@@ -7724,7 +9147,7 @@ export class AssistantDeliveryService extends Service {
7724
9147
  }
7725
9148
  async tick() {
7726
9149
  // Timer-driven entry: a tick that fires after dispose is a no-op, not an error.
7727
- if (!this.active)
9150
+ if (!this.active || !this.acceptingAdmissions)
7728
9151
  return;
7729
9152
  if (this.tickFlight !== undefined)
7730
9153
  return await this.tickFlight;
@@ -7736,7 +9159,7 @@ export class AssistantDeliveryService extends Service {
7736
9159
  await flight;
7737
9160
  }
7738
9161
  async runTick() {
7739
- if (!this.active)
9162
+ if (!this.active || !this.acceptingAdmissions)
7740
9163
  return;
7741
9164
  await this.drainInboundAdmissions();
7742
9165
  if (!this.active)
@@ -7781,6 +9204,9 @@ export class AssistantDeliveryService extends Service {
7781
9204
  if (!this.active)
7782
9205
  return;
7783
9206
  await this.drainWorkflowTraces();
9207
+ if (!this.active)
9208
+ return;
9209
+ await this.drainHandbackWakes();
7784
9210
  }
7785
9211
  async whenIdle() {
7786
9212
  this.assertActive();
@@ -7797,10 +9223,26 @@ export class AssistantDeliveryService extends Service {
7797
9223
  this.inboundAdmissionRecoveryFlight,
7798
9224
  this.interruptedInboxNoticeFlight,
7799
9225
  this.restartFlight,
9226
+ Promise.allSettled(this.convergeFlights.values()),
9227
+ this.drainHandbackWakes(),
7800
9228
  ]);
9229
+ while (this.active && (this.handbackWakeFlights.size > 0 || this.pendingHandbackWakes.size > 0 || this.convergeFlights.size > 0)) {
9230
+ await this.drainHandbackWakes();
9231
+ if (this.handbackWakeFlights.size > 0) {
9232
+ await Promise.all(this.handbackWakeFlights);
9233
+ }
9234
+ if (this.convergeFlights.size > 0) {
9235
+ await Promise.allSettled(this.convergeFlights.values());
9236
+ }
9237
+ }
7801
9238
  }
7802
9239
  start() {
7803
9240
  this.assertActive();
9241
+ if (!this.acceptingAdmissions)
9242
+ return;
9243
+ if (this.convergeController.signal.aborted) {
9244
+ this.convergeController = new AbortController();
9245
+ }
7804
9246
  if (this.timer !== undefined)
7805
9247
  return;
7806
9248
  this.timer = setInterval(() => void this.tick().catch(() => { }), this.config.tickIntervalMs);
@@ -7816,23 +9258,72 @@ export class AssistantDeliveryService extends Service {
7816
9258
  const existing = this.bindingFlights.get(key);
7817
9259
  if (existing !== undefined)
7818
9260
  return existing;
7819
- const runtime = this.runtime;
9261
+ const runtime = this.runtime ?? (!this.acceptingAdmissions ? this.drainingRuntime : undefined);
7820
9262
  if (runtime === undefined)
7821
9263
  throw new AssistantDeliveryError('runtime-unavailable', 'inbound runtime is unavailable');
7822
9264
  const promise = (async () => {
7823
9265
  signal?.throwIfAborted();
9266
+ const principalRecord = this.deliveryStore.getPrincipal(envelope.principal);
7824
9267
  const current = this.deliveryStore.getActiveBinding(envelope.conversation);
7825
- if (current !== undefined)
9268
+ if (current !== undefined) {
9269
+ if (principalRecord?.status === 'active' && principalRecord.role === 'owner') {
9270
+ const canonical = this.deliveryStore.ensureCanonicalOwnerSession({
9271
+ rootOwnerId: principalRecord.id,
9272
+ workspace: current.workspace,
9273
+ agentPreset: current.agentPreset,
9274
+ canonicalSessionId: current.sessionId,
9275
+ primaryBindingId: current.id,
9276
+ });
9277
+ this.pinCanonicalFrontConsciousness(canonical.canonicalSessionId);
9278
+ if (canonical.canonicalSessionId !== current.sessionId) {
9279
+ return this.deliveryStore.convergeBindingSessionId(current.id, canonical.canonicalSessionId);
9280
+ }
9281
+ }
7826
9282
  return current;
9283
+ }
7827
9284
  const generation = this.deliveryStore.nextBindingGeneration(envelope.conversation);
9285
+ if (principalRecord?.status === 'active' && principalRecord.role === 'owner') {
9286
+ const existingCanonical = this.deliveryStore.getCanonicalOwnerSession({
9287
+ rootOwnerId: principalRecord.id,
9288
+ workspace: this.config.defaultWorkspace,
9289
+ agentPreset: this.config.defaultAgentPreset,
9290
+ });
9291
+ if (existingCanonical !== undefined) {
9292
+ this.pinCanonicalFrontConsciousness(existingCanonical.canonicalSessionId);
9293
+ return this.deliveryStore.createBinding({
9294
+ conversation: envelope.conversation,
9295
+ principal: envelope.principal,
9296
+ workspace: existingCanonical.workspace,
9297
+ agentPreset: existingCanonical.agentPreset,
9298
+ sessionId: existingCanonical.canonicalSessionId,
9299
+ policyRef: this.config.policyRef,
9300
+ expectedGeneration: generation,
9301
+ });
9302
+ }
9303
+ }
7828
9304
  const created = await runtime.createSession({
7829
9305
  envelope, generation, signal: signal ?? new AbortController().signal,
7830
9306
  });
7831
9307
  signal?.throwIfAborted();
7832
9308
  this.assertActive();
7833
- return this.deliveryStore.createBinding({ conversation: envelope.conversation, principal: envelope.principal,
9309
+ let binding = this.deliveryStore.createBinding({ conversation: envelope.conversation, principal: envelope.principal,
7834
9310
  workspace: created.workspace, agentPreset: created.agentPreset, sessionId: created.sessionId,
7835
9311
  policyRef: created.policyRef, expectedGeneration: generation });
9312
+ if (principalRecord?.status === 'active' && principalRecord.role === 'owner') {
9313
+ const canonical = this.deliveryStore.ensureCanonicalOwnerSession({
9314
+ rootOwnerId: principalRecord.id,
9315
+ workspace: binding.workspace,
9316
+ agentPreset: binding.agentPreset,
9317
+ canonicalSessionId: binding.sessionId,
9318
+ primaryBindingId: binding.id,
9319
+ });
9320
+ this.pinCanonicalFrontConsciousness(canonical.canonicalSessionId);
9321
+ if (canonical.canonicalSessionId !== binding.sessionId) {
9322
+ binding = this.deliveryStore.convergeBindingSessionId(binding.id, canonical.canonicalSessionId);
9323
+ }
9324
+ this.emitCanonicalSessionUpdated(canonical);
9325
+ }
9326
+ return binding;
7836
9327
  })().finally(() => this.bindingFlights.delete(key));
7837
9328
  this.bindingFlights.set(key, promise);
7838
9329
  return promise;
@@ -7885,9 +9376,10 @@ export class AssistantDeliveryService extends Service {
7885
9376
  || !this.isInboundAuthorized(binding, current.envelope)
7886
9377
  || this.registry.get(binding.conversation.channel, binding.conversation.account) === undefined)
7887
9378
  continue;
9379
+ const summary = this.deliveryStore.getInterruptedTurnSummary(current.id);
7888
9380
  this.replyCommand(binding, { idempotencyKey: `inbound:${current.id}:interrupted`,
7889
9381
  interruptedInboxId: current.id, replyToEventId: current.eventId,
7890
- text: interruptedTurnNoticeForFailureCode(current.failureCode) });
9382
+ text: interruptedTurnNoticeForFailureCode(current.failureCode, summary) });
7891
9383
  }
7892
9384
  catch (error) {
7893
9385
  if (!this.active)
@@ -8014,7 +9506,8 @@ export class AssistantDeliveryService extends Service {
8014
9506
  failureCode: reset ? 'new-session-before-dispatch' : 'user-stopped-before-dispatch',
8015
9507
  });
8016
9508
  const cancellationCommand = reset ? 'new' : 'stop';
8017
- await this.runtime?.cancelActive?.(binding, cancellationCommand);
9509
+ const activeRuntime = this.runtime ?? (!this.acceptingAdmissions ? this.drainingRuntime : undefined);
9510
+ await activeRuntime?.cancelActive?.(binding, cancellationCommand);
8018
9511
  signal?.throwIfAborted();
8019
9512
  await this.inbound.cancelUndispatchedClaims(fence.claimedInboxIds, cancellationCommand);
8020
9513
  signal?.throwIfAborted();
@@ -8026,13 +9519,18 @@ export class AssistantDeliveryService extends Service {
8026
9519
  }
8027
9520
  }
8028
9521
  }
8029
- async runConversationTransition(conversation, task) {
9522
+ async runConversationTransition(conversation, task, trackDuringShutdown = false) {
8030
9523
  const key = JSON.stringify(canonicalConversation(conversation));
8031
9524
  const previous = this.conversationTransitions.get(key) ?? Promise.resolve();
8032
9525
  let release;
8033
9526
  const own = new Promise(resolve => { release = resolve; });
8034
9527
  const fence = previous.catch(() => { }).then(() => own);
8035
9528
  this.conversationTransitions.set(key, fence);
9529
+ let tracked;
9530
+ if (trackDuringShutdown) {
9531
+ tracked = fence.catch(() => { });
9532
+ this.midShutdownCommandTransitions.add(tracked);
9533
+ }
8036
9534
  await previous.catch(() => { });
8037
9535
  try {
8038
9536
  return await task();
@@ -8041,6 +9539,8 @@ export class AssistantDeliveryService extends Service {
8041
9539
  release();
8042
9540
  if (this.conversationTransitions.get(key) === fence)
8043
9541
  this.conversationTransitions.delete(key);
9542
+ if (tracked !== undefined)
9543
+ this.midShutdownCommandTransitions.delete(tracked);
8044
9544
  }
8045
9545
  }
8046
9546
  async rotateBinding(envelope, previous, commandInboxId, signal) {
@@ -8048,7 +9548,7 @@ export class AssistantDeliveryService extends Service {
8048
9548
  const existing = this.bindingFlights.get(key);
8049
9549
  if (existing !== undefined)
8050
9550
  return existing;
8051
- const runtime = this.runtime;
9551
+ const runtime = this.runtime ?? (!this.acceptingAdmissions ? this.drainingRuntime : undefined);
8052
9552
  if (runtime === undefined)
8053
9553
  throw new AssistantDeliveryError('runtime-unavailable', 'inbound runtime is unavailable');
8054
9554
  const promise = (async () => {
@@ -8066,14 +9566,25 @@ export class AssistantDeliveryService extends Service {
8066
9566
  previous: current, signal: signal ?? new AbortController().signal });
8067
9567
  signal?.throwIfAborted();
8068
9568
  this.assertActive();
8069
- return this.deliveryStore.rotateBindingAndQueueCommand({
9569
+ const rotated = this.deliveryStore.rotateBindingAndQueueCommand({
8070
9570
  bindingId: current.id,
8071
9571
  expectedVersion: current.version,
8072
9572
  sessionId: created.sessionId,
8073
9573
  inboxId: commandInboxId,
8074
9574
  }).binding;
8075
- })().finally(() => this.bindingFlights.delete(key));
9575
+ if (this.ownsSession(rotated.sessionId)) {
9576
+ this.pinCanonicalFrontConsciousness(rotated.sessionId);
9577
+ const canonical = this.deliveryStore.getCanonicalOwnerSessionBySessionId(rotated.sessionId);
9578
+ if (canonical !== undefined)
9579
+ this.emitCanonicalSessionUpdated(canonical);
9580
+ }
9581
+ return rotated;
9582
+ })().finally(() => {
9583
+ this.bindingFlights.delete(key);
9584
+ this.activeBindingRotations.delete(promise);
9585
+ });
8076
9586
  this.bindingFlights.set(key, promise);
9587
+ this.activeBindingRotations.add(promise);
8077
9588
  return promise;
8078
9589
  }
8079
9590
  clearSchedulerTimers() {
@@ -8095,6 +9606,10 @@ export class AssistantDeliveryService extends Service {
8095
9606
  this.cancelModelSelectionWaiters();
8096
9607
  this.inboundAdmissionRecoveryController.abort(new Error('assistant-delivery is stopping'));
8097
9608
  this.restartController.abort(new Error('assistant-delivery is stopping'));
9609
+ this.handbackWakeController.abort(new Error('assistant-delivery is stopping'));
9610
+ this.convergeController.abort(new Error('assistant-delivery is stopping'));
9611
+ this.pendingHandbackWakes.clear();
9612
+ this.handbackRetryCounts.clear();
8098
9613
  const admissionRecovery = this.inboundAdmissionRecoveryFlight === undefined
8099
9614
  ? undefined
8100
9615
  : Promise.race([
@@ -8113,9 +9628,30 @@ export class AssistantDeliveryService extends Service {
8113
9628
  timeout.unref?.();
8114
9629
  }),
8115
9630
  ]);
9631
+ const handbackDrain = this.handbackWakeFlights.size === 0
9632
+ ? undefined
9633
+ : Promise.race([
9634
+ Promise.allSettled(this.handbackWakeFlights).then(() => { }),
9635
+ new Promise(resolve => {
9636
+ const timeout = setTimeout(resolve, Math.max(1, Math.floor(this.config.leaseMs / 3)));
9637
+ timeout.unref?.();
9638
+ }),
9639
+ ]);
9640
+ const convergeDrain = this.convergeFlights.size === 0
9641
+ ? undefined
9642
+ : Promise.race([
9643
+ Promise.allSettled(this.convergeFlights.values()).then(() => { }),
9644
+ new Promise(resolve => {
9645
+ const timeout = setTimeout(resolve, Math.max(1, Math.floor(this.config.leaseMs / 3)));
9646
+ timeout.unref?.();
9647
+ }),
9648
+ ]);
9649
+ const reloadCode = this.reloadInterruptionCode ?? 'service-reload-interrupted';
8116
9650
  await Promise.all([
8117
9651
  tickDrain,
8118
- this.inbound.stop(),
9652
+ handbackDrain,
9653
+ convergeDrain,
9654
+ this.inbound.stop(reloadCode),
8119
9655
  this.outbound.stop(),
8120
9656
  admissionRecovery,
8121
9657
  this.modelSelectionFlight,