@dsh-ray/assistant-delivery 0.2.4 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +15 -2
  2. package/cordis.patch.yml +0 -2
  3. package/lib/agent-runtime.d.ts +15 -0
  4. package/lib/agent-runtime.d.ts.map +1 -1
  5. package/lib/agent-runtime.js +446 -51
  6. package/lib/agent-runtime.js.map +1 -1
  7. package/lib/attention-audit-store.d.ts +2 -1
  8. package/lib/attention-audit-store.d.ts.map +1 -1
  9. package/lib/attention-audit-store.js +3 -0
  10. package/lib/attention-audit-store.js.map +1 -1
  11. package/lib/coordinator.d.ts +21 -1
  12. package/lib/coordinator.d.ts.map +1 -1
  13. package/lib/coordinator.js +255 -68
  14. package/lib/coordinator.js.map +1 -1
  15. package/lib/feedback-command.d.ts +1 -0
  16. package/lib/feedback-command.d.ts.map +1 -1
  17. package/lib/feedback-command.js +1 -1
  18. package/lib/feedback-command.js.map +1 -1
  19. package/lib/index.d.ts +2 -1
  20. package/lib/index.d.ts.map +1 -1
  21. package/lib/index.js +1 -0
  22. package/lib/index.js.map +1 -1
  23. package/lib/interrupted-notices.d.ts +20 -5
  24. package/lib/interrupted-notices.d.ts.map +1 -1
  25. package/lib/interrupted-notices.js +238 -24
  26. package/lib/interrupted-notices.js.map +1 -1
  27. package/lib/learning-command.d.ts +2 -0
  28. package/lib/learning-command.d.ts.map +1 -1
  29. package/lib/learning-command.js +2 -0
  30. package/lib/learning-command.js.map +1 -1
  31. package/lib/native-web-owner.d.ts +12 -0
  32. package/lib/native-web-owner.d.ts.map +1 -1
  33. package/lib/native-web-owner.js +653 -80
  34. package/lib/native-web-owner.js.map +1 -1
  35. package/lib/operator-snapshot.d.ts +1 -1
  36. package/lib/operator-snapshot.d.ts.map +1 -1
  37. package/lib/operator-snapshot.js +6 -5
  38. package/lib/operator-snapshot.js.map +1 -1
  39. package/lib/ray-worker-runtime.d.ts +192 -0
  40. package/lib/ray-worker-runtime.d.ts.map +1 -0
  41. package/lib/ray-worker-runtime.js +1300 -0
  42. package/lib/ray-worker-runtime.js.map +1 -0
  43. package/lib/service.d.ts +286 -3
  44. package/lib/service.d.ts.map +1 -1
  45. package/lib/service.js +1608 -72
  46. package/lib/service.js.map +1 -1
  47. package/lib/session-commands.d.ts +6 -0
  48. package/lib/session-commands.d.ts.map +1 -1
  49. package/lib/session-commands.js +14 -0
  50. package/lib/session-commands.js.map +1 -1
  51. package/lib/session-lease-runtime.d.ts +31 -6
  52. package/lib/session-lease-runtime.d.ts.map +1 -1
  53. package/lib/session-lease-runtime.js +553 -43
  54. package/lib/session-lease-runtime.js.map +1 -1
  55. package/lib/sqlite.d.ts +1 -1
  56. package/lib/sqlite.d.ts.map +1 -1
  57. package/lib/sqlite.js +83 -3
  58. package/lib/sqlite.js.map +1 -1
  59. package/lib/store.d.ts +93 -2
  60. package/lib/store.d.ts.map +1 -1
  61. package/lib/store.js +695 -24
  62. package/lib/store.js.map +1 -1
  63. package/lib/tools.d.ts.map +1 -1
  64. package/lib/tools.js +319 -0
  65. package/lib/tools.js.map +1 -1
  66. package/lib/version-query.d.ts.map +1 -1
  67. package/lib/version-query.js +109 -20
  68. package/lib/version-query.js.map +1 -1
  69. package/lib/version.d.ts +1 -1
  70. package/lib/version.js +1 -1
  71. package/lib/work-item-feedback-store.d.ts +2 -1
  72. package/lib/work-item-feedback-store.d.ts.map +1 -1
  73. package/lib/work-item-feedback-store.js +1 -0
  74. package/lib/work-item-feedback-store.js.map +1 -1
  75. package/lib/work-item-replies-store.d.ts +2 -1
  76. package/lib/work-item-replies-store.d.ts.map +1 -1
  77. package/lib/work-item-replies-store.js +3 -0
  78. package/lib/work-item-replies-store.js.map +1 -1
  79. package/package.json +11 -11
@@ -1,8 +1,18 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { isAbsolute } from 'node:path';
3
+ import { SessionId } from '@deepseek-ai/dsh-session';
3
4
  import { observeNativeTermination } from './native-termination.js';
5
+ import { summarizeTurnToolMutations, } from './interrupted-notices.js';
4
6
  import { externalPrincipalId, canonicalPrincipal } from './canonical.js';
5
7
  import { DeliverySessionLeases, SessionLeaseUnavailable } from './session-lease-runtime.js';
8
+ import { parseDeliveryCommand } from './session-commands.js';
9
+ function isInternalOrWorkerSessionId(sessionId) {
10
+ return sessionId === 'undefined'
11
+ || sessionId === ''
12
+ || sessionId.startsWith('ray_worker_')
13
+ || sessionId.startsWith('memory-extract-')
14
+ || sessionId.startsWith('memory-review-');
15
+ }
6
16
  /** Fixed single-owner Host capability. No RPC payload may choose its principal or scope. */
