@yu_robotics/remote-cli 1.6.241 → 1.6.243

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 (59) hide show
  1. package/dist/client/MessageHandler.d.ts +6 -2
  2. package/dist/client/MessageHandler.d.ts.map +1 -1
  3. package/dist/client/MessageHandler.js +99 -4
  4. package/dist/client/MessageHandler.js.map +1 -1
  5. package/dist/executor/ClaudePersistentExecutor.d.ts.map +1 -1
  6. package/dist/executor/ClaudePersistentExecutor.js +2 -1
  7. package/dist/executor/ClaudePersistentExecutor.js.map +1 -1
  8. package/dist/executor/DshExecutor.d.ts +1 -1
  9. package/dist/executor/DshExecutor.d.ts.map +1 -1
  10. package/dist/executor/DshExecutor.js +1 -0
  11. package/dist/executor/DshExecutor.js.map +1 -1
  12. package/dist/maintenance/release-notes.json +1 -1
  13. package/dist/managed/tools.d.ts +38 -2
  14. package/dist/managed/tools.d.ts.map +1 -1
  15. package/dist/scheduling/ReviewedNativeCleanup.d.ts +3 -0
  16. package/dist/scheduling/ReviewedNativeCleanup.d.ts.map +1 -1
  17. package/dist/scheduling/ReviewedNativeCleanup.js.map +1 -1
  18. package/dist/scheduling/ScheduleCommand.d.ts +7 -0
  19. package/dist/scheduling/ScheduleCommand.d.ts.map +1 -1
  20. package/dist/scheduling/ScheduleCommand.js +11 -0
  21. package/dist/scheduling/ScheduleCommand.js.map +1 -1
  22. package/dist/scheduling/SchedulePurgeVerification.d.ts +7 -0
  23. package/dist/scheduling/SchedulePurgeVerification.d.ts.map +1 -0
  24. package/dist/scheduling/SchedulePurgeVerification.js +40 -0
  25. package/dist/scheduling/SchedulePurgeVerification.js.map +1 -0
  26. package/dist/scheduling/ScheduleService.d.ts +54 -2
  27. package/dist/scheduling/ScheduleService.d.ts.map +1 -1
  28. package/dist/scheduling/ScheduleService.js +283 -20
  29. package/dist/scheduling/ScheduleService.js.map +1 -1
  30. package/dist/scheduling/ScheduleToolScope.d.ts +13 -0
  31. package/dist/scheduling/ScheduleToolScope.d.ts.map +1 -1
  32. package/dist/scheduling/ScheduleToolScope.js +33 -0
  33. package/dist/scheduling/ScheduleToolScope.js.map +1 -1
  34. package/dist/scheduling/claude/ClaudeScheduleOwnership.d.ts +1 -0
  35. package/dist/scheduling/claude/ClaudeScheduleOwnership.d.ts.map +1 -1
  36. package/dist/scheduling/claude/ClaudeScheduleOwnership.js +6 -1
  37. package/dist/scheduling/claude/ClaudeScheduleOwnership.js.map +1 -1
  38. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts +4 -0
  39. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts.map +1 -1
  40. package/dist/scheduling/claude/ClaudeSessionSchedules.js +25 -1
  41. package/dist/scheduling/claude/ClaudeSessionSchedules.js.map +1 -1
  42. package/dist/scheduling/dsh/SessionScheduleClient.d.ts.map +1 -1
  43. package/dist/scheduling/dsh/SessionScheduleClient.js +2 -0
  44. package/dist/scheduling/dsh/SessionScheduleClient.js.map +1 -1
  45. package/dist/scheduling/toolContract.d.ts +19 -1
  46. package/dist/scheduling/toolContract.d.ts.map +1 -1
  47. package/dist/scheduling/toolContract.js +4 -2
  48. package/dist/scheduling/toolContract.js.map +1 -1
  49. package/dist/scheduling/types.d.ts +6 -0
  50. package/dist/scheduling/types.d.ts.map +1 -1
  51. package/native/prebuilds/darwin-arm64/managed_native.node +0 -0
  52. package/native/prebuilds/darwin-arm64/manifest.json +1 -1
  53. package/native/prebuilds/darwin-x64/managed_native.node +0 -0
  54. package/native/prebuilds/darwin-x64/manifest.json +1 -1
  55. package/native/prebuilds/win32-arm64/managed_native.node +0 -0
  56. package/native/prebuilds/win32-arm64/manifest.json +1 -1
  57. package/native/prebuilds/win32-x64/managed_native.node +0 -0
  58. package/native/prebuilds/win32-x64/manifest.json +1 -1
  59. package/package.json +1 -1
