@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
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { Context } from '@deepseek-ai/cordis';
2
3
  // Cordis publishes this as an erased const enum. Keep the value type-checked
3
4
  // against its exact member without requiring a nonexistent runtime export.
4
5
  const activeFiberState = 2;
@@ -9,23 +10,79 @@ export class SessionLeaseUnavailable extends Error {
9
10
  this.kind = kind;
10
11
  }
11
12
  }
13
+ const RESERVED_NON_NATIVE_INPUT_SOURCES = new Set([
14
+ 'delivery',
15
+ 'assistant-delivery',
16
+ 'goal',
17
+ 'assistant-goals',
18
+ 'subagent',
19
+ 'agent-message',
20
+ 'subagent-settled',
21
+ 'memory',
22
+ 'personal-memory',
23
+ 'ray-episodic',
24
+ 'ray-worker',
25
+ 'ray-worker-handback',
26
+ 'ray-dreaming',
27
+ 'assistant-dreaming',
28
+ 'assistant-proactive',
29
+ 'assistant-growth-driver',
30
+ 'assistant-automations',
31
+ 'assistant-memory-learning',
32
+ 'assistant-verifier',
33
+ 'assistant-evaluation',
34
+ 'assistant-policy',
35
+ 'assistant-evolution',
36
+ 'system',
37
+ 'runtime-context',
38
+ 'model-selection',
39
+ 'skill-catalog',
40
+ 'skill-invocation',
41
+ 'compact-checkpoint',
42
+ 'ptc-mode',
43
+ 'user-approval',
44
+ 'retry',
45
+ ]);
12
46
  /** One process-local owner of a durable token. Unknown is never a takeover grant. */
