@yu_robotics/remote-cli 1.6.263 → 1.6.265

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 (145) hide show
  1. package/README.md +41 -0
  2. package/dist/client/MessageHandler.d.ts +12 -2
  3. package/dist/client/MessageHandler.d.ts.map +1 -1
  4. package/dist/client/MessageHandler.js +320 -168
  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 +12 -1
  46. package/dist/executor/agy/AgyAcpRuntime.d.ts.map +1 -1
  47. package/dist/executor/agy/AgyAcpRuntime.js +125 -11
  48. package/dist/executor/agy/AgyAcpRuntime.js.map +1 -1
  49. package/dist/executor/agy/AgyChatHost.d.ts +4 -1
  50. package/dist/executor/agy/AgyChatHost.d.ts.map +1 -1
  51. package/dist/executor/agy/AgyChatHost.js +3 -2
  52. package/dist/executor/agy/AgyChatHost.js.map +1 -1
  53. package/dist/executor/agy/AgySessionSelection.d.ts +3 -0
  54. package/dist/executor/agy/AgySessionSelection.d.ts.map +1 -1
  55. package/dist/executor/agy/AgySessionSelection.js +24 -0
  56. package/dist/executor/agy/AgySessionSelection.js.map +1 -1
  57. package/dist/executor/dsh/DshAcpClient.d.ts +1 -1
  58. package/dist/executor/dsh/DshAcpClient.d.ts.map +1 -1
  59. package/dist/executor/dsh/DshAcpClient.js +2 -2
  60. package/dist/executor/dsh/DshAcpClient.js.map +1 -1
  61. package/dist/executor/pi/PiClient.d.ts +3 -1
  62. package/dist/executor/pi/PiClient.d.ts.map +1 -1
  63. package/dist/executor/pi/PiClient.js +15 -1
  64. package/dist/executor/pi/PiClient.js.map +1 -1
  65. package/dist/executor/pi/PiTypes.d.ts +3 -1
  66. package/dist/executor/pi/PiTypes.d.ts.map +1 -1
  67. package/dist/executor/pi/PiTypes.js.map +1 -1
  68. package/dist/executor/zcode/ZCodeClient.d.ts +2 -2
  69. package/dist/executor/zcode/ZCodeClient.d.ts.map +1 -1
  70. package/dist/executor/zcode/ZCodeClient.js +26 -7
  71. package/dist/executor/zcode/ZCodeClient.js.map +1 -1
  72. package/dist/maintenance/release-notes.json +1 -1
  73. package/dist/managed/tools.d.ts +6 -6
  74. package/dist/scheduling/ScheduleCapabilities.d.ts +59 -14
  75. package/dist/scheduling/ScheduleCapabilities.d.ts.map +1 -1
  76. package/dist/scheduling/ScheduleCapabilities.js +33 -29
  77. package/dist/scheduling/ScheduleCapabilities.js.map +1 -1
  78. package/dist/scheduling/ScheduleCardService.d.ts.map +1 -1
  79. package/dist/scheduling/ScheduleCardService.js +3 -1
  80. package/dist/scheduling/ScheduleCardService.js.map +1 -1
  81. package/dist/scheduling/ScheduleCleanup.d.ts +3 -2
  82. package/dist/scheduling/ScheduleCleanup.d.ts.map +1 -1
  83. package/dist/scheduling/ScheduleCleanup.js +3 -0
  84. package/dist/scheduling/ScheduleCleanup.js.map +1 -1
  85. package/dist/scheduling/ScheduleCommand.d.ts +1 -3
  86. package/dist/scheduling/ScheduleCommand.d.ts.map +1 -1
  87. package/dist/scheduling/ScheduleCommand.js +10 -62
  88. package/dist/scheduling/ScheduleCommand.js.map +1 -1
  89. package/dist/scheduling/ScheduleDeliveryClient.d.ts +2 -1
  90. package/dist/scheduling/ScheduleDeliveryClient.d.ts.map +1 -1
  91. package/dist/scheduling/ScheduleDeliveryClient.js +20 -8
  92. package/dist/scheduling/ScheduleDeliveryClient.js.map +1 -1
  93. package/dist/scheduling/ScheduleService.d.ts +44 -4
  94. package/dist/scheduling/ScheduleService.d.ts.map +1 -1
  95. package/dist/scheduling/ScheduleService.js +537 -72
  96. package/dist/scheduling/ScheduleService.js.map +1 -1
  97. package/dist/scheduling/ScheduleToolScope.d.ts +4 -1
  98. package/dist/scheduling/ScheduleToolScope.d.ts.map +1 -1
  99. package/dist/scheduling/ScheduleToolScope.js +14 -13
  100. package/dist/scheduling/ScheduleToolScope.js.map +1 -1
  101. package/dist/scheduling/agy/AgyHookRelay.d.ts +3 -0
  102. package/dist/scheduling/agy/AgyHookRelay.d.ts.map +1 -1
  103. package/dist/scheduling/agy/AgyHookRelay.js +15 -1
  104. package/dist/scheduling/agy/AgyHookRelay.js.map +1 -1
  105. package/dist/scheduling/agy/AgyScheduleHost.d.ts +3 -1
  106. package/dist/scheduling/agy/AgyScheduleHost.d.ts.map +1 -1
  107. package/dist/scheduling/agy/AgyScheduleHost.js +2 -2
  108. package/dist/scheduling/agy/AgyScheduleHost.js.map +1 -1
  109. package/dist/scheduling/agy/AgySessionSchedules.d.ts +1 -0
  110. package/dist/scheduling/agy/AgySessionSchedules.d.ts.map +1 -1
  111. package/dist/scheduling/agy/AgySessionSchedules.js +9 -0
  112. package/dist/scheduling/agy/AgySessionSchedules.js.map +1 -1
  113. package/dist/scheduling/claude/ClaudeScheduleOwnership.d.ts +2 -0
  114. package/dist/scheduling/claude/ClaudeScheduleOwnership.d.ts.map +1 -1
  115. package/dist/scheduling/claude/ClaudeScheduleOwnership.js +11 -0
  116. package/dist/scheduling/claude/ClaudeScheduleOwnership.js.map +1 -1
  117. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts +3 -2
  118. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts.map +1 -1
  119. package/dist/scheduling/claude/ClaudeSessionSchedules.js +12 -4
  120. package/dist/scheduling/claude/ClaudeSessionSchedules.js.map +1 -1
  121. package/dist/scheduling/dsh/ScheduledSessionGuard.js +1 -1
  122. package/dist/scheduling/dsh/ScheduledSessionGuard.js.map +1 -1
  123. package/dist/scheduling/host/HostScheduleRule.d.ts +6 -0
  124. package/dist/scheduling/host/HostScheduleRule.d.ts.map +1 -0
  125. package/dist/scheduling/host/HostScheduleRule.js +144 -0
  126. package/dist/scheduling/host/HostScheduleRule.js.map +1 -0
  127. package/dist/scheduling/toolContract.d.ts +3 -3
  128. package/dist/scheduling/toolContract.js +4 -4
  129. package/dist/scheduling/toolContract.js.map +1 -1
  130. package/dist/scheduling/types.d.ts +20 -2
  131. package/dist/scheduling/types.d.ts.map +1 -1
  132. package/dist/scheduling/types.js.map +1 -1
  133. package/dist/types/ScheduleCards.d.ts +2 -1
  134. package/dist/types/ScheduleCards.d.ts.map +1 -1
  135. package/dist/types/index.d.ts +2 -0
  136. package/dist/types/index.d.ts.map +1 -1
  137. package/native/prebuilds/darwin-arm64/managed_native.node +0 -0
  138. package/native/prebuilds/darwin-arm64/manifest.json +1 -1
  139. package/native/prebuilds/darwin-x64/managed_native.node +0 -0
  140. package/native/prebuilds/darwin-x64/manifest.json +1 -1
  141. package/native/prebuilds/win32-arm64/managed_native.node +0 -0
  142. package/native/prebuilds/win32-arm64/manifest.json +1 -1
  143. package/native/prebuilds/win32-x64/managed_native.node +0 -0
  144. package/native/prebuilds/win32-x64/manifest.json +1 -1
  145. 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,243 @@ 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
