@yu_robotics/remote-cli 1.6.264 → 1.6.266

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 (133) hide show
  1. package/README.md +41 -0
  2. package/dist/client/MessageHandler.d.ts +13 -2
  3. package/dist/client/MessageHandler.d.ts.map +1 -1
  4. package/dist/client/MessageHandler.js +393 -172
  5. package/dist/client/MessageHandler.js.map +1 -1
  6. package/dist/client/WebSocketClient.d.ts.map +1 -1
  7. package/dist/client/WebSocketClient.js +1 -0
  8. package/dist/client/WebSocketClient.js.map +1 -1
  9. package/dist/delegation/piExtension.js +1 -1
  10. package/dist/delegation/piExtension.js.map +1 -1
  11. package/dist/executor/AcpExecutor.d.ts +11 -4
  12. package/dist/executor/AcpExecutor.d.ts.map +1 -1
  13. package/dist/executor/AcpExecutor.js +64 -11
  14. package/dist/executor/AcpExecutor.js.map +1 -1
  15. package/dist/executor/AgyExecutor.d.ts +6 -0
  16. package/dist/executor/AgyExecutor.d.ts.map +1 -1
  17. package/dist/executor/AgyExecutor.js +126 -9
  18. package/dist/executor/AgyExecutor.js.map +1 -1
  19. package/dist/executor/ClaudePersistentExecutor.d.ts +5 -1
  20. package/dist/executor/ClaudePersistentExecutor.d.ts.map +1 -1
  21. package/dist/executor/ClaudePersistentExecutor.js +81 -17
  22. package/dist/executor/ClaudePersistentExecutor.js.map +1 -1
  23. package/dist/executor/CodexAppServerClient.d.ts +1 -1
  24. package/dist/executor/CodexAppServerClient.d.ts.map +1 -1
  25. package/dist/executor/CodexAppServerClient.js +8 -2
  26. package/dist/executor/CodexAppServerClient.js.map +1 -1
  27. package/dist/executor/CodexAppServerExecutor.d.ts +3 -1
  28. package/dist/executor/CodexAppServerExecutor.d.ts.map +1 -1
  29. package/dist/executor/CodexAppServerExecutor.js +67 -22
  30. package/dist/executor/CodexAppServerExecutor.js.map +1 -1
  31. package/dist/executor/DshExecutor.d.ts +2 -0
  32. package/dist/executor/DshExecutor.d.ts.map +1 -1
  33. package/dist/executor/DshExecutor.js +26 -6
  34. package/dist/executor/DshExecutor.js.map +1 -1
  35. package/dist/executor/IExecutor.d.ts +4 -0
  36. package/dist/executor/IExecutor.d.ts.map +1 -1
  37. package/dist/executor/PiExecutor.d.ts +2 -0
  38. package/dist/executor/PiExecutor.d.ts.map +1 -1
  39. package/dist/executor/PiExecutor.js +96 -23
  40. package/dist/executor/PiExecutor.js.map +1 -1
  41. package/dist/executor/acp/AcpClient.d.ts +4 -3
  42. package/dist/executor/acp/AcpClient.d.ts.map +1 -1
  43. package/dist/executor/acp/AcpClient.js +18 -2
  44. package/dist/executor/acp/AcpClient.js.map +1 -1
  45. package/dist/executor/agy/AgyAcpRuntime.d.ts +8 -1
  46. package/dist/executor/agy/AgyAcpRuntime.d.ts.map +1 -1
  47. package/dist/executor/agy/AgyAcpRuntime.js +47 -3
  48. package/dist/executor/agy/AgyAcpRuntime.js.map +1 -1
  49. package/dist/executor/agy/AgySessionSelection.d.ts +3 -0
  50. package/dist/executor/agy/AgySessionSelection.d.ts.map +1 -1
  51. package/dist/executor/agy/AgySessionSelection.js +24 -0
  52. package/dist/executor/agy/AgySessionSelection.js.map +1 -1
  53. package/dist/executor/dsh/DshAcpClient.d.ts +1 -1
  54. package/dist/executor/dsh/DshAcpClient.d.ts.map +1 -1
  55. package/dist/executor/dsh/DshAcpClient.js +2 -2
  56. package/dist/executor/dsh/DshAcpClient.js.map +1 -1
  57. package/dist/executor/pi/PiClient.d.ts +3 -1
  58. package/dist/executor/pi/PiClient.d.ts.map +1 -1
  59. package/dist/executor/pi/PiClient.js +15 -1
  60. package/dist/executor/pi/PiClient.js.map +1 -1
  61. package/dist/executor/pi/PiTypes.d.ts +3 -1
  62. package/dist/executor/pi/PiTypes.d.ts.map +1 -1
  63. package/dist/executor/pi/PiTypes.js.map +1 -1
  64. package/dist/executor/zcode/ZCodeClient.d.ts +2 -2
  65. package/dist/executor/zcode/ZCodeClient.d.ts.map +1 -1
  66. package/dist/executor/zcode/ZCodeClient.js +26 -7
  67. package/dist/executor/zcode/ZCodeClient.js.map +1 -1
  68. package/dist/maintenance/release-notes.json +1 -1
  69. package/dist/managed/tools.d.ts +6 -6
  70. package/dist/scheduling/ScheduleCapabilities.d.ts +59 -14
  71. package/dist/scheduling/ScheduleCapabilities.d.ts.map +1 -1
  72. package/dist/scheduling/ScheduleCapabilities.js +33 -29
  73. package/dist/scheduling/ScheduleCapabilities.js.map +1 -1
  74. package/dist/scheduling/ScheduleCardService.d.ts.map +1 -1
  75. package/dist/scheduling/ScheduleCardService.js +3 -1
  76. package/dist/scheduling/ScheduleCardService.js.map +1 -1
  77. package/dist/scheduling/ScheduleCleanup.d.ts +3 -2
  78. package/dist/scheduling/ScheduleCleanup.d.ts.map +1 -1
  79. package/dist/scheduling/ScheduleCleanup.js +3 -0
  80. package/dist/scheduling/ScheduleCleanup.js.map +1 -1
  81. package/dist/scheduling/ScheduleCommand.d.ts +1 -3
  82. package/dist/scheduling/ScheduleCommand.d.ts.map +1 -1
  83. package/dist/scheduling/ScheduleCommand.js +10 -62
  84. package/dist/scheduling/ScheduleCommand.js.map +1 -1
  85. package/dist/scheduling/ScheduleDeliveryClient.d.ts +2 -1
  86. package/dist/scheduling/ScheduleDeliveryClient.d.ts.map +1 -1
  87. package/dist/scheduling/ScheduleDeliveryClient.js +20 -8
  88. package/dist/scheduling/ScheduleDeliveryClient.js.map +1 -1
  89. package/dist/scheduling/ScheduleService.d.ts +48 -4
  90. package/dist/scheduling/ScheduleService.d.ts.map +1 -1
  91. package/dist/scheduling/ScheduleService.js +582 -73
  92. package/dist/scheduling/ScheduleService.js.map +1 -1
  93. package/dist/scheduling/ScheduleToolScope.d.ts +4 -1
  94. package/dist/scheduling/ScheduleToolScope.d.ts.map +1 -1
  95. package/dist/scheduling/ScheduleToolScope.js +14 -13
  96. package/dist/scheduling/ScheduleToolScope.js.map +1 -1
  97. package/dist/scheduling/agy/AgyHookRelay.d.ts +3 -0
  98. package/dist/scheduling/agy/AgyHookRelay.d.ts.map +1 -1
  99. package/dist/scheduling/agy/AgyHookRelay.js +15 -1
  100. package/dist/scheduling/agy/AgyHookRelay.js.map +1 -1
  101. package/dist/scheduling/claude/ClaudeScheduleOwnership.d.ts +2 -0
  102. package/dist/scheduling/claude/ClaudeScheduleOwnership.d.ts.map +1 -1
  103. package/dist/scheduling/claude/ClaudeScheduleOwnership.js +11 -0
  104. package/dist/scheduling/claude/ClaudeScheduleOwnership.js.map +1 -1
  105. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts +3 -2
  106. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts.map +1 -1
  107. package/dist/scheduling/claude/ClaudeSessionSchedules.js +12 -4
  108. package/dist/scheduling/claude/ClaudeSessionSchedules.js.map +1 -1
  109. package/dist/scheduling/dsh/ScheduledSessionGuard.js +1 -1
  110. package/dist/scheduling/dsh/ScheduledSessionGuard.js.map +1 -1
  111. package/dist/scheduling/host/HostScheduleRule.d.ts +6 -0
  112. package/dist/scheduling/host/HostScheduleRule.d.ts.map +1 -0
  113. package/dist/scheduling/host/HostScheduleRule.js +144 -0
  114. package/dist/scheduling/host/HostScheduleRule.js.map +1 -0
  115. package/dist/scheduling/toolContract.d.ts +3 -3
  116. package/dist/scheduling/toolContract.js +4 -4
  117. package/dist/scheduling/toolContract.js.map +1 -1
  118. package/dist/scheduling/types.d.ts +20 -2
  119. package/dist/scheduling/types.d.ts.map +1 -1
  120. package/dist/scheduling/types.js.map +1 -1
  121. package/dist/types/ScheduleCards.d.ts +2 -1
  122. package/dist/types/ScheduleCards.d.ts.map +1 -1
  123. package/dist/types/index.d.ts +2 -0
  124. package/dist/types/index.d.ts.map +1 -1
  125. package/native/prebuilds/darwin-arm64/managed_native.node +0 -0
  126. package/native/prebuilds/darwin-arm64/manifest.json +1 -1
  127. package/native/prebuilds/darwin-x64/managed_native.node +0 -0
  128. package/native/prebuilds/darwin-x64/manifest.json +1 -1
  129. package/native/prebuilds/win32-arm64/managed_native.node +0 -0
  130. package/native/prebuilds/win32-arm64/manifest.json +1 -1
  131. package/native/prebuilds/win32-x64/managed_native.node +0 -0
  132. package/native/prebuilds/win32-x64/manifest.json +1 -1
  133. package/package.json +1 -1
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.ScheduleService = exports.SCHEDULE_CATALOG_FILE = void 0;
39
+ exports.ScheduleService = exports.HOST_SCHEDULE_CATALOG_FILE = exports.SCHEDULE_CATALOG_FILE = void 0;
40
40
  const ScheduleCleanup_1 = require("./ScheduleCleanup");
