@fabric-harness/sdk 6.0.0 → 6.1.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 (48) hide show
  1. package/dist/abort.d.ts +16 -0
  2. package/dist/abort.d.ts.map +1 -0
  3. package/dist/abort.js +82 -0
  4. package/dist/abort.js.map +1 -0
  5. package/dist/history.d.ts +2 -2
  6. package/dist/history.d.ts.map +1 -1
  7. package/dist/history.js +101 -66
  8. package/dist/history.js.map +1 -1
  9. package/dist/index.d.ts +1 -1
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +1 -1
  12. package/dist/index.js.map +1 -1
  13. package/dist/loop.d.ts +10 -8
  14. package/dist/loop.d.ts.map +1 -1
  15. package/dist/loop.js +120 -73
  16. package/dist/loop.js.map +1 -1
  17. package/dist/model.d.ts +2 -0
  18. package/dist/model.d.ts.map +1 -1
  19. package/dist/model.js +1 -1
  20. package/dist/model.js.map +1 -1
  21. package/dist/otel-observer.d.ts +6 -4
  22. package/dist/otel-observer.d.ts.map +1 -1
  23. package/dist/otel-observer.js +139 -52
  24. package/dist/otel-observer.js.map +1 -1
  25. package/dist/pi-loop-runtime.d.ts +4 -4
  26. package/dist/pi-loop-runtime.d.ts.map +1 -1
  27. package/dist/pi-loop-runtime.js +118 -72
  28. package/dist/pi-loop-runtime.js.map +1 -1
  29. package/dist/session.d.ts.map +1 -1
  30. package/dist/session.js +46 -21
  31. package/dist/session.js.map +1 -1
  32. package/dist/strict.d.ts +1 -1
  33. package/dist/strict.d.ts.map +1 -1
  34. package/dist/strict.js +1 -1
  35. package/dist/strict.js.map +1 -1
  36. package/dist/submission-runner.d.ts +15 -13
  37. package/dist/submission-runner.d.ts.map +1 -1
  38. package/dist/submission-runner.js +231 -94
  39. package/dist/submission-runner.js.map +1 -1
  40. package/dist/submission-telemetry.d.ts +11 -11
  41. package/dist/submission-telemetry.d.ts.map +1 -1
  42. package/dist/submission-telemetry.js +1 -1
  43. package/dist/submission-telemetry.js.map +1 -1
  44. package/dist/tools.d.ts +16 -0
  45. package/dist/tools.d.ts.map +1 -1
  46. package/dist/tools.js +291 -47
  47. package/dist/tools.js.map +1 -1
  48. package/package.json +26 -17
@@ -12,46 +12,48 @@
12
12
  * (SessionEntry DAG; `session.prompt({ submission })` is idempotent by
13
13
  * submission id, so re-execution after a crash never double-applies input).
14
14
  */
15
- import { LEASE_DURATION_MS, createDispatchAgentSubmissionInput, submissionStoreSessionId, } from './submission-store.js';
16
- import { materializeMessageAttachments } from './attachment-store.js';
17
- import { submissionSettlementEntryId } from './submission-state.js';
18
- import { runWithSubmissionContext } from './submission-context.js';
19
- import { emitSubmissionTelemetry } from './submission-telemetry.js';
15
+ import { LEASE_DURATION_MS, createDispatchAgentSubmissionInput, submissionStoreSessionId, } from "./submission-store.js";
16
+ import { materializeMessageAttachments } from "./attachment-store.js";
17
+ import { submissionSettlementEntryId } from "./submission-state.js";
18
+ import { runWithSubmissionContext } from "./submission-context.js";
19
+ import { emitSubmissionTelemetry } from "./submission-telemetry.js";
20
20
  // ─── Errors ─────────────────────────────────────────────────────────────────
21
21
  export class SubmissionAbortedError extends Error {
22
- code = 'SUBMISSION_ABORTED';
22
+ code = "SUBMISSION_ABORTED";
23
23
  constructor() {
24
- super('The agent submission was aborted.');
25
- this.name = 'SubmissionAbortedError';
24
+ super("The agent submission was aborted.");
25
+ this.name = "SubmissionAbortedError";
26
26
  }
27
27
  }
28
28
  export class SubmissionTimeoutError extends Error {
29
- code = 'SUBMISSION_TIMEOUT';
29
+ code = "SUBMISSION_TIMEOUT";
30
30
  constructor() {
31
- super('The agent submission exceeded its execution timeout.');
32
- this.name = 'SubmissionTimeoutError';
31
+ super("The agent submission exceeded its execution timeout.");
32
+ this.name = "SubmissionTimeoutError";
33
33
  }
34
34
  }
35
35
  export class SubmissionRetryExhaustedError extends Error {
36
- code = 'SUBMISSION_RETRY_EXHAUSTED';
36
+ code = "SUBMISSION_RETRY_EXHAUSTED";
37
37
  interruptedTools;
38
38
  constructor(options) {
39
39
  super(`The agent submission exceeded its maximum recovery attempts (${options.attemptCount}/${options.maxAttempts}).`);
40
- this.name = 'SubmissionRetryExhaustedError';
40
+ this.name = "SubmissionRetryExhaustedError";
41
41
  this.interruptedTools = options.interruptedTools;
42
42
  }
43
43
  }