7
17
  export class NativeWebOwner {
8
18
  ownerCtx;
@@ -12,10 +22,13 @@ export class NativeWebOwner {
12
22
  port;
13
23
  #config;
14
24
  #lineage;
25
+ #rootOwnerId;
15
26
  #controller = new AbortController();
16
27
  #entries = new Map();
28
+ #boundAgents = new WeakSet();
17
29
  #ownerId = `native-web-${randomUUID()}`;
18
30
  #timer;
31
+ #drainListeners = new Set();
19
32
  #disposed = false;
20
33
  #disposing;
21
34
  constructor(ownerCtx, store, leases, policy, port, config) {
@@ -31,10 +44,15 @@ export class NativeWebOwner {
31
44
  }
32
45
  this.#config = Object.freeze({ principal: Object.freeze(principal), workspace: config.workspace, preset: config.preset, maxExecutionMs: config.maxExecutionMs ?? 300_000 });
33
46
  const owner = store.getPrincipal(principal);
34
- if (owner?.status !== 'active' || owner.role !== 'owner') {
47
+ const rootOwnerId = owner?.status === 'active'
48
+ && (owner.role === 'owner' || (owner.principal.channel === 'web' && owner.role === 'linked'))
49
+ ? store.resolveCanonicalOwnerRoot(owner)
50
+ : undefined;
51
+ if (owner === undefined || rootOwnerId === undefined) {
35
52
  throw new Error('assistant-delivery: pair this Web owner locally before enabling its Controller');
36
53
  }
37
54
  this.#lineage = { principalRecordId: owner.id, principalVersion: owner.version };
55
+ this.#rootOwnerId = rootOwnerId;
38
56
  // Idle Agents yield the durable lane to Automations/Delivery. Active input
39
57
  // claims renew alongside their Session lease; neither timer dispatches work.
40
58
  this.#timer = setInterval(() => {
@@ -42,47 +60,182 @@ export class NativeWebOwner {
42
60
  if (entry.closing !== undefined)
43
61
  continue;
44
62
  try {
45
- if (entry.deadlineSignal.aborted || Date.now() >= entry.deadlineAt) {
46
- entry.terminationCause = 'execution-timeout';
63
+ const now = Date.now();
64
+ const activeHolders = [];
65
+ const nonClosedHolders = [];
66
+ const expiredHolders = [];
67
+ for (const holder of entry.holders) {
68
+ if (holder.closed)
69
+ continue;
70
+ nonClosedHolders.push(holder);
71
+ if (this.#isHolderActive(holder, now)) {
72
+ activeHolders.push(holder);
73
+ continue;
74
+ }
75
+ if (holder.deadlineSignal.aborted || now >= holder.deadlineAt) {
76
+ expiredHolders.push(holder);
77
+ }
78
+ }
79
+ if (activeHolders.length === 0) {
80
+ if (nonClosedHolders.length > 0 && expiredHolders.length >= nonClosedHolders.length) {
81
+ entry.terminationCause = 'execution-timeout';
82
+ }
47
83
  throw new SessionLeaseUnavailable('denied');
48
84
  }
49
85
  this.assertSession(id);
50
- entry.lease.assertAgent(entry.handle.agent);
51
- if (entry.input !== undefined && !store.renewInboxClaim({ inboxId: entry.input.inboxId,
52
- ownerId: this.#ownerId, fencingToken: entry.input.fencingToken, leaseMs: port.leaseMs })) {
86
+ let activeLeaseHolder;
87
+ for (const holder of activeHolders) {
88
+ try {
89
+ holder.lease.assertAgent(entry.agent);
90
+ activeLeaseHolder ??= holder;
91
+ }
92
+ catch {
93
+ // Ignore individual co-holder assertion failure if another co-holder remains valid;
94
+ // root lease failures abort all co-holders synchronously inside assertAgent().
95
+ }
96
+ }
97
+ if (activeLeaseHolder === undefined || !this.#isHolderActive(activeLeaseHolder, now)) {
53
98
  throw new SessionLeaseUnavailable('denied');
54
99
  }
55
- if (entry.input?.admitting !== true && entry.handle.agent.status === 'idle' && !(entry.handle.agent.inbox.nextTurn.length > 0 || entry.handle.agent.inbox.nextStep.length > 0)
56
- && !this.#awaitingNativeGoal(entry.handle.agent))
100
+ let hasAdmitting = false;
101
+ for (const execInput of entry.inputs.values()) {
102
+ if (execInput.settled)
103
+ continue;
104
+ if (execInput.admitting)
105
+ hasAdmitting = true;
106
+ if (!store.renewInboxClaim({ inboxId: execInput.inboxId,
107
+ ownerId: this.#ownerId, fencingToken: execInput.fencingToken, leaseMs: port.leaseMs })) {
108
+ throw new SessionLeaseUnavailable('denied');
109
+ }
110
+ }
111
+ for (const stale of nonClosedHolders) {
112
+ if (!activeHolders.includes(stale)) {
113
+ void this.#releaseHolder(id, entry, stale);
114
+ }
115
+ }
116
+ if (!hasAdmitting && entry.agent.status === 'idle' && !(entry.agent.inbox.nextTurn.length > 0 || entry.agent.inbox.nextStep.length > 0)
117
+ && !this.#awaitingNativeGoal(entry.agent))
57
118
  void this.#close(id, entry);
58
119
  }
59
120
  catch {
121
+ this.#reconcileCompletedTurnsBeforeAbort(entry);
60
122
  entry.terminationCause ??= 'lease-or-authority-lost';
61
- entry.lease.cancel();
123
+ for (const holder of entry.holders)
124
+ holder.lease.cancel();
62
125
  void this.#close(id, entry);
63
126
  }
64
127
  }
65
128
  }, Math.max(1, Math.min(100, Math.floor(port.leaseMs / 3))));
66
129
  this.#timer.unref?.();
130
+ ownerCtx.on('session/event', (session, event) => {
131
+ if (event.type === 'turn/end' && event.data.reason.kind === 'completed') {
132
+ const now = Date.now();
133
+ for (const entry of this.#entries.values()) {
134
+ if (entry.agent.session !== session || entry.closing !== undefined)
135
+ continue;
136
+ const hasActiveHolder = [...entry.holders].some(holder => this.#isHolderActive(holder, now));
137
+ if (hasActiveHolder) {
138
+ entry.completedTurnsBeforeAbort.add(event.data.turn);
139
+ for (const execInput of entry.inputs.values()) {
140
+ if (!execInput.settled && execInput.turn === event.data.turn) {
141
+ execInput.completed = true;
142
+ execInput.completedBeforeDisposeAbort = true;
143
+ }
144
+ }
145
+ }
146
+ }
147
+ }
148
+ for (const listener of this.#drainListeners)
149
+ listener();
150
+ });
151
+ ownerCtx.on('agent/status', () => {
152
+ for (const listener of this.#drainListeners)
153
+ listener();
154
+ });
67
155
  ownerCtx.effect(() => () => this.dispose(), 'assistant-delivery.native-web-owner');
68
156
  }
157
+ #isHolderActive(holder, now = Date.now()) {
158
+ return !holder.closed
159
+ && !holder.lease.signal.aborted
160
+ && !holder.deadlineSignal.aborted
161
+ && now < holder.deadlineAt;
162
+ }
163
+ #assertAnyActiveHolder(entry, requireAgent = false, now = Date.now()) {
164
+ let lastError;
165
+ for (const holder of entry.holders) {
166
+ if (!this.#isHolderActive(holder, now))
167
+ continue;
168
+ try {
169
+ if (requireAgent)
170
+ holder.lease.assertAgent(entry.agent);
171
+ else
172
+ holder.lease.assert();
173
+ return holder;
174
+ }
175
+ catch (error) {
176
+ lastError = error;
177
+ }
178
+ }
179
+ if (lastError !== undefined)
180
+ throw lastError;
181
+ const hasNonClosed = [...entry.holders].some(holder => !holder.closed);
182
+ throw new SessionLeaseUnavailable(hasNonClosed ? 'denied' : 'busy');
183
+ }
69
184
  #assertOwner() {
70
185
  this.port.assertActive();
71
186
  this.#controller.signal.throwIfAborted();
72
187
  const owner = this.store.getPrincipal(this.#config.principal);
73
- if (owner?.id !== this.#lineage.principalRecordId || owner.version !== this.#lineage.principalVersion
74
- || owner.status !== 'active' || owner.role !== 'owner')
188
+ const rootOwnerId = owner?.id === this.#lineage.principalRecordId
189
+ && owner.version === this.#lineage.principalVersion
190
+ && owner.status === 'active'
191
+ && (owner.role === 'owner' || (owner.principal.channel === 'web' && owner.role === 'linked'))
192
+ ? this.store.resolveCanonicalOwnerRoot(owner)
193
+ : undefined;
194
+ if (rootOwnerId === undefined || rootOwnerId !== this.#rootOwnerId)
75
195
  throw new SessionLeaseUnavailable('denied');
196
+ return rootOwnerId;
76
197
  }
77
198
  #binding(sessionId) {
78
- this.#assertOwner();
79
- const binding = this.store.getBindingBySession(sessionId);
80
- if (binding?.status !== 'active' || binding.workspace !== this.#config.workspace
81
- || binding.agentPreset !== this.#config.preset
82
- || externalPrincipalId(binding.principal) !== externalPrincipalId(this.#config.principal)) {
199
+ const rootOwnerId = this.#assertOwner();
200
+ if (isInternalOrWorkerSessionId(sessionId))
83
201
  throw new SessionLeaseUnavailable('denied');
84
- }
85
- return binding;
202
+ const bindings = this.store.listBindingsBySession(sessionId).filter(binding => binding.status === 'active');
203
+ const exactWeb = bindings.find(binding => binding.workspace === this.#config.workspace
204
+ && binding.agentPreset === this.#config.preset
205
+ && externalPrincipalId(binding.principal) === externalPrincipalId(this.#config.principal));
206
+ if (exactWeb !== undefined)
207
+ return exactWeb;
208
+ const ownerBinding = bindings.find(binding => {
209
+ if (binding.workspace !== this.#config.workspace || binding.agentPreset !== this.#config.preset)
210
+ return false;
211
+ const principal = this.store.getPrincipal(binding.principal);
212
+ return this.store.resolveCanonicalOwnerRoot(principal) === rootOwnerId;
213
+ });
214
+ if (ownerBinding !== undefined)
215
+ return ownerBinding;
216
+ throw new SessionLeaseUnavailable('denied');
217
+ }
218
+ #ensureWebBinding(sessionId) {
219
+ const existing = this.store.listBindingsBySession(sessionId).find(binding => binding.status === 'active'
220
+ && binding.workspace === this.#config.workspace
221
+ && binding.agentPreset === this.#config.preset
222
+ && externalPrincipalId(binding.principal) === externalPrincipalId(this.#config.principal));
223
+ if (existing !== undefined)
224
+ return existing;
225
+ return this.store.createBinding({
226
+ conversation: {
227
+ channel: 'web',
228
+ account: this.#config.principal.account,
229
+ tenant: this.#config.principal.tenant,
230
+ kind: 'dm',
231
+ chat: sessionId,
232
+ },
233
+ principal: this.#config.principal,
234
+ workspace: this.#config.workspace,
235
+ agentPreset: this.#config.preset,
236
+ sessionId,
237
+ policyRef: this.port.policyRef,
238
+ });
86
239
  }
87
240
  /** An armed active Goal is owned by the native round driver after this turn's idle edge. */
88
241
  #awaitingNativeGoal(agent) {
@@ -123,22 +276,44 @@ export class NativeWebOwner {
123
276
  this.assertSession(sessionId);
124
277
  if (entry.closing !== undefined)
125
278
  throw new SessionLeaseUnavailable('busy');
126
- entry.lease.assertAgent(entry.handle.agent);
127
- return entry.handle.agent;
279
+ this.#assertAnyActiveHolder(entry, true);
280
+ return entry.agent;
128
281
  }
129
282
  async create(options) {
130
- this.#assertOwner();
283
+ if (this.#disposed)
284
+ throw new SessionLeaseUnavailable('denied');
285
+ const rootOwnerId = this.#assertOwner();
131
286
  const sessionId = String(options.sessionId);
132
287
  if (options.meta?.cwd !== this.#config.workspace || options.meta?.agentPreset !== this.#config.preset
133
- || sessionId === 'undefined' || this.store.getBindingBySession(sessionId) !== undefined) {
288
+ || isInternalOrWorkerSessionId(sessionId)) {
134
289
  throw new SessionLeaseUnavailable('denied');
135
290
  }
291
+ const existingBySession = this.store.listBindingsBySession(sessionId);
292
+ for (const existing of existingBySession) {
293
+ if (existing.status !== 'active'
294
+ || existing.workspace !== this.#config.workspace
295
+ || existing.agentPreset !== this.#config.preset
296
+ || this.store.resolveCanonicalOwnerRoot(this.store.getPrincipal(existing.principal)) !== rootOwnerId) {
297
+ throw new SessionLeaseUnavailable('denied');
298
+ }
299
+ }
300
+ const canonical = this.store.getCanonicalOwnerSession({
301
+ rootOwnerId,
302
+ workspace: this.#config.workspace,
303
+ agentPreset: this.#config.preset,
304
+ });
305
+ if (canonical !== undefined) {
306
+ this.#ensureWebBinding(canonical.canonicalSessionId);
307
+ return await this.resume({ ...options, resumeSessionId: SessionId(canonical.canonicalSessionId) });
308
+ }
309
+ if (existingBySession.length > 0)
310
+ throw new SessionLeaseUnavailable('denied');
136
311
  const conversation = { channel: 'web', account: this.#config.principal.account,
137
312
  tenant: this.#config.principal.tenant, kind: 'dm', chat: sessionId };
138
313
  const deadlineAt = Date.now() + this.#config.maxExecutionMs;
139
314
  const deadlineSignal = AbortSignal.timeout(this.#config.maxExecutionMs);
140
315
  const lease = this.leases.open({ kind: 'construction', sessionId, conversation,
141
- principal: this.#config.principal, workspace: this.#config.workspace, agentPreset: this.#config.preset, generation: 1 }, AbortSignal.any([this.#controller.signal, deadlineSignal]));
316
+ principal: this.#config.principal, workspace: this.#config.workspace, agentPreset: this.#config.preset, generation: 1 }, AbortSignal.any([this.#controller.signal, deadlineSignal]), { promotableToCoHolder: true });
142
317
  let handle;
143
318
  try {
144
319
  lease.dispatch();
@@ -146,35 +321,60 @@ export class NativeWebOwner {
146
321
  if (!await this.ownerCtx.sessions.flush(handle.agent.session))
147
322
  throw new Error('assistant-delivery: Web Session was not durable');
148
323
  this.#assertOwner();
149
- this.store.createBinding({ conversation, principal: this.#config.principal, workspace: this.#config.workspace,
324
+ const created = this.store.createBinding({ conversation, principal: this.#config.principal, workspace: this.#config.workspace,
150
325
  agentPreset: this.#config.preset, sessionId, policyRef: this.port.policyRef, expectedGeneration: 1, constructionLease: lease.token });
151
- return this.#track(sessionId, lease, handle, deadlineAt, deadlineSignal);
326
+ const canonicalRecord = this.store.ensureCanonicalOwnerSession({
327
+ rootOwnerId,
328
+ workspace: this.#config.workspace,
329
+ agentPreset: this.#config.preset,
330
+ canonicalSessionId: sessionId,
331
+ primaryBindingId: created.id,
332
+ });
333
+ if (canonicalRecord.canonicalSessionId !== sessionId) {
334
+ this.store.convergeBindingSessionId(created.id, canonicalRecord.canonicalSessionId);
335
+ lease.cancel();
336
+ lease.close();
337
+ await Promise.resolve(handle.dispose()).catch(() => { });
338
+ handle = undefined;
339
+ this.port.onCanonicalSessionCreated?.(canonicalRecord.canonicalSessionId);
340
+ return await this.resume({ ...options, resumeSessionId: SessionId(canonicalRecord.canonicalSessionId) });
341
+ }
342
+ if (!this.leases.promoteToCoHolders(sessionId))
343
+ throw new SessionLeaseUnavailable('denied');
344
+ this.port.onCanonicalSessionCreated?.(canonicalRecord.canonicalSessionId);
345
+ return await this.#track(sessionId, lease, handle, deadlineAt, deadlineSignal);
152
346
  }
153
347
  catch (error) {
154
348
  lease.cancel();
155
349
  lease.close();
156
350
  if (handle !== undefined)
157
- void handle.dispose().catch(() => { });
351
+ void Promise.resolve(handle.dispose()).catch(() => { });
158
352
  throw error;
159
353
  }
160
354
  }
161
355
  async resume(options) {
356
+ if (this.#disposed)
357
+ throw new SessionLeaseUnavailable('denied');
162
358
  const binding = this.#binding(String(options.resumeSessionId));
359
+ const prev = this.#entries.get(binding.sessionId);
360
+ if (prev?.closing !== undefined)
361
+ await prev.closing.catch(() => { });
362
+ const webBinding = this.#ensureWebBinding(binding.sessionId);
163
363
  const deadlineAt = Date.now() + this.#config.maxExecutionMs;
164
364
  const deadlineSignal = AbortSignal.timeout(this.#config.maxExecutionMs);
165
- const lease = this.leases.open({ kind: 'bound', binding }, AbortSignal.any([this.#controller.signal, deadlineSignal]));
365
+ const lease = this.leases.open({ kind: 'bound', binding: webBinding }, AbortSignal.any([this.#controller.signal, deadlineSignal]), { allowConcurrentOwner: true });
166
366
  let handle;
167
367
  try {
168
368
  lease.dispatch();
169
369
  handle = await this.leases.resume(this.ownerCtx, { ...options, setup: this.#setup(options.setup) });
170
- this.#binding(binding.sessionId);
171
- return this.#track(binding.sessionId, lease, handle, deadlineAt, deadlineSignal);
370
+ this.#binding(webBinding.sessionId);
371
+ return await this.#track(webBinding.sessionId, lease, handle, deadlineAt, deadlineSignal);
172
372
  }
173
373
  catch (error) {
174
374
  lease.cancel();
175
375
  lease.close();
176
376
  if (handle !== undefined)
177
- void handle.dispose().catch(() => { });
377
+ void Promise.resolve(handle.dispose()).catch(() => { });
178
378
  throw error;
179
379
  }
180
380
  }
@@ -185,26 +385,69 @@ export class NativeWebOwner {
185
385
  if (agent === undefined || agent.session.header.cwd !== this.#config.workspace
186
386
  || agent.session.header.agentPreset !== this.#config.preset)
187
387
  throw new SessionLeaseUnavailable('denied');
188
- ctx.effect(() => this.policy.bindInitiator(agent, 'external', externalPrincipalId(this.#config.principal)));
388
+ if (!this.#boundAgents.has(agent)) {
389
+ this.#boundAgents.add(agent);
390
+ ctx.effect(() => this.policy.bindInitiator(agent, 'external', externalPrincipalId(this.#config.principal)));
391
+ }
189
392
  const prepared = await original?.(ctx, agent);
190
393
  return { commit: () => { this.#assertOwner(); prepared?.commit?.(); this.#assertOwner(); } };
191
394
  };
192
395
  }
193
- #track(id, lease, handle, deadlineAt, deadlineSignal) {
194
- const entry = { lease, handle, deadlineAt, deadlineSignal };
396
+ async #track(id, lease, handle, deadlineAt, deadlineSignal) {
397
+ let existing = this.#entries.get(id);
398
+ if (existing?.closing !== undefined) {
399
+ await existing.closing.catch(() => { });
400
+ existing = this.#entries.get(id);
401
+ }
402
+ if (existing !== undefined && existing.agent !== handle.agent) {
403
+ await this.#close(id, existing).catch(() => { });
404
+ existing = this.#entries.get(id);
405
+ }
406
+ const holder = { lease, handle, deadlineAt, deadlineSignal, closed: false };
407
+ if (existing !== undefined) {
408
+ existing.holders.add(holder);
409
+ return { agent: existing.agent, dispose: () => this.#releaseHolder(id, existing, holder) };
410
+ }
411
+ const entry = { agent: handle.agent, holders: new Set([holder]), completedTurnsBeforeAbort: new Set(), inputs: new Map() };
195
412
  this.#entries.set(id, entry);
196
413
  // The native header is emitted after adapter defaults resolve the actual
197
414
  // paid route. Never substitute the current UI/preset selection for it.
198
415
  entry.removeModelObservation = this.ownerCtx.on('session/event', (session, event) => {
199
- if (session !== handle.agent.session || event.type !== 'request/header')
416
+ if (session !== entry.agent.session || event.type !== 'request/header')
200
417
  return;
201
- const inboxId = entry.input?.executionInboxId;
202
- if (inboxId !== undefined)
203
- this.port.recordExecutionModelSelection(inboxId, event.data.header.config);
418
+ const eventTurn = event.data.turn;
419
+ for (const execInput of entry.inputs.values()) {
420
+ if (execInput.settled || execInput.executionInboxId === undefined)
421
+ continue;
422
+ if (eventTurn !== undefined && execInput.turn !== undefined && execInput.turn !== eventTurn)
423
+ continue;
424
+ this.port.recordExecutionModelSelection(execInput.executionInboxId, event.data.header.config);
425
+ }
204
426
  });
205
- return { agent: handle.agent, dispose: () => this.#close(id, entry) };
427
+ return { agent: entry.agent, dispose: () => this.#releaseHolder(id, entry, holder) };
428
+ }
429
+ async #releaseHolder(id, entry, holder) {
430
+ if (holder.closed)
431
+ return;
432
+ if (entry.closing !== undefined) {
433
+ await entry.closing;
434
+ return;
435
+ }
436
+ const now = Date.now();
437
+ const hasOtherActiveHolder = [...entry.holders].some(other => other !== holder && this.#isHolderActive(other, now));
438
+ if (hasOtherActiveHolder) {
439
+ holder.closed = true;
440
+ entry.holders.delete(holder);
441
+ holder.lease.cancel();
442
+ await Promise.resolve(holder.handle.dispose()).catch(() => { });
443
+ holder.lease.close();
444
+ return;
445
+ }
446
+ await this.#close(id, entry);
206
447
  }
207
448
  async prompt(input, invoke, signal) {
449
+ if (this.#disposed)
450
+ throw new SessionLeaseUnavailable('denied');
208
451
  signal.throwIfAborted();
209
452
  if (!input.content.length || input.content.some(part => typeof part !== 'object' || part === null
210
453
  || part.type !== 'text' || typeof part.text !== 'string')) {
@@ -212,11 +455,73 @@ export class NativeWebOwner {
212
455
  }
213
456
  if (input.text !== input.content.map(part => part.text).join(''))
214
457
  throw new Error('assistant-delivery: native input text does not match its content');
215
- const binding = this.#binding(input.sessionId);
458
+ const resolvedBinding = this.#binding(input.sessionId);
459
+ const trimmedText = input.text.trimStart();
460
+ const parsedVeto = parseDeliveryCommand({ kind: 'command', text: trimmedText });
461
+ if (parsedVeto?.name === 'veto' && typeof this.port.executeOwnerVeto === 'function') {
462
+ const binding = this.#ensureWebBinding(resolvedBinding.sessionId);
463
+ const vetoEnvelope = {
464
+ channel: 'web',
465
+ account: this.#config.principal.account,
466
+ eventId: input.requestId,
467
+ occurredAt: Date.now(),
468
+ principal: binding.principal,
469
+ conversation: binding.conversation,
470
+ kind: 'command',
471
+ text: trimmedText,
472
+ metadata: { 'native.content.sha256': createHash('sha256').update(JSON.stringify(input.content)).digest('hex') },
473
+ };
474
+ const accepted = this.store.claimNativeInbox({
475
+ envelope: vetoEnvelope,
476
+ binding,
477
+ ownerLineage: this.#lineage,
478
+ ownerId: this.#ownerId,
479
+ leaseMs: this.port.leaseMs,
480
+ });
481
+ if (accepted.duplicate || accepted.fencingToken === undefined) {
482
+ throw new Error('assistant-delivery: native input already admitted; inspect its Session');
483
+ }
484
+ const claim = { inboxId: accepted.record.id, ownerId: this.#ownerId, fencingToken: accepted.fencingToken };
485
+ try {
486
+ const decision = this.policy.authorize({
487
+ subject: { kind: 'external', id: externalPrincipalId(binding.principal) },
488
+ action: 'ingest',
489
+ resource: { kind: 'message', id: `inbound:web/${vetoEnvelope.account}` },
490
+ context: { initiator: 'external' },
491
+ }, { idempotencyKey: `message-inbound:${claim.inboxId}` });
492
+ if (decision.effect !== 'allow')
493
+ throw new SessionLeaseUnavailable('denied');
494
+ this.#assertOwner();
495
+ signal.throwIfAborted();
496
+ this.store.markInboxDispatching({ ...claim, binding });
497
+ await this.port.executeOwnerVeto(binding, vetoEnvelope, parsedVeto);
498
+ this.store.finishInbox({ ...claim, outcome: 'processed' });
499
+ return { accepted: true };
500
+ }
501
+ catch (error) {
502
+ this.store.finishInbox({
503
+ ...claim,
504
+ outcome: 'dead_letter',
505
+ failureCode: error instanceof Error ? error.message : 'native-veto-failed',
506
+ });
507
+ throw error;
508
+ }
509
+ }
216
510
  const entry = this.#entries.get(input.sessionId);
217
- if (entry === undefined || entry.closing !== undefined || entry.input !== undefined
218
- || entry.handle.agent.status !== 'idle' || (entry.handle.agent.inbox.nextTurn.length > 0 || entry.handle.agent.inbox.nextStep.length > 0))
511
+ if (entry === undefined || entry.closing !== undefined)
219
512
  throw new SessionLeaseUnavailable('busy');
513
+ const now = Date.now();
514
+ let activeHolder = this.#assertAnyActiveHolder(entry, false, now);
515
+ const staleHolders = [];
516
+ for (const holder of entry.holders) {
517
+ if (holder !== activeHolder && !holder.closed && !this.#isHolderActive(holder, now)) {
518
+ staleHolders.push(holder);
519
+ }
520
+ }
521
+ for (const holder of staleHolders) {
522
+ void this.#releaseHolder(input.sessionId, entry, holder);
523
+ }
524
+ const binding = this.#ensureWebBinding(resolvedBinding.sessionId);
220
525
  const envelope = { channel: 'web', account: this.#config.principal.account,
221
526
  eventId: input.requestId, occurredAt: Date.now(), principal: binding.principal,
222
527
  conversation: binding.conversation, kind: 'text', text: input.text,
@@ -226,6 +531,7 @@ export class NativeWebOwner {
226
531
  throw new Error('assistant-delivery: native input already admitted; inspect its Session');
227
532
  const claim = { inboxId: accepted.record.id, ownerId: this.#ownerId, fencingToken: accepted.fencingToken };
228
533
  let acceptance;
534
+ let execInput;
229
535
  try {
230
536
  const decision = this.policy.authorize({ subject: { kind: 'external', id: externalPrincipalId(binding.principal) },
231
537
  action: 'ingest', resource: { kind: 'message', id: `inbound:web/${envelope.account}` },
@@ -235,32 +541,92 @@ export class NativeWebOwner {
235
541
  acceptance = this.port.prepare(binding, envelope);
236
542
  this.#assertOwner();
237
543
  signal.throwIfAborted();
238
- const permit = this.leases.admitNativeInput(entry.handle.agent, { requestId: input.requestId, content: input.content,
544
+ const currentExecInput = {
545
+ requestId: input.requestId,
546
+ ...claim,
547
+ envelope,
548
+ ...(acceptance === undefined ? {} : { acceptance }),
549
+ permit: { inserted: () => false, dispose: () => { } },
550
+ admitting: true,
551
+ };
552
+ const permit = this.leases.admitNativeInput(entry.agent, { requestId: input.requestId, content: input.content,
239
553
  onClaimed: turn => {
240
554
  this.#binding(input.sessionId);
241
- if (entry.input === undefined)
555
+ if (currentExecInput.settled)
242
556
  throw new SessionLeaseUnavailable('denied');
243
- entry.input.turn = turn;
244
- this.port.claimed(entry.handle.agent, envelope, turn);
557
+ currentExecInput.turn = turn;
558
+ if (entry.completedTurnsBeforeAbort.has(turn)) {
559
+ currentExecInput.completed = true;
560
+ currentExecInput.completedBeforeDisposeAbort = true;
561
+ }
562
+ this.port.claimed(entry.agent, envelope, turn);
245
563
  } });
246
- entry.input = { ...claim, envelope, ...(acceptance === undefined ? {} : { acceptance }), permit, admitting: true };
564
+ currentExecInput.permit = permit;
565
+ execInput = currentExecInput;
566
+ entry.inputs.set(input.requestId, currentExecInput);
247
567
  const executionInboxId = this.port.beginExecution(binding, envelope);
248
568
  if (executionInboxId !== undefined)
249
- entry.input.executionInboxId = executionInboxId;
569
+ currentExecInput.executionInboxId = executionInboxId;
250
570
  this.store.markInboxDispatching({ ...claim, binding });
251
- entry.lease.assert();
571
+ activeHolder = this.#assertAnyActiveHolder(entry);
252
572
  const result = await invoke();
253
- entry.input.admitting = false;
573
+ currentExecInput.admitting = false;
574
+ if (currentExecInput.settled || entry.closing !== undefined) {
575
+ if (entry.closing !== undefined)
576
+ await entry.closing;
577
+ throw new SessionLeaseUnavailable('denied');
578
+ }
254
579
  if (!permit.inserted())
255
580
  throw new Error('assistant-delivery: native prompt did not insert its exact admitted message');
256
- entry.lease.assertAgent(entry.handle.agent);
581
+ activeHolder = this.#assertAnyActiveHolder(entry, true);
257
582
  return result;
258
583
  }
259
584
  catch (error) {
260
- if (entry.input !== undefined) {
261
- entry.terminationCause ??= entry.deadlineSignal.aborted ? 'execution-timeout' : 'runtime-error';
262
- entry.lease.cancel();
263
- await this.#close(input.sessionId, entry);
585
+ const catchNow = Date.now();
586
+ const hasOtherActiveHolder = [...entry.holders].some(holder => holder !== activeHolder && this.#isHolderActive(holder, catchNow));
587
+ const activeTimedOut = activeHolder.deadlineSignal.aborted || catchNow >= activeHolder.deadlineAt;
588
+ if (execInput !== undefined) {
589
+ if (execInput.settled)
590
+ throw error;
591
+ if (entry.closing !== undefined) {
592
+ await entry.closing;
593
+ throw error;
594
+ }
595
+ const nonClosedHolders = [...entry.holders].filter(holder => !holder.closed);
596
+ const allDeadlinesExpired = nonClosedHolders.length > 0
597
+ && nonClosedHolders.every(holder => holder.deadlineSignal.aborted || catchNow >= holder.deadlineAt);
598
+ const timedOut = activeTimedOut || allDeadlinesExpired;
599
+ if (entry.inputs.size <= 1 && !hasOtherActiveHolder) {
600
+ entry.terminationCause ??= timedOut ? 'execution-timeout' : 'runtime-error';
601
+ for (const holder of entry.holders)
602
+ holder.lease.cancel();
603
+ await this.#close(input.sessionId, entry);
604
+ }
605
+ else {
606
+ execInput.settled = true;
607
+ execInput.admitting = false;
608
+ execInput.permit.dispose();
609
+ entry.inputs.delete(input.requestId);
610
+ if (execInput.executionInboxId !== undefined) {
611
+ this.port.completeExecution(execInput.executionInboxId, {
612
+ status: 'failed',
613
+ quiescent: false,
614
+ termination: observeNativeTermination({
615
+ producer: 'native-web',
616
+ reason: undefined,
617
+ cause: timedOut ? 'execution-timeout' : 'runtime-error',
618
+ handleDisposed: false,
619
+ completed: false,
620
+ }),
621
+ });
622
+ }
623
+ if (execInput.acceptance !== undefined)
624
+ await this.port.complete(execInput.acceptance, { status: 'failed', quiescent: true });
625
+ this.store.finishInbox({ ...claim, outcome: 'dead_letter', failureCode: 'native-input-rejected' });
626
+ if (!this.#isHolderActive(activeHolder, catchNow)) {
627
+ await this.#releaseHolder(input.sessionId, entry, activeHolder);
628
+ }
629
+ }
264
630
  }
265
631
  else {
266
632
  if (acceptance !== undefined)
@@ -273,44 +639,214 @@ export class NativeWebOwner {
273
639
  #close(id, entry) {
274
640
  return entry.closing ??= this.#drain(id, entry).catch(() => {
275
641
  // A Store or sink outage retains its fenced claim for recovery, never replay.
276
- entry.lease.cancel();
277
- entry.lease.close();
278
- }).finally(() => entry.removeModelObservation?.());
642
+ for (const holder of entry.holders) {
643
+ holder.closed = true;
644
+ holder.lease.cancel();
645
+ holder.lease.close();
646
+ }
647
+ }).finally(() => {
648
+ entry.removeModelObservation?.();
649
+ entry.completedTurnsBeforeAbort.clear();
650
+ });
651
+ }
652
+ #reconcileCompletedTurnsBeforeAbort(entry) {
653
+ for (const execInput of entry.inputs.values()) {
654
+ if (!execInput.settled && execInput.turn !== undefined && entry.completedTurnsBeforeAbort.has(execInput.turn)) {
655
+ execInput.completed = true;
656
+ execInput.completedBeforeDisposeAbort = true;
657
+ }
658
+ }
659
+ }
660
+ hasActiveInputs() {
661
+ return this.#hasActiveInputs();
662
+ }
663
+ hasPendingDrain() {
664
+ for (const entry of this.#entries.values()) {
665
+ if (entry.closing === undefined)
666
+ return true;
667
+ for (const execInput of entry.inputs.values()) {
668
+ if (!execInput.settled)
669
+ return true;
670
+ }
671
+ }
672
+ return false;
673
+ }
674
+ #entryHasActiveInputs(entry) {
675
+ if (entry.closing !== undefined)
676
+ return false;
677
+ const events = entry.agent.session.snapshotEvents();
678
+ let hasActive = false;
679
+ for (const execInput of entry.inputs.values()) {
680
+ if (execInput.settled)
681
+ continue;
682
+ if (execInput.turn !== undefined) {
683
+ const terminal = events.findLast(event => event.type === 'turn/end' && event.data.turn === execInput.turn);
684
+ if (terminal?.type === 'turn/end') {
685
+ execInput.completed = terminal.data.reason.kind === 'completed';
686
+ if (execInput.completed && entry.completedTurnsBeforeAbort.has(execInput.turn)) {
687
+ execInput.completedBeforeDisposeAbort = true;
688
+ }
689
+ continue;
690
+ }
691
+ }
692
+ hasActive = true;
693
+ }
694
+ return hasActive;
695
+ }
696
+ #hasActiveInputs() {
697
+ for (const entry of this.#entries.values()) {
698
+ if (this.#entryHasActiveInputs(entry))
699
+ return true;
700
+ }
701
+ return false;
702
+ }
703
+ async #waitForActiveInputs(graceMs) {
704
+ const closeCompletedEntries = () => {
705
+ const closing = [];
706
+ for (const [id, entry] of this.#entries) {
707
+ if (entry.closing !== undefined)
708
+ continue;
709
+ const events = entry.agent.session.snapshotEvents();
710
+ let allSettledOrCompleted = true;
711
+ for (const execInput of entry.inputs.values()) {
712
+ if (execInput.settled)
713
+ continue;
714
+ if (execInput.turn === undefined) {
715
+ allSettledOrCompleted = false;
716
+ continue;
717
+ }
718
+ const terminal = events.findLast(event => event.type === 'turn/end' && event.data.turn === execInput.turn);
719
+ if (terminal?.type === 'turn/end') {
720
+ execInput.completed = terminal.data.reason.kind === 'completed';
721
+ if (execInput.completed && entry.completedTurnsBeforeAbort.has(execInput.turn)) {
722
+ execInput.completedBeforeDisposeAbort = true;
723
+ }
724
+ if (!execInput.completed)
725
+ allSettledOrCompleted = false;
726
+ continue;
727
+ }
728
+ allSettledOrCompleted = false;
729
+ }
730
+ if (allSettledOrCompleted
731
+ && entry.agent.status === 'idle'
732
+ && entry.agent.inbox.nextTurn.length === 0
733
+ && entry.agent.inbox.nextStep.length === 0
734
+ && !this.#awaitingNativeGoal(entry.agent)) {
735
+ closing.push(this.#close(id, entry));
736
+ }
737
+ }
738
+ return closing;
739
+ };
740
+ await new Promise(resolve => {
741
+ let finished = false;
742
+ let timeout;
743
+ let poll;
744
+ const done = () => {
745
+ if (finished)
746
+ return;
747
+ finished = true;
748
+ if (timeout !== undefined)
749
+ clearTimeout(timeout);
750
+ if (poll !== undefined)
751
+ clearInterval(poll);
752
+ this.#drainListeners.delete(check);
753
+ this.#controller.signal.removeEventListener('abort', onAbort);
754
+ resolve();
755
+ };
756
+ const onAbort = () => done();
757
+ const check = () => {
758
+ if (this.#controller.signal.aborted) {
759
+ done();
760
+ return;
761
+ }
762
+ const closing = closeCompletedEntries();
763
+ if (!this.#hasActiveInputs()) {
764
+ if (closing.length > 0) {
765
+ void Promise.allSettled(closing).then(() => done());
766
+ }
767
+ else {
768
+ done();
769
+ }
770
+ }
771
+ };
772
+ this.#controller.signal.addEventListener('abort', onAbort, { once: true });
773
+ this.#drainListeners.add(check);
774
+ poll = setInterval(check, 20);
775
+ poll.unref?.();
776
+ timeout = setTimeout(done, graceMs);
777
+ timeout.unref?.();
778
+ check();
779
+ });
279
780
  }
280
781
  async #drain(id, entry) {
281
782
  // Reuse the exact deadline that fenced construction; slow create/flush
282
783
  // must not turn its earlier timeout into an apparent lease revocation.
283
- if (entry.deadlineSignal.aborted)
784
+ const now = Date.now();
785
+ const holders = [...entry.holders];
786
+ const nonClosedHolders = holders.filter(holder => !holder.closed);
787
+ const hasActiveHolder = holders.some(holder => this.#isHolderActive(holder, now));
788
+ if (nonClosedHolders.length > 0
789
+ && nonClosedHolders.every(holder => holder.deadlineSignal.aborted || now >= holder.deadlineAt)) {
284
790
  entry.terminationCause ??= 'execution-timeout';
285
- if (entry.input?.turn !== undefined) {
286
- const terminal = entry.handle.agent.session.snapshotEvents().findLast(event => event.type === 'turn/end' && event.data.turn === entry.input.turn);
287
- if (terminal?.type === 'turn/end')
288
- entry.input.completed = terminal.data.reason.kind === 'completed';
289
- }
290
- const succeeded = entry.input?.completed === true && !entry.lease.signal.aborted;
291
- entry.lease.cancel();
292
- entry.lease.close();
791
+ }
792
+ const events = entry.agent.session.snapshotEvents();
793
+ for (const execInput of entry.inputs.values()) {
794
+ if (execInput.settled || execInput.turn === undefined)
795
+ continue;
796
+ const terminal = events.findLast(event => event.type === 'turn/end' && event.data.turn === execInput.turn);
797
+ if (terminal?.type === 'turn/end') {
798
+ execInput.completed = terminal.data.reason.kind === 'completed';
799
+ if (execInput.completed && entry.completedTurnsBeforeAbort.has(execInput.turn)) {
800
+ execInput.completedBeforeDisposeAbort = true;
801
+ }
802
+ }
803
+ }
804
+ const leaseAborted = !hasActiveHolder && holders.some(holder => holder.lease.signal.aborted);
805
+ for (const holder of holders) {
806
+ holder.closed = true;
807
+ holder.lease.cancel();
808
+ }
293
809
  let timeout;
294
810
  const quiescent = await Promise.race([
295
- entry.handle.dispose().then(() => true, () => false),
811
+ Promise.all(holders.map(holder => holder.handle.dispose())).then(() => true, () => false),
296
812
  new Promise(resolve => { timeout = setTimeout(() => resolve(false), 5_000); }),
297
813
  ]);
298
814
  clearTimeout(timeout);
299
- entry.input?.permit.dispose();
300
- if (entry.input !== undefined) {
301
- const status = !quiescent ? 'unknown' : succeeded ? 'succeeded' : entry.input.completed === false ? 'failed' : 'cancelled';
302
- const terminal = entry.input.turn === undefined ? undefined : entry.handle.agent.session.snapshotEvents().findLast(event => event.type === 'turn/end' && event.data.turn === entry.input.turn);
303
- if (entry.input.executionInboxId !== undefined)
304
- this.port.completeExecution(entry.input.executionInboxId, { status, quiescent,
815
+ for (const holder of holders) {
816
+ holder.lease.close();
817
+ }
818
+ const reloadFailureCode = entry.terminationCause === 'host-disposed'
819
+ ? (this.port.getReloadInterruptionCode?.() ?? 'service-reload-interrupted')
820
+ : undefined;
821
+ for (const execInput of entry.inputs.values()) {
822
+ if (execInput.settled)
823
+ continue;
824
+ execInput.settled = true;
825
+ execInput.permit.dispose();
826
+ const succeeded = execInput.completed === true && (!leaseAborted || execInput.completedBeforeDisposeAbort === true);
827
+ const status = !quiescent ? 'unknown' : succeeded ? 'succeeded' : execInput.completed === false ? 'failed' : 'cancelled';
828
+ const terminal = execInput.turn === undefined ? undefined : events.findLast(event => event.type === 'turn/end' && event.data.turn === execInput.turn);
829
+ if (execInput.executionInboxId !== undefined)
830
+ this.port.completeExecution(execInput.executionInboxId, { status, quiescent,
305
831
  termination: observeNativeTermination({ producer: 'native-web',
306
832
  reason: terminal?.type === 'turn/end' ? terminal.data.reason : undefined,
307
833
  cause: entry.terminationCause, handleDisposed: quiescent, completed: status === 'succeeded' }),
308
834
  });
309
- if (entry.input.acceptance !== undefined)
310
- await this.port.complete(entry.input.acceptance, { status, quiescent });
311
- this.store.finishInbox({ inboxId: entry.input.inboxId, ownerId: this.#ownerId, fencingToken: entry.input.fencingToken,
835
+ if (execInput.acceptance !== undefined)
836
+ await this.port.complete(execInput.acceptance, { status, quiescent });
837
+ const failedReloadCode = !(succeeded && quiescent) ? reloadFailureCode : undefined;
838
+ if (failedReloadCode !== undefined) {
839
+ const summary = summarizeTurnToolMutations(events, 0, execInput.turn);
840
+ try {
841
+ this.port.recordInterruptedTurnSummary?.(execInput.inboxId, failedReloadCode, summary);
842
+ }
843
+ catch { }
844
+ }
845
+ this.store.finishInbox({ inboxId: execInput.inboxId, ownerId: this.#ownerId, fencingToken: execInput.fencingToken,
312
846
  outcome: succeeded && quiescent ? 'processed' : 'dead_letter',
313
- ...(succeeded && quiescent ? {} : { failureCode: quiescent ? 'native-input-failed' : 'processor-ambiguous' }) });
847
+ ...(succeeded && quiescent
848
+ ? {}
849
+ : { failureCode: failedReloadCode ?? (quiescent ? 'native-input-failed' : 'processor-ambiguous') }) });
314
850
  }
315
851
  if (this.#entries.get(id) === entry)
316
852
  this.#entries.delete(id);
@@ -323,12 +859,49 @@ export class NativeWebOwner {
323
859
  return;
324
860
  this.#disposed = true;
325
861
  clearInterval(this.#timer);
862
+ const graceMs = Math.min(this.port.shutdownGraceMs ?? 0, Math.max(0, Math.floor(this.port.leaseMs / 2)));
863
+ if (graceMs > 0 && this.#hasActiveInputs()) {
864
+ await this.#waitForActiveInputs(graceMs);
865
+ }
866
+ // Start closing entries whose Web inputs are already completed (e.g. when a
867
+ // co-holder still keeps the shared Agent non-idle) before aborting
868
+ // #controller, and preserve pre-abort completions on mixed entries.
869
+ const closes = [];
870
+ for (const [id, entry] of this.#entries) {
871
+ if (entry.closing !== undefined) {
872
+ closes.push(entry.closing);
873
+ continue;
874
+ }
875
+ this.#reconcileCompletedTurnsBeforeAbort(entry);
876
+ if (!this.#entryHasActiveInputs(entry)) {
877
+ closes.push(this.#close(id, entry));
878
+ continue;
879
+ }
880
+ const disposeNow = Date.now();
881
+ const hasActiveHolder = [...entry.holders].some(holder => this.#isHolderActive(holder, disposeNow));
882
+ if (hasActiveHolder) {
883
+ for (const execInput of entry.inputs.values()) {
884
+ if (!execInput.settled && execInput.completed === true) {
885
+ execInput.completedBeforeDisposeAbort = true;
886
+ }
887
+ }
888
+ }
889
+ }
326
890
  this.#controller.abort();
327
891
  try {
328
- await Promise.all([...this.#entries].map(([id, entry]) => {
892
+ const now = Date.now();
893
+ for (const [id, entry] of this.#entries) {
894
+ if (entry.closing !== undefined)
895
+ continue;
896
+ const nonClosedHolders = [...entry.holders].filter(holder => !holder.closed);
897
+ if (nonClosedHolders.length > 0
898
+ && nonClosedHolders.every(holder => holder.deadlineSignal.aborted || now >= holder.deadlineAt)) {
899
+ entry.terminationCause ??= 'execution-timeout';
900
+ }
329
901
  entry.terminationCause ??= 'host-disposed';
330
- return this.#close(id, entry);
331
- }));
902
+ closes.push(this.#close(id, entry));
903
+ }
904
+ await Promise.all(closes);
332
905
  }
333
906
  finally {
334
907
  this.port.released();