41
41
  const OwnershipRuntime_1 = require("../delegation/OwnershipRuntime");
42
42
  const node_fs_1 = require("node:fs");
@@ -46,9 +46,12 @@ const node_crypto_1 = require("node:crypto");
46
46
  const ScheduleCommand_1 = require("./ScheduleCommand");
47
47
  const types_1 = require("./types");
48
48
  const ScheduleCapabilities_1 = require("./ScheduleCapabilities");
49
+ const HostScheduleRule_1 = require("./host/HostScheduleRule");
49
50
  exports.SCHEDULE_CATALOG_FILE = 'schedule-catalog.json';
51
+ exports.HOST_SCHEDULE_CATALOG_FILE = 'host-schedule-catalog.json';
50
52
  const OUTPUT_BYTES = 16 * 1024;
51
53
  const ERROR_BYTES = 4096;
54
+ const HOST_BUSY_RETRY_MS = 1000;
52
55
  const LIVE = new Set(['creating', 'active', 'running']);
53
56
  const STATES = new Set([...LIVE, 'completed', 'cancelled', 'interrupted', 'failed']);
54
57
  const RESTART_REASON = 'Native schedule interrupted by service restart; not recreated or resumed.';
@@ -78,7 +81,8 @@ function text(value, max = 256) {
78
81
  throw new Error('Invalid schedule identifier or path.');
79
82
  }
80
83
  function ownerOf(record) {
81
- return { threadId: record.threadId, openId: record.openId, generation: record.generation };
84
+ return { threadId: record.threadId, openId: record.openId, generation: record.generation,
85
+ ...(record.bindingEpoch !== undefined && { bindingEpoch: record.bindingEpoch }) };
82
86
  }