13
47
  export class SessionExecutionLease {
14
48
  token;
15
49
  port;
16
50
  released;
51
+ root;
52
+ promotableToCoHolder;
17
53
  controller = new AbortController();
18
54
  agents = new Map();
55
+ #coHolders = new Set();
56
+ #allowsCoHolders;
19
57
  #closed = false;
20
58
  #released = false;
59
+ #dispatched = false;
21
60
  #pending = 0;
22
61
  #unobservedCleanup = false;
23
62
  #timer;
24
63
  #removeAbort;
25
- constructor(token, port, outer, released) {
64
+ #removeRootAbort;
65
+ constructor(token, port, outer, released, allowsCoHolders = false, root, promotableToCoHolder = false) {
26
66
  this.token = token;
27
67
  this.port = port;
28
68
  this.released = released;
69
+ this.root = root;
70
+ this.promotableToCoHolder = promotableToCoHolder;
71
+ this.#allowsCoHolders = allowsCoHolders;
72
+ if (root !== undefined) {
73
+ const abortOuter = () => this.cancel(outer.reason);
74
+ outer.addEventListener('abort', abortOuter, { once: true });
75
+ this.#removeAbort = () => outer.removeEventListener('abort', abortOuter);
76
+ const abortRoot = () => { if (!this.signal.aborted)
77
+ this.controller.abort(root.signal.reason); };
78
+ root.signal.addEventListener('abort', abortRoot, { once: true });
79
+ this.#removeRootAbort = () => root.signal.removeEventListener('abort', abortRoot);
80
+ if (root.signal.aborted)
81
+ abortRoot();
82
+ if (outer.aborted)
83
+ abortOuter();
84
+ return;
85
+ }
29
86
  const abort = () => this.cancel(outer.reason);
30
87
  outer.addEventListener('abort', abort, { once: true });
31
88
  this.#removeAbort = () => outer.removeEventListener('abort', abort);
@@ -42,7 +99,50 @@ export class SessionExecutionLease {
42
99
  abort();
43
100
  }
44
101
  get signal() { return this.controller.signal; }
102
+ get allowsCoHolders() { return this.#allowsCoHolders; }
103
+ promoteToCoHolders() {
104
+ if (this.root !== undefined) {
105
+ this.root.promoteToCoHolders();
106
+ return;
107
+ }
108
+ if (this.promotableToCoHolder && !this.#closed && !this.#released && !this.signal.aborted) {
109
+ this.#allowsCoHolders = true;
110
+ }
111
+ }
112
+ canAddCoHolder() {
113
+ if (this.root !== undefined)
114
+ return this.root.canAddCoHolder();
115
+ return this.#allowsCoHolders && !this.#closed && !this.#released && !this.signal.aborted;
116
+ }
117
+ addCoHolder(outer, initialConstruction = false) {
118
+ if (this.root !== undefined)
119
+ return this.root.addCoHolder(outer, initialConstruction);
120
+ if (initialConstruction) {
121
+ if (!this.promotableToCoHolder || this.#closed || this.#released || this.signal.aborted) {
122
+ throw new SessionLeaseUnavailable('denied');
123
+ }
124
+ }
125
+ else if (!this.canAddCoHolder()) {
126
+ throw new SessionLeaseUnavailable('denied');
127
+ }
128
+ const holder = new SessionExecutionLease(this.token, this.port, outer, () => { }, true, this);
129
+ this.#coHolders.add(holder);
130
+ return holder;
131
+ }
132
+ #activeCoHolderCount() {
133
+ let count = 0;
134
+ for (const holder of this.#coHolders)
135
+ if (!holder.#closed && !holder.signal.aborted)
136
+ count += 1;
137
+ return count;
138
+ }
45
139
  assert() {
140
+ if (this.root !== undefined) {
141
+ if (this.#closed || this.signal.aborted)
142
+ throw new SessionLeaseUnavailable('denied');
143
+ this.root.assert();
144
+ return;
145
+ }
46
146
  if (this.#closed || this.#released || this.signal.aborted)
47
147
  throw new SessionLeaseUnavailable('denied');
48
148
  try {
@@ -54,24 +154,54 @@ export class SessionExecutionLease {
54
154
  throw new SessionLeaseUnavailable('denied');
55
155
  }
56
156
  assertAgent(agent) {
157
+ if (this.root !== undefined) {
158
+ this.assert();
159
+ this.root.assertAgent(agent);
160
+ return;
161
+ }
57
162
  this.assert();
58
163
  if (this.agents.get(agent) !== false)
59
164
  throw new SessionLeaseUnavailable('denied');
60
165
  }
61
166
  dispatch() {
167
+ if (this.root !== undefined) {
168
+ this.assert();
169
+ if (!this.root.#dispatched)
170
+ this.root.dispatch();
171
+ return;
172
+ }
62
173
  this.assert();
174
+ if (this.#dispatched)
175
+ return;
63
176
  if (!this.port.dispatch(this.token)) {
64
177
  this.cancel();
65
178
  throw new SessionLeaseUnavailable('denied');
66
179
  }
180
+ this.#dispatched = true;
181
+ }
182
+ attach(agent) {
183
+ if (this.root !== undefined) {
184
+ this.assert();
185
+ this.root.attach(agent);
186
+ return;
187
+ }
188
+ this.assert();
189
+ this.agents.set(agent, false);
67
190
  }
68
- attach(agent) { this.assert(); this.agents.set(agent, false); }
69
191
  disposed(agent) {
192
+ if (this.root !== undefined) {
193
+ this.root.disposed(agent);
194
+ return;
195
+ }
70
196
  if (this.agents.has(agent))
71
197
  this.agents.set(agent, true);
72
198
  this.#settle();
73
199
  }
74
200
  enter() {
201
+ if (this.root !== undefined) {
202
+ this.assert();
203
+ return this.root.enter();
204
+ }
75
205
  this.assert();
76
206
  this.#pending += 1;
77
207
  let done = false;
@@ -79,8 +209,19 @@ export class SessionExecutionLease {
79
209
  return; done = true; this.#pending -= 1; this.#settle(); };
80
210
  }
81
211
  cancel(reason = new SessionLeaseUnavailable('denied')) {
212
+ if (this.root !== undefined) {
213
+ if (!this.signal.aborted)
214
+ this.controller.abort(reason);
215
+ if (this.root.#activeCoHolderCount() === 0)
216
+ this.root.cancel(reason);
217
+ return;
218
+ }
82
219
  if (!this.signal.aborted)
83
220
  this.controller.abort(reason);
221
+ for (const holder of this.#coHolders) {
222
+ if (!holder.signal.aborted)
223
+ holder.controller.abort(reason);
224
+ }
84
225
  for (const [agent, disposed] of this.agents)
85
226
  if (!disposed) {
86
227
  try {
@@ -90,15 +231,37 @@ export class SessionExecutionLease {
90
231
  }
91
232
  }
92
233
  close() {
234
+ if (this.root !== undefined) {
235
+ if (this.#closed)
236
+ return;
237
+ this.#closed = true;
238
+ this.#removeAbort();
239
+ this.#removeRootAbort?.();
240
+ this.root.#coHolders.delete(this);
241
+ if (this.root.#coHolders.size === 0)
242
+ this.root.close();
243
+ return;
244
+ }
93
245
  if (this.#closed)
94
246
  return;
95
247
  this.#closed = true;
96
- clearInterval(this.#timer);
248
+ if (this.#timer !== undefined)
249
+ clearInterval(this.#timer);
97
250
  this.#removeAbort();
98
251
  this.#settle();
99
252
  }
100
253
  /** A rejected cold resume can leave an unobservable, abort-raced load behind. */
101
254
  abandonConstruction() {
255
+ if (this.root !== undefined) {
256
+ const hasOtherActiveCoHolder = [...this.root.#coHolders].some(holder => holder !== this && !holder.#closed && !holder.signal.aborted);
257
+ if (!hasOtherActiveCoHolder)
258
+ this.root.abandonConstruction();
259
+ else {
260
+ this.cancel();
261
+ this.close();
262
+ }
263
+ return;
264
+ }
102
265
  this.#unobservedCleanup = true;
103
266
  this.cancel();
104
267
  this.close();
@@ -121,10 +284,14 @@ export class DeliverySessionLeases {
121
284
  ctx;
122
285
  port;
123
286
  #active = new Map();
287
+ #sharedHandles = new Map();
288
+ #drainingHandles = new Map();
124
289
  #agents = new WeakMap();
125
290
  #nativeInputs = new WeakMap();
126
291
  #factoryGeneration = 0;
127
292
  #live = true;
293
+ #teardownFinished = false;
294
+ #teardownPromise;
128
295
  constructor(ctx, port) {
129
296
  this.ctx = ctx;
130
297
  this.port = port;
@@ -135,27 +302,57 @@ export class DeliverySessionLeases {
135
302
  this.#factoryGeneration += 1;
136
303
  });
137
304
  const nativeInput = (agent, message, turn) => {
138
- if (message.source !== undefined && message.source.kind !== 'user')
139
- return;
140
- const permit = this.#nativeInputs.get(agent);
141
305
  const source = message.source;
142
- try {
143
- this.#agents.get(agent)?.assertAgent(agent);
144
- if (permit !== undefined && source?.kind === 'user' && source.rpcId === permit.requestId
145
- && JSON.stringify(message.content) === permit.content) {
146
- if (turn === undefined && permit.message === undefined) {
147
- permit.message = message;
148
- return;
306
+ const permits = this.#nativeInputs.get(agent);
307
+ const lease = this.#agents.get(agent);
308
+ if (source !== undefined && source.kind !== 'user') {
309
+ if (RESERVED_NON_NATIVE_INPUT_SOURCES.has(String(source.kind ?? '')))
310
+ return;
311
+ if (permits === undefined || permits.size === 0)
312
+ return;
313
+ const serialized = JSON.stringify(message.content);
314
+ try {
315
+ lease?.assertAgent(agent);
316
+ for (const permit of permits) {
317
+ if (permit.content !== serialized)
318
+ continue;
319
+ if (turn === undefined && permit.message === undefined) {
320
+ permit.message = message;
321
+ return;
322
+ }
323
+ if (turn !== undefined && permit.message === message && !permit.claimed) {
324
+ permit.claimed = true;
325
+ permit.onClaimed(turn);
326
+ return;
327
+ }
149
328
  }
150
- if (turn !== undefined && permit.message === message && !permit.claimed) {
151
- permit.claimed = true;
152
- permit.onClaimed(turn);
153
- return;
329
+ }
330
+ catch {
331
+ lease?.cancel();
332
+ }
333
+ return;
334
+ }
335
+ try {
336
+ lease?.assertAgent(agent);
337
+ if (permits !== undefined && source?.kind === 'user' && typeof source.rpcId === 'string') {
338
+ const serialized = JSON.stringify(message.content);
339
+ for (const permit of permits) {
340
+ if (source.rpcId === permit.requestId && serialized === permit.content) {
341
+ if (turn === undefined && permit.message === undefined) {
342
+ permit.message = message;
343
+ return;
344
+ }
345
+ if (turn !== undefined && permit.message === message && !permit.claimed) {
346
+ permit.claimed = true;
347
+ permit.onClaimed(turn);
348
+ return;
349
+ }
350
+ }
154
351
  }
155
352
  }
156
353
  }
157
354
  catch { /* A stale or invalid exact admission cancels the whole lane. */ }
158
- this.#agents.get(agent)?.cancel();
355
+ lease?.cancel();
159
356
  };
160
357
  ctx.on('agent/inbox/inserted', ({ agent, message }) => nativeInput(agent, message), { prepend: true });
161
358
  ctx.on('agent/inbox/claimed', ({ agent, message, turn }) => nativeInput(agent, message, turn), { prepend: true });
@@ -195,68 +392,322 @@ export class DeliverySessionLeases {
195
392
  ctx.on('llm/stream', this.#stream.bind(this), { prepend: true });
196
393
  ctx.effect(() => () => {
197
394
  this.#live = false;
198
- for (const lease of this.#active.values()) {
199
- lease.cancel();
200
- lease.close();
395
+ const drainInbound = this.port.hasActiveInboundDrain?.() === true && this.port.onInboundDisposeDrain !== undefined;
396
+ const drainNative = this.port.hasActiveNativeDrain?.() === true && this.port.onNativeDisposeDrain !== undefined;
397
+ if (!drainInbound && !drainNative) {
398
+ for (const lease of this.#active.values()) {
399
+ lease.cancel();
400
+ lease.close();
401
+ }
402
+ return;
201
403
  }
404
+ const teardown = (this.#teardownPromise ??= Promise.all([
405
+ drainInbound ? this.port.onInboundDisposeDrain().catch(() => { }) : undefined,
406
+ drainNative ? this.port.onNativeDisposeDrain().catch(() => { }) : undefined,
407
+ ]).then(() => {
408
+ for (const lease of this.#active.values()) {
409
+ lease.cancel();
410
+ lease.close();
411
+ }
412
+ }));
413
+ return teardown;
202
414
  }, 'assistant-delivery.session-leases');
203
415
  }
204
- /** Host-only, one occurrence: a client source tag alone never grants owner authority. */
416
+ #waitOwnerDrain(owner) {
417
+ if (owner === this.ctx) {
418
+ if (this.port.hasActiveInboundDrain?.() === true && this.port.onInboundDisposeDrain !== undefined) {
419
+ return this.port.onInboundDisposeDrain().catch(() => { });
420
+ }
421
+ return undefined;
422
+ }
423
+ if (this.port.hasActiveNativeDrain?.() === true && this.port.onNativeDisposeDrain !== undefined) {
424
+ return this.port.onNativeDisposeDrain().catch(() => { });
425
+ }
426
+ return undefined;
427
+ }
428
+ beginShutdown() {
429
+ this.#live = false;
430
+ }
431
+ async finishTeardown() {
432
+ this.#live = false;
433
+ this.#teardownFinished = true;
434
+ if (this.#teardownPromise !== undefined) {
435
+ await this.#teardownPromise;
436
+ }
437
+ for (const lease of this.#active.values()) {
438
+ lease.cancel();
439
+ lease.close();
440
+ }
441
+ }
442
+ /** Host-only, one occurrence per permit: a client source tag alone never grants owner authority. */
205
443
  admitNativeInput(agent, input) {
206
444
  const lease = this.#agents.get(agent);
207
- if (lease === undefined || this.#nativeInputs.has(agent))
445
+ if (lease === undefined)
208
446
  throw new SessionLeaseUnavailable('denied');
209
447
  lease.assertAgent(agent);
210
- const permit = { requestId: input.requestId, content: JSON.stringify(input.content),
211
- claimed: false, onClaimed: input.onClaimed, message: undefined };
212
- this.#nativeInputs.set(agent, permit);
213
- return { inserted: () => permit.message !== undefined, dispose: () => {
214
- if (this.#nativeInputs.get(agent) === permit)
448
+ const sessionId = String(agent.session.id);
449
+ let permits = this.#nativeInputs.get(agent);
450
+ if (permits !== undefined && permits.size > 0) {
451
+ if (this.port.isActiveOwnerSession?.(sessionId) !== true)
452
+ throw new SessionLeaseUnavailable('denied');
453
+ for (const existing of permits) {
454
+ if (existing.requestId === input.requestId)
455
+ throw new SessionLeaseUnavailable('denied');
456
+ }
457
+ }
458
+ if (permits === undefined) {
459
+ permits = new Set();
460
+ this.#nativeInputs.set(agent, permits);
461
+ }
462
+ const permit = {
463
+ requestId: input.requestId,
464
+ content: JSON.stringify(input.content),
465
+ claimed: false,
466
+ onClaimed: input.onClaimed,
467
+ message: undefined,
468
+ };
469
+ permits.add(permit);
470
+ return {
471
+ inserted: () => permit.message !== undefined,
472
+ dispose: () => {
473
+ const current = this.#nativeInputs.get(agent);
474
+ if (current === undefined)
475
+ return;
476
+ current.delete(permit);
477
+ if (current.size === 0)
215
478
  this.#nativeInputs.delete(agent);
216
- } };
479
+ },
480
+ };
217
481
  }
218
482
  get leaseMs() { return this.port.leaseMs; }
483
+ async waitForDrain(sessionId) {
484
+ const draining = this.#drainingHandles.get(sessionId);
485
+ if (draining !== undefined)
486
+ await draining.catch(() => { });
487
+ }
488
+ #resolveAgentOwnerScopeHost(owner) {
489
+ let host = owner;
490
+ while (host !== undefined
491
+ && host.fiber !== undefined
492
+ && host.fiber.uid !== 0
493
+ && (host.fiber === owner.fiber
494
+ || host.fiber === this.ctx.fiber
495
+ || host.fiber === this.port.serviceFiber
496
+ || host.fiber.uid === null
497
+ || host.fiber.state !== activeFiberState)) {
498
+ const parent = host.fiber.parent;
499
+ if (parent === undefined || parent === host)
500
+ break;
501
+ host = parent;
502
+ }
503
+ if (host === undefined
504
+ || host === owner
505
+ || host.fiber === undefined
506
+ || host.fiber.uid === null
507
+ || host.fiber.state !== activeFiberState)
508
+ return undefined;
509
+ const hostIsolate = host[Context.isolate];
510
+ const ownerIsolate = owner[Context.isolate];
511
+ if (hostIsolate === undefined || ownerIsolate === undefined)
512
+ return undefined;
513
+ if (hostIsolate['agents'] !== ownerIsolate['agents'] || hostIsolate['sessions'] !== ownerIsolate['sessions']) {
514
+ return undefined;
515
+ }
516
+ return host;
517
+ }
518
+ #traceAgentsFor(agentOwner) {
519
+ const rawAgents = this.ctx.agents?.[Symbol.for('cordis.original')];
520
+ return agentOwner.reflect.trace(rawAgents ?? this.ctx.agents);
521
+ }
219
522
  /**
220
523
  * Use the host's one factory and the caller's ownership scope. These methods
221
524
  * only consume an already admitted lease; they do not authorize Web input.
222
525
  */
223
- create(owner, options) {
224
- const agents = owner.reflect.trace(this.ctx.agents);
225
- return this.#construct(owner, 'create', String(options.sessionId), options, (setup, signal) => agents.create({ ...options, setup, signal }));
526
+ create(owner, options, internalOptions) {
527
+ return this.#construct(owner, 'create', String(options.sessionId), options, (agentOwner, setup, signal) => this.#traceAgentsFor(agentOwner).create({ ...options, setup, signal }), internalOptions);
226
528
  }
227
- resume(owner, options) {
228
- const agents = owner.reflect.trace(this.ctx.agents);
229
- return this.#construct(owner, 'resume', String(options.resumeSessionId), options, (setup, signal) => agents.resume({ ...options, setup, signal }));
529
+ resume(owner, options, internalOptions) {
530
+ return this.#construct(owner, 'resume', String(options.resumeSessionId), options, (agentOwner, setup, signal) => this.#traceAgentsFor(agentOwner).resume({ ...options, setup, signal }), internalOptions);
230
531
  }
231
- async #construct(owner, kind, sessionId, options, factory) {
532
+ #wrapSharedHandle(owner, root, shared) {
533
+ const drain = () => {
534
+ if (shared.drainPromise !== undefined)
535
+ return shared.drainPromise;
536
+ shared.drainPromise = Promise.resolve()
537
+ .then(() => shared.handle.dispose())
538
+ .then(() => root.disposed(shared.handle.agent))
539
+ .finally(() => shared.disposeScope?.());
540
+ return shared.drainPromise;
541
+ };
542
+ let released = false;
543
+ let detached = false;
544
+ const releaseCoHolder = async () => {
545
+ if (released)
546
+ return;
547
+ released = true;
548
+ shared.refs -= 1;
549
+ if (shared.refs > 0)
550
+ return;
551
+ shared.disposed = true;
552
+ if (this.#sharedHandles.get(shared.sessionId) === shared)
553
+ this.#sharedHandles.delete(shared.sessionId);
554
+ const draining = drain().finally(() => {
555
+ if (this.#drainingHandles.get(shared.sessionId) === draining)
556
+ this.#drainingHandles.delete(shared.sessionId);
557
+ });
558
+ this.#drainingHandles.set(shared.sessionId, draining);
559
+ await draining;
560
+ };
561
+ const detachOwner = owner.effect(() => async () => {
562
+ if (detached)
563
+ return;
564
+ detached = true;
565
+ const ownerDrain = this.#waitOwnerDrain(owner);
566
+ if (ownerDrain !== undefined)
567
+ await ownerDrain;
568
+ if (!released && shared.refs <= 1 && !shared.disposed) {
569
+ root.cancel();
570
+ }
571
+ await releaseCoHolder();
572
+ if (shared.refs <= 0) {
573
+ root.close();
574
+ }
575
+ }, 'assistant-delivery.owned-agent');
576
+ return {
577
+ agent: shared.handle.agent,
578
+ dispose: async () => {
579
+ await releaseCoHolder();
580
+ if (!detached) {
581
+ detached = true;
582
+ await detachOwner();
583
+ }
584
+ },
585
+ };
586
+ }
587
+ async #construct(owner, kind, sessionId, options, factory, internalOptions) {
232
588
  const lease = this.#active.get(sessionId);
233
589
  if (lease === undefined)
234
590
  throw new SessionLeaseUnavailable('denied');
591
+ if (kind === 'resume' && lease.allowsCoHolders) {
592
+ while (true) {
593
+ const draining = this.#drainingHandles.get(sessionId);
594
+ if (draining !== undefined) {
595
+ await draining.catch(() => { });
596
+ continue;
597
+ }
598
+ const existing = this.#sharedHandles.get(sessionId);
599
+ if (existing === undefined || existing.root !== lease || existing.disposed)
600
+ break;
601
+ if (existing.constructing !== undefined) {
602
+ await existing.constructing.catch(() => { });
603
+ continue;
604
+ }
605
+ if (existing.handle !== undefined && existing.agentCtx !== undefined) {
606
+ lease.assert();
607
+ options.signal?.throwIfAborted();
608
+ const finishJoin = lease.enter();
609
+ existing.refs += 1;
610
+ try {
611
+ const setup = await options.setup?.(existing.agentCtx, existing.handle.agent);
612
+ lease.assertAgent(existing.handle.agent);
613
+ setup?.commit?.();
614
+ lease.assertAgent(existing.handle.agent);
615
+ return this.#wrapSharedHandle(owner, lease, existing);
616
+ }
617
+ catch (error) {
618
+ existing.refs -= 1;
619
+ if (existing.refs <= 0 && !existing.disposed) {
620
+ existing.disposed = true;
621
+ if (this.#sharedHandles.get(sessionId) === existing)
622
+ this.#sharedHandles.delete(sessionId);
623
+ const draining = (existing.drainPromise ??= Promise.resolve()
624
+ .then(() => existing.handle.dispose())
625
+ .then(() => existing.root.disposed(existing.handle.agent))
626
+ .finally(() => existing.disposeScope?.())).finally(() => {
627
+ if (this.#drainingHandles.get(sessionId) === draining)
628
+ this.#drainingHandles.delete(sessionId);
629
+ });
630
+ this.#drainingHandles.set(sessionId, draining);
631
+ await draining.catch(() => { });
632
+ }
633
+ throw error;
634
+ }
635
+ finally {
636
+ finishJoin();
637
+ }
638
+ }
639
+ break;
640
+ }
641
+ }
235
642
  lease.assert();
236
643
  options.signal?.throwIfAborted();
644
+ const scopeHost = this.#resolveAgentOwnerScopeHost(owner);
645
+ const ownerUnloading = owner.fiber !== undefined && (owner.fiber.uid === null || owner.fiber.state !== activeFiberState);
646
+ const effectOwner = internalOptions?.allowDuringDrain === true && ownerUnloading && scopeHost !== undefined
647
+ ? scopeHost
648
+ : owner;
237
649
  const ownerAbort = new AbortController();
238
650
  let constructing = true;
239
- const unwatchOwner = owner.effect(() => () => {
651
+ const unwatchOwner = effectOwner.effect(() => () => {
240
652
  if (constructing)
241
653
  ownerAbort.abort(new SessionLeaseUnavailable('denied'));
242
654
  }, 'assistant-delivery.agent-construction');
243
- const signal = AbortSignal.any([lease.signal, ownerAbort.signal, ...(options.signal === undefined ? [] : [options.signal])]);
655
+ const signal = (lease.allowsCoHolders || lease.promotableToCoHolder)
656
+ ? AbortSignal.any([lease.signal, ownerAbort.signal])
657
+ : AbortSignal.any([lease.signal, ownerAbort.signal, ...(options.signal === undefined ? [] : [options.signal])]);
244
658
  const factoryGeneration = this.#factoryGeneration;
245
659
  const nativeFactory = this.ctx.get('agentLoop') !== undefined;
246
660
  // A cold persistence load may not have produced an Agent yet. It still
247
661
  // occupies the lease until the factory settles and native rollback drains.
248
662
  let finishConstruction;
249
663
  let prepared;
664
+ let preparedCtx;
250
665
  let native;
666
+ let sharedEntry;
667
+ let resolveSharedConstruction;
668
+ let disposeScope;
669
+ let agentOwner = owner;
670
+ if ((kind === 'resume' && lease.allowsCoHolders) || (kind === 'create' && lease.promotableToCoHolder)) {
671
+ let resolve;
672
+ const constructingPromise = new Promise(r => { resolve = r; });
673
+ resolveSharedConstruction = resolve;
674
+ sharedEntry = { sessionId, root: lease, refs: 1, disposed: false, constructing: constructingPromise };
675
+ this.#sharedHandles.set(sessionId, sharedEntry);
676
+ }
251
677
  try {
252
678
  finishConstruction = lease.enter();
253
- native = await factory(async (agentCtx, preparedAgent) => {
679
+ if (scopeHost !== undefined) {
680
+ let scopedCtx;
681
+ const entryKey = Symbol.for('cordis.entry');
682
+ const pluginHost = scopeHost[entryKey] !== undefined
683
+ ? scopeHost.extend({ [entryKey]: undefined })
684
+ : scopeHost;
685
+ const scopeFiber = pluginHost.plugin({
686
+ name: 'assistant-delivery-agent-lease-scope',
687
+ apply: ctx => { scopedCtx = ctx; },
688
+ });
689
+ disposeScope = async () => {
690
+ if (scopeFiber.uid !== null)
691
+ await Promise.resolve(scopeFiber.dispose()).catch(() => { });
692
+ };
693
+ await scopeFiber;
694
+ if (ownerAbort.signal.aborted)
695
+ throw ownerAbort.signal.reason;
696
+ if (scopedCtx === undefined || scopedCtx.fiber.uid === null || scopedCtx.fiber.state !== activeFiberState) {
697
+ throw new SessionLeaseUnavailable('denied');
698
+ }
699
+ agentOwner = scopedCtx;
700
+ if (sharedEntry !== undefined)
701
+ sharedEntry.disposeScope = disposeScope;
702
+ }
703
+ native = await factory(agentOwner, async (agentCtx, preparedAgent) => {
254
704
  const agent = preparedAgent;
255
705
  if (agent === undefined || String(agent.session.id) !== sessionId)
256
706
  throw new SessionLeaseUnavailable('denied');
257
707
  lease.attach(agent);
258
708
  this.#agents.set(agent, lease);
259
709
  prepared = agent;
710
+ preparedCtx = agentCtx;
260
711
  const setup = await options.setup?.(agentCtx, agent);
261
712
  lease.assertAgent(agent);
262
713
  // Preserve the native setup commit and revalidate at publication, not
@@ -271,18 +722,29 @@ export class DeliverySessionLeases {
271
722
  throw new SessionLeaseUnavailable('denied');
272
723
  lease.assertAgent(native.agent);
273
724
  const handle = native;
725
+ if (sharedEntry !== undefined && preparedCtx !== undefined) {
726
+ sharedEntry.handle = handle;
727
+ sharedEntry.agentCtx = preparedCtx;
728
+ sharedEntry.constructing = undefined;
729
+ resolveSharedConstruction?.();
730
+ return this.#wrapSharedHandle(owner, lease, sharedEntry);
731
+ }
274
732
  let disposal;
275
733
  const drain = () => disposal ??= Promise.resolve().then(() => handle.dispose())
276
- .then(() => lease.disposed(handle.agent));
734
+ .then(() => lease.disposed(handle.agent))
735
+ .finally(() => disposeScope?.());
277
736
  let detached = false;
278
737
  // Controller consumers may retain only the Agent. The owner's fiber
279
738
  // must still await the native memoized disposer, not merely observe an
280
739
  // idle status or a registry notification. This also covers concurrent
281
740
  // teardown by the upstream factory's own owner effect.
282
- const detachOwner = owner.effect(() => async () => {
741
+ const detachOwner = effectOwner.effect(() => async () => {
283
742
  if (detached)
284
743
  return;
285
744
  detached = true;
745
+ const ownerDrain = this.#waitOwnerDrain(owner);
746
+ if (ownerDrain !== undefined)
747
+ await ownerDrain;
286
748
  lease.cancel();
287
749
  lease.close();
288
750
  await drain();
@@ -296,6 +758,13 @@ export class DeliverySessionLeases {
296
758
  } };
297
759
  }
298
760
  catch (error) {
761
+ if (sharedEntry !== undefined) {
762
+ sharedEntry.disposed = true;
763
+ sharedEntry.constructing = undefined;
764
+ if (this.#sharedHandles.get(sessionId) === sharedEntry)
765
+ this.#sharedHandles.delete(sessionId);
766
+ resolveSharedConstruction?.();
767
+ }
299
768
  // rc.1 races prepare against caller, owner and factory cancellation.
300
769
  // Only an unchanged live native factory + live owner + non-aborted
301
770
  // caller rules out all three abort branches. Otherwise the rejected
@@ -314,6 +783,7 @@ export class DeliverySessionLeases {
314
783
  await native.dispose();
315
784
  if (prepared !== undefined)
316
785
  lease.disposed(prepared);
786
+ await disposeScope?.();
317
787
  throw error;
318
788
  }
319
789
  finally {
@@ -326,13 +796,42 @@ export class DeliverySessionLeases {
326
796
  }
327
797
  }
328
798
  }
329
- open(target, signal) {
330
- if (!this.#live)
799
+ open(target, signal, options) {
800
+ const allowDrainConstruction = options?.allowDuringDrain === true
801
+ && target.kind === 'construction'
802
+ && !this.#teardownFinished;
803
+ if (!this.#live && !allowDrainConstruction)
331
804
  throw new SessionLeaseUnavailable('denied');
332
805
  signal.throwIfAborted();
806
+ const sessionId = target.kind === 'bound' ? target.binding.sessionId : target.sessionId;
807
+ const allowConcurrent = options?.allowConcurrentOwner === true
808
+ && target.kind === 'bound'
809
+ && this.port.isActiveOwnerSession?.(sessionId) === true;
810
+ const existingRoot = this.#active.get(sessionId);
811
+ if (allowConcurrent && existingRoot !== undefined && existingRoot.canAddCoHolder()) {
812
+ return existingRoot.addCoHolder(signal);
813
+ }
333
814
  const claim = this.port.claim(target, `delivery-session-${randomUUID()}`, this.port.leaseMs);
334
815
  if (claim.kind !== 'claimed')
335
816
  throw new SessionLeaseUnavailable(claim.kind);
817
+ if (options?.promotableToCoHolder === true) {
818
+ const rootAbort = new AbortController();
819
+ const root = new SessionExecutionLease(claim.lease, this.port, rootAbort.signal, () => {
820
+ if (this.#active.get(claim.lease.sessionId) === root)
821
+ this.#active.delete(claim.lease.sessionId);
822
+ }, false, undefined, true);
823
+ this.#active.set(claim.lease.sessionId, root);
824
+ return root.addCoHolder(signal, true);
825
+ }
826
+ if (allowConcurrent) {
827
+ const rootAbort = new AbortController();
828
+ const root = new SessionExecutionLease(claim.lease, this.port, rootAbort.signal, () => {
829
+ if (this.#active.get(claim.lease.sessionId) === root)
830
+ this.#active.delete(claim.lease.sessionId);
831
+ }, true);
832
+ this.#active.set(claim.lease.sessionId, root);
833
+ return root.addCoHolder(signal);
834
+ }
336
835
  const lease = new SessionExecutionLease(claim.lease, this.port, signal, () => {
337
836
  if (this.#active.get(claim.lease.sessionId) === lease)
338
837
  this.#active.delete(claim.lease.sessionId);
@@ -340,6 +839,17 @@ export class DeliverySessionLeases {
340
839
  this.#active.set(claim.lease.sessionId, lease);
341
840
  return lease;
342
841
  }
842
+ promoteToCoHolders(sessionId) {
843
+ if (!this.#live)
844
+ return false;
845
+ if (this.port.isActiveOwnerSession?.(sessionId) !== true)
846
+ return false;
847
+ const root = this.#active.get(sessionId);
848
+ if (root === undefined || !root.promotableToCoHolder)
849
+ return false;
850
+ root.promoteToCoHolders();
851
+ return root.canAddCoHolder();
852
+ }
343
853
  attach(agent) {
344
854
  const lease = this.#active.get(String(agent.session.id));
345
855
  if (lease === undefined)