+ delete record.inFlightDueAt;
502
+ delete record.nextDueAt;
503
+ // Host slots advance monotonically. The persisted next/in-flight slot
504
+ // fences replay even after an old diagnostic receipt leaves this window.
505
+ record.completedOccurrences = [...(record.completedOccurrences ?? []), occurrenceId].slice(-this.maxOccurrences);
506
+ this.pending.set(id, { id, scheduleId: record.id, occurrenceId, success: result.success,
507
+ ...(record.cancelRequested && { afterCancellation: true }),
508
+ ...(result.output !== undefined && { output: bounded(result.output, OUTPUT_BYTES) }),
509
+ ...(result.error !== undefined && { error: bounded(result.error, ERROR_BYTES) }) });
510
+ if (record.cancelRequested)
511
+ record.state = 'cancelled';
512
+ else if (!result.success) {
513
+ record.state = 'failed';
514
+ record.error = bounded(result.error ?? 'Host schedule execution failed.', ERROR_BYTES);
515
+ }
516
+ else if (record.rule.kind === 'once')
517
+ record.state = 'completed';
518
+ else
519
+ this.advanceHost(record, Math.max(due, this.now()));
520
+ return id;
521
+ }
522
+ cancelHost(record) {
523
+ record.cancelRequested = true;
524
+ if (LIVE.has(record.state))
525
+ record.state = 'cancelled';
526
+ delete record.nextDueAt;
527
+ this.hostRetryAt.delete(record.id);
528
+ for (const delivery of this.pending.values())
529
+ if (delivery.scheduleId === record.id)
530
+ delivery.afterCancellation = true;
531
+ }
532
+ hostOwnerStatus(record) {
533
+ return record.bindingEpoch === undefined ? false : this.ownerStatus(record);
534
+ }
535
+ retireHost(record) {
536
+ const reason = 'Host schedule owner is no longer current.';
537
+ const changed = record.state !== 'interrupted' || record.error !== reason;
538
+ record.state = 'interrupted';
539
+ record.error = reason;
540
+ delete record.nextDueAt;
541
+ delete record.inFlightDueAt;
542
+ this.hostRetryAt.delete(record.id);
543
+ const count = this.pending.size;
544
+ this.dropPending(record.id);
545
+ return changed || count !== this.pending.size;
546
+ }
547
+ retireStaleHosts() {
548
+ let changed = false;
549
+ for (const record of this.records.values()) {
550
+ if (record.engine === 'host' && this.hostOwnerStatus(record) === false && this.retireHost(record))
551
+ changed = true;
552
+ }
553
+ return changed;
554
+ }
555
+ /** An unresolved admission is never executed again. If the outbox is full,
556
+ * its original disk receipt stays intact until an ACK releases capacity. */
557
+ reconcileHost(record, now, deliveries) {
558
+ if (this.hostAttempts.has(record.id))
559
+ return false;
560
+ const due = record.inFlightDueAt ?? record.nextDueAt;
561
+ if (due === undefined)
562
+ return false;
563
+ if (this.hostOwnerStatus(record) !== true)
564
+ return false;
565
+ if (record.inFlightDueAt === undefined && record.cancelRequested) {
566
+ this.cancelHost(record);
567
+ return true;
568
+ }
569
+ const missed = due < this.hostStartup;
570
+ if (record.inFlightDueAt === undefined && record.rule.kind === 'cron' && (missed || now - due >= 60_000)) {
571
+ this.advanceHost(record, Math.max(now, this.hostStartup));
572
+ return true;
573
+ }
574
+ if (record.inFlightDueAt === undefined && !missed)
575
+ return false;
576
+ if (this.outboxFull(record.id))
577
+ return false;
578
+ const error = record.inFlightDueAt !== undefined
579
+ ? 'Host schedule execution outcome is unknown after restart. The occurrence was not replayed.'
580
+ : 'One-shot schedule was missed while the service was offline.';
581
+ deliveries.push(this.finishHost(record, due, { success: false, error }));
582
+ return true;
583
+ }
584
+ armHostTimer() {
585
+ let earliest = Infinity;
586
+ if (this.initialized && !this.closing && !this.fault) {
587
+ for (const record of this.records.values()) {
588
+ if (record.engine !== 'host' || this.hostAttempts.has(record.id) || this.outboxFull(record.id)
589
+ || this.hostOwnerStatus(record) === undefined)
590
+ continue;
591
+ const due = record.inFlightDueAt !== undefined ? 0 : record.nextDueAt;
592
+ if (due !== undefined)
593
+ earliest = Math.min(earliest, Math.max(due, this.hostRetryAt.get(record.id) ?? 0));
594
+ }
595
+ }
596
+ if (this.hostTimer && this.hostTimerAt === earliest)
597
+ return;
598
+ clearTimeout(this.hostTimer);
599
+ this.hostTimer = undefined;
600
+ this.hostTimerAt = earliest;
601
+ if (earliest === Infinity)
602
+ return;
603
+ // Node clamps overflowing timer delays to one millisecond.
604
+ const delay = Math.min(0x7fffffff, Math.max(0, earliest - this.now()));
605
+ this.hostTimer = setTimeout(() => {
606
+ this.hostTimer = undefined;
607
+ this.track(this.wakeHosts());
608
+ }, delay);
609
+ this.hostTimer.unref();
610
+ }
611
+ outboxFull(id) {
612
+ const host = this.hostCatalogIds.has(id);
613
+ const pending = [...this.pending.values()].filter(item => this.hostCatalogIds.has(item.scheduleId) === host);
614
+ const reservations = [...this.hostAttempts].filter(key => this.hostCatalogIds.has(key) === host && this.records.get(key)?.state !== 'interrupted');
615
+ return pending.length + reservations.length >= this.maxPending;
616
+ }
617
+ async wakeHosts() {
618
+ const deliveries = [];
619
+ const ready = [];
620
+ await this.serial(async () => {
621
+ if (this.closing || this.fault)
622
+ return;
623
+ let changed = this.retireStaleHosts();
624
+ const now = this.now();
625
+ for (const record of this.records.values()) {
626
+ if (record.engine !== 'host' || this.hostAttempts.has(record.id))
627
+ continue;
628
+ if (this.reconcileHost(record, now, deliveries))
629
+ changed = true;
630
+ const due = record.nextDueAt;
631
+ if (due === undefined || due > now || this.hostOwnerStatus(record) !== true || (this.hostRetryAt.get(record.id) ?? 0) > now
632
+ || this.outboxFull(record.id))
633
+ continue;
634
+ this.hostAttempts.add(record.id);
635
+ ready.push({ record, due });
636
+ }
637
+ if (changed)
638
+ await this.persist();
639
+ else
640
+ this.armHostTimer();
641
+ });
642
+ for (const { record, due } of ready)
643
+ this.track(this.dispatchHost(record, due));
644
+ if (deliveries.length)
645
+ await this.attemptDeliveries(deliveries);
646
+ }
647
+ async dispatchHost(record, due) {
648
+ const eligible = () => !this.closing && !this.fault && this.records.get(record.id) === record
649
+ && !record.cancelRequested && record.state === 'active' && record.nextDueAt === due && this.current(record);
650
+ let open = true;
651
+ const admit = () => this.serial(async () => {
652
+ if (!open || !eligible())
653
+ return false;
654
+ record.state = 'running';
655
+ record.inFlightDueAt = due;
656
+ delete record.nextDueAt;
657
+ await this.persist();
658
+ if (!open || this.closing)
659
+ return false;
660
+ const status = this.hostOwnerStatus(record);
661
+ if (status === true)
662
+ return true;
663
+ // No execution authority left this callback. Keep the original slot when
664
+ // registration changed while the admission receipt was being written.
665
+ if (status === false)
666
+ this.retireHost(record);
667
+ else {
668
+ delete record.inFlightDueAt;
669
+ record.nextDueAt = due;
670
+ record.state = 'active';
671
+ }
672
+ await this.persist();
673
+ return false;
674
+ });
675
+ let result;
676
+ try {
677
+ if (eligible()) {
678
+ if (!this.options.hostDispatch)
679
+ throw new Error('Host schedule dispatch is unavailable.');
680
+ result = await this.options.hostDispatch(structuredClone(record), `host-${due}`, admit);
681
+ if (result?.success && record.inFlightDueAt !== due)
682
+ throw new Error('Host dispatch completed without admission.');
683
+ if (!result && record.inFlightDueAt === due)
684
+ throw new Error('Admitted host occurrence returned no result. Its outcome is unknown.');
685
+ }
686
+ }
687
+ catch (error) {
688
+ result = { success: false, error: errorText(error) };
689
+ }
690
+ finally {
691
+ open = false;
692
+ }
693
+ const delivery = await this.serial(async () => {
694
+ this.hostAttempts.delete(record.id);
695
+ this.hostRetryAt.delete(record.id);
696
+ if (this.closing || this.fault || this.records.get(record.id) !== record)
697
+ return;
698
+ let id;
699
+ if (this.hostOwnerStatus(record) === false) {
700
+ this.retireHost(record);
701
+ await this.persist();
702
+ }
703
+ else if (result && (record.inFlightDueAt === due || eligible())) {
704
+ id = this.finishHost(record, due, result);
705
+ await this.persist();
706
+ }
707
+ else {
708
+ if (eligible())
709
+ this.hostRetryAt.set(record.id, this.now() + HOST_BUSY_RETRY_MS);
710
+ this.armHostTimer();
711
+ }
712
+ return id;
713
+ });
714
+ if (delivery)
715
+ await this.attemptDeliveries([delivery]);
716
+ }
375
717
  /** Called under the catalog serial queue, never through output-erasing purge.
376
718
  * A refusal is proof about this fresh attempt, not historical native absence. */