83
87
  function validateOwner(owner) {
84
88
  if (!owner || typeof owner !== 'object')
@@ -86,15 +90,19 @@ function validateOwner(owner) {
86
90
  text(owner.threadId);
87
91
  text(owner.openId);
88
92
  text(owner.generation);
93
+ if (owner.bindingEpoch !== undefined)
94
+ text(owner.bindingEpoch);
89
95
  }
90
96
  function sameOwner(left, right) {
91
- return left.threadId === right.threadId && left.openId === right.openId && left.generation === right.generation;
97
+ return left.threadId === right.threadId && left.openId === right.openId && left.generation === right.generation
98
+ && (left.bindingEpoch === undefined ? left.engine !== 'host' : left.bindingEpoch === right.bindingEpoch);
92
99
  }
93
100
  /** Deletion-only obligations and receipts remain manageable by the same user in
94
101
  * the same thread after reset. Original provenance stays immutable; live records
95
102
  * and all execution admission continue to require exact generation ownership. */
96
103
  function sameCleanupOwner(left, right) {
97
- return left.threadId === right.threadId && left.openId === right.openId;
104
+ return left.threadId === right.threadId && left.openId === right.openId
105
+ && (left.bindingEpoch === undefined || sameOwner(left, right));
98
106
  }
99
107
  /** Unknown native mutation/queued reminders remain cleanup obligations after host loss. */
100
108
  function unsettledNativeWork(record) {
@@ -106,7 +114,7 @@ function deliveryId(scheduleId, occurrenceId) {
106
114
  return `${scheduleId}:${occurrenceId}`;
107
115
  }
108
116
  /**
109
- * Single service instance per directory. Native processes, never this service, own timing.
117
+ * Single timing and catalog owner per directory.
110
118
  * Delivery is fenced immediately before invoking the callback; an external send already
111
119
  * in flight cannot be revoked. A crash between sending and persisting acknowledgement
112
120
  * can replay an outbox entry after explicit reconnect. Consumers receive a stable ID.
@@ -140,7 +148,19 @@ class ScheduleService {
140
148
  pendingCreates = 0;
141
149
  fault;
142
150
  catalogPath = '';
151
+ hostCatalogPath = '';
152
+ hostCatalogIds = new Set();
153
+ hostPurgeRequests = new Set();
154
+ catalogDigests = new Map();
155
+ unavailableLegacyIds = new Set();
156
+ legacyUnavailable = false;
157
+ get legacyCatalogUnavailable() { return this.legacyUnavailable; }
143
158
  catalogGate;
159
+ hostTimer;
160
+ hostTimerAt;
161
+ hostStartup = 0;
162
+ hostAttempts = new Set();
163
+ hostRetryAt = new Map();
144
164
  constructor(options) {
145
165
  this.options = { ...options };
146
166
  this.now = options.now ?? Date.now;
@@ -162,18 +182,43 @@ class ScheduleService {
162
182
  await fs.mkdir(this.options.directory, { recursive: true, mode: 0o700 });
163
183
  const directory = await fs.realpath(this.options.directory);
164
184
  this.catalogPath = node_path_1.default.join(directory, exports.SCHEDULE_CATALOG_FILE);
185
+ this.hostCatalogPath = node_path_1.default.join(directory, exports.HOST_SCHEDULE_CATALOG_FILE);
165
186
  this.catalogGate = (0, OwnershipRuntime_1.kernelGate)(`${this.catalogPath}.lock`);
166
187
  if (!this.catalogGate)
167
188
  throw new Error('Another client owns the schedule catalog.');
168
- const data = await this.readCatalog();
169
- if (data !== undefined)
170
- this.load(data);
189
+ const data = await this.readCatalog(this.catalogPath);
190
+ if (data !== undefined) {
191
+ try {
192
+ this.load(data);
193
+ }
194
+ catch (error) {
195
+ // Published pre-host formats can carry retired provider checkpoints.
196
+ // Preserve their bytes and replay fences without interpreting them as host work.
197
+ const legacy = data;
198
+ if (!this.options.hostDispatch || ![1, 2, 3, 4, 5, 6].includes(legacy?.version ?? 0)
199
+ || !Array.isArray(legacy.records) || legacy.purged !== undefined && !Array.isArray(legacy.purged)
200
+ || legacy.records.some(row => row && ['engine', 'sessionId', 'bindingEpoch', 'nextDueAt', 'inFlightDueAt'].some(key => Object.hasOwn(row, key))))
201
+ throw error;
202
+ this.legacyUnavailable = true;
203
+ for (const row of [...legacy.records, ...(legacy.purged ?? [])]) {
204
+ if (typeof row?.id === 'string')
205
+ this.unavailableLegacyIds.add(row.id);
206
+ }
207
+ console.warn('[Schedules] The legacy native catalog is incompatible and has been preserved. Only host schedules are available.');
208
+ }
209
+ }
210
+ const hostData = await this.readCatalog(this.hostCatalogPath);
211
+ if (hostData !== undefined)
212
+ this.load(hostData, true);
171
213
  // Inspect the loaded outbox before ordinary startup pruning. Missing
172
214
  // delivery ownership must not turn a refused row into an absence claim.
173
215
  for (const record of [...this.records.values()])
174
216
  await this.compactRefusedCreation(record);
175
217
  let changed = false;
218
+ this.hostStartup = this.now();
176
219
  for (const record of this.records.values()) {
220
+ if (record.engine === 'host')
221
+ continue;
177
222
  if (record.recovery && record.recovery.status !== 'blocked') {
178
223
  record.recovery.status = 'blocked';
179
224
  changed = true;
@@ -186,14 +231,24 @@ class ScheduleService {
186
231
  }
187
232
  for (const [id, delivery] of this.pending) {
188
233
  const record = this.records.get(delivery.scheduleId);
189
- if (record.state === 'cancelled' && !delivery.afterCancellation || !this.current(record)) {
234
+ if (record.state === 'cancelled' && !delivery.afterCancellation || record.engine !== 'host' && !this.current(record)) {
190
235
  this.pending.delete(id);
191
236
  changed = true;
192
237
  }
193
238
  }
239
+ if (this.retireStaleHosts())
240
+ changed = true;
241
+ const recoveryDeliveries = [];
242
+ for (const record of this.records.values()) {
243
+ if (record.engine === 'host' && this.reconcileHost(record, this.hostStartup, recoveryDeliveries))
244
+ changed = true;
245
+ }
194
246
  if (changed || data === undefined || data.version !== 6)
195
247
  await this.persist();
196
248
  this.initialized = true;
249
+ this.armHostTimer();
250
+ if (recoveryDeliveries.length)
251
+ this.track(this.attemptDeliveries(recoveryDeliveries));
197
252
  }).catch(error => { this.catalogGate?.close(); this.catalogGate = undefined; throw error; });
198
253
  }
199
254
  validateOwnershipMetadata(value) {
@@ -240,8 +295,13 @@ class ScheduleService {
240
295
  const backend = input.backend === undefined ? 'claude' : input.backend;
241
296
  // The service accepts installed providers independently of the foreground
242
297
  // executor availability policy. MessageHandler keeps that admission gate.
243
- if (!(0, ScheduleCapabilities_1.isNativeScheduleBackend)(backend))
298
+ if (input.engine === 'host')
299
+ (0, ScheduleCapabilities_1.assertHostScheduleBackend)(backend);
300
+ else {
244
301
  (0, ScheduleCapabilities_1.assertNativeScheduleBackend)(backend);
302
+ if (this.legacyUnavailable)
303
+ throw new Error('Legacy native catalog is unavailable.');
304
+ }
245
305
  const createdAt = this.now();
246
306
  if (!Number.isSafeInteger(createdAt) || createdAt < 0)
247
307
  throw new Error('Invalid schedule clock.');
@@ -249,43 +309,88 @@ class ScheduleService {
249
309
  (0, ScheduleCommand_1.validateScheduleId)(input.id);
250
310
  (0, ScheduleCommand_1.validateSchedulePrompt)(input.prompt);
251
311
  (0, ScheduleCommand_1.validateScheduleRule)(input.rule, createdAt);
312
+ if (input.engine !== undefined && input.engine !== 'host')
313
+ throw new Error('Unknown schedule engine.');
314
+ if (input.engine === 'host' || input.sessionId !== undefined) {
315
+ if (input.engine !== 'host')
316
+ throw new Error('Session binding requires host scheduling.');
317
+ text(input.sessionId);
318
+ }
319
+ const host = input.engine === 'host';
320
+ if (host) {
321
+ text(input.bindingEpoch);
322
+ if (owner.bindingEpoch !== undefined && owner.bindingEpoch !== input.bindingEpoch)
323
+ throw new Error('Host schedule binding epoch changed.');
324
+ }
325
+ else if (input.bindingEpoch !== undefined)
326
+ throw new Error('Unexpected native schedule binding epoch.');
327
+ if (host && !this.options.hostDispatch)
328
+ throw new Error('Host schedule dispatch is unavailable.');
329
+ const nextDueAt = host ? this.hostDue(input.rule, createdAt) : undefined;
252
330
  text(input.cwd, 4096);
253
331
  if (!node_path_1.default.isAbsolute(input.cwd))
254
332
  throw new Error('Schedule working directory must be absolute.');
255
- const originalOwner = ownerOf(owner);
256
- const nativeInput = { ...structuredClone(input), backend, threadId: owner.threadId };
333
+ const originalOwner = ownerOf({ ...owner, bindingEpoch: host ? input.bindingEpoch : undefined });
334
+ const definition = { ...structuredClone(input), backend, threadId: owner.threadId };
335
+ const nativeInput = !host && (0, ScheduleCapabilities_1.isNativeScheduleBackend)(backend)
336
+ ? { ...definition, backend } : undefined;
257
337
  // Never trust a caller-supplied provider checkpoint.
258
- delete nativeInput.recovery;
338
+ if (nativeInput)
339
+ delete nativeInput.recovery;
259
340
  for (const value of [input.command, input.model, input.effort])
260
341
  if (value !== undefined)
261
342
  text(value, 4096);
262
- const cleanup = this.options.provider.cleanupFor?.(nativeInput);
263
- if (cleanup) {
343
+ const cleanup = nativeInput && this.options.provider.cleanupFor?.(nativeInput);
344
+ if (cleanup && nativeInput) {
264
345
  nativeInput.recovery = { version: 1, provider: cleanup.provider, strategy: cleanup.strategy,
265
346
  identity: cleanup.describe(structuredClone(nativeInput), originalOwner) };
266
347
  this.validateOwnershipMetadata(nativeInput.recovery);
267
348
  }
268
- const runtime = this.newRuntime();
349
+ const runtime = host ? undefined : this.newRuntime();
269
350
  await this.serial(async () => {
270
351
  this.checkReady();
271
352
  if (!this.current(originalOwner))
272
353
  throw new Error('Schedule owner is no longer current.');
273
- if (this.records.has(nativeInput.id) || this.purged.has(nativeInput.id))
354
+ if (this.records.has(definition.id) || this.purged.has(definition.id) || this.unavailableLegacyIds.has(definition.id)) {
274
355
  throw new Error('Schedule ID already exists or was purged.');
275
- if (this.records.size >= this.maxRecords)
276
- throw new Error('Schedule catalog is full; history was not pruned.');
277
- const liveCount = [...this.records.values()].filter(record => LIVE.has(record.state)
278
- || this.hasRetainedCleanupRoute(record)
279
- || (this.runtimes.has(record.id) && !this.runtimes.get(record.id).stopped)).length;
356
+ }
357
+ if (host && this.retireStaleHosts()) {
358
+ await this.persist();
359
+ if (!this.current(originalOwner))
360
+ throw new Error('Schedule owner changed during creation.');
361
+ }
362
+ const records = [...this.records.values()];
363
+ let stale;
364
+ if (records.filter(record => this.hostCatalogIds.has(record.id) === host).length >= this.maxRecords) {
365
+ if (host)
366
+ stale = records.find(record => this.hostCatalogIds.has(record.id) && record.state === 'interrupted'
367
+ && this.hostOwnerStatus(record) === false && !this.hostAttempts.has(record.id) && !this.delivering.has(record.id)
368
+ && !this.recordOperations.has(record.id) && !this.purges.has(record.id));
369
+ if (!stale || this.purgeFencesFull(stale.id))
370
+ throw new Error('Schedule catalog is full; history was not pruned.');
371
+ }
372
+ const liveCount = records.filter(record => (record.engine === 'host') === host && (LIVE.has(record.state)
373
+ || record.inFlightDueAt !== undefined || this.hasRetainedCleanupRoute(record)
374
+ || (this.runtimes.has(record.id) && !this.runtimes.get(record.id).stopped))).length;
280
375
  if (liveCount >= this.maxLive)
281
- throw new Error('Live native schedule limit reached.');
282
- this.records.set(nativeInput.id, { ...originalOwner, id: nativeInput.id, backend,
283
- cwd: nativeInput.cwd, prompt: nativeInput.prompt, rule: structuredClone(nativeInput.rule),
284
- createdAt, state: 'creating', execution: { command: input.command, model: input.model, effort: input.effort },
285
- ...(nativeInput.recovery && { recovery: { ...nativeInput.recovery, status: 'blocked' } }) });
376
+ throw new Error(host ? 'Live host schedule limit reached.' : 'Live native schedule limit reached.');
377
+ if (stale) {
378
+ this.purged.set(stale.id, ownerOf(stale));
379
+ this.records.delete(stale.id);
380
+ }
381
+ if (host)
382
+ this.hostCatalogIds.add(definition.id);
383
+ this.records.set(definition.id, { ...originalOwner, id: definition.id, backend,
384
+ cwd: definition.cwd, prompt: definition.prompt, rule: structuredClone(definition.rule),
385
+ createdAt, state: host ? 'active' : 'creating', execution: { command: definition.command, model: definition.model, effort: definition.effort },
386
+ ...(host && { engine: 'host', sessionId: definition.sessionId, nextDueAt }),
387
+ ...(nativeInput?.recovery && { recovery: { ...nativeInput.recovery, status: 'blocked' } }) });
286
388
  await this.persist();
287
- this.runtimes.set(nativeInput.id, runtime);
389
+ if (runtime)
390
+ this.runtimes.set(definition.id, runtime);
288
391
  });
392
+ if (!runtime || !nativeInput)
393
+ return structuredClone(this.records.get(definition.id));
289
394
  try {
290
395
  const handle = await this.options.provider.create(structuredClone(nativeInput), event => {
291
396
  if (this.runtimes.get(nativeInput.id) !== runtime) {
@@ -372,6 +477,244 @@ class ScheduleService {
372
477
  throw error;
373
478
  }
374
479
  }
480
+ hostDue(rule, after) {
481
+ const due = (0, HostScheduleRule_1.nextHostDue)(rule, after);
482
+ if (due === undefined || !Number.isSafeInteger(due) || due <= after)
483
+ throw new Error('Schedule has no future occurrence.');
484
+ return due;
485
+ }
486
+ advanceHost(record, after) {
487
+ try {
488
+ record.nextDueAt = this.hostDue(record.rule, after);
489
+ record.state = 'active';
490
+ }
491
+ catch (error) {
492
+ delete record.nextDueAt;
493
+ record.state = 'failed';
494
+ record.error = errorText(error);
495
+ }
496
+ }
497
+ /** All calls hold the catalog queue and have a reserved outbox slot. */
498
+ finishHost(record, due, result) {
499
+ const occurrenceId = `host-${due}`;
500
+ const id = deliveryId(record.id, occurrenceId);
501
+ const interruptedCron = result.abortedByUser && record.inFlightDueAt === due && record.rule.kind === 'cron';
502
+ delete record.inFlightDueAt;
503
+ delete record.nextDueAt;
504
+ // Host slots advance monotonically. The persisted next/in-flight slot
505
+ // fences replay even after an old diagnostic receipt leaves this window.
506
+ record.completedOccurrences = [...(record.completedOccurrences ?? []), occurrenceId].slice(-this.maxOccurrences);
507
+ this.pending.set(id, { id, scheduleId: record.id, occurrenceId, success: result.success,
508
+ ...(record.cancelRequested && { afterCancellation: true }),
509
+ ...(result.output !== undefined && { output: bounded(result.output, OUTPUT_BYTES) }),
510
+ ...(result.error !== undefined && { error: bounded(result.error, ERROR_BYTES) }) });
511
+ if (record.cancelRequested)
512
+ record.state = 'cancelled';
513
+ else if (!result.success && !interruptedCron) {
514
+ record.state = 'failed';
515
+ record.error = bounded(result.error ?? 'Host schedule execution failed.', ERROR_BYTES);
516
+ }
517
+ else if (record.rule.kind === 'once')
518
+ record.state = 'completed';
519
+ else
520
+ this.advanceHost(record, Math.max(due, this.now()));
521
+ return id;
522
+ }
523
+ cancelHost(record) {
524
+ record.cancelRequested = true;
525
+ if (LIVE.has(record.state))
526
+ record.state = 'cancelled';
527
+ delete record.nextDueAt;
528
+ this.hostRetryAt.delete(record.id);
529
+ for (const delivery of this.pending.values())
530
+ if (delivery.scheduleId === record.id)
531
+ delivery.afterCancellation = true;
532
+ }
533
+ hostOwnerStatus(record) {
534
+ return record.bindingEpoch === undefined ? false : this.ownerStatus(record);
535
+ }
536
+ retireHost(record) {
537
+ const reason = 'Host schedule owner is no longer current.';
538
+ const changed = record.state !== 'interrupted' || record.error !== reason;
539
+ record.state = 'interrupted';
540
+ record.error = reason;
541
+ delete record.nextDueAt;
542
+ delete record.inFlightDueAt;
543
+ this.hostRetryAt.delete(record.id);
544
+ const count = this.pending.size;
545
+ this.dropPending(record.id);
546
+ return changed || count !== this.pending.size;
547
+ }
548
+ retireStaleHosts() {
549
+ let changed = false;
550
+ for (const record of this.records.values()) {
551
+ if (record.engine === 'host' && this.hostOwnerStatus(record) === false && this.retireHost(record))
552
+ changed = true;
553
+ }
554
+ return changed;
555
+ }
556
+ /** An unresolved admission is never executed again. If the outbox is full,
557
+ * its original disk receipt stays intact until an ACK releases capacity. */
558
+ reconcileHost(record, now, deliveries) {
559
+ if (this.hostAttempts.has(record.id))
560
+ return false;
561
+ const due = record.inFlightDueAt ?? record.nextDueAt;
562
+ if (due === undefined)
563
+ return false;
564
+ if (this.hostOwnerStatus(record) !== true)
565
+ return false;
566
+ if (record.inFlightDueAt === undefined && record.cancelRequested) {
567
+ this.cancelHost(record);
568
+ return true;
569
+ }
570
+ const missed = due < this.hostStartup;
571
+ if (record.inFlightDueAt === undefined && record.rule.kind === 'cron' && (missed || now - due >= 60_000)) {
572
+ this.advanceHost(record, Math.max(now, this.hostStartup));
573
+ return true;
574
+ }
575
+ if (record.inFlightDueAt === undefined && !missed)
576
+ return false;
577
+ if (this.outboxFull(record.id))
578
+ return false;
579
+ const error = record.inFlightDueAt !== undefined
580
+ ? 'Host schedule execution outcome is unknown after restart. The occurrence was not replayed.'
581
+ : 'One-shot schedule was missed while the service was offline.';
582
+ deliveries.push(this.finishHost(record, due, { success: false, error }));
583
+ return true;
584
+ }
585
+ armHostTimer() {
586
+ let earliest = Infinity;
587
+ if (this.initialized && !this.closing && !this.fault) {
588
+ for (const record of this.records.values()) {
589
+ if (record.engine !== 'host' || this.hostAttempts.has(record.id) || this.outboxFull(record.id)
590
+ || this.hostOwnerStatus(record) === undefined)
591
+ continue;
592
+ const due = record.inFlightDueAt !== undefined ? 0 : record.nextDueAt;
593
+ if (due !== undefined)
594
+ earliest = Math.min(earliest, Math.max(due, this.hostRetryAt.get(record.id) ?? 0));
595
+ }
596
+ }
597
+ if (this.hostTimer && this.hostTimerAt === earliest)
598
+ return;
599
+ clearTimeout(this.hostTimer);
600
+ this.hostTimer = undefined;
601
+ this.hostTimerAt = earliest;
602
+ if (earliest === Infinity)
603
+ return;
604
+ // Node clamps overflowing timer delays to one millisecond.
605
+ const delay = Math.min(0x7fffffff, Math.max(0, earliest - this.now()));
606
+ this.hostTimer = setTimeout(() => {
607
+ this.hostTimer = undefined;
608
+ this.track(this.wakeHosts());
609
+ }, delay);
610
+ this.hostTimer.unref();
611
+ }
612
+ outboxFull(id) {
613
+ const host = this.hostCatalogIds.has(id);
614
+ const pending = [...this.pending.values()].filter(item => this.hostCatalogIds.has(item.scheduleId) === host);
615
+ const reservations = [...this.hostAttempts].filter(key => this.hostCatalogIds.has(key) === host && this.records.get(key)?.state !== 'interrupted');
616
+ return pending.length + reservations.length >= this.maxPending;
617
+ }
618
+ async wakeHosts() {
619
+ const deliveries = [];
620
+ const ready = [];
621
+ await this.serial(async () => {
622
+ if (this.closing || this.fault)
623
+ return;
624
+ let changed = this.retireStaleHosts();
625
+ const now = this.now();
626
+ for (const record of this.records.values()) {
627
+ if (record.engine !== 'host' || this.hostAttempts.has(record.id))
628
+ continue;
629
+ if (this.reconcileHost(record, now, deliveries))
630
+ changed = true;
631
+ const due = record.nextDueAt;
632
+ if (due === undefined || due > now || this.hostOwnerStatus(record) !== true || (this.hostRetryAt.get(record.id) ?? 0) > now
633
+ || this.outboxFull(record.id))
634
+ continue;
635
+ this.hostAttempts.add(record.id);
636
+ ready.push({ record, due });
637
+ }
638
+ if (changed)
639
+ await this.persist();
640
+ else
641
+ this.armHostTimer();
642
+ });
643
+ for (const { record, due } of ready)
644
+ this.track(this.dispatchHost(record, due));
645
+ if (deliveries.length)
646
+ await this.attemptDeliveries(deliveries);
647
+ }
648
+ async dispatchHost(record, due) {
649
+ const eligible = () => !this.closing && !this.fault && this.records.get(record.id) === record
650
+ && !record.cancelRequested && record.state === 'active' && record.nextDueAt === due && this.current(record);
651
+ let open = true;
652
+ const admit = () => this.serial(async () => {
653
+ if (!open || !eligible())
654
+ return false;
655
+ record.state = 'running';
656
+ record.inFlightDueAt = due;
657
+ delete record.nextDueAt;
658
+ await this.persist();
659
+ if (!open || this.closing)
660
+ return false;
661
+ const status = this.hostOwnerStatus(record);
662
+ if (status === true)
663
+ return true;
664
+ // No execution authority left this callback. Keep the original slot when
665
+ // registration changed while the admission receipt was being written.
666
+ if (status === false)
667
+ this.retireHost(record);
668
+ else {
669
+ delete record.inFlightDueAt;
670
+ record.nextDueAt = due;
671
+ record.state = 'active';
672
+ }
673
+ await this.persist();
674
+ return false;
675
+ });
676
+ let result;
677
+ try {
678
+ if (eligible()) {
679
+ if (!this.options.hostDispatch)
680
+ throw new Error('Host schedule dispatch is unavailable.');
681
+ result = await this.options.hostDispatch(structuredClone(record), `host-${due}`, admit);
682
+ if (result?.success && record.inFlightDueAt !== due)
683
+ throw new Error('Host dispatch completed without admission.');
684
+ if (!result && record.inFlightDueAt === due)
685
+ throw new Error('Admitted host occurrence returned no result. Its outcome is unknown.');
686
+ }
687
+ }
688
+ catch (error) {
689
+ result = { success: false, error: errorText(error) };
690
+ }
691
+ finally {
692
+ open = false;
693
+ }
694
+ const delivery = await this.serial(async () => {
695
+ this.hostAttempts.delete(record.id);
696
+ this.hostRetryAt.delete(record.id);
697
+ if (this.closing || this.fault || this.records.get(record.id) !== record)
698
+ return;
699
+ let id;
700
+ if (this.hostOwnerStatus(record) === false) {
701
+ this.retireHost(record);
702
+ await this.persist();
703
+ }
704
+ else if (result && (record.inFlightDueAt === due || eligible())) {
705
+ id = this.finishHost(record, due, result);
706
+ await this.persist();
707
+ }
708
+ else {
709
+ if (eligible())
710
+ this.hostRetryAt.set(record.id, this.now() + HOST_BUSY_RETRY_MS);
711
+ this.armHostTimer();
712
+ }
713
+ return id;
714
+ });
715
+ if (delivery)
716
+ await this.attemptDeliveries([delivery]);
717
+ }
375
718
  /** Called under the catalog serial queue, never through output-erasing purge.
376
719
  * A refusal is proof about this fresh attempt, not historical native absence. */
377
720
  async compactRefusedCreation(record) {
@@ -385,7 +728,7 @@ class ScheduleService {
385
728
  || this.options.isNativeMutationPending?.(ownerOf(record))
386
729
  || runtime && (!runtime.stopped || runtime.handle || runtime.observedOccurrence || runtime.running.size || runtime.completed.size
387
730
  || runtime.heldDeliveries.size || runtime.cancelling || runtime.cancelPromise || runtime.stopPromise)
388
- || this.purged.size >= MAX_PURGED_IDS)
731
+ || this.purgeFencesFull(id))
389
732
  return;
390
733
  this.purged.set(id, ownerOf(record));
391
734
  this.records.delete(id);
@@ -406,12 +749,56 @@ class ScheduleService {
406
749
  validateOwner(owner);
407
750
  return this.serial(async () => [...this.records.values()].filter(record => sameOwner(record, owner)).map(record => structuredClone(record)));
408
751
  }
752
+ /** Commit context erasure before reset advances its generation. Late host results
753
+ * require their original record object and cannot recreate a removed definition. */
754
+ clearHostContext(threadId, authorize, allowNativeRecovery) {
755
+ return this.operation(this.serial(async () => {
756
+ this.checkReady();
757
+ const thread = [...this.records.values()].filter(row => row.threadId === threadId);
758
+ if (!allowNativeRecovery && thread.some(row => row.engine !== 'host' && this.isActiveSchedule(row))) {
759
+ throw new Error('Cancel this thread\'s native schedules with /schedule cancel <id> before resetting its conversation.');
760
+ }
761
+ const hosts = thread.filter(row => row.engine === 'host');
762
+ if (!hosts.length)
763
+ return 0;
764
+ const owner = authorize();
765
+ if (owner && (!owner.bindingEpoch || owner.threadId !== threadId || !this.current(owner))) {
766
+ throw new Error('The schedule binding changed before conversation reset.');
767
+ }
768
+ const selected = hosts.filter(row => owner && sameOwner(row, owner));
769
+ const pendingSchedules = new Set([...this.pending.values()].map(delivery => delivery.scheduleId));
770
+ if (hosts.some(row => (!owner || !sameOwner(row, owner)) && (this.isActiveSchedule(row)
771
+ || pendingSchedules.has(row.id) || this.delivering.has(row.id) || this.hostAttempts.has(row.id)))) {
772
+ throw new Error('A host schedule still owns a different binding or conversation context.');
773
+ }
774
+ if (!selected.length)
775
+ return 0;
776
+ if (selected.some(row => this.delivering.has(row.id) || this.purges.has(row.id) || this.recordOperations.has(row.id))) {
777
+ throw new Error('Schedule delivery or management is in progress. Retry the conversation reset after it settles.');
778
+ }
779
+ if ([...this.purged.keys()].filter(id => this.hostCatalogIds.has(id)).length + selected.length > MAX_PURGED_IDS) {
780
+ throw new Error('Host schedule replay fence capacity reached. Conversation reset was refused.');
781
+ }
782
+ for (const row of selected) {
783
+ this.purged.set(row.id, ownerOf(row));
784
+ this.records.delete(row.id);
785
+ this.dropPending(row.id);
786
+ this.hostRetryAt.delete(row.id);
787
+ }
788
+ await this.persist();
789
+ return selected.length;
790
+ }));
791
+ }
409
792
  /** Operational deletion ledger, separate from user history and never recoverable. */
410
793
  async listCleanup(owner) {
411
794
  this.checkReady();
412
795
  validateOwner(owner);
413
796
  return this.serial(async () => [...this.cleanup.values()].filter(record => sameCleanupOwner(record, owner)).map(record => structuredClone(record)));
414
797
  }
798
+ purgeFencesFull(id) {
799
+ const host = this.hostCatalogIds.has(id);
800
+ return [...this.purged.keys()].filter(key => this.hostCatalogIds.has(key) === host).length >= MAX_PURGED_IDS;
801
+ }
415
802
  /** Preserve the last known original-session route while deletion is unresolved. */
416
803
  hasCleanupContext(threadId) {
417
804
  return [...this.cleanup.values()].some(item => item.threadId === threadId && item.backend === 'claude' && !!item.attribution);
@@ -438,9 +825,13 @@ class ScheduleService {
438
825
  throw new Error('Purge requestId was reused with a different selection.');
439
826
  return [...previous.ids];
440
827
  }
441
- const references = [...this.purgeRequests.values()].reduce((count, receipt) => count + receipt.ids.length, 0);
442
- if (this.purgeRequests.size >= MAX_PURGE_REQUESTS || references + ids.length > MAX_PURGE_SELECTION_IDS)
828
+ const host = ids.some(id => this.hostCatalogIds.has(id)) || this.legacyUnavailable;
829
+ const receipts = [...this.purgeRequests].filter(([key]) => this.hostPurgeRequests.has(key) === host);
830
+ const references = receipts.reduce((count, [, receipt]) => count + receipt.ids.length, 0);
831
+ if (receipts.length >= MAX_PURGE_REQUESTS || references + ids.length > MAX_PURGE_SELECTION_IDS)
443
832
  throw new Error('Durable purge request capacity reached (1000 requests / 20000 selected IDs); no retry selection was discarded.');
833
+ if (host)
834
+ this.hostPurgeRequests.add(key);
444
835
  this.purgeRequests.set(key, { digest, ids });
445
836
  try {
446
837
  await this.persist();
@@ -461,7 +852,7 @@ class ScheduleService {
461
852
  const ids = value.all === true ? [...this.records.values()].filter(record => sameOwner(record, owner)).map(record => record.id)
462
853
  .concat([...this.cleanup.values()].filter(record => sameCleanupOwner(record, owner)).map(record => record.id))
463
854
  : [...value.ids];
464
- if (ids.length > this.maxRecords + MAX_CLEANUP_RECORDS || new Set(ids).size !== ids.length)
855
+ if (ids.length > 2 * this.maxRecords + MAX_CLEANUP_RECORDS || new Set(ids).size !== ids.length)
465
856
  throw new Error('Invalid schedule purge selection.');
466
857
  ids.forEach(ScheduleCommand_1.validateScheduleId);
467
858
  return ids;
@@ -486,7 +877,10 @@ class ScheduleService {
486
877
  continue;
487
878
  if (forgetUnresolved)
488
879
  continue;
489
- record.cancelRequested = true;
880
+ if (record.engine === 'host')
881
+ this.cancelHost(record);
882
+ else
883
+ record.cancelRequested = true;
490
884
  if (record.recovery)
491
885
  record.recovery.status = 'blocked';
492
886
  changed = true;
@@ -581,6 +975,8 @@ class ScheduleService {
581
975
  }
582
976
  async retryCleanup(owner, id, isCurrent) {
583
977
  const item = this.cleanup.get(id);
978
+ if (this.hostCatalogIds.has(id))
979
+ return { status: 'alreadyRemoved' };
584
980
  if (this.options.isNativeMutationPending?.(owner))
585
981
  return { status: 'pending', reason: 'operation_pending', detail: 'A native mutation receipt is unsettled; retry after reconciliation.' };
586
982
  if (!item || !this.options.withPurgeVerification)
@@ -636,7 +1032,12 @@ class ScheduleService {
636
1032
  const current = () => !this.closing && !this.fault && isCurrent() && this.current(owner)
637
1033
  && this.records.get(id) === record && record.cancelRequested === true;
638
1034
  const busy = () => {
639
- if (this.options.isNativeMutationPending?.(owner) || this.recordOperations.has(id) || this.refreshes || this.retainedCancellations.has(id)) {
1035
+ if (record.inFlightDueAt !== undefined)
1036
+ return pending('occurrence_running', 'An admitted host occurrence is awaiting its result.');
1037
+ if (this.hostAttempts.has(id))
1038
+ return pending('operation_pending', 'Host dispatch is reserving the thread.');
1039
+ if ((record.engine !== 'host' && this.options.isNativeMutationPending?.(owner)) || this.recordOperations.has(id)
1040
+ || this.refreshes || this.retainedCancellations.has(id)) {
640
1041
  return pending('operation_pending', 'Creation, inspection or cleanup is still pending. Retry these same IDs.');
641
1042
  }
642
1043
  if (this.delivering.has(id))
@@ -645,13 +1046,13 @@ class ScheduleService {
645
1046
  const active = busy();
646
1047
  if (active)
647
1048
  return active;
648
- if (this.purged.size >= MAX_PURGED_IDS)
1049
+ if (this.purgeFencesFull(id))
649
1050
  return pending('fence_capacity', 'Durable purge ID capacity reached; no replay fence was discarded.');
650
1051
  const runtime = this.runtimes.get(id);
651
1052
  // Do not interpret terminal state, an absent handle or a stopped process as
652
1053
  // native definition absence. Existing cancelRetained owns its stronger proof.
653
1054
  let retainedVerified = false;
654
- const clean = !runtime && record.cleanupConfirmed === true;
1055
+ const clean = record.engine === 'host' || !runtime && record.cleanupConfirmed === true;
655
1056
  if (runtime?.handle && !runtime.stopped) {
656
1057
  await this.cancel(owner, id);
657
1058
  }
@@ -684,7 +1085,7 @@ class ScheduleService {
684
1085
  const changed = busy();
685
1086
  if (changed)
686
1087
  return changed;
687
- if (this.purged.size >= MAX_PURGED_IDS)
1088
+ if (this.purgeFencesFull(id))
688
1089
  return pending('fence_capacity', 'Durable purge ID capacity reached; no replay fence was discarded.');
689
1090
  if (this.runtimes.get(id) !== runtime || runtime?.running.size || runtime && !runtime.stopped
690
1091
  || handleProof && runtime?.handle?.nativeDefinitionAbsent === false) {
@@ -739,8 +1140,11 @@ class ScheduleService {
739
1140
  hasPendingResults() { return this.pending.size > 0; }
740
1141
  /** Includes terminal jobs whose native process exit is still unconfirmed. */
741
1142
  hasActiveSchedules(threadId) {
742
- return [...this.records.values()].some(record => (!threadId || record.threadId === threadId)
743
- && (LIVE.has(record.state) || this.hasRetainedCleanupRoute(record) || (this.runtimes.has(record.id) && !this.runtimes.get(record.id).stopped)));
1143
+ return [...this.records.values()].some(record => (!threadId || record.threadId === threadId) && this.isActiveSchedule(record));
1144
+ }
1145
+ isActiveSchedule(record) {
1146
+ return LIVE.has(record.state) || record.inFlightDueAt !== undefined || this.hasRetainedCleanupRoute(record)
1147
+ || (this.runtimes.has(record.id) && !this.runtimes.get(record.id).stopped);
744
1148
  }
745
1149
  /** Read-only admission for purge of an owned runtime, including cancelled jobs. */
746
1150
  needsNativePurge(owner, id) {
@@ -773,6 +1177,8 @@ class ScheduleService {
773
1177
  throw new Error('Cleanup catalog owner changed.');
774
1178
  for (const id of ids) {
775
1179
  const record = this.owned(owner, id);
1180
+ if (record.engine === 'host')
1181
+ continue;
776
1182
  delete record.cleanupConfirmed;
777
1183
  record.cancelRequested = true;
778
1184
  if (record.recovery)
@@ -804,6 +1210,8 @@ class ScheduleService {
804
1210
  (0, ScheduleCommand_1.validateScheduleId)(id);
805
1211
  await this.serial(async () => {
806
1212
  const record = this.owned(owner, id);
1213
+ if (record.engine === 'host')
1214
+ return;
807
1215
  if (this.runtimes.get(id)?.stopped)
808
1216
  return;
809
1217
  record.error = errorText(error);
@@ -877,6 +1285,14 @@ class ScheduleService {
877
1285
  let operation;
878
1286
  await this.serial(async () => {
879
1287
  const record = this.owned(owner, id);
1288
+ if (record.engine === 'host') {
1289
+ if (!this.current(owner))
1290
+ throw new Error('Host schedule owner is no longer current.');
1291
+ this.cancelHost(record);
1292
+ await this.persist();
1293
+ operation = Promise.resolve(structuredClone(record));
1294
+ return;
1295
+ }
880
1296
  existing = this.retainedCancellations.get(id);
881
1297
  if (existing)
882
1298
  return;
@@ -924,7 +1340,9 @@ class ScheduleService {
924
1340
  return unsettledNativeWork(record) && !!record.recovery && this.supportsRetainedCancellation(record);
925
1341
  }
926
1342
  supportsRetainedCancellation(record) {
927
- const cleanup = this.options.provider.cleanupFor?.({ ...record, ...record.execution });
1343
+ if (record.engine === 'host' || !(0, ScheduleCapabilities_1.isNativeScheduleBackend)(record.backend))
1344
+ return false;
1345
+ const cleanup = this.options.provider.cleanupFor?.({ ...record, backend: record.backend, ...record.execution });
928
1346
  return !!record.recovery && !!cleanup?.cancelRetained && cleanup.provider === record.recovery.provider
929
1347
  && cleanup.strategy === record.recovery.strategy;
930
1348
  }
@@ -932,6 +1350,8 @@ class ScheduleService {
932
1350
  const current = () => !this.closing && !this.fault && this.current(record) && record.cancelRequested === true;
933
1351
  try {
934
1352
  const ownership = record.recovery;
1353
+ if (record.engine === 'host' || !(0, ScheduleCapabilities_1.isNativeScheduleBackend)(record.backend))
1354
+ throw new Error('Native cleanup requires a legacy schedule.');
935
1355
  const provider = this.options.provider.cleanupFor?.({ id: record.id, threadId: record.threadId,
936
1356
  backend: record.backend, cwd: record.cwd, prompt: record.prompt, rule: record.rule,
937
1357
  ...record.execution, recovery: ownership });
@@ -972,12 +1392,19 @@ class ScheduleService {
972
1392
  /** Explicit reconnect retry. No timer or periodic retry is installed. */
973
1393
  async retryDeliveries() {
974
1394
  this.checkReady();
975
- const ids = await this.serial(async () => [...this.pending.keys()]);
1395
+ const ids = await this.serial(async () => {
1396
+ if (this.retireStaleHosts())
1397
+ await this.persist();
1398
+ else
1399
+ this.armHostTimer();
1400
+ return [...this.pending.keys()];
1401
+ });
976
1402
  await this.attemptDeliveries(ids);
977
1403
  }
978
1404
  /** Idle future definitions do not block updates. Active work and durable deliveries still do. */
979
1405
  canRestartWithoutActiveWork() {
980
1406
  return this.initialized && !this.closing && !this.fault && !this.operations.size
1407
+ && !this.hostAttempts.size && ![...this.records.values()].some(record => record.inFlightDueAt !== undefined)
981
1408
  && !this.pending.size && !this.delivering.size && [...this.runtimes].every(([id, runtime]) => (!['cancelled', 'failed', 'completed', 'interrupted'].includes(this.records.get(id)?.state ?? '') || runtime.stopped) &&
982
1409
  !runtime.running.size && !runtime.cancelling) && ![...this.records.values()].some(record => record.state === 'creating');
983
1410
  }
@@ -986,6 +1413,7 @@ class ScheduleService {
986
1413
  if (this.destruction)
987
1414
  return this.destruction;
988
1415
  this.closing = true;
1416
+ clearTimeout(this.hostTimer);
989
1417
  return this.destruction = (async () => {
990
1418
  await this.initialization?.catch(() => { });
991
1419
  // Complete only writes already in this process's serial filesystem queue.
@@ -1137,7 +1565,7 @@ class ScheduleService {
1137
1565
  runtime.running.delete(event.occurrenceId);
1138
1566
  runtime.completed.add(event.occurrenceId);
1139
1567
  record.completedOccurrences = [...runtime.completed];
1140
- if (this.pending.size >= this.maxPending) {
1568
+ if (this.outboxFull(id)) {
1141
1569
  record.state = 'interrupted';
1142
1570
  record.error = 'Delivery outbox is full; latest result could not be retained. Native schedule stopped.';
1143
1571
  cleanup = true;
@@ -1189,7 +1617,17 @@ class ScheduleService {
1189
1617
  if (this.purges.has(pending.scheduleId))
1190
1618
  return;
1191
1619
  const record = this.records.get(pending.scheduleId);
1192
- if (!this.current(record) || record.state === 'cancelled' && !pending.afterCancellation) {
1620
+ if (record.engine === 'host') {
1621
+ const status = this.hostOwnerStatus(record);
1622
+ if (status === undefined)
1623
+ return;
1624
+ if (!status) {
1625
+ this.retireHost(record);
1626
+ await this.persist();
1627
+ return;
1628
+ }
1629
+ }
1630
+ if (record.engine !== 'host' && !this.current(record) || record.state === 'cancelled' && !pending.afterCancellation) {
1193
1631
  this.pending.delete(id);
1194
1632
  await this.persist();
1195
1633
  return;
@@ -1224,6 +1662,8 @@ class ScheduleService {
1224
1662
  this.delivering.delete(delivery.schedule.id);
1225
1663
  }
1226
1664
  await this.serial(async () => {
1665
+ if (this.closing)
1666
+ return; // A successor retries the durably unacknowledged result.
1227
1667
  this.pending.delete(id);
1228
1668
  await this.persist();
1229
1669
  });
@@ -1319,14 +1759,17 @@ class ScheduleService {
1319
1759
  this.recordOperations.delete(id);
1320
1760
  });
1321
1761
  }
1322
- current(owner) {
1762
+ ownerStatus(owner) {
1323
1763
  try {
1324
- return this.options.isOwnerCurrent(ownerOf(owner)) === true;
1764
+ return this.options.isOwnerCurrent(ownerOf(owner));
1325
1765
  }
1326
1766
  catch {
1327
- return false;
1767
+ return undefined;
1328
1768
  }
1329
1769
  }
1770
+ current(owner) {
1771
+ return this.ownerStatus(owner) === true;
1772
+ }
1330
1773
  owned(owner, id) {
1331
1774
  const record = this.records.get(id);
1332
1775
  if (!record || !sameOwner(record, owner))
@@ -1349,13 +1792,13 @@ class ScheduleService {
1349
1792
  this.tail = task.catch(() => { });
1350
1793
  return task;
1351
1794
  }
1352
- async readCatalog() {
1795
+ async readCatalog(filename) {
1353
1796
  let handle;
1354
1797
  try {
1355
- const stat = await fs.lstat(this.catalogPath);
1798
+ const stat = await fs.lstat(filename);
1356
1799
  if (!stat.isFile() || stat.isSymbolicLink())
1357
1800
  throw new Error('Schedule catalog must be a regular file, not a symlink.');
1358
- handle = await fs.open(this.catalogPath, node_fs_1.constants.O_RDONLY | (node_fs_1.constants.O_NOFOLLOW ?? 0));
1801
+ handle = await fs.open(filename, node_fs_1.constants.O_RDONLY | (node_fs_1.constants.O_NOFOLLOW ?? 0));
1359
1802
  }
1360
1803
  catch (error) {
1361
1804
  if (error.code === 'ENOENT')
@@ -1390,20 +1833,22 @@ class ScheduleService {
1390
1833
  await handle.close();
1391
1834
  }
1392
1835
  }
1393
- load(data) {
1836
+ load(data, hostCatalog = false) {
1394
1837
  const catalog = object(data, ['version', 'records', 'pending', 'purged', 'cleanup', 'purgeRequests']);
1395
- if (![1, 2, 3, 4, 5, 6].includes(catalog.version) || !Array.isArray(catalog.records) || catalog.records.length > this.maxRecords
1838
+ if (!(hostCatalog ? [6, 7] : [1, 2, 3, 4, 5, 6]).includes(catalog.version) || !Array.isArray(catalog.records) || catalog.records.length > this.maxRecords
1396
1839
  || !Array.isArray(catalog.pending) || catalog.pending.length > this.maxPending)
1397
1840
  throw new Error('Invalid schedule catalog envelope.');
1398
1841
  const records = new Map();
1399
1842
  const pending = new Map();
1400
1843
  for (const value of catalog.records) {
1401
- const record = object(value, ['id', 'backend', 'cwd', 'prompt', 'rule', 'createdAt', 'nativeId', 'state', 'error', 'threadId', 'openId', 'generation', 'execution', 'cancelRequested', 'creationRefused', 'cleanupConfirmed', 'recovery', 'completedOccurrences', 'skippedOccurrences']);
1844
+ const record = object(value, ['id', 'backend', 'cwd', 'prompt', 'rule', 'createdAt', 'nativeId', 'state', 'error', 'threadId', 'openId', 'generation', 'execution', 'cancelRequested', 'creationRefused', 'cleanupConfirmed', 'recovery', 'completedOccurrences', 'skippedOccurrences',
1845
+ 'engine', 'sessionId', ...(catalog.version === 7 ? ['bindingEpoch'] : []), 'nextDueAt', 'inFlightDueAt']);
1402
1846
  (0, ScheduleCommand_1.validateScheduleId)(record.id);
1403
1847
  validateOwner(record);
1404
1848
  (0, ScheduleCommand_1.validateSchedulePrompt)(record.prompt);
1405
1849
  text(record.cwd, 4096);
1406
- if (!node_path_1.default.isAbsolute(record.cwd) || !(0, ScheduleCapabilities_1.isNativeScheduleBackend)(record.backend) || !STATES.has(record.state)
1850
+ if (!node_path_1.default.isAbsolute(record.cwd) || !(record.engine === 'host' ? (0, ScheduleCapabilities_1.isHostScheduleBackend)(record.backend) : (0, ScheduleCapabilities_1.isNativeScheduleBackend)(record.backend))
1851
+ || !STATES.has(record.state)
1407
1852
  || typeof record.createdAt !== 'number' || !Number.isSafeInteger(record.createdAt) || record.createdAt < 0
1408
1853
  || records.has(record.id))
1409
1854
  throw new Error('Invalid schedule catalog record.');
@@ -1453,6 +1898,30 @@ class ScheduleService {
1453
1898
  else
1454
1899
  object(rule, ['kind', 'expression', 'timezone']);
1455
1900
  (0, ScheduleCommand_1.validateScheduleRule)(rule);
1901
+ if (record.engine === 'host') {
1902
+ if (Number(catalog.version) < 6 || record.nativeId !== undefined || record.recovery !== undefined
1903
+ || record.cleanupConfirmed !== undefined || record.creationRefused !== undefined || record.skippedOccurrences !== undefined
1904
+ || record.state === 'creating')
1905
+ throw new Error('Invalid host schedule identity.');
1906
+ if (catalog.version === 7 && record.bindingEpoch === undefined && record.state !== 'interrupted')
1907
+ throw new Error('Missing host binding epoch.');
1908
+ if (record.bindingEpoch !== undefined || record.sessionId !== undefined)
1909
+ text(record.sessionId);
1910
+ const due = record.nextDueAt !== undefined ? record.nextDueAt : record.inFlightDueAt;
1911
+ if ((record.nextDueAt !== undefined) !== (record.state === 'active')
1912
+ || (record.state === 'running' && record.inFlightDueAt === undefined)
1913
+ || record.inFlightDueAt !== undefined && !['running', 'cancelled'].includes(record.state)
1914
+ || record.cancelRequested && LIVE.has(record.state)
1915
+ || record.state === 'cancelled' && !record.cancelRequested)
1916
+ throw new Error('Invalid host schedule state.');
1917
+ if (due !== undefined && (typeof due !== 'number' || !Number.isSafeInteger(due) || due <= record.createdAt
1918
+ || (0, HostScheduleRule_1.nextHostDue)(rule, due - 1) !== due
1919
+ || Array.isArray(record.completedOccurrences) && record.completedOccurrences.includes(`host-${due}`)))
1920
+ throw new Error('Invalid host occurrence receipt.');
1921
+ }
1922
+ else if (record.engine !== undefined || record.sessionId !== undefined || record.nextDueAt !== undefined
1923
+ || record.inFlightDueAt !== undefined)
1924
+ throw new Error('Unexpected host schedule fields.');
1456
1925
  records.set(record.id, structuredClone(record));
1457
1926
  }
1458
1927
  for (const value of catalog.pending) {
@@ -1475,7 +1944,7 @@ class ScheduleService {
1475
1944
  if (!Array.isArray(catalog.purged) || catalog.purged.length > MAX_PURGED_IDS)
1476
1945
  throw new Error('Invalid purge fences.');
1477
1946
  for (const value of catalog.purged) {
1478
- const fence = object(value, ['id', 'threadId', 'openId', 'generation']);
1947
+ const fence = object(value, ['id', 'threadId', 'openId', 'generation', ...(catalog.version === 7 ? ['bindingEpoch'] : [])]);
1479
1948
  (0, ScheduleCommand_1.validateScheduleId)(fence.id);
1480
1949
  validateOwner(fence);
1481
1950
  if (records.has(fence.id) || purged.has(fence.id))
@@ -1487,7 +1956,7 @@ class ScheduleService {
1487
1956
  throw new Error('Purge fences require catalog version 3 or newer.');
1488
1957
  const cleanup = new Map();
1489
1958
  const purgeRequests = new Map();
1490
- if (catalog.version === 5 || catalog.version === 6) {
1959
+ if (Number(catalog.version) >= 5) {
1491
1960
  if (!Array.isArray(catalog.cleanup) || catalog.cleanup.length > MAX_CLEANUP_RECORDS)
1492
1961
  throw new Error('Invalid cleanup ledger.');
1493
1962
  for (const value of catalog.cleanup) {
@@ -1534,11 +2003,32 @@ class ScheduleService {
1534
2003
  }
1535
2004
  else if (catalog.cleanup !== undefined || catalog.purgeRequests !== undefined)
1536
2005
  throw new Error('Cleanup ledger requires catalog version 5 or newer.');
1537
- this.records = records;
1538
- this.pending = pending;
1539
- this.purged = purged;
1540
- this.cleanup = cleanup;
1541
- this.purgeRequests = purgeRequests;
2006
+ if (hostCatalog) {
2007
+ if (cleanup.size || [...records.values()].some(row => row.engine !== 'host')) {
2008
+ throw new Error('Invalid host schedule catalog.');
2009
+ }
2010
+ for (const id of [...records.keys(), ...purged.keys()]) {
2011
+ if (this.records.has(id) || this.purged.has(id) || this.unavailableLegacyIds.has(id))
2012
+ throw new Error('Conflicting schedule catalog ID.');
2013
+ this.hostCatalogIds.add(id);
2014
+ }
2015
+ for (const key of purgeRequests.keys()) {
2016
+ if (this.purgeRequests.has(key))
2017
+ throw new Error('Conflicting schedule purge request.');
2018
+ this.hostPurgeRequests.add(key);
2019
+ }
2020
+ }
2021
+ for (const [id, row] of records)
2022
+ this.records.set(id, row);
2023
+ for (const [id, row] of pending)
2024
+ this.pending.set(id, row);
2025
+ for (const [id, row] of purged)
2026
+ this.purged.set(id, row);
2027
+ for (const [id, row] of cleanup)
2028
+ this.cleanup.set(id, row);
2029
+ for (const [key, row] of purgeRequests)
2030
+ this.purgeRequests.set(key, row);
2031
+ this.catalogDigests.set(hostCatalog ? this.hostCatalogPath : this.catalogPath, (0, node_crypto_1.createHash)('sha256').update(JSON.stringify(data)).digest('hex'));
1542
2032
  }
1543
2033
  async persist() {
1544
2034
  if (!this.catalogGate)
@@ -1546,10 +2036,36 @@ class ScheduleService {
1546
2036
  this.catalogGate.verify();
1547
2037
  if (this.fault)
1548
2038
  throw this.fault;
1549
- const temporary = node_path_1.default.join(node_path_1.default.dirname(this.catalogPath), `.schedule-${(0, node_crypto_1.randomUUID)()}.tmp`);
2039
+ try {
2040
+ if (!this.legacyUnavailable)
2041
+ await this.persistCatalog(false);
2042
+ if (this.hostCatalogIds.size || this.hostPurgeRequests.size)
2043
+ await this.persistCatalog(true);
2044
+ this.armHostTimer();
2045
+ }
2046
+ catch (error) {
2047
+ this.fault = error instanceof Error ? error : new Error('Schedule catalog write failed.');
2048
+ for (const [id, runtime] of this.runtimes)
2049
+ void this.stop(id, runtime).catch(() => { });
2050
+ throw this.fault;
2051
+ }
2052
+ }
2053
+ async persistCatalog(host) {
2054
+ const filename = host ? this.hostCatalogPath : this.catalogPath;
2055
+ const belongs = (id) => this.hostCatalogIds.has(id) === host;
2056
+ const snapshot = JSON.stringify({ version: host ? 7 : 6,
2057
+ records: [...this.records.values()].filter(row => belongs(row.id)),
2058
+ pending: [...this.pending.values()].filter(row => belongs(row.scheduleId)),
2059
+ cleanup: host ? [] : [...this.cleanup.values()],
2060
+ purgeRequests: [...this.purgeRequests].filter(([key]) => this.hostPurgeRequests.has(key) === host).map(([key, receipt]) => ({ key, ...receipt })),
2061
+ purged: [...this.purged].filter(([id]) => belongs(id)).map(([id, owner]) => ({ id, ...owner })) });
2062
+ const digest = (0, node_crypto_1.createHash)('sha256').update(snapshot).digest('hex');
2063
+ if (this.catalogDigests.get(filename) === digest)
2064
+ return;
2065
+ const temporary = node_path_1.default.join(node_path_1.default.dirname(filename), `.schedule-${(0, node_crypto_1.randomUUID)()}.tmp`);
1550
2066
  try {
1551
2067
  try {
1552
- const stat = await fs.lstat(this.catalogPath);
2068
+ const stat = await fs.lstat(filename);
1553
2069
  if (!stat.isFile() || stat.isSymbolicLink())
1554
2070
  throw new Error('Schedule catalog is not a regular file.');
1555
2071
  }
@@ -1559,22 +2075,15 @@ class ScheduleService {
1559
2075
  }
1560
2076
  const handle = await fs.open(temporary, 'wx', 0o600);
1561
2077
  try {
1562
- await handle.writeFile(JSON.stringify({ version: 6, records: [...this.records.values()], pending: [...this.pending.values()],
1563
- cleanup: [...this.cleanup.values()], purgeRequests: [...this.purgeRequests].map(([key, receipt]) => ({ key, ...receipt })),
1564
- purged: [...this.purged].map(([id, owner]) => ({ id, ...owner })) }), 'utf8');
2078
+ await handle.writeFile(snapshot, 'utf8');
1565
2079
  await handle.sync();
1566
2080
  }
1567
2081
  finally {
1568
2082
  await handle.close();
1569
2083
  }
1570
- await fs.rename(temporary, this.catalogPath);
1571
- (0, OwnershipRuntime_1.syncDirectory)(node_path_1.default.dirname(this.catalogPath));
1572
- }
1573
- catch (error) {
1574
- this.fault = error instanceof Error ? error : new Error('Schedule catalog write failed.');
1575
- for (const [id, runtime] of this.runtimes)
1576
- void this.stop(id, runtime).catch(() => { });
1577
- throw this.fault;
2084
+ await fs.rename(temporary, filename);
2085
+ (0, OwnershipRuntime_1.syncDirectory)(node_path_1.default.dirname(filename));
2086
+ this.catalogDigests.set(filename, digest);
1578
2087
  }
1579
2088
  finally {
1580
2089
  await fs.unlink(temporary).catch(() => { });