44
44
  export class SubmissionInterruptedError extends Error {
45
- code = 'SUBMISSION_INTERRUPTED';
45
+ code = "SUBMISSION_INTERRUPTED";
46
46
  phase;
47
47
  constructor(phase, detail) {
48
- super(phase === 'retry_exhausted_before_input'
49
- ? `The agent submission was interrupted repeatedly before its input could be applied${detail ? ` (${detail})` : ''}.`
50
- : 'The agent submission was interrupted after its input was applied and could not be recovered.');
51
- this.name = 'SubmissionInterruptedError';
48
+ super(phase === "retry_exhausted_before_input"
49
+ ? `The agent submission was interrupted repeatedly before its input could be applied${detail ? ` (${detail})` : ""}.`
50
+ : "The agent submission was interrupted after its input was applied and could not be recovered.");
51
+ this.name = "SubmissionInterruptedError";
52
52
  this.phase = phase;
53
53
  }
54
54
  }
55
+ /** Grace allowed after a live attempt is signalled before force-settlement. */
56
+ export const SUBMISSION_SETTLE_GRACE_MS = 60_000;
55
57
  export function createSubmissionRunner(options) {
56
58
  const { submissions, executor } = options;
57
59
  const onError = options.onError ??
@@ -63,6 +65,8 @@ export function createSubmissionRunner(options) {
63
65
  /** Owner id for lease-based submission ownership. */
64
66
  const ownerId = crypto.randomUUID();
65
67
  const activeSubmissions = new Map();
68
+ /** The first deadline/abort signal time belongs to an attempt controller. */
69
+ const attemptDeadlineSignaledAt = new WeakMap();
66
70
  /** Local settlement notifications for same-process waiters. */
67
71
  const localSettlements = new Map();
68
72
  const settlementListeners = new Map();
@@ -94,7 +98,7 @@ export function createSubmissionRunner(options) {
94
98
  function notifySettled(submissionId, settlement, submission) {
95
99
  if (submission) {
96
100
  emitSubmissionTelemetry(options.telemetry, {
97
- type: 'submission_settled',
101
+ type: "submission_settled",
98
102
  ...telemetryBase(submission),
99
103
  ...(submission.attemptId !== undefined ? { attemptId: submission.attemptId } : {}),
100
104
  outcome: settlement.outcome,
@@ -112,7 +116,7 @@ export function createSubmissionRunner(options) {
112
116
  listener(settlement);
113
117
  }
114
118
  catch (error) {
115
- onError('settlement listener failed', error);
119
+ onError("settlement listener failed", error);
116
120
  }
117
121
  }
118
122
  }
@@ -120,7 +124,7 @@ export function createSubmissionRunner(options) {
120
124
  options.onSettled?.(submissionId, settlement);
121
125
  }
122
126
  catch (error) {
123
- onError('onSettled callback failed', error);
127
+ onError("onSettled callback failed", error);
124
128
  }
125
129
  }
126
130
  function serializeError(error) {
@@ -145,7 +149,7 @@ export function createSubmissionRunner(options) {
145
149
  ...(submission.input.actor !== undefined ? { actor: submission.input.actor } : {}),
146
150
  };
147
151
  }
148
- const telemetryError = (error) => onError('telemetry sink failed', error);
152
+ const telemetryError = (error) => onError("telemetry sink failed", error);
149
153
  // ── Settlement ───────────────────────────────────────────────────────
150
154
  /**
151
155
  * Two-phase settlement for direct submissions: reserve the exact canonical
@@ -159,17 +163,34 @@ export function createSubmissionRunner(options) {
159
163
  const pending = (await submissions.listPendingSubmissionSettlements()).find((obligation) => obligation.submissionId === submission.submissionId);
160
164
  const record = pending?.record ??
161
165
  {
162
- type: 'submission_settled',
166
+ type: "submission_settled",
163
167
  submissionId: submission.submissionId,
164
168
  outcome,
165
- ...(outcome === 'completed' && result !== undefined
166
- ? { resultText: typeof result === 'string' ? result : JSON.stringify(result) }
169
+ ...(outcome === "completed" && result !== undefined
170
+ ? { resultText: typeof result === "string" ? result : JSON.stringify(result) }
171
+ : {}),
172
+ ...(outcome !== "completed"
173
+ ? { error: serializeError(error ?? new Error("unknown error")) }
167
174
  : {}),
168
- ...(outcome !== 'completed' ? { error: serializeError(error ?? new Error('unknown error')) } : {}),
169
175
  };
170
176
  const obligation = pending ?? (await submissions.reserveSubmissionSettlement(attempt, { recordId, record }));
171
- if (!obligation)
177
+ if (!obligation) {
178
+ const row = await submissions.getSubmission(attempt.submissionId).catch(() => null);
179
+ if (row && row.status !== "settled") {
180
+ const error = new Error("Settlement reservation refused for an unsettled submission; reconciliation will retry it.");
181
+ emitSubmissionTelemetry(options.telemetry, {
182
+ type: "submission_recovery",
183
+ ...telemetryBase(row),
184
+ operation: "process_submission",
185
+ outcome: "deferred",
186
+ attemptCount: row.attemptCount,
187
+ maxAttempts: row.maxRetry,
188
+ error: error.message,
189
+ }, telemetryError);
190
+ onError(`settlement reservation refused for ${attempt.submissionId}`, error);
191
+ }
172
192
  return;
193
+ }
173
194
  await executor.appendSettlement(submission, obligation);
174
195
  await submissions.finalizeSubmissionSettlement(attempt, recordId);
175
196
  notifySettled(submission.submissionId, {
@@ -179,7 +200,7 @@ export function createSubmissionRunner(options) {
179
200
  }, submission);
180
201
  }
181
202
  async function settleDispatch(submission, attempt, outcome, result, error) {
182
- if (outcome === 'completed') {
203
+ if (outcome === "completed") {
183
204
  if (!(await submissions.completeSubmission(attempt)))
184
205
  return;
185
206
  }
@@ -189,12 +210,14 @@ export function createSubmissionRunner(options) {
189
210
  notifySettled(submission.submissionId, {
190
211
  outcome,
191
212
  ...(result !== undefined ? { result } : {}),
192
- ...(outcome !== 'completed' ? { error: serializeError(error ?? new SubmissionAbortedError()) } : {}),
213
+ ...(outcome !== "completed"
214
+ ? { error: serializeError(error ?? new SubmissionAbortedError()) }
215
+ : {}),
193
216
  }, submission);
194
217
  }
195
218
  async function settle(submission, attempt, outcome, result, error) {
196
219
  await settleJoinedWithHost(submission, attempt, outcome, result, error);
197
- if (submission.kind === 'direct') {
220
+ if (submission.kind === "direct") {
198
221
  await settleDirect(submission, attempt, outcome, result, error);
199
222
  }
200
223
  else {
@@ -204,12 +227,12 @@ export function createSubmissionRunner(options) {
204
227
  async function resolveInterruptedJoins(host, attempt) {
205
228
  const resolved = [];
206
229
  for (const joined of await submissions.listJoinedSubmissions(host.submissionId)) {
207
- if (joined.status === 'joined') {
230
+ if (joined.status === "joined") {
208
231
  resolved.push(joined);
209
232
  continue;
210
233
  }
211
234
  const state = await executor.inspect(joined);
212
- if (state === 'absent') {
235
+ if (state === "absent") {
213
236
  await submissions.revertJoiningSubmission(attempt, joined.submissionId);
214
237
  continue;
215
238
  }
@@ -224,15 +247,15 @@ export function createSubmissionRunner(options) {
224
247
  async function settleJoinedWithHost(host, attempt, outcome, result, error) {
225
248
  for (const joined of await resolveInterruptedJoins(host, attempt)) {
226
249
  const record = {
227
- type: 'submission_settled',
250
+ type: "submission_settled",
228
251
  submissionId: joined.submissionId,
229
252
  outcome,
230
253
  answeredBySubmissionId: host.submissionId,
231
- ...(outcome === 'completed' && result !== undefined
232
- ? { resultText: typeof result === 'string' ? result : JSON.stringify(result) }
254
+ ...(outcome === "completed" && result !== undefined
255
+ ? { resultText: typeof result === "string" ? result : JSON.stringify(result) }
233
256
  : {}),
234
- ...(outcome !== 'completed'
235
- ? { error: serializeError(error ?? new Error('unknown error')) }
257
+ ...(outcome !== "completed"
258
+ ? { error: serializeError(error ?? new Error("unknown error")) }
236
259
  : {}),
237
260
  };
238
261
  const obligation = {
@@ -259,14 +282,14 @@ export function createSubmissionRunner(options) {
259
282
  await executor.recordTerminal(submission, {
260
283
  submissionId: submission.submissionId,
261
284
  kind: submission.kind,
262
- reason: 'aborted',
285
+ reason: "aborted",
263
286
  message: error.message,
264
287
  });
265
288
  }
266
289
  catch (advisoryError) {
267
290
  onError(`abort advisory failed for ${submission.submissionId}`, advisoryError);
268
291
  }
269
- await settle(submission, attempt, 'aborted', undefined, error);
292
+ await settle(submission, attempt, "aborted", undefined, error);
270
293
  }
271
294
  async function failInterrupted(submission, attempt, reason, createError) {
272
295
  // Best-effort terminal record: a persistent save failure must not wedge
@@ -284,7 +307,7 @@ export function createSubmissionRunner(options) {
284
307
  onError(`terminal record failed for ${submission.submissionId}`, terminalError);
285
308
  }
286
309
  const error = createError(interruptedTools?.length ? interruptedTools : undefined);
287
- await settle(submission, attempt, 'failed', undefined, error);
310
+ await settle(submission, attempt, "failed", undefined, error);
288
311
  }
289
312
  // ── Processing ───────────────────────────────────────────────────────
290
313
  async function processClaimed(claimed, signal) {
@@ -292,11 +315,11 @@ export function createSubmissionRunner(options) {
292
315
  if (!attempt)
293
316
  return;
294
317
  const persisted = await submissions.getSubmission(claimed.submissionId);
295
- if (persisted?.status !== 'running' || persisted.attemptId !== attempt.attemptId)
318
+ if (persisted?.status !== "running" || persisted.attemptId !== attempt.attemptId)
296
319
  return;
297
320
  await submissions.insertAttemptMarker(attempt);
298
321
  emitSubmissionTelemetry(options.telemetry, {
299
- type: 'submission_running',
322
+ type: "submission_running",
300
323
  ...telemetryBase(claimed),
301
324
  attemptId: attempt.attemptId,
302
325
  attemptCount: persisted.attemptCount,
@@ -329,7 +352,7 @@ export function createSubmissionRunner(options) {
329
352
  signal,
330
353
  onInputApplied: async () => {
331
354
  if (!(await submissions.markSubmissionInputApplied(attempt, claimed.input.durability))) {
332
- throw new Error('[fabric-harness] Submission attempt lost ownership before input application.');
355
+ throw new Error("[fabric-harness] Submission attempt lost ownership before input application.");
333
356
  }
334
357
  },
335
358
  takeJoinedInputs: async () => {
@@ -339,7 +362,7 @@ export function createSubmissionRunner(options) {
339
362
  message: submission.input.message,
340
363
  onInputApplied: async () => {
341
364
  if (!(await submissions.finalizeJoinedSubmission(attempt, submission.submissionId))) {
342
- throw new Error('[fabric-harness] Joined submission lost host ownership before input application.');
365
+ throw new Error("[fabric-harness] Joined submission lost host ownership before input application.");
343
366
  }
344
367
  },
345
368
  }));
@@ -355,10 +378,10 @@ export function createSubmissionRunner(options) {
355
378
  await settleAborted(claimed, attempt);
356
379
  return;
357
380
  }
358
- await settle(claimed, attempt, 'failed', undefined, error);
381
+ await settle(claimed, attempt, "failed", undefined, error);
359
382
  throw error;
360
383
  }
361
- await settle(claimed, attempt, 'completed', result);
384
+ await settle(claimed, attempt, "completed", result);
362
385
  }
363
386
  finally {
364
387
  await submissions.deleteAttemptMarker(attempt).catch((error) => {
@@ -368,6 +391,11 @@ export function createSubmissionRunner(options) {
368
391
  }
369
392
  function spawnSubmissionTask(claimed) {
370
393
  const controller = new AbortController();
394
+ let released = false;
395
+ let resolveReleased;
396
+ const releasedPromise = new Promise((resolve) => {
397
+ resolveReleased = resolve;
398
+ });
371
399
  // Defer execution by one microtask so the controller is registered before
372
400
  // processClaimed can cross its first await. An immediate abort after
373
401
  // admission must never mark the store while missing the live attempt.
@@ -377,10 +405,10 @@ export function createSubmissionRunner(options) {
377
405
  if (isAbortError(error))
378
406
  return;
379
407
  emitSubmissionTelemetry(options.telemetry, {
380
- type: 'submission_recovery',
408
+ type: "submission_recovery",
381
409
  ...telemetryBase(claimed),
382
- operation: 'process_submission',
383
- outcome: 'deferred',
410
+ operation: "process_submission",
411
+ outcome: "deferred",
384
412
  attemptCount: claimed.attemptCount,
385
413
  maxAttempts: claimed.maxRetry,
386
414
  error: serializeError(error),
@@ -388,10 +416,24 @@ export function createSubmissionRunner(options) {
388
416
  onError(`processing failed for ${claimed.submissionId}`, error);
389
417
  })
390
418
  .finally(() => {
391
- activeSubmissions.delete(claimed.submissionId);
419
+ if (activeSubmissions.get(claimed.submissionId) === active) {
420
+ activeSubmissions.delete(claimed.submissionId);
421
+ }
422
+ active.release();
392
423
  wake();
393
424
  });
394
- activeSubmissions.set(claimed.submissionId, { task, abort: controller });
425
+ const active = {
426
+ task,
427
+ abort: controller,
428
+ released: releasedPromise,
429
+ release() {
430
+ if (released)
431
+ return;
432
+ released = true;
433
+ resolveReleased();
434
+ },
435
+ };
436
+ activeSubmissions.set(claimed.submissionId, active);
395
437
  }
396
438
  // ── Claim loop ───────────────────────────────────────────────────────
397
439
  async function runClaimPass() {
@@ -426,7 +468,7 @@ export function createSubmissionRunner(options) {
426
468
  } while (progressed || wakeRequested);
427
469
  }
428
470
  catch (error) {
429
- onError('claim pass failed, retrying', error);
471
+ onError("claim pass failed, retrying", error);
430
472
  await new Promise((resolve) => setTimeout(resolve, 1000));
431
473
  wakeRequested = true;
432
474
  }
@@ -448,7 +490,7 @@ export function createSubmissionRunner(options) {
448
490
  return;
449
491
  loopRunning = true;
450
492
  void claimLoop().catch((error) => {
451
- onError('fatal claim loop error', error);
493
+ onError("fatal claim loop error", error);
452
494
  loopRunning = false;
453
495
  });
454
496
  if (!heartbeatInterval) {
@@ -457,7 +499,7 @@ export function createSubmissionRunner(options) {
457
499
  if (ids.length === 0)
458
500
  return;
459
501
  submissions.renewLeases(ownerId, ids).catch((error) => {
460
- onError('lease renewal failed', error);
502
+ onError("lease renewal failed", error);
461
503
  });
462
504
  }, heartbeatIntervalMs);
463
505
  heartbeatInterval.unref?.();
@@ -475,8 +517,90 @@ export function createSubmissionRunner(options) {
475
517
  if (now - lastLeaseScanAt < leaseScanIntervalMs)
476
518
  return;
477
519
  lastLeaseScanAt = now;
520
+ await enforceActiveDeadlines();
478
521
  await reconcileRunningSubmissions();
479
522
  }
523
+ /**
524
+ * Enforce timeout and durable abort over work that is still live locally.
525
+ * A heartbeat proves process liveness, not attempt progress, so this sweep
526
+ * must run independently of the task and must never await it.
527
+ *
528
+ * State-machine behavior follows Flue v2.0.2's Node coordinator
529
+ * (Apache-2.0), adapted to Fabric's settlement-obligation store contract.
530
+ */
531
+ async function enforceActiveDeadlines() {
532
+ for (const [submissionId, active] of [...activeSubmissions]) {
533
+ if (stopping)
534
+ return;
535
+ let submission;
536
+ try {
537
+ submission = await submissions.getSubmission(submissionId);
538
+ }
539
+ catch {
540
+ continue;
541
+ }
542
+ if (submission?.status !== "running")
543
+ continue;
544
+ const now = Date.now();
545
+ const timedOut = submission.timeoutAt > 0 && now >= submission.timeoutAt;
546
+ const abortRequested = submission.abortRequestedAt !== undefined;
547
+ if (!timedOut && !abortRequested)
548
+ continue;
549
+ const reason = abortRequested ? new SubmissionAbortedError() : new SubmissionTimeoutError();
550
+ active.abort.abort(reason);
551
+ const existingSignalTime = attemptDeadlineSignaledAt.get(active.abort);
552
+ const signaledAt = existingSignalTime ??
553
+ (abortRequested && submission.abortRequestedAt !== undefined
554
+ ? Math.min(submission.abortRequestedAt, now)
555
+ : now);
556
+ if (existingSignalTime === undefined) {
557
+ attemptDeadlineSignaledAt.set(active.abort, signaledAt);
558
+ }
559
+ if (now < signaledAt + SUBMISSION_SETTLE_GRACE_MS) {
560
+ emitSubmissionTelemetry(options.telemetry, {
561
+ type: "submission_recovery",
562
+ ...telemetryBase(submission),
563
+ operation: "enforce_deadline",
564
+ outcome: "deferred",
565
+ attemptCount: submission.attemptCount,
566
+ maxAttempts: submission.maxRetry,
567
+ error: reason.message,
568
+ }, telemetryError);
569
+ continue;
570
+ }
571
+ emitSubmissionTelemetry(options.telemetry, {
572
+ type: "submission_recovery",
573
+ ...telemetryBase(submission),
574
+ operation: "enforce_deadline",
575
+ outcome: "terminated",
576
+ attemptCount: submission.attemptCount,
577
+ maxAttempts: submission.maxRetry,
578
+ error: reason.message,
579
+ }, telemetryError);
580
+ try {
581
+ await reconcileInterrupted(submission);
582
+ const current = activeSubmissions.get(submissionId);
583
+ const settled = await submissions.getSubmission(submissionId);
584
+ if (current === active && settled?.status === "settled") {
585
+ activeSubmissions.delete(submissionId);
586
+ active.release();
587
+ wake();
588
+ }
589
+ }
590
+ catch (error) {
591
+ emitSubmissionTelemetry(options.telemetry, {
592
+ type: "submission_recovery",
593
+ ...telemetryBase(submission),
594
+ operation: "enforce_deadline",
595
+ outcome: "deferred",
596
+ attemptCount: submission.attemptCount,
597
+ maxAttempts: submission.maxRetry,
598
+ error: serializeError(error),
599
+ }, telemetryError);
600
+ onError(`deadline enforcement failed for ${submissionId}`, error);
601
+ }
602
+ }
603
+ }
480
604
  /** Single-flight expired-lease reconciliation (see flue for the race this closes). */
481
605
  function reconcileRunningSubmissions() {
482
606
  reconcilePassInFlight ??= runReconciliationPass().finally(() => {
@@ -500,7 +624,7 @@ export function createSubmissionRunner(options) {
500
624
  // Finalize settlements that crashed between reserve and finalize.
501
625
  for (const pending of await submissions.listPendingSubmissionSettlements()) {
502
626
  const submission = await submissions.getSubmission(pending.submissionId);
503
- if (!submission || submission.kind !== 'direct')
627
+ if (!submission || submission.kind !== "direct")
504
628
  continue;
505
629
  if (activeSubmissions.has(submission.submissionId) || submission.leaseExpiresAt > Date.now())
506
630
  continue;
@@ -516,10 +640,10 @@ export function createSubmissionRunner(options) {
516
640
  catch (error) {
517
641
  if (submission) {
518
642
  emitSubmissionTelemetry(options.telemetry, {
519
- type: 'submission_recovery',
643
+ type: "submission_recovery",
520
644
  ...telemetryBase(submission),
521
- operation: 'finalize_settlement',
522
- outcome: 'deferred',
645
+ operation: "finalize_settlement",
646
+ outcome: "deferred",
523
647
  attemptCount: submission.attemptCount,
524
648
  maxAttempts: submission.maxRetry,
525
649
  error: serializeError(error),
@@ -541,10 +665,10 @@ export function createSubmissionRunner(options) {
541
665
  }
542
666
  catch (error) {
543
667
  emitSubmissionTelemetry(options.telemetry, {
544
- type: 'submission_recovery',
668
+ type: "submission_recovery",
545
669
  ...telemetryBase(submission),
546
- operation: 'reconcile_submission',
547
- outcome: 'deferred',
670
+ operation: "reconcile_submission",
671
+ outcome: "deferred",
548
672
  attemptCount: submission.attemptCount,
549
673
  maxAttempts: submission.maxRetry,
550
674
  error: serializeError(error),
@@ -580,8 +704,8 @@ export function createSubmissionRunner(options) {
580
704
  // retry budget and timeout gate only the retry/requeue branches below,
581
705
  // and must never discard finished provider work.
582
706
  const state = await executor.inspect(submission);
583
- if (state === 'completed') {
584
- await settle(submission, attempt, 'completed');
707
+ if (state === "completed") {
708
+ await settle(submission, attempt, "completed");
585
709
  return undefined;
586
710
  }
587
711
  // A crash-interrupted abort is never resurrected; and the budget/timeout
@@ -591,8 +715,8 @@ export function createSubmissionRunner(options) {
591
715
  return undefined;
592
716
  }
593
717
  if (submission.attemptCount >= submission.maxRetry) {
594
- await failInterrupted(submission, attempt, 'exhausted_retry_budget', (interruptedTools) => submission.inputAppliedAt === undefined
595
- ? new SubmissionInterruptedError('retry_exhausted_before_input', `${submission.attemptCount}/${submission.maxRetry} attempts`)
718
+ await failInterrupted(submission, attempt, "exhausted_retry_budget", (interruptedTools) => submission.inputAppliedAt === undefined
719
+ ? new SubmissionInterruptedError("retry_exhausted_before_input", `${submission.attemptCount}/${submission.maxRetry} attempts`)
596
720
  : new SubmissionRetryExhaustedError({
597
721
  attemptCount: submission.attemptCount,
598
722
  maxAttempts: submission.maxRetry,
@@ -601,19 +725,22 @@ export function createSubmissionRunner(options) {
601
725
  return undefined;
602
726
  }
603
727
  if (submission.timeoutAt > 0 && Date.now() >= submission.timeoutAt) {
604
- await failInterrupted(submission, attempt, 'exceeded_timeout', () => new SubmissionTimeoutError());
728
+ await failInterrupted(submission, attempt, "exceeded_timeout", () => new SubmissionTimeoutError());
605
729
  return undefined;
606
730
  }
607
731
  // Canonical input exists but the input-applied marker did not land (the
608
732
  // crash window between the entry write and the marker CAS). Re-acquire
609
733
  // the attempt, install the marker, and resume from canonical state.
610
- if (submission.inputAppliedAt === undefined && state !== 'absent') {
734
+ if (submission.inputAppliedAt === undefined && state !== "absent") {
611
735
  const replacement = await submissions.replaceSubmissionAttempt(attempt, crypto.randomUUID(), {
612
736
  ownerId,
613
737
  leaseExpiresAt: Date.now() + LEASE_DURATION_MS,
614
738
  });
615
739
  if (replacement?.attemptId) {
616
- const replacementAttempt = { submissionId: replacement.submissionId, attemptId: replacement.attemptId };
740
+ const replacementAttempt = {
741
+ submissionId: replacement.submissionId,
742
+ attemptId: replacement.attemptId,
743
+ };
617
744
  if (!(await submissions.markSubmissionInputApplied(replacementAttempt, submission.input.durability))) {
618
745
  return undefined;
619
746
  }
@@ -625,7 +752,7 @@ export function createSubmissionRunner(options) {
625
752
  // next prompt) or the one accepted provider-redispatch window
626
753
  // ('uncertain': nothing observable persisted). Acquire the replacement
627
754
  // attempt (the fencing CAS) before any recovery side effect.
628
- if (state === 'continuable' || state === 'uncertain') {
755
+ if (state === "continuable" || state === "uncertain") {
629
756
  const replacement = await submissions.replaceSubmissionAttempt(attempt, crypto.randomUUID(), {
630
757
  ownerId,
631
758
  leaseExpiresAt: Date.now() + LEASE_DURATION_MS,
@@ -641,7 +768,7 @@ export function createSubmissionRunner(options) {
641
768
  await submissions.requeueSubmissionBeforeInputApplied(attempt);
642
769
  return undefined;
643
770
  }
644
- await failInterrupted(submission, attempt, 'interrupted_after_input_application', () => new SubmissionInterruptedError('after_input_application'));
771
+ await failInterrupted(submission, attempt, "interrupted_after_input_application", () => new SubmissionInterruptedError("after_input_application"));
645
772
  return undefined;
646
773
  }
647
774
  // ── Attachment materialization (pre-admission) ───────────────────────
@@ -660,8 +787,12 @@ export function createSubmissionRunner(options) {
660
787
  scope,
661
788
  idPrefix: `att_${admissionId}`,
662
789
  ...(attachmentOptions.maxCount !== undefined ? { maxCount: attachmentOptions.maxCount } : {}),
663
- ...(attachmentOptions.maxAttachmentBytes !== undefined ? { maxAttachmentBytes: attachmentOptions.maxAttachmentBytes } : {}),
664
- ...(attachmentOptions.maxTotalBytes !== undefined ? { maxTotalBytes: attachmentOptions.maxTotalBytes } : {}),
790
+ ...(attachmentOptions.maxAttachmentBytes !== undefined
791
+ ? { maxAttachmentBytes: attachmentOptions.maxAttachmentBytes }
792
+ : {}),
793
+ ...(attachmentOptions.maxTotalBytes !== undefined
794
+ ? { maxTotalBytes: attachmentOptions.maxTotalBytes }
795
+ : {}),
665
796
  });
666
797
  return { ...input, message };
667
798
  }
@@ -669,7 +800,7 @@ export function createSubmissionRunner(options) {
669
800
  const runner = {
670
801
  async admitDispatch(input) {
671
802
  if (stopping)
672
- throw new Error('[fabric-harness] Submission runner is shutting down.');
803
+ throw new Error("[fabric-harness] Submission runner is shutting down.");
673
804
  const validated = await options.validateInput?.(createDispatchAgentSubmissionInput(input));
674
805
  const preparedInput = validated
675
806
  ? {
@@ -683,20 +814,21 @@ export function createSubmissionRunner(options) {
683
814
  : input;
684
815
  const admissionInput = await materializeForAdmission(preparedInput, submissionStoreSessionId(preparedInput), preparedInput.dispatchId);
685
816
  const admission = await submissions.admitDispatch(admissionInput);
686
- if (admission.kind !== 'submission')
817
+ if (admission.kind !== "submission")
687
818
  return admission;
688
819
  let submission = admission.submission;
689
820
  if (submission.canonicalReadyAt === null) {
690
- submission = (await submissions.markSubmissionCanonicalReady(submission.submissionId)) ?? submission;
821
+ submission =
822
+ (await submissions.markSubmissionCanonicalReady(submission.submissionId)) ?? submission;
691
823
  }
692
- emitSubmissionTelemetry(options.telemetry, { type: 'submission_queued', ...telemetryBase(submission) }, telemetryError);
824
+ emitSubmissionTelemetry(options.telemetry, { type: "submission_queued", ...telemetryBase(submission) }, telemetryError);
693
825
  ensureClaimLoop();
694
826
  wake();
695
- return { kind: 'submission', submission };
827
+ return { kind: "submission", submission };
696
828
  },
697
829
  async admitDirect(input) {
698
830
  if (stopping)
699
- throw new Error('[fabric-harness] Submission runner is shutting down.');
831
+ throw new Error("[fabric-harness] Submission runner is shutting down.");
700
832
  const validated = await options.validateInput?.(input);
701
833
  const preparedInput = validated ?? input;
702
834
  const admissionInput = await materializeForAdmission(preparedInput, submissionStoreSessionId(preparedInput), preparedInput.submissionId);
@@ -704,7 +836,7 @@ export function createSubmissionRunner(options) {
704
836
  if (admitted.canonicalReadyAt === null) {
705
837
  await submissions.markSubmissionCanonicalReady(admitted.submissionId);
706
838
  }
707
- emitSubmissionTelemetry(options.telemetry, { type: 'submission_queued', ...telemetryBase(admitted) }, telemetryError);
839
+ emitSubmissionTelemetry(options.telemetry, { type: "submission_queued", ...telemetryBase(admitted) }, telemetryError);
708
840
  ensureClaimLoop();
709
841
  wake();
710
842
  return admitted;
@@ -725,7 +857,7 @@ export function createSubmissionRunner(options) {
725
857
  wake();
726
858
  if (hasInactive) {
727
859
  void reconcileRunningSubmissions().catch((error) => {
728
- onError('reconcile after abort failed', error);
860
+ onError("reconcile after abort failed", error);
729
861
  });
730
862
  }
731
863
  return affected;
@@ -734,6 +866,7 @@ export function createSubmissionRunner(options) {
734
866
  if (!(await submissions.hasUnsettledSubmissions()))
735
867
  return;
736
868
  ensureClaimLoop();
869
+ await enforceActiveDeadlines();
737
870
  await reconcileRunningSubmissions();
738
871
  await runner.waitForIdle();
739
872
  },
@@ -751,7 +884,7 @@ export function createSubmissionRunner(options) {
751
884
  done = true;
752
885
  if (timer)
753
886
  clearTimeout(timer);
754
- waitOptions.signal?.removeEventListener('abort', onAbort);
887
+ waitOptions.signal?.removeEventListener("abort", onAbort);
755
888
  resolve(settlement);
756
889
  };
757
890
  const onAbort = () => {
@@ -761,7 +894,9 @@ export function createSubmissionRunner(options) {
761
894
  if (timer)
762
895
  clearTimeout(timer);
763
896
  listeners?.delete(finish);
764
- reject(waitOptions.signal?.reason instanceof Error ? waitOptions.signal.reason : new Error('waitForSettlement aborted'));
897
+ reject(waitOptions.signal?.reason instanceof Error
898
+ ? waitOptions.signal.reason
899
+ : new Error("waitForSettlement aborted"));
765
900
  };
766
901
  let listeners = settlementListeners.get(submissionId);
767
902
  if (!listeners) {
@@ -769,7 +904,7 @@ export function createSubmissionRunner(options) {
769
904
  settlementListeners.set(submissionId, listeners);
770
905
  }
771
906
  listeners.add(finish);
772
- waitOptions.signal?.addEventListener('abort', onAbort, { once: true });
907
+ waitOptions.signal?.addEventListener("abort", onAbort, { once: true });
773
908
  // Cross-process fallback: poll the store; outcome precision comes
774
909
  // from the canonical settlement record when one exists.
775
910
  const poll = async () => {
@@ -777,17 +912,19 @@ export function createSubmissionRunner(options) {
777
912
  return;
778
913
  try {
779
914
  const submission = await submissions.getSubmission(submissionId);
780
- if (submission?.status === 'settled') {
915
+ if (submission?.status === "settled") {
781
916
  const canonical = await executor.getSettlement(submission).catch(() => null);
782
917
  finish(canonical
783
918
  ? {
784
919
  outcome: canonical.outcome,
785
- ...(canonical.resultText !== undefined ? { result: canonical.resultText } : {}),
920
+ ...(canonical.resultText !== undefined
921
+ ? { result: canonical.resultText }
922
+ : {}),
786
923
  ...(canonical.error !== undefined ? { error: canonical.error } : {}),
787
924
  }
788
925
  : submission.error !== undefined
789
- ? { outcome: 'failed', error: submission.error }
790
- : { outcome: 'completed' });
926
+ ? { outcome: "failed", error: submission.error }
927
+ : { outcome: "completed" });
791
928
  return;
792
929
  }
793
930
  }
@@ -796,7 +933,7 @@ export function createSubmissionRunner(options) {
796
933
  }
797
934
  if (!done)
798
935
  timer = setTimeout(poll, pollIntervalMs);
799
- if (timer && typeof timer === 'object' && 'unref' in timer)
936
+ if (timer && typeof timer === "object" && "unref" in timer)
800
937
  timer.unref();
801
938
  };
802
939
  void poll();
@@ -807,7 +944,7 @@ export function createSubmissionRunner(options) {
807
944
  if (stopping)
808
945
  return;
809
946
  if (activeSubmissions.size > 0) {
810
- await Promise.allSettled([...activeSubmissions.values()].map((entry) => entry.task));
947
+ await Promise.all([...activeSubmissions.values()].map((entry) => entry.released));
811
948
  }
812
949
  if (stopping)
813
950
  return;
@@ -830,7 +967,7 @@ export function createSubmissionRunner(options) {
830
967
  stopping = true;
831
968
  wake();
832
969
  for (const { abort } of activeSubmissions.values()) {
833
- abort.abort(new DOMException('Submission runner shutting down.', 'AbortError'));
970
+ abort.abort(new DOMException("Submission runner shutting down.", "AbortError"));
834
971
  }
835
972
  if (activeSubmissions.size > 0) {
836
973
  const settlement = Promise.allSettled([...activeSubmissions.values()].map((entry) => entry.task));
@@ -849,7 +986,7 @@ export function createSubmissionRunner(options) {
849
986
  leaseScanInterval = null;
850
987
  }
851
988
  if (activeSubmissions.size > 0) {
852
- onError('shutdown timeout', new Error(`${activeSubmissions.size} submission(s) did not settle within ${timeoutMs}ms; leases will be reclaimed on next startup.`));
989
+ onError("shutdown timeout", new Error(`${activeSubmissions.size} submission(s) did not settle within ${timeoutMs}ms; leases will be reclaimed on next startup.`));
853
990
  }
854
991
  },
855
992
  wake,
@@ -857,7 +994,7 @@ export function createSubmissionRunner(options) {
857
994
  return {
858
995
  enqueue: async (input) => {
859
996
  const admission = await runner.admitDispatch(input);
860
- if (admission.kind === 'retained_receipt') {
997
+ if (admission.kind === "retained_receipt") {
861
998
  const retained = await submissions.getSubmission(admission.receipt.submissionId);
862
999
  return {
863
1000
  dispatchId: admission.receipt.submissionId,
@@ -865,7 +1002,7 @@ export function createSubmissionRunner(options) {
865
1002
  ...(retained?.input.instanceUid ? { uid: retained.input.instanceUid } : {}),
866
1003
  };
867
1004
  }
868
- if (admission.kind === 'conflict') {
1005
+ if (admission.kind === "conflict") {
869
1006
  throw new Error(`[fabric-harness] dispatch target agent "${input.agent}" rejected a conflicting dispatch replay.`);
870
1007
  }
871
1008
  return {
@@ -886,6 +1023,6 @@ export function submissionSessionKey(input) {
886
1023
  return submissionStoreSessionId(input);
887
1024
  }
888
1025
  function isAbortError(error) {
889
- return error instanceof DOMException && error.name === 'AbortError';
1026
+ return error instanceof DOMException && error.name === "AbortError";
890
1027
  }
891
1028
  //# sourceMappingURL=submission-runner.js.map