@@ -51,6 +51,7 @@ const ERROR_BYTES = 4096;
51
51
  const LIVE = new Set(['creating', 'active', 'running']);
52
52
  const STATES = new Set([...LIVE, 'completed', 'cancelled', 'interrupted', 'failed']);
53
53
  const RESTART_REASON = 'Native schedule interrupted by service restart; not recreated or resumed.';
54
+ const MAX_PURGED_IDS = 10_000;
54
55
  function bounded(value, limit) {
55
56
  if (Buffer.byteLength(value, 'utf8') <= limit)
56
57
  return value;
@@ -109,6 +110,11 @@ class ScheduleService {
109
110
  pending = new Map();
110
111
  runtimes = new Map();
111
112
  retainedCancellations = new Map();
113
+ purged = new Map();
114
+ purges = new Map();
115
+ recordOperations = new Map();
116
+ delivering = new Set();
117
+ refreshes = 0;
112
118
  tail = Promise.resolve();
113
119
  deliveryTail = Promise.resolve();
114
120
  tasks = new Set();
@@ -209,6 +215,8 @@ class ScheduleService {
209
215
  if (this.closing || this.fault)
210
216
  return;
211
217
  const record = this.records.get(id);
218
+ if (!record)
219
+ continue;
212
220
  if (record.cancelRequested || !this.current(record)) {
213
221
  await this.blockRecovery(record, 'Recovery owner retired or cancellation was requested.');
214
222
  continue;
@@ -381,7 +389,7 @@ class ScheduleService {
381
389
  });
382
390
  }
383
391
  create(owner, input) {
384
- return this.operation(this.createSchedule(owner, input));
392
+ return this.operation(this.recordOperation(input.id, this.createSchedule(owner, input)));
385
393
  }
386
394
  async createSchedule(owner, input) {
387
395
  this.checkReady();
@@ -415,8 +423,8 @@ class ScheduleService {
415
423
  this.checkReady();
416
424
  if (!this.current(originalOwner))
417
425
  throw new Error('Schedule owner is no longer current.');
418
- if (this.records.has(nativeInput.id))
419
- throw new Error('Schedule ID already exists.');
426
+ if (this.records.has(nativeInput.id) || this.purged.has(nativeInput.id))
427
+ throw new Error('Schedule ID already exists or was purged.');
420
428
  if (this.records.size >= this.maxRecords)
421
429
  throw new Error('Schedule catalog is full; history was not pruned.');
422
430
  const liveCount = [...this.records.values()].filter(record => LIVE.has(record.state)
@@ -476,6 +484,9 @@ class ScheduleService {
476
484
  record.state = 'failed';
477
485
  record.error = errorText(error);
478
486
  }
487
+ if (error instanceof types_1.NativeScheduleNotAdmittedError && !runtime.handle && !runtime.running.size && !runtime.completed.size) {
488
+ record.creationRefused = true;
489
+ }
479
490
  if (!this.fault)
480
491
  await this.persist();
481
492
  });
@@ -492,6 +503,176 @@ class ScheduleService {
492
503
  validateOwner(owner);
493
504
  return this.serial(async () => [...this.records.values()].filter(record => sameOwner(record, owner)).map(record => structuredClone(record)));
494
505
  }
506
+ /** Cancel first, then erase only verified retired history. No native sweep or
507
+ * recovery admission is implied. Missing/foreign IDs never count as removed. */
508
+ purge(owner, selection) {
509
+ return this.operation(this.purgeSelected(structuredClone(owner), structuredClone(selection)));
510
+ }
511
+ async purgeSelected(owner, selection) {
512
+ this.checkReady();
513
+ validateOwner(owner);
514
+ const selectedIds = await this.serial(async () => {
515
+ if (!this.current(owner))
516
+ throw new Error('Schedule purge owner is no longer current.');
517
+ const value = object(selection, ['ids', 'all']);
518
+ if (value.all !== undefined ? value.all !== true || value.ids !== undefined : !Array.isArray(value.ids)) {
519
+ throw new Error('Select exact schedule IDs or all current-owner schedules.');
520
+ }
521
+ const ids = value.all === true ? [...this.records.values()].filter(record => sameOwner(record, owner)).map(record => record.id)
522
+ : [...value.ids];
523
+ if (ids.length > this.maxRecords || new Set(ids).size !== ids.length)
524
+ throw new Error('Invalid schedule purge selection.');
525
+ ids.forEach(ScheduleCommand_1.validateScheduleId);
526
+ let changed = false;
527
+ for (const id of ids) {
528
+ const record = this.records.get(id);
529
+ if (!record || !sameOwner(record, owner))
530
+ continue;
531
+ record.cancelRequested = true;
532
+ if (record.recovery)
533
+ record.recovery.status = 'blocked';
534
+ this.runtimes.get(id)?.recoveryAbort?.abort();
535
+ changed = true;
536
+ }
537
+ // Persist admission/recovery denial before any external cleanup attempt.
538
+ if (changed)
539
+ await this.persist();
540
+ return ids;
541
+ });
542
+ const result = { selectedIds, removedIds: [], alreadyRemovedIds: [], pending: [], errors: [] };
543
+ for (const id of selectedIds) {
544
+ const previouslyPurged = this.purged.has(id);
545
+ try {
546
+ const record = this.records.get(id);
547
+ const prior = this.purged.get(id);
548
+ if ((!record || !sameOwner(record, owner)) && (!prior || !sameOwner(prior, owner))) {
549
+ throw new Error('Schedule not found for this owner.');
550
+ }
551
+ let task = this.purges.get(id);
552
+ if (!task) {
553
+ task = this.purgeRecord(owner, id);
554
+ this.purges.set(id, task);
555
+ void task.finally(() => { if (this.purges.get(id) === task)
556
+ this.purges.delete(id); }).catch(() => { });
557
+ }
558
+ const outcome = await task;
559
+ if (outcome.status === 'pending')
560
+ result.pending.push({ id, reason: outcome.reason, detail: outcome.detail });
561
+ else
562
+ (outcome.status === 'removed' ? result.removedIds : result.alreadyRemovedIds).push(id);
563
+ }
564
+ catch (error) {
565
+ if (!previouslyPurged && this.purged.has(id) && sameOwner(this.purged.get(id), owner))
566
+ result.removedIds.push(id);
567
+ result.errors.push({ id, error: errorText(error) });
568
+ }
569
+ }
570
+ return result;
571
+ }
572
+ async purgeRecord(owner, id) {
573
+ const pending = (reason, detail) => ({ status: 'pending', reason, detail });
574
+ this.checkReady();
575
+ if (!this.current(owner))
576
+ throw new Error('Schedule purge owner is no longer current.');
577
+ if (this.purged.has(id))
578
+ return { status: 'alreadyRemoved' };
579
+ const record = this.owned(owner, id);
580
+ const current = () => !this.closing && !this.fault && !this.suspending && this.current(owner)
581
+ && this.records.get(id) === record && record.cancelRequested === true;
582
+ const busy = () => {
583
+ if (this.recordOperations.has(id) || this.recoveryRun || this.refreshes || this.retainedCancellations.has(id)) {
584
+ return pending('operation_pending', 'Creation, recovery, inspection or cleanup is still pending. Retry these same IDs.');
585
+ }
586
+ if (this.delivering.has(id))
587
+ return pending('delivery_pending', 'An external delivery is already in flight; its outcome cannot be revoked.');
588
+ };
589
+ const active = busy();
590
+ if (active)
591
+ return active;
592
+ if (this.purged.size >= MAX_PURGED_IDS)
593
+ return pending('fence_capacity', 'Durable purge ID capacity reached; no replay fence was discarded.');
594
+ const runtime = this.runtimes.get(id);
595
+ // Do not interpret terminal state, an absent handle or a stopped process as
596
+ // native definition absence. Existing cancelRetained owns its stronger proof.
597
+ let retainedVerified = false;
598
+ const clean = !runtime && (record.cleanupConfirmed === true || record.recovery?.handoff === 'clean' && record.recovery.nativeDefinitionAbsent === true);
599
+ if (runtime?.handle && !runtime.stopped) {
600
+ await this.cancel(owner, id);
601
+ }
602
+ else if (!runtime && !record.creationRefused && !clean && record.recovery && this.supportsRetainedCancellation(record)) {
603
+ try {
604
+ await this.recordOperation(id, this.cancelRetained(record));
605
+ retainedVerified = true;
606
+ }
607
+ catch (error) {
608
+ // A failed receipt (including error-after-commit) is not absence proof.
609
+ // Exact framework verification may still resolve it without recreating.
610
+ if (!this.options.withPurgeVerification)
611
+ throw error;
612
+ }
613
+ }
614
+ if (!current())
615
+ throw new Error('Schedule purge context changed during cleanup.');
616
+ const unfinished = busy();
617
+ if (unfinished)
618
+ return unfinished;
619
+ if (runtime?.running.size)
620
+ return pending('occurrence_running', 'Future cancellation does not revoke an already admitted occurrence.');
621
+ if (runtime && (!runtime.stopped || runtime.releaseAdmission))
622
+ return pending('operation_pending', 'Native runtime retirement is unconfirmed.');
623
+ const handleProof = runtime?.removalConfirmed && runtime.handle?.nativeDefinitionAbsent !== false;
624
+ const erase = (evidence) => this.serial(async () => {
625
+ this.checkReady();
626
+ if (!current() || evidence?.status === 'verified' && !evidence.isCurrent())
627
+ throw new Error('Schedule purge evidence expired before persistence.');
628
+ const changed = busy();
629
+ if (changed)
630
+ return changed;
631
+ if (this.purged.size >= MAX_PURGED_IDS)
632
+ return pending('fence_capacity', 'Durable purge ID capacity reached; no replay fence was discarded.');
633
+ if (this.runtimes.get(id) !== runtime || runtime?.running.size || runtime && !runtime.stopped
634
+ || handleProof && runtime?.handle?.nativeDefinitionAbsent === false) {
635
+ return pending('operation_pending', 'Native ownership changed before history removal.');
636
+ }
637
+ // The ID-only owner fence prevents delayed CREATE retries from resurrecting
638
+ // deleted history. Prompts, results and recovery identities are not retained.
639
+ const outputs = [...this.pending].filter(([, entry]) => entry.scheduleId === id);
640
+ this.purged.set(id, ownerOf(record));
641
+ this.records.delete(id);
642
+ this.dropPending(id);
643
+ try {
644
+ await this.persist();
645
+ }
646
+ catch (error) {
647
+ this.records.set(id, record);
648
+ this.purged.delete(id);
649
+ for (const [key, entry] of outputs)
650
+ this.pending.set(key, entry);
651
+ throw error;
652
+ }
653
+ this.runtimes.delete(id);
654
+ return { status: 'removed' };
655
+ });
656
+ if (record.creationRefused || clean || retainedVerified || handleProof)
657
+ return erase();
658
+ if (!this.options.withPurgeVerification)
659
+ return pending('native_absence_unknown', 'Native absence and execution retirement require exact provider verification; terminal state and current-session absence alone are insufficient.');
660
+ let accepted = false;
661
+ // The framework keeps its native scope/lease open until accept() finishes
662
+ // persisting removal. A receipt returned after closing that lease is unsafe.
663
+ return this.options.withPurgeVerification(structuredClone(record), { isCurrent: current }, async (evidence) => {
664
+ if (accepted)
665
+ throw new Error('Purge verification was already consumed.');
666
+ accepted = true;
667
+ if (!current())
668
+ throw new Error('Schedule purge context changed during verification.');
669
+ if (evidence.status === 'unresolved')
670
+ return pending(evidence.reason, bounded(evidence.detail, ERROR_BYTES));
671
+ if (evidence.status !== 'verified' || typeof evidence.isCurrent !== 'function')
672
+ throw new Error('Invalid native purge verification.');
673
+ return erase(evidence);
674
+ });
675
+ }
495
676
  /** Includes terminal jobs whose native process exit is still unconfirmed. */
496
677
  hasActiveSchedules(threadId) {
497
678
  return [...this.records.values()].some(record => (!threadId || record.threadId === threadId)
@@ -507,8 +688,9 @@ class ScheduleService {
507
688
  return LIVE.has(record.state) || recoveryOwnsWork(record) || record.state === 'interrupted' && !!record.nativeId && this.supportsRetainedCancellation(record)
508
689
  || Boolean(runtime && !runtime.stopped);
509
690
  }
510
- /** Newly observed local cleanup facts do not supply historical recovery proof. */
511
- async recordReviewedCleanup(owner, ids, absent) {
691
+ /** Newly observed cleanup facts never supply historical recovery proof. The optional
692
+ * retirement callback is framework-owned and checked under the native cleanup lease. */
693
+ async recordReviewedCleanup(owner, ids, absent, retirementConfirmed) {
512
694
  this.checkReady();
513
695
  validateOwner(owner);
514
696
  ids.forEach(ScheduleCommand_1.validateScheduleId);
@@ -519,6 +701,7 @@ class ScheduleService {
519
701
  throw new Error('Cleanup catalog owner changed.');
520
702
  for (const id of ids) {
521
703
  const record = this.owned(owner, id);
704
+ delete record.cleanupConfirmed;
522
705
  record.cancelRequested = true;
523
706
  if (record.recovery)
524
707
  record.recovery.status = 'blocked';
@@ -526,6 +709,18 @@ class ScheduleService {
526
709
  record.state = 'interrupted';
527
710
  record.error = absent ? 'Owner-reviewed native definition absent on current host; predecessor work remains unknown.'
528
711
  : 'Owner-reviewed native deletion requested; absence and predecessor work remain unconfirmed.';
712
+ const runtime = this.runtimes.get(id);
713
+ if (absent && retirementConfirmed?.() === true && (!runtime || runtime.stopped && !runtime.running.size)
714
+ && !this.recordOperations.has(id) && !this.recoveryRun && !this.refreshes && !this.retainedCancellations.has(id)) {
715
+ record.state = 'cancelled';
716
+ record.cleanupConfirmed = true;
717
+ delete record.error;
718
+ // Native-only cleanup must not discard already-admitted output. History
719
+ // purge owns output removal after checking in-flight delivery fences.
720
+ for (const pending of this.pending.values())
721
+ if (pending.scheduleId === id)
722
+ pending.afterCancellation = true;
723
+ }
529
724
  }
530
725
  await this.persist();
531
726
  });
@@ -545,7 +740,8 @@ class ScheduleService {
545
740
  }
546
741
  /** User-requested native reconciliation only; no background polling is installed. */
547
742
  refresh(owner) {
548
- return this.operation(this.refreshNative(owner));
743
+ this.refreshes++;
744
+ return this.operation(this.refreshNative(owner).finally(() => { this.refreshes--; }));
549
745
  }
550
746
  async refreshNative(owner) {
551
747
  this.checkReady();
@@ -588,7 +784,7 @@ class ScheduleService {
588
784
  }
589
785
  }
590
786
  cancel(owner, id) {
591
- return this.operation(this.cancelSchedule(owner, id));
787
+ return this.operation(this.recordOperation(id, this.cancelSchedule(owner, id)));
592
788
  }
593
789
  async cancelSchedule(owner, id) {
594
790
  this.checkReady();
@@ -671,6 +867,7 @@ class ScheduleService {
671
867
  if (!current())
672
868
  throw new Error('Native cancellation owner changed before its receipt was saved.');
673
869
  record.state = 'cancelled';
870
+ record.cleanupConfirmed = true;
674
871
  delete record.error;
675
872
  for (const [key, pending] of this.pending)
676
873
  if (pending.scheduleId === record.id && !pending.afterCancellation)
@@ -930,8 +1127,10 @@ class ScheduleService {
930
1127
  try {
931
1128
  const handle = await runtime.ready;
932
1129
  if (handle && !runtime.stopped) {
933
- if (LIVE.has(this.records.get(id).state) || handle.cancellationKeepsRunning)
1130
+ if (LIVE.has(this.records.get(id).state) || handle.cancellationKeepsRunning) {
934
1131
  await handle.cancel();
1132
+ runtime.removalConfirmed = true;
1133
+ }
935
1134
  else
936
1135
  await this.stop(id, runtime);
937
1136
  }
@@ -978,6 +1177,8 @@ class ScheduleService {
978
1177
  let cleanup = false;
979
1178
  const runtime = this.runtimes.get(id);
980
1179
  await this.serial(async () => {
1180
+ if (!runtime || this.runtimes.get(id) !== runtime || !this.records.has(id))
1181
+ return;
981
1182
  if (this.fault)
982
1183
  throw this.fault;
983
1184
  const record = this.records.get(id);
@@ -1111,6 +1312,8 @@ class ScheduleService {
1111
1312
  const pending = this.pending.get(id);
1112
1313
  if (!pending)
1113
1314
  return;
1315
+ if (this.purges.has(pending.scheduleId))
1316
+ return;
1114
1317
  const record = this.records.get(pending.scheduleId);
1115
1318
  if (!this.current(record) || record.state === 'cancelled' && !pending.afterCancellation) {
1116
1319
  this.pending.delete(id);
@@ -1127,7 +1330,8 @@ class ScheduleService {
1127
1330
  success: pending.success, ...(pending.output !== undefined && { output: pending.output }),
1128
1331
  ...(pending.error !== undefined && { error: pending.error }) };
1129
1332
  });
1130
- if (!delivery || this.closing || !this.current(delivery.schedule) || !this.pending.has(id))
1333
+ if (!delivery || this.closing || !this.current(delivery.schedule) || !this.pending.has(id)
1334
+ || this.purges.has(delivery.schedule.id))
1131
1335
  continue;
1132
1336
  const runtime = this.runtimes.get(delivery.schedule.id);
1133
1337
  if (runtime?.cancelling) {
@@ -1135,12 +1339,16 @@ class ScheduleService {
1135
1339
  runtime.heldDeliveries.add(id);
1136
1340
  continue;
1137
1341
  }
1342
+ this.delivering.add(delivery.schedule.id);
1138
1343
  try {
1139
1344
  await this.options.deliver(delivery);
1140
1345
  }
1141
1346
  catch {
1142
1347
  continue;
1143
1348
  } // Keep the persisted outbox; only explicit reconnect retries it.
1349
+ finally {
1350
+ this.delivering.delete(delivery.schedule.id);
1351
+ }
1144
1352
  await this.serial(async () => { this.pending.delete(id); await this.persist(); });
1145
1353
  }
1146
1354
  });
@@ -1148,8 +1356,10 @@ class ScheduleService {
1148
1356
  return run;
1149
1357
  }
1150
1358
  stop(id, runtime) {
1151
- if (runtime.stopped)
1359
+ if (this.runtimes.get(id) !== runtime)
1152
1360
  return Promise.resolve();
1361
+ if (runtime.stopped)
1362
+ return this.rememberCleanup(id, runtime);
1153
1363
  if (runtime.stopPromise)
1154
1364
  return runtime.recoveryAbort ? this.boundRecovery(runtime.stopPromise, 'Native cleanup remains unresolved; ownership retained.') : runtime.stopPromise;
1155
1365
  const operation = (async () => {
@@ -1158,8 +1368,12 @@ class ScheduleService {
1158
1368
  throw new Error('Recovery receipt is unresolved; native ownership retained.');
1159
1369
  }
1160
1370
  const handle = await runtime.ready;
1161
- if (handle && !runtime.stopped)
1371
+ if (handle && !runtime.stopped) {
1162
1372
  await handle.stop();
1373
+ // Process/job retirement is not itself proof that persisted timing was deleted.
1374
+ if (handle.nativeDefinitionAbsent === true)
1375
+ runtime.removalConfirmed = true;
1376
+ }
1163
1377
  // A shared session can delete future firings while an occurrence still
1164
1378
  // finishes. Keep ownership until its terminal stopped notification.
1165
1379
  if (!handle?.cancellationKeepsRunning || !runtime.running.size)
@@ -1167,6 +1381,7 @@ class ScheduleService {
1167
1381
  if (runtime.stopped) {
1168
1382
  runtime.releaseAdmission?.();
1169
1383
  runtime.releaseAdmission = undefined;
1384
+ await this.rememberCleanup(id, runtime);
1170
1385
  }
1171
1386
  }
1172
1387
  catch (error) {
@@ -1178,10 +1393,22 @@ class ScheduleService {
1178
1393
  throw error;
1179
1394
  }
1180
1395
  })();
1181
- runtime.stopPromise = operation;
1396
+ const tracked = this.recordOperation(id, operation);
1397
+ runtime.stopPromise = tracked;
1182
1398
  void operation.finally(() => { if (!runtime.stopped)
1183
1399
  runtime.stopPromise = undefined; }).catch(() => { });
1184
- return runtime.recoveryAbort ? this.boundRecovery(operation, 'Native cleanup remains unresolved; ownership retained.') : operation;
1400
+ return runtime.recoveryAbort ? this.boundRecovery(tracked, 'Native cleanup remains unresolved; ownership retained.') : tracked;
1401
+ }
1402
+ rememberCleanup(id, runtime) {
1403
+ return this.serial(async () => {
1404
+ const record = this.records.get(id);
1405
+ if (this.runtimes.get(id) === runtime && runtime.stopped && !runtime.running.size
1406
+ && runtime.removalConfirmed && runtime.handle?.nativeDefinitionAbsent === true
1407
+ && record?.cancelRequested && record.state === 'cancelled' && !record.cleanupConfirmed) {
1408
+ record.cleanupConfirmed = true;
1409
+ await this.persist();
1410
+ }
1411
+ });
1185
1412
  }
1186
1413
  async boundRecovery(operation, message) {
1187
1414
  let timer;
@@ -1220,6 +1447,16 @@ class ScheduleService {
1220
1447
  void task.finally(() => this.operations.delete(task)).catch(() => { });
1221
1448
  return task;
1222
1449
  }
1450
+ recordOperation(id, task) {
1451
+ this.recordOperations.set(id, (this.recordOperations.get(id) ?? 0) + 1);
1452
+ return task.finally(() => {
1453
+ const remaining = this.recordOperations.get(id) - 1;
1454
+ if (remaining)
1455
+ this.recordOperations.set(id, remaining);
1456
+ else
1457
+ this.recordOperations.delete(id);
1458
+ });
1459
+ }
1223
1460
  current(owner) {
1224
1461
  try {
1225
1462
  return this.options.isOwnerCurrent(ownerOf(owner)) === true;
@@ -1266,7 +1503,7 @@ class ScheduleService {
1266
1503
  try {
1267
1504
  // JSON can expand one control byte to six bytes (for example, "\\u0001").
1268
1505
  const maxBytes = (this.maxRecords + this.maxPending) * (160 * 1024)
1269
- + this.maxRecords * this.maxOccurrences * 515 + 4096;
1506
+ + this.maxRecords * this.maxOccurrences * 515 + MAX_PURGED_IDS * 2048 + 4096;
1270
1507
  const size = (await handle.stat()).size;
1271
1508
  if (size > maxBytes)
1272
1509
  throw new Error('Schedule catalog exceeds its size limit.');
@@ -1291,14 +1528,14 @@ class ScheduleService {
1291
1528
  }
1292
1529
  }
1293
1530
  load(data) {
1294
- const catalog = object(data, ['version', 'records', 'pending']);
1295
- if (![1, 2].includes(catalog.version) || !Array.isArray(catalog.records) || catalog.records.length > this.maxRecords
1531
+ const catalog = object(data, ['version', 'records', 'pending', 'purged']);
1532
+ if (![1, 2, 3, 4].includes(catalog.version) || !Array.isArray(catalog.records) || catalog.records.length > this.maxRecords
1296
1533
  || !Array.isArray(catalog.pending) || catalog.pending.length > this.maxPending)
1297
1534
  throw new Error('Invalid schedule catalog envelope.');
1298
1535
  const records = new Map();
1299
1536
  const pending = new Map();
1300
1537
  for (const value of catalog.records) {
1301
- const record = object(value, ['id', 'backend', 'cwd', 'prompt', 'rule', 'createdAt', 'nativeId', 'state', 'error', 'threadId', 'openId', 'generation', 'execution', 'cancelRequested', 'recovery', 'completedOccurrences', 'skippedOccurrences']);
1538
+ const record = object(value, ['id', 'backend', 'cwd', 'prompt', 'rule', 'createdAt', 'nativeId', 'state', 'error', 'threadId', 'openId', 'generation', 'execution', 'cancelRequested', 'creationRefused', 'cleanupConfirmed', 'recovery', 'completedOccurrences', 'skippedOccurrences']);
1302
1539
  (0, ScheduleCommand_1.validateScheduleId)(record.id);
1303
1540
  validateOwner(record);
1304
1541
  (0, ScheduleCommand_1.validateSchedulePrompt)(record.prompt);
@@ -1313,6 +1550,13 @@ class ScheduleService {
1313
1550
  throw new Error('Invalid schedule error.');
1314
1551
  if (record.cancelRequested !== undefined && record.cancelRequested !== true)
1315
1552
  throw new Error('Invalid cancellation intent.');
1553
+ if (record.creationRefused !== undefined && (Number(catalog.version) < 3 || record.creationRefused !== true || record.nativeId !== undefined
1554
+ || !['failed', 'cancelled', 'interrupted'].includes(record.state)
1555
+ || record.completedOccurrences !== undefined))
1556
+ throw new Error('Invalid native admission refusal.');
1557
+ if (record.cleanupConfirmed !== undefined && (catalog.version !== 4 || record.cleanupConfirmed !== true
1558
+ || record.cancelRequested !== true || record.state !== 'cancelled'))
1559
+ throw new Error('Invalid confirmed cleanup receipt.');
1316
1560
  if (record.execution !== undefined) {
1317
1561
  const execution = object(record.execution, ['command', 'model', 'effort']);
1318
1562
  for (const value of Object.values(execution))
@@ -1320,8 +1564,8 @@ class ScheduleService {
1320
1564
  text(value, 4096);
1321
1565
  }
1322
1566
  if (record.recovery !== undefined) {
1323
- if (catalog.version !== 2)
1324
- throw new Error('Recovery requires catalog version 2.');
1567
+ if (catalog.version === 1)
1568
+ throw new Error('Recovery requires catalog version 2 or newer.');
1325
1569
  const recovery = object(record.recovery, ['version', 'provider', 'strategy', 'identity', 'status', 'orderlyOnly', 'futureOnly', 'handoff', 'nativeDefinitionAbsent', 'handoffPolicy']);
1326
1570
  this.validateCheckpoint(recovery);
1327
1571
  if (!['eligible', 'pending', 'blocked'].includes(recovery.status))
@@ -1363,8 +1607,24 @@ class ScheduleService {
1363
1607
  throw new Error('Invalid cancellation delivery flag.');
1364
1608
  pending.set(item.id, structuredClone(item));
1365
1609
  }
1610
+ const purged = new Map();
1611
+ if (Number(catalog.version) >= 3) {
1612
+ if (!Array.isArray(catalog.purged) || catalog.purged.length > MAX_PURGED_IDS)
1613
+ throw new Error('Invalid purge fences.');
1614
+ for (const value of catalog.purged) {
1615
+ const fence = object(value, ['id', 'threadId', 'openId', 'generation']);
1616
+ (0, ScheduleCommand_1.validateScheduleId)(fence.id);
1617
+ validateOwner(fence);
1618
+ if (records.has(fence.id) || purged.has(fence.id))
1619
+ throw new Error('Conflicting purge fence.');
1620
+ purged.set(fence.id, ownerOf(fence));
1621
+ }
1622
+ }
1623
+ else if (catalog.purged !== undefined)
1624
+ throw new Error('Purge fences require catalog version 3 or newer.');
1366
1625
  this.records = records;
1367
1626
  this.pending = pending;
1627
+ this.purged = purged;
1368
1628
  }
1369
1629
  async persist() {
1370
1630
  if (!this.catalogGate)
@@ -1385,7 +1645,10 @@ class ScheduleService {
1385
1645
  }
1386
1646
  const handle = await fs.open(temporary, 'wx', 0o600);
1387
1647
  try {
1388
- await handle.writeFile(JSON.stringify({ version: 2, records: [...this.records.values()], pending: [...this.pending.values()] }), 'utf8');
1648
+ const confirmedCleanup = [...this.records.values()].some(record => record.cleanupConfirmed);
1649
+ const upgraded = confirmedCleanup || this.purged.size > 0 || [...this.records.values()].some(record => record.creationRefused);
1650
+ await handle.writeFile(JSON.stringify({ version: confirmedCleanup ? 4 : upgraded ? 3 : 2, records: [...this.records.values()], pending: [...this.pending.values()],
1651
+ ...(upgraded ? { purged: [...this.purged].map(([id, owner]) => ({ id, ...owner })) } : {}) }), 'utf8');
1389
1652
  await handle.sync();
1390
1653
  }
1391
1654
  finally {