377
719
  async compactRefusedCreation(record) {
@@ -385,7 +727,7 @@ class ScheduleService {
385
727
  || this.options.isNativeMutationPending?.(ownerOf(record))
386
728
  || runtime && (!runtime.stopped || runtime.handle || runtime.observedOccurrence || runtime.running.size || runtime.completed.size
387
729
  || runtime.heldDeliveries.size || runtime.cancelling || runtime.cancelPromise || runtime.stopPromise)
388
- || this.purged.size >= MAX_PURGED_IDS)
730
+ || this.purgeFencesFull(id))
389
731
  return;
390
732
  this.purged.set(id, ownerOf(record));
391
733
  this.records.delete(id);
@@ -412,6 +754,10 @@ class ScheduleService {
412
754
  validateOwner(owner);
413
755
  return this.serial(async () => [...this.cleanup.values()].filter(record => sameCleanupOwner(record, owner)).map(record => structuredClone(record)));
414
756
  }
757
+ purgeFencesFull(id) {
758
+ const host = this.hostCatalogIds.has(id);
759
+ return [...this.purged.keys()].filter(key => this.hostCatalogIds.has(key) === host).length >= MAX_PURGED_IDS;
760
+ }
415
761
  /** Preserve the last known original-session route while deletion is unresolved. */
416
762
  hasCleanupContext(threadId) {
417
763
  return [...this.cleanup.values()].some(item => item.threadId === threadId && item.backend === 'claude' && !!item.attribution);
@@ -438,9 +784,13 @@ class ScheduleService {
438
784
  throw new Error('Purge requestId was reused with a different selection.');
439
785
  return [...previous.ids];
440
786
  }
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)
787
+ const host = ids.some(id => this.hostCatalogIds.has(id)) || this.legacyUnavailable;
788
+ const receipts = [...this.purgeRequests].filter(([key]) => this.hostPurgeRequests.has(key) === host);
789
+ const references = receipts.reduce((count, [, receipt]) => count + receipt.ids.length, 0);
790
+ if (receipts.length >= MAX_PURGE_REQUESTS || references + ids.length > MAX_PURGE_SELECTION_IDS)
443
791
  throw new Error('Durable purge request capacity reached (1000 requests / 20000 selected IDs); no retry selection was discarded.');
792
+ if (host)
793
+ this.hostPurgeRequests.add(key);
444
794
  this.purgeRequests.set(key, { digest, ids });
445
795
  try {
446
796
  await this.persist();
@@ -461,7 +811,7 @@ class ScheduleService {
461
811
  const ids = value.all === true ? [...this.records.values()].filter(record => sameOwner(record, owner)).map(record => record.id)
462
812
  .concat([...this.cleanup.values()].filter(record => sameCleanupOwner(record, owner)).map(record => record.id))
463
813
  : [...value.ids];
464
- if (ids.length > this.maxRecords + MAX_CLEANUP_RECORDS || new Set(ids).size !== ids.length)
814
+ if (ids.length > 2 * this.maxRecords + MAX_CLEANUP_RECORDS || new Set(ids).size !== ids.length)
465
815
  throw new Error('Invalid schedule purge selection.');
466
816
  ids.forEach(ScheduleCommand_1.validateScheduleId);
467
817
  return ids;
@@ -486,7 +836,10 @@ class ScheduleService {
486
836
  continue;
487
837
  if (forgetUnresolved)
488
838
  continue;
489
- record.cancelRequested = true;
839
+ if (record.engine === 'host')
840
+ this.cancelHost(record);
841
+ else
842
+ record.cancelRequested = true;
490
843
  if (record.recovery)
491
844
  record.recovery.status = 'blocked';
492
845
  changed = true;
@@ -581,6 +934,8 @@ class ScheduleService {
581
934
  }
582
935
  async retryCleanup(owner, id, isCurrent) {
583
936
  const item = this.cleanup.get(id);
937
+ if (this.hostCatalogIds.has(id))
938
+ return { status: 'alreadyRemoved' };
584
939
  if (this.options.isNativeMutationPending?.(owner))
585
940
  return { status: 'pending', reason: 'operation_pending', detail: 'A native mutation receipt is unsettled; retry after reconciliation.' };
586
941
  if (!item || !this.options.withPurgeVerification)
@@ -636,7 +991,12 @@ class ScheduleService {
636
991
  const current = () => !this.closing && !this.fault && isCurrent() && this.current(owner)
637
992
  && this.records.get(id) === record && record.cancelRequested === true;
638
993
  const busy = () => {
639
- if (this.options.isNativeMutationPending?.(owner) || this.recordOperations.has(id) || this.refreshes || this.retainedCancellations.has(id)) {
994
+ if (record.inFlightDueAt !== undefined)
995
+ return pending('occurrence_running', 'An admitted host occurrence is awaiting its result.');
996
+ if (this.hostAttempts.has(id))
997
+ return pending('operation_pending', 'Host dispatch is reserving the thread.');
998
+ if ((record.engine !== 'host' && this.options.isNativeMutationPending?.(owner)) || this.recordOperations.has(id)
999
+ || this.refreshes || this.retainedCancellations.has(id)) {
640
1000
  return pending('operation_pending', 'Creation, inspection or cleanup is still pending. Retry these same IDs.');
641
1001
  }
642
1002
  if (this.delivering.has(id))
@@ -645,13 +1005,13 @@ class ScheduleService {
645
1005
  const active = busy();
646
1006
  if (active)
647
1007
  return active;
648
- if (this.purged.size >= MAX_PURGED_IDS)
1008
+ if (this.purgeFencesFull(id))
649
1009
  return pending('fence_capacity', 'Durable purge ID capacity reached; no replay fence was discarded.');
650
1010
  const runtime = this.runtimes.get(id);
651
1011
  // Do not interpret terminal state, an absent handle or a stopped process as
652
1012
  // native definition absence. Existing cancelRetained owns its stronger proof.
653
1013
  let retainedVerified = false;
654
- const clean = !runtime && record.cleanupConfirmed === true;
1014
+ const clean = record.engine === 'host' || !runtime && record.cleanupConfirmed === true;
655
1015
  if (runtime?.handle && !runtime.stopped) {
656
1016
  await this.cancel(owner, id);
657
1017
  }
@@ -684,7 +1044,7 @@ class ScheduleService {
684
1044
  const changed = busy();
685
1045
  if (changed)
686
1046
  return changed;
687
- if (this.purged.size >= MAX_PURGED_IDS)
1047
+ if (this.purgeFencesFull(id))
688
1048
  return pending('fence_capacity', 'Durable purge ID capacity reached; no replay fence was discarded.');
689
1049
  if (this.runtimes.get(id) !== runtime || runtime?.running.size || runtime && !runtime.stopped
690
1050
  || handleProof && runtime?.handle?.nativeDefinitionAbsent === false) {
@@ -740,7 +1100,7 @@ class ScheduleService {
740
1100
  /** Includes terminal jobs whose native process exit is still unconfirmed. */
741
1101
  hasActiveSchedules(threadId) {
742
1102
  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)));
1103
+ && (LIVE.has(record.state) || record.inFlightDueAt !== undefined || this.hasRetainedCleanupRoute(record) || (this.runtimes.has(record.id) && !this.runtimes.get(record.id).stopped)));
744
1104
  }
745
1105
  /** Read-only admission for purge of an owned runtime, including cancelled jobs. */
746
1106
  needsNativePurge(owner, id) {
@@ -773,6 +1133,8 @@ class ScheduleService {
773
1133
  throw new Error('Cleanup catalog owner changed.');
774
1134
  for (const id of ids) {
775
1135
  const record = this.owned(owner, id);
1136
+ if (record.engine === 'host')
1137
+ continue;
776
1138
  delete record.cleanupConfirmed;
777
1139
  record.cancelRequested = true;
778
1140
  if (record.recovery)
@@ -804,6 +1166,8 @@ class ScheduleService {
804
1166
  (0, ScheduleCommand_1.validateScheduleId)(id);
805
1167
  await this.serial(async () => {
806
1168
  const record = this.owned(owner, id);
1169
+ if (record.engine === 'host')
1170
+ return;
807
1171
  if (this.runtimes.get(id)?.stopped)
808
1172
  return;
809
1173
  record.error = errorText(error);
@@ -877,6 +1241,14 @@ class ScheduleService {
877
1241
  let operation;
878
1242
  await this.serial(async () => {
879
1243
  const record = this.owned(owner, id);
1244
+ if (record.engine === 'host') {
1245
+ if (!this.current(owner))
1246
+ throw new Error('Host schedule owner is no longer current.');
1247
+ this.cancelHost(record);
1248
+ await this.persist();
1249
+ operation = Promise.resolve(structuredClone(record));
1250
+ return;
1251
+ }
880
1252
  existing = this.retainedCancellations.get(id);
881
1253
  if (existing)
882
1254
  return;
@@ -924,7 +1296,9 @@ class ScheduleService {
924
1296
  return unsettledNativeWork(record) && !!record.recovery && this.supportsRetainedCancellation(record);
925
1297
  }
926
1298
  supportsRetainedCancellation(record) {
927
- const cleanup = this.options.provider.cleanupFor?.({ ...record, ...record.execution });
1299
+ if (record.engine === 'host' || !(0, ScheduleCapabilities_1.isNativeScheduleBackend)(record.backend))
1300
+ return false;
1301
+ const cleanup = this.options.provider.cleanupFor?.({ ...record, backend: record.backend, ...record.execution });
928
1302
  return !!record.recovery && !!cleanup?.cancelRetained && cleanup.provider === record.recovery.provider
929
1303
  && cleanup.strategy === record.recovery.strategy;
930
1304
  }
@@ -932,6 +1306,8 @@ class ScheduleService {
932
1306
  const current = () => !this.closing && !this.fault && this.current(record) && record.cancelRequested === true;
933
1307
  try {
934
1308
  const ownership = record.recovery;
1309
+ if (record.engine === 'host' || !(0, ScheduleCapabilities_1.isNativeScheduleBackend)(record.backend))
1310
+ throw new Error('Native cleanup requires a legacy schedule.');
935
1311
  const provider = this.options.provider.cleanupFor?.({ id: record.id, threadId: record.threadId,
936
1312
  backend: record.backend, cwd: record.cwd, prompt: record.prompt, rule: record.rule,
937
1313
  ...record.execution, recovery: ownership });
@@ -972,12 +1348,19 @@ class ScheduleService {
972
1348
  /** Explicit reconnect retry. No timer or periodic retry is installed. */
973
1349
  async retryDeliveries() {
974
1350
  this.checkReady();
975
- const ids = await this.serial(async () => [...this.pending.keys()]);
1351
+ const ids = await this.serial(async () => {
1352
+ if (this.retireStaleHosts())
1353
+ await this.persist();
1354
+ else
1355
+ this.armHostTimer();
1356
+ return [...this.pending.keys()];
1357
+ });
976
1358
  await this.attemptDeliveries(ids);
977
1359
  }
978
1360
  /** Idle future definitions do not block updates. Active work and durable deliveries still do. */
979
1361
  canRestartWithoutActiveWork() {
980
1362
  return this.initialized && !this.closing && !this.fault && !this.operations.size
1363
+ && !this.hostAttempts.size && ![...this.records.values()].some(record => record.inFlightDueAt !== undefined)
981
1364
  && !this.pending.size && !this.delivering.size && [...this.runtimes].every(([id, runtime]) => (!['cancelled', 'failed', 'completed', 'interrupted'].includes(this.records.get(id)?.state ?? '') || runtime.stopped) &&
982
1365
  !runtime.running.size && !runtime.cancelling) && ![...this.records.values()].some(record => record.state === 'creating');
983
1366
  }
@@ -986,6 +1369,7 @@ class ScheduleService {
986
1369
  if (this.destruction)
987
1370
  return this.destruction;
988
1371
  this.closing = true;
1372
+ clearTimeout(this.hostTimer);
989
1373
  return this.destruction = (async () => {
990
1374
  await this.initialization?.catch(() => { });
991
1375
  // Complete only writes already in this process's serial filesystem queue.
@@ -1137,7 +1521,7 @@ class ScheduleService {
1137
1521
  runtime.running.delete(event.occurrenceId);
1138
1522
  runtime.completed.add(event.occurrenceId);
1139
1523
  record.completedOccurrences = [...runtime.completed];
1140
- if (this.pending.size >= this.maxPending) {
1524
+ if (this.outboxFull(id)) {
1141
1525
  record.state = 'interrupted';
1142
1526
  record.error = 'Delivery outbox is full; latest result could not be retained. Native schedule stopped.';
1143
1527
  cleanup = true;
@@ -1189,7 +1573,17 @@ class ScheduleService {
1189
1573
  if (this.purges.has(pending.scheduleId))
1190
1574
  return;
1191
1575
  const record = this.records.get(pending.scheduleId);
1192
- if (!this.current(record) || record.state === 'cancelled' && !pending.afterCancellation) {
1576
+ if (record.engine === 'host') {
1577
+ const status = this.hostOwnerStatus(record);
1578
+ if (status === undefined)
1579
+ return;
1580
+ if (!status) {
1581
+ this.retireHost(record);
1582
+ await this.persist();
1583
+ return;
1584
+ }
1585
+ }
1586
+ if (record.engine !== 'host' && !this.current(record) || record.state === 'cancelled' && !pending.afterCancellation) {
1193
1587
  this.pending.delete(id);
1194
1588
  await this.persist();
1195
1589
  return;
@@ -1224,6 +1618,8 @@ class ScheduleService {
1224
1618
  this.delivering.delete(delivery.schedule.id);
1225
1619
  }
1226
1620
  await this.serial(async () => {
1621
+ if (this.closing)
1622
+ return; // A successor retries the durably unacknowledged result.
1227
1623
  this.pending.delete(id);
1228
1624
  await this.persist();
1229
1625
  });
@@ -1319,14 +1715,17 @@ class ScheduleService {
1319
1715
  this.recordOperations.delete(id);
1320
1716
  });
1321
1717
  }
1322
- current(owner) {
1718
+ ownerStatus(owner) {
1323
1719
  try {
1324
- return this.options.isOwnerCurrent(ownerOf(owner)) === true;
1720
+ return this.options.isOwnerCurrent(ownerOf(owner));
1325
1721
  }
1326
1722
  catch {
1327
- return false;
1723
+ return undefined;
1328
1724
  }
1329
1725
  }
1726
+ current(owner) {
1727
+ return this.ownerStatus(owner) === true;
1728
+ }
1330
1729
  owned(owner, id) {
1331
1730
  const record = this.records.get(id);
1332
1731
  if (!record || !sameOwner(record, owner))
@@ -1349,13 +1748,13 @@ class ScheduleService {
1349
1748
  this.tail = task.catch(() => { });
1350
1749
  return task;
1351
1750
  }
1352
- async readCatalog() {
1751
+ async readCatalog(filename) {
1353
1752
  let handle;
1354
1753
  try {
1355
- const stat = await fs.lstat(this.catalogPath);
1754
+ const stat = await fs.lstat(filename);
1356
1755
  if (!stat.isFile() || stat.isSymbolicLink())
1357
1756
  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));
1757
+ handle = await fs.open(filename, node_fs_1.constants.O_RDONLY | (node_fs_1.constants.O_NOFOLLOW ?? 0));
1359
1758
  }
1360
1759
  catch (error) {
1361
1760
  if (error.code === 'ENOENT')
@@ -1390,20 +1789,22 @@ class ScheduleService {
1390
1789
  await handle.close();
1391
1790
  }
1392
1791
  }
1393
- load(data) {
1792
+ load(data, hostCatalog = false) {
1394
1793
  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
1794
+ if (!(hostCatalog ? [6, 7] : [1, 2, 3, 4, 5, 6]).includes(catalog.version) || !Array.isArray(catalog.records) || catalog.records.length > this.maxRecords
1396
1795
  || !Array.isArray(catalog.pending) || catalog.pending.length > this.maxPending)
1397
1796
  throw new Error('Invalid schedule catalog envelope.');
1398
1797
  const records = new Map();
1399
1798
  const pending = new Map();
1400
1799
  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']);
1800
+ const record = object(value, ['id', 'backend', 'cwd', 'prompt', 'rule', 'createdAt', 'nativeId', 'state', 'error', 'threadId', 'openId', 'generation', 'execution', 'cancelRequested', 'creationRefused', 'cleanupConfirmed', 'recovery', 'completedOccurrences', 'skippedOccurrences',
1801
+ 'engine', 'sessionId', ...(catalog.version === 7 ? ['bindingEpoch'] : []), 'nextDueAt', 'inFlightDueAt']);
1402
1802
  (0, ScheduleCommand_1.validateScheduleId)(record.id);
1403
1803
  validateOwner(record);
1404
1804
  (0, ScheduleCommand_1.validateSchedulePrompt)(record.prompt);
1405
1805
  text(record.cwd, 4096);
1406
- if (!node_path_1.default.isAbsolute(record.cwd) || !(0, ScheduleCapabilities_1.isNativeScheduleBackend)(record.backend) || !STATES.has(record.state)
1806
+ if (!node_path_1.default.isAbsolute(record.cwd) || !(record.engine === 'host' ? (0, ScheduleCapabilities_1.isHostScheduleBackend)(record.backend) : (0, ScheduleCapabilities_1.isNativeScheduleBackend)(record.backend))
1807
+ || !STATES.has(record.state)
1407
1808
  || typeof record.createdAt !== 'number' || !Number.isSafeInteger(record.createdAt) || record.createdAt < 0
1408
1809
  || records.has(record.id))
1409
1810
  throw new Error('Invalid schedule catalog record.');
@@ -1453,6 +1854,30 @@ class ScheduleService {
1453
1854
  else
1454
1855
  object(rule, ['kind', 'expression', 'timezone']);
1455
1856
  (0, ScheduleCommand_1.validateScheduleRule)(rule);
1857
+ if (record.engine === 'host') {
1858
+ if (Number(catalog.version) < 6 || record.nativeId !== undefined || record.recovery !== undefined
1859
+ || record.cleanupConfirmed !== undefined || record.creationRefused !== undefined || record.skippedOccurrences !== undefined
1860
+ || record.state === 'creating')
1861
+ throw new Error('Invalid host schedule identity.');
1862
+ if (catalog.version === 7 && record.bindingEpoch === undefined && record.state !== 'interrupted')
1863
+ throw new Error('Missing host binding epoch.');
1864
+ if (record.bindingEpoch !== undefined || record.sessionId !== undefined)
1865
+ text(record.sessionId);
1866
+ const due = record.nextDueAt !== undefined ? record.nextDueAt : record.inFlightDueAt;
1867
+ if ((record.nextDueAt !== undefined) !== (record.state === 'active')
1868
+ || (record.state === 'running' && record.inFlightDueAt === undefined)
1869
+ || record.inFlightDueAt !== undefined && !['running', 'cancelled'].includes(record.state)
1870
+ || record.cancelRequested && LIVE.has(record.state)
1871
+ || record.state === 'cancelled' && !record.cancelRequested)
1872
+ throw new Error('Invalid host schedule state.');
1873
+ if (due !== undefined && (typeof due !== 'number' || !Number.isSafeInteger(due) || due <= record.createdAt
1874
+ || (0, HostScheduleRule_1.nextHostDue)(rule, due - 1) !== due
1875
+ || Array.isArray(record.completedOccurrences) && record.completedOccurrences.includes(`host-${due}`)))
1876
+ throw new Error('Invalid host occurrence receipt.');
1877
+ }
1878
+ else if (record.engine !== undefined || record.sessionId !== undefined || record.nextDueAt !== undefined
1879
+ || record.inFlightDueAt !== undefined)
1880
+ throw new Error('Unexpected host schedule fields.');
1456
1881
  records.set(record.id, structuredClone(record));
1457
1882
  }
1458
1883
  for (const value of catalog.pending) {
@@ -1475,7 +1900,7 @@ class ScheduleService {
1475
1900
  if (!Array.isArray(catalog.purged) || catalog.purged.length > MAX_PURGED_IDS)
1476
1901
  throw new Error('Invalid purge fences.');
1477
1902
  for (const value of catalog.purged) {
1478
- const fence = object(value, ['id', 'threadId', 'openId', 'generation']);
1903
+ const fence = object(value, ['id', 'threadId', 'openId', 'generation', ...(catalog.version === 7 ? ['bindingEpoch'] : [])]);
1479
1904
  (0, ScheduleCommand_1.validateScheduleId)(fence.id);
1480
1905
  validateOwner(fence);
1481
1906
  if (records.has(fence.id) || purged.has(fence.id))
@@ -1487,7 +1912,7 @@ class ScheduleService {
1487
1912
  throw new Error('Purge fences require catalog version 3 or newer.');
1488
1913
  const cleanup = new Map();
1489
1914
  const purgeRequests = new Map();
1490
- if (catalog.version === 5 || catalog.version === 6) {
1915
+ if (Number(catalog.version) >= 5) {
1491
1916
  if (!Array.isArray(catalog.cleanup) || catalog.cleanup.length > MAX_CLEANUP_RECORDS)
1492
1917
  throw new Error('Invalid cleanup ledger.');
1493
1918
  for (const value of catalog.cleanup) {
@@ -1534,11 +1959,32 @@ class ScheduleService {
1534
1959
  }
1535
1960
  else if (catalog.cleanup !== undefined || catalog.purgeRequests !== undefined)
1536
1961
  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;
1962
+ if (hostCatalog) {
1963
+ if (cleanup.size || [...records.values()].some(row => row.engine !== 'host')) {
1964
+ throw new Error('Invalid host schedule catalog.');
1965
+ }
1966
+ for (const id of [...records.keys(), ...purged.keys()]) {
1967
+ if (this.records.has(id) || this.purged.has(id) || this.unavailableLegacyIds.has(id))
1968
+ throw new Error('Conflicting schedule catalog ID.');
1969
+ this.hostCatalogIds.add(id);
1970
+ }
1971
+ for (const key of purgeRequests.keys()) {
1972
+ if (this.purgeRequests.has(key))
1973
+ throw new Error('Conflicting schedule purge request.');
1974
+ this.hostPurgeRequests.add(key);
1975
+ }
1976
+ }
1977
+ for (const [id, row] of records)
1978
+ this.records.set(id, row);
1979
+ for (const [id, row] of pending)
1980
+ this.pending.set(id, row);
1981
+ for (const [id, row] of purged)
1982
+ this.purged.set(id, row);
1983
+ for (const [id, row] of cleanup)
1984
+ this.cleanup.set(id, row);
1985
+ for (const [key, row] of purgeRequests)
1986
+ this.purgeRequests.set(key, row);
1987
+ this.catalogDigests.set(hostCatalog ? this.hostCatalogPath : this.catalogPath, (0, node_crypto_1.createHash)('sha256').update(JSON.stringify(data)).digest('hex'));
1542
1988
  }
1543
1989
  async persist() {
1544
1990
  if (!this.catalogGate)
@@ -1546,10 +1992,36 @@ class ScheduleService {
1546
1992
  this.catalogGate.verify();
1547
1993
  if (this.fault)
1548
1994
  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`);
1995
+ try {
1996
+ if (!this.legacyUnavailable)
1997
+ await this.persistCatalog(false);
1998
+ if (this.hostCatalogIds.size || this.hostPurgeRequests.size)
1999
+ await this.persistCatalog(true);
2000
+ this.armHostTimer();
2001
+ }
2002
+ catch (error) {
2003
+ this.fault = error instanceof Error ? error : new Error('Schedule catalog write failed.');
2004
+ for (const [id, runtime] of this.runtimes)
2005
+ void this.stop(id, runtime).catch(() => { });
2006
+ throw this.fault;
2007
+ }
2008
+ }
2009
+ async persistCatalog(host) {
2010
+ const filename = host ? this.hostCatalogPath : this.catalogPath;
2011
+ const belongs = (id) => this.hostCatalogIds.has(id) === host;
2012
+ const snapshot = JSON.stringify({ version: host ? 7 : 6,
2013
+ records: [...this.records.values()].filter(row => belongs(row.id)),
2014
+ pending: [...this.pending.values()].filter(row => belongs(row.scheduleId)),
2015
+ cleanup: host ? [] : [...this.cleanup.values()],
2016
+ purgeRequests: [...this.purgeRequests].filter(([key]) => this.hostPurgeRequests.has(key) === host).map(([key, receipt]) => ({ key, ...receipt })),
2017
+ purged: [...this.purged].filter(([id]) => belongs(id)).map(([id, owner]) => ({ id, ...owner })) });
2018
+ const digest = (0, node_crypto_1.createHash)('sha256').update(snapshot).digest('hex');
2019
+ if (this.catalogDigests.get(filename) === digest)
2020
+ return;
2021
+ const temporary = node_path_1.default.join(node_path_1.default.dirname(filename), `.schedule-${(0, node_crypto_1.randomUUID)()}.tmp`);
1550
2022
  try {
1551
2023
  try {
1552
- const stat = await fs.lstat(this.catalogPath);
2024
+ const stat = await fs.lstat(filename);
1553
2025
  if (!stat.isFile() || stat.isSymbolicLink())
1554
2026
  throw new Error('Schedule catalog is not a regular file.');
1555
2027
  }
@@ -1559,22 +2031,15 @@ class ScheduleService {
1559
2031
  }
1560
2032
  const handle = await fs.open(temporary, 'wx', 0o600);
1561
2033
  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');
2034
+ await handle.writeFile(snapshot, 'utf8');
1565
2035
  await handle.sync();
1566
2036
  }
1567
2037
  finally {
1568
2038
  await handle.close();
1569
2039
  }
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;
2040
+ await fs.rename(temporary, filename);
2041
+ (0, OwnershipRuntime_1.syncDirectory)(node_path_1.default.dirname(filename));
2042
+ this.catalogDigests.set(filename, digest);
1578
2043
  }
1579
2044
  finally {
1580
2045
  await fs.unlink(temporary).catch(() => { });