@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
@@ -63,7 +63,6 @@ const ScheduleDeliveryClient_1 = require("../scheduling/ScheduleDeliveryClient")
63
63
  const ScheduleCommand_1 = require("../scheduling/ScheduleCommand");
64
64
  const ScheduleCapabilities_1 = require("../scheduling/ScheduleCapabilities");
65
65
  const types_2 = require("../scheduling/types");
66
- const ClaudeSandbox_1 = require("../executor/claude/ClaudeSandbox");
67
66
  const EFFORT_BACKENDS = new Set(['claude', 'codex', 'agy', 'opencode', 'kimi', 'zcode', 'pi', 'dsh']);
68
67
  const SLASH_SESSION_BACKENDS = new Set(['opencode', 'kimi', 'zcode', 'pi']);
69
68
  const NATIVE_SKILLS_BACKENDS = new Set(['claude', 'agy', 'opencode', 'kimi', 'zcode', 'pi']);
@@ -220,6 +219,7 @@ class MessageHandler {
220
219
  pendingOutputFiles = new PendingOutputFiles_1.PendingOutputFiles();
221
220
  imageConnectionEpoch = 0;
222
221
  scheduleResultsSupported = false;
222
+ scheduleBinding;
223
223
  scheduleCardsSupported = false;
224
224
  scheduleToolCardsSupported = false;
225
225
  scheduleToolOperations = new ScheduleToolScope_1.ScheduleToolOperations();
@@ -233,6 +233,7 @@ class MessageHandler {
233
233
  schedulePurgeHosts = new Map();
234
234
  scheduleOwners = new Map();
235
235
  scheduleManagement = new Set();
236
+ hostOccurrences = new Map();
236
237
  constructor(wsClient, threadPool, threadManager, directoryGuard, config) {
237
238
  this.wsClient = wsClient;
238
239
  this.threadPool = threadPool;
@@ -242,7 +243,7 @@ class MessageHandler {
242
243
  this.scheduleCards = new ScheduleCardService_1.ScheduleCardService({
243
244
  current: owner => {
244
245
  try {
245
- return !this.isDestroyed && this.scheduleGeneration(owner.threadId) === owner.generation;
246
+ return !this.isDestroyed && this.scheduleOwnerCurrent(owner);
246
247
  }
247
248
  catch {
248
249
  return false;
@@ -251,36 +252,14 @@ class MessageHandler {
251
252
  threadName: id => this.threadManager.getThread(id)?.name ?? id,
252
253
  records: owner => this.schedules.list(owner),
253
254
  canCancel: (owner, id) => this.schedules.canCancel(owner, id),
254
- refresh: owner => this.schedules.refresh(owner),
255
- cancel: (owner, id) => this.schedules.cancel(owner, id),
256
- exclusive: async (owner, body) => {
257
- if (!this.schedules || this.isDestroyed || this.automaticUpdateInProgress
258
- || this.scheduleManagement.has(owner.threadId))
259
- throw new Error('Schedule controls are busy.');
260
- this.scheduleManagement.add(owner.threadId);
261
- try {
262
- const executor = this.threadPool.getExecutor(owner.threadId);
263
- if (!['claude', 'agy'].includes(this.threadPool.getBackendKey(owner.threadId)) || !executor.withNativeScheduleOperation
264
- || !this.schedules.hasActiveSchedules(owner.threadId))
265
- return await body();
266
- const epoch = this.imageConnectionEpoch;
267
- return await executor.withNativeScheduleOperation((0, uuid_1.v4)(), () => {
268
- try {
269
- return !this.isDestroyed && this.wsClient.isConnected() && epoch === this.imageConnectionEpoch
270
- && this.scheduleGeneration(owner.threadId) === owner.generation;
271
- }
272
- catch {
273
- return false;
274
- }
275
- }, body, false);
276
- }
277
- finally {
278
- this.scheduleManagement.delete(owner.threadId);
279
- }
280
- },
255
+ refresh: async (owner) => { await this.runScheduleOperation(owner, { kind: 'list' }); },
256
+ cancel: (owner, id) => this.runScheduleOperation(owner, { kind: 'cancel', id }),
257
+ // Each operation acquires the same record-specific admission as its slash command.
258
+ exclusive: (_owner, body) => body(),
281
259
  });
282
260
  this.wsClient.onClose?.(() => {
283
261
  this.imageConnectionEpoch++;
262
+ this.scheduleBinding = undefined;
284
263
  this.scheduleResultsSupported = false;
285
264
  this.scheduleCardsSupported = false;
286
265
  this.scheduleToolCardsSupported = false;
@@ -446,14 +425,27 @@ class MessageHandler {
446
425
  return;
447
426
  case 'binding_confirm': {
448
427
  const data = message.data;
428
+ this.scheduleResultsSupported = data?.success === true && data.capabilities?.scheduleResultsV1 === true;
429
+ const binding = data?.scheduleBinding;
430
+ const previousBinding = this.scheduleBinding;
431
+ this.scheduleBinding = this.scheduleResultsSupported && data.capabilities?.hostSchedulesV1 === true
432
+ && typeof binding?.deviceId === 'string' && binding.deviceId === this.config.get('deviceId')
433
+ && typeof binding.openId === 'string' && binding.openId.length > 0
434
+ && typeof binding.epoch === 'string' && binding.epoch.length > 0 && binding.epoch.length <= 256
435
+ ? { deviceId: binding.deviceId, openId: binding.openId, epoch: binding.epoch } : undefined;
436
+ if (previousBinding?.openId !== this.scheduleBinding?.openId || previousBinding?.epoch !== this.scheduleBinding?.epoch
437
+ || previousBinding?.deviceId !== this.scheduleBinding?.deviceId) {
438
+ this.imageConnectionEpoch++;
439
+ this.scheduleCards.invalidate();
440
+ this.clearScheduleCardReceipts();
441
+ }
442
+ this.scheduleCardsSupported = this.scheduleResultsSupported && data.capabilities?.scheduleCardsV1 === true;
443
+ this.scheduleToolCardsSupported = this.scheduleCardsSupported && data.capabilities?.scheduleToolCardsV1 === true;
449
444
  if (data?.success !== true)
450
445
  return;
451
446
  this.attachmentHintsSupported = data.capabilities?.outputAttachmentHintsV1 === true;
452
447
  this.pendingOutputSupported = data.capabilities?.pendingOutputFilesV1 === true;
453
448
  this.routerVersion = typeof data.routerVersion === 'string' ? data.routerVersion : undefined;
454
- this.scheduleResultsSupported = data.capabilities?.scheduleResultsV1 === true;
455
- this.scheduleCardsSupported = this.scheduleResultsSupported && data.capabilities?.scheduleCardsV1 === true;
456
- this.scheduleToolCardsSupported = this.scheduleCardsSupported && data.capabilities?.scheduleToolCardsV1 === true;
457
449
  void this.loadScheduleCatalog().catch(() => {
458
450
  if (this.isDestroyed)
459
451
  return;
@@ -507,6 +499,15 @@ class MessageHandler {
507
499
  this.delegationProgressTextSupported = this.delegationProgressSupported
508
500
  && data.capabilities?.delegationProgressText === true;
509
501
  for (const pending of this.pendingApprovalCards.values()) {
502
+ const occurrence = this.hostOccurrences.get(pending.request.threadId);
503
+ if (occurrence && !this.hostBindingCurrent(occurrence.record)) {
504
+ try {
505
+ pending.executor.respondToApproval?.(pending.request.messageId, 'deny');
506
+ }
507
+ catch { /* Retire the card even if the original executor has exited. */ }
508
+ this.resolveApprovalCard(pending.request.messageId, 'expired');
509
+ continue;
510
+ }
510
511
  if (this.approvalCardsSupported)
511
512
  this.sendApprovalMessage(pending.request);
512
513
  else
@@ -572,6 +573,11 @@ class MessageHandler {
572
573
  const threadId = message.threadId ?? this.threadManager.getDefaultThread().id;
573
574
  const content = message.content?.trim() ?? '';
574
575
  this.messageOpenIds.set(message.messageId, message.openId);
576
+ const occurrence = this.hostOccurrences.get(threadId);
577
+ if (occurrence && (occurrence.record.openId !== message.openId || !this.hostBindingCurrent(occurrence.record))) {
578
+ this.sendResponse(message.messageId, threadId, { success: false, error: 'This scheduled turn belongs to another owner.' }, true);
579
+ return;
580
+ }
575
581
  if ((this.automaticUpdateInProgress) && content === '/schedule list') {
576
582
  this.messageOpenIds.set(message.messageId, message.openId);
577
583
  await this.handleScheduleCommand(message, threadId);
@@ -1462,7 +1468,7 @@ Use /compact to reduce conversation context or /clear to start a fresh context.`
1462
1468
  - /effort [auto|level] - Open effort settings, or set a native supported level with a text argument
1463
1469
  - /goal [objective|pause|resume|clear] - Manage a native Codex goal; optional --budget <tokens> on start or resume
1464
1470
  - /sandbox [on|off|read-only|default|allow <directory>|remove <directory>|network on|off] - Configure this thread's sandbox (Codex, Claude Code)
1465
- - /schedule [capabilities|list|cancel <id>|after|at|cron] - Manage native scheduled tasks; /schedule shows examples
1471
+ - /schedule [capabilities|list|cancel <id>|after|at|cron] - Manage scheduled tasks; /schedule shows examples
1466
1472
  - /delegation [on|off|reset [backend]] - Delegate tasks between installed agent backends; reset saved worker context when needed
1467
1473
  - /backend - Open backend settings (Current thread by default; Confirm applies)
1468
1474
  - /backend <index> - Switch all threads and clear per-thread backend overrides
@@ -2570,7 +2576,7 @@ You can also use natural language commands to control Claude Code CLI.`,
2570
2576
  if (this.isDestroyed || this.abortOperations.has(threadId))
2571
2577
  throw new Error('Attachment task cancelled.');
2572
2578
  }
2573
- const openId = this.getMessageOpenId(messageId);
2579
+ const openId = this.messageOpenIds.get(messageId);
2574
2580
  const thread = this.threadManager.getThread(threadId);
2575
2581
  const outputGeneration = thread?.delegationWorkspaceGeneration ?? 0;
2576
2582
  if (goalRequest && thread && (0, DelegationSettings_1.isDelegationEnabled)(thread)) {
@@ -2644,7 +2650,7 @@ You can also use natural language commands to control Claude Code CLI.`,
2644
2650
  await executor.configureDelegation(undefined);
2645
2651
  }
2646
2652
  if (thread && openId && !goalRequest && executor.configureManagedTools) {
2647
- const owner = { threadId, openId, generation: this.scheduleGeneration(threadId) };
2653
+ const owner = this.scheduleOwner(threadId, openId);
2648
2654
  const epoch = this.imageConnectionEpoch;
2649
2655
  const backend = this.threadPool.getBackendKey(threadId);
2650
2656
  const config = structuredClone(this.executorConfiguration());
@@ -2656,8 +2662,8 @@ You can also use natural language commands to control Claude Code CLI.`,
2656
2662
  try {
2657
2663
  const latest = this.threadManager.getThread(threadId);
2658
2664
  return isCurrent() && !this.abortOperations.has(threadId) && !this.automaticUpdateInProgress && this.wsClient.isConnected()
2659
- && epoch === this.imageConnectionEpoch && this.scheduleGeneration(threadId) === owner.generation
2660
- && this.threadPool.getBackendKey(threadId) === backend && !!latest
2665
+ && epoch === this.imageConnectionEpoch && this.scheduleOwnerCurrent(owner)
2666
+ && this.threadPool.getBackendKey(threadId) === backend && this.threadPool.getExistingExecutor(threadId) === executor && !!latest
2661
2667
  && JSON.stringify({ config: this.executorConfiguration(), models: latest.models, model: latest.model, efforts: latest.efforts }) === settings;
2662
2668
  }
2663
2669
  catch {
@@ -2681,13 +2687,13 @@ You can also use natural language commands to control Claude Code CLI.`,
2681
2687
  await executor.configureManagedTools(connection);
2682
2688
  assertCurrent();
2683
2689
  }
2684
- scheduleScope = this.scheduleToolOperations.scope({ owner, messageId, backend, current: context.current,
2690
+ scheduleScope = this.scheduleToolOperations.scope({ owner, messageId, backend, bindingEpoch: this.scheduleBinding?.epoch, current: context.current,
2685
2691
  nativeAction: id => executor.nativeScheduleAction?.(id),
2686
2692
  deleteCleanup: (command, id) => this.runReviewedNativeCleanup(owner, command, id, context.current),
2687
2693
  listCleanup: async () => (await (await this.initializeSchedules()).listCleanup(owner)).map(ScheduleCleanup_1.cleanupSummary),
2688
2694
  purge: (selection, id) => this.runSchedulePurge(owner, selection, id, context.current),
2689
2695
  reviewCleanup: id => this.runReviewedNativeCleanup(owner, { kind: 'cleanup-review' }, id, context.current),
2690
- run: (command, id) => this.runScheduleOperation(owner, command, id, context),
2696
+ run: (command, id, allowNativeAction) => this.runScheduleOperation(owner, command, id, context, allowNativeAction),
2691
2697
  present: async (records, operationId) => {
2692
2698
  if (!context.current() || !this.scheduleToolCardsSupported)
2693
2699
  return 'Management card unavailable. Use /schedule list; do not recreate the task.';
@@ -3146,8 +3152,9 @@ You can also use natural language commands to control Claude Code CLI.`,
3146
3152
  }
3147
3153
  handleApprovalResponse(message) {
3148
3154
  const pending = this.pendingApprovalCards.get(message.messageId);
3155
+ const occurrence = this.hostOccurrences.get(message.threadId);
3149
3156
  if (!pending || pending.request.threadId !== message.threadId || pending.request.openId !== message.openId
3150
- || pending.request.taskMessageId !== message.taskMessageId) {
3157
+ || pending.request.taskMessageId !== message.taskMessageId || occurrence && !this.hostBindingCurrent(occurrence.record)) {
3151
3158
  this.sendApprovalMessage({ type: 'approval_resolved', messageId: message.messageId,
3152
3159
  openId: message.openId, threadId: message.threadId, status: 'expired', timestamp: Date.now() });
3153
3160
  return;
@@ -3400,6 +3407,41 @@ You can also use natural language commands to control Claude Code CLI.`,
3400
3407
  })).digest('hex');
3401
3408
  return path_1.default.join(directory, 'schedules', namespace);
3402
3409
  }
3410
+ scheduleOwner(threadId, openId) {
3411
+ return { threadId, openId, generation: this.scheduleGeneration(threadId),
3412
+ ...(this.scheduleBinding?.openId === openId && { bindingEpoch: this.scheduleBinding.epoch }) };
3413
+ }
3414
+ scheduleOwnerCurrent(owner) {
3415
+ const configuredOwner = this.config.get('openId');
3416
+ return (!configuredOwner || configuredOwner === owner.openId)
3417
+ && (!this.scheduleBinding || this.scheduleBinding.openId === owner.openId)
3418
+ && (!this.scheduleBinding || !owner.bindingEpoch || this.scheduleBinding.epoch === owner.bindingEpoch)
3419
+ && this.scheduleGeneration(owner.threadId) === owner.generation;
3420
+ }
3421
+ requireHostBinding(owner, expectedEpoch) {
3422
+ const binding = this.scheduleBinding;
3423
+ if (!this.wsClient.isConnected() || !binding)
3424
+ throw new Error('Host scheduling requires a connected Router with hostSchedulesV1 binding support. Upgrade or reconnect the Router.');
3425
+ if (binding.deviceId !== this.config.get('deviceId') || binding.openId !== owner.openId
3426
+ || !this.scheduleOwnerCurrent(owner) || expectedEpoch !== undefined && binding.epoch !== expectedEpoch) {
3427
+ throw new Error('Scheduled task no longer belongs to the current device binding and thread.');
3428
+ }
3429
+ return binding.epoch;
3430
+ }
3431
+ checkHostRecordBinding(record) {
3432
+ if (!record.bindingEpoch)
3433
+ throw new Error('Scheduled task has no original device binding receipt.');
3434
+ this.requireHostBinding(record, record.bindingEpoch);
3435
+ }
3436
+ hostBindingCurrent(record) {
3437
+ try {
3438
+ this.checkHostRecordBinding(record);
3439
+ return true;
3440
+ }
3441
+ catch {
3442
+ return false;
3443
+ }
3444
+ }
3403
3445
  /** Fence the updater before connection/version callbacks can race catalog loading. */
3404
3446
  async prepareScheduleStartup() {
3405
3447
  this.threadPool.setScheduleCatalog?.(() => {
@@ -3411,17 +3453,26 @@ You can also use natural language commands to control Claude Code CLI.`,
3411
3453
  return;
3412
3454
  this.scheduleCatalogPending = true;
3413
3455
  try {
3414
- await fs_1.default.promises.lstat(path_1.default.join(directory, ScheduleService_1.SCHEDULE_CATALOG_FILE));
3456
+ await this.loadScheduleCatalog();
3415
3457
  }
3416
- catch (error) {
3417
- if (['ENOENT', 'ENOTDIR'].includes(error.code ?? '')) {
3418
- this.scheduleCatalogPending = false;
3419
- return;
3458
+ catch {
3459
+ console.warn('[Schedules] Local schedule catalog is unavailable. Use /schedule list for details.');
3460
+ }
3461
+ }
3462
+ async hasScheduleCatalog(directory) {
3463
+ for (const file of [ScheduleService_1.SCHEDULE_CATALOG_FILE, ScheduleService_1.HOST_SCHEDULE_CATALOG_FILE]) {
3464
+ try {
3465
+ await fs_1.default.promises.lstat(path_1.default.join(directory, file));
3466
+ return true;
3467
+ }
3468
+ catch (error) {
3469
+ if (!['ENOENT', 'ENOTDIR'].includes(error.code ?? ''))
3470
+ throw error;
3420
3471
  }
3421
- throw error;
3422
3472
  }
3473
+ return false;
3423
3474
  }
3424
- /** Catalog loading waits for transport readiness and never creates an absent catalog. */
3475
+ /** Recover the local catalog before Router registration confirms the binding. */
3425
3476
  async loadScheduleCatalog() {
3426
3477
  if (this.isDestroyed)
3427
3478
  return;
@@ -3429,13 +3480,9 @@ You can also use natural language commands to control Claude Code CLI.`,
3429
3480
  const directory = this.scheduleDirectory();
3430
3481
  if (!directory)
3431
3482
  return;
3432
- try {
3433
- await fs_1.default.promises.lstat(path_1.default.join(directory, ScheduleService_1.SCHEDULE_CATALOG_FILE));
3434
- }
3435
- catch (error) {
3436
- if (['ENOENT', 'ENOTDIR'].includes(error.code ?? ''))
3437
- return;
3438
- throw error;
3483
+ if (!await this.hasScheduleCatalog(directory) && !this.scheduleInitialization) {
3484
+ this.scheduleCatalogPending = false;
3485
+ return;
3439
3486
  }
3440
3487
  }
3441
3488
  // A disconnect or shutdown can happen while storage is being checked. Never
@@ -3461,9 +3508,12 @@ You can also use natural language commands to control Claude Code CLI.`,
3461
3508
  throw new Error('Local schedule storage is unavailable.');
3462
3509
  const service = new ScheduleService_1.ScheduleService({
3463
3510
  directory,
3511
+ hostDispatch: (record, occurrenceId, admit) => this.dispatchHostOccurrence(record, occurrenceId, admit),
3464
3512
  isNativeMutationPending: owner => this.threadPool.getExistingExecutor(owner.threadId)?.hasPendingScheduleMutation?.() ?? false,
3465
3513
  withPurgeVerification: (record, context, accept) => (0, SchedulePurgeVerification_1.verifySchedulePurge)(record, this.schedulePurgeHosts.get(record.threadId), context.isCurrent, accept),
3466
3514
  provider: { cleanupFor: input => {
3515
+ if (input.engine === 'host')
3516
+ return undefined;
3467
3517
  if (!input.threadId || this.threadPool.getBackendKey(input.threadId) !== input.backend)
3468
3518
  return undefined;
3469
3519
  return this.threadPool.getExecutor(input.threadId).nativeScheduleCleanup;
@@ -3472,6 +3522,8 @@ You can also use natural language commands to control Claude Code CLI.`,
3472
3522
  let executor;
3473
3523
  let generation;
3474
3524
  try {
3525
+ if (input.engine === 'host')
3526
+ throw new Error('Host schedules cannot create native timer definitions.');
3475
3527
  (0, ScheduleCapabilities_1.assertNativeScheduleBackend)(backend);
3476
3528
  if (!input.threadId)
3477
3529
  throw new Error('Native scheduling requires the original thread.');
@@ -3507,8 +3559,10 @@ You can also use natural language commands to control Claude Code CLI.`,
3507
3559
  } },
3508
3560
  isOwnerCurrent: owner => {
3509
3561
  // Shutdown blocks delivery separately; it does not invalidate persisted ownership.
3562
+ if (owner.bindingEpoch !== undefined && (!this.wsClient.isConnected() || !this.scheduleBinding))
3563
+ return undefined;
3510
3564
  try {
3511
- return this.scheduleGeneration(owner.threadId) === owner.generation;
3565
+ return this.scheduleOwnerCurrent(owner);
3512
3566
  }
3513
3567
  catch {
3514
3568
  return false;
@@ -3517,6 +3571,10 @@ You can also use natural language commands to control Claude Code CLI.`,
3517
3571
  deliver: async (delivery) => {
3518
3572
  if (!this.scheduleResultsSupported || this.isDestroyed)
3519
3573
  throw new Error('Scheduled result delivery is unavailable.');
3574
+ if (delivery.schedule.engine === 'host')
3575
+ this.checkHostRecordBinding(delivery.schedule);
3576
+ else if (!this.scheduleOwnerCurrent(delivery.schedule))
3577
+ throw new Error('Scheduled result owner changed.');
3520
3578
  const thread = this.threadManager.getThread(delivery.schedule.threadId);
3521
3579
  if (!thread)
3522
3580
  throw new Error('The original thread no longer exists.');
@@ -3525,12 +3583,131 @@ You can also use natural language commands to control Claude Code CLI.`,
3525
3583
  });
3526
3584
  await service.initialize();
3527
3585
  if (!this.isDestroyed)
3528
- this.scheduleDelivery = new ScheduleDeliveryClient_1.ScheduleDeliveryClient(this.wsClient);
3586
+ this.scheduleDelivery = new ScheduleDeliveryClient_1.ScheduleDeliveryClient(this.wsClient, record => record.engine === 'host' ? this.hostBindingCurrent(record) : this.scheduleOwnerCurrent(record));
3529
3587
  this.schedules = service;
3530
3588
  return service;
3531
3589
  })();
3532
3590
  return this.scheduleInitialization;
3533
3591
  }
3592
+ async dispatchHostOccurrence(record, occurrenceId, admit) {
3593
+ const { threadId, openId, sessionId, cwd } = record;
3594
+ if (!this.scheduleBinding || !this.wsClient.isConnected())
3595
+ return undefined;
3596
+ if (this.settingsBusy(threadId) || this.settingsAdmission.isBlocked(threadId)
3597
+ || this.scheduleManagement.has(threadId) || this.activeThreadOperations.has(threadId)
3598
+ || this.pendingGoalActivations.has(threadId))
3599
+ return undefined;
3600
+ const messageId = `${record.id}:${occurrenceId}`;
3601
+ return this.settingsAdmission.command(threadId, messageId, async () => {
3602
+ const token = this.beginThreadOperation(threadId);
3603
+ const occurrence = { record, cancelled: false };
3604
+ this.hostOccurrences.set(threadId, occurrence);
3605
+ this.messageOpenIds.set(messageId, openId);
3606
+ try {
3607
+ const checkOwner = (allowDisconnectedResult = false) => {
3608
+ // A completed response can enter its original owner's outbox while offline.
3609
+ // Admission, approvals and transport still require a confirmed live binding.
3610
+ if (!allowDisconnectedResult || this.scheduleBinding)
3611
+ this.checkHostRecordBinding(record);
3612
+ else if (!this.scheduleOwnerCurrent(record))
3613
+ throw new Error('Scheduled result owner changed.');
3614
+ if (this.isDestroyed || this.cancelledOperations.has(token) || this.activeThreadOperations.get(threadId)?.token !== token
3615
+ || !openId || record.engine !== 'host' || this.threadPool.getBackendKey(threadId) !== record.backend
3616
+ || this.directoryGuard.resolveWorkingDirectory(this.threadManager.getThread(threadId).workingDirectory) !== cwd) {
3617
+ throw new Error('Scheduled occurrence lost its original conversation or owner.');
3618
+ }
3619
+ };
3620
+ checkOwner();
3621
+ if (!sessionId)
3622
+ throw new Error('Scheduled task has no native conversation identity.');
3623
+ const executor = this.threadPool.getExecutor(threadId);
3624
+ if (executor.hasPendingCancellation?.() || executor.hasPendingScheduleMutation?.()
3625
+ || executor.hasPendingSettingsChange?.() || executor.isGoalRunning?.() || executor.isBusy?.())
3626
+ return undefined;
3627
+ const check = (allowDisconnectedResult = false) => {
3628
+ checkOwner(allowDisconnectedResult);
3629
+ if (this.threadPool.getExistingExecutor(threadId) !== executor)
3630
+ throw new Error('Scheduled executor changed.');
3631
+ this.checkHostSession(executor, sessionId, cwd);
3632
+ };
3633
+ check();
3634
+ (0, WorkingDirectory_1.assertWorkingDirectoryExists)(cwd);
3635
+ if (this.delegation.blocksWorkspace(cwd, threadId))
3636
+ return undefined;
3637
+ await this.delegation.assertExecutionSafe(cwd, threadId);
3638
+ check();
3639
+ if (occurrence.cancelled || !await admit())
3640
+ return undefined;
3641
+ const beforePrompt = () => {
3642
+ check();
3643
+ if (occurrence.cancelled)
3644
+ throw new Error('Scheduled occurrence was cancelled before prompt dispatch.');
3645
+ };
3646
+ beforePrompt();
3647
+ let display = '';
3648
+ const result = await executor.execute(record.prompt, {
3649
+ hostScheduleSessionId: sessionId,
3650
+ // Claude checks queued authorization before process startup and again before stdin.
3651
+ ...(record.backend === 'claude' && { nativeScheduleCurrent: () => {
3652
+ try {
3653
+ beforePrompt();
3654
+ return true;
3655
+ }
3656
+ catch {
3657
+ return false;
3658
+ }
3659
+ } }),
3660
+ resolvePrompt: actual => {
3661
+ beforePrompt();
3662
+ if (actual !== sessionId)
3663
+ throw new Error('Scheduled task could not resume its original native session.');
3664
+ return record.prompt;
3665
+ },
3666
+ onDisplayText: chunk => { if (display.length < 65537)
3667
+ display += chunk.slice(0, 65537 - display.length); },
3668
+ onApprovalRequest: approval => {
3669
+ try {
3670
+ check();
3671
+ }
3672
+ catch {
3673
+ return false;
3674
+ }
3675
+ return this.forwardApproval(approval, executor, messageId, threadId);
3676
+ },
3677
+ onApprovalResolved: (id, status) => this.resolveApprovalCard(id, status),
3678
+ onStream: chunk => {
3679
+ if (!executor.isWaitingInput?.())
3680
+ return;
3681
+ try {
3682
+ check();
3683
+ }
3684
+ catch {
3685
+ return;
3686
+ }
3687
+ this.sendStreamChunk(messageId, threadId, chunk);
3688
+ },
3689
+ });
3690
+ check(true);
3691
+ // Prefer the public display stream, but preserve the executor's final
3692
+ // output when a backend only returns its answer at turn completion.
3693
+ return { success: result.success, output: display || result.output, error: result.error };
3694
+ }
3695
+ catch (error) {
3696
+ return { success: false, error: error instanceof Error ? error.message : 'Scheduled execution failed.' };
3697
+ }
3698
+ finally {
3699
+ for (const [id, pending] of this.pendingApprovalCards) {
3700
+ if (pending.request.taskMessageId === messageId)
3701
+ this.resolveApprovalCard(id, 'expired');
3702
+ }
3703
+ this.messageOpenIds.delete(messageId);
3704
+ this.hostOccurrences.delete(threadId);
3705
+ this.cancelledOperations.delete(token);
3706
+ if (this.finishThreadOperation(threadId, token) && !this.isDestroyed)
3707
+ void this.startNextQueuedCommand(threadId);
3708
+ }
3709
+ });
3710
+ }
3534
3711
  async activeSchedules(threadId) {
3535
3712
  const owner = this.scheduleOwners.get(threadId);
3536
3713
  if (!owner || !this.schedules)
@@ -3546,14 +3723,8 @@ You can also use natural language commands to control Claude Code CLI.`,
3546
3723
  const directory = this.scheduleDirectory();
3547
3724
  if (!directory)
3548
3725
  return;
3549
- try {
3550
- await fs_1.default.promises.lstat(path_1.default.join(directory, ScheduleService_1.SCHEDULE_CATALOG_FILE));
3551
- }
3552
- catch (error) {
3553
- if (['ENOENT', 'ENOTDIR'].includes(error.code ?? ''))
3554
- return;
3555
- throw error;
3556
- }
3726
+ if (!await this.hasScheduleCatalog(directory))
3727
+ return;
3557
3728
  await this.initializeSchedules();
3558
3729
  }
3559
3730
  if (this.schedules?.hasCleanupContext(threadId)) {
@@ -3593,133 +3764,111 @@ You can also use natural language commands to control Claude Code CLI.`,
3593
3764
  resolve('Management card unavailable. Use /schedule list; do not recreate the task.');
3594
3765
  });
3595
3766
  }
3596
- /** Shared admission for slash commands and scoped model tools. Native providers alone own timing. */
3597
- async runScheduleOperation(owner, command, id = (0, uuid_1.v4)(), context, nativeBound = false) {
3767
+ /** Slash commands, management cards and in-turn tools share record-specific admission. */
3768
+ async runScheduleOperation(owner, command, id = (0, uuid_1.v4)(), context, allowNativeAction) {
3769
+ const { threadId } = owner;
3770
+ const epoch = this.imageConnectionEpoch;
3771
+ const backend = context?.backend ?? this.threadPool.getBackendKey(threadId);
3598
3772
  const current = () => {
3599
3773
  try {
3600
- return !this.isDestroyed && this.scheduleGeneration(owner.threadId) === owner.generation && (!context || context.current());
3774
+ return !this.isDestroyed && !this.automaticUpdateInProgress && epoch === this.imageConnectionEpoch
3775
+ && this.scheduleOwnerCurrent(owner) && this.threadPool.getBackendKey(threadId) === backend
3776
+ && (!context || context.current());
3601
3777
  }
3602
3778
  catch {
3603
3779
  return false;
3604
3780
  }
3605
3781
  };
3606
- const check = () => { if (!current() || this.automaticUpdateInProgress)
3782
+ const check = () => { if (!current())
3607
3783
  throw new Error('Scheduling context changed or client is shutting down/updating.'); };
3608
3784
  check();
3609
- if (command.kind === 'list' && this.threadPool.getExistingExecutor(owner.threadId)?.hasPendingCancellation?.()) {
3785
+ if (command.kind === 'list') {
3610
3786
  const service = await this.initializeSchedules();
3787
+ const records = await service.list(owner);
3611
3788
  check();
3612
- return service.list(owner); // Catalog-only recovery visibility; never acquire native management admission.
3789
+ return records;
3613
3790
  }
3614
- if (!nativeBound && this.scheduleManagement.has(owner.threadId))
3791
+ if (this.scheduleManagement.has(threadId))
3615
3792
  throw new Error('A schedule operation is already in progress for this thread.');
3616
- this.scheduleManagement.add(owner.threadId);
3793
+ this.scheduleManagement.add(threadId);
3617
3794
  try {
3618
- const backend = context?.backend ?? this.threadPool.getBackendKey(owner.threadId);
3619
- const config = context?.config ?? this.executorConfiguration();
3795
+ let captured;
3620
3796
  if (command.kind === 'create') {
3621
- (0, ScheduleCapabilities_1.assertNativeScheduleBackend)(backend);
3622
- if (!this.scheduleResultsSupported || !this.wsClient.isConnected())
3623
- throw new Error('Schedule creation requires a connected Router with scheduleResultsV1 support.');
3624
- if (backend === 'claude' && new ClaudeSandbox_1.ClaudeSandbox(this.directoryGuard, config.claude?.sandbox, owner.threadId).isRestricted()) {
3625
- throw new Error('This native scheduling adapter does not support restricted Claude sandboxes. No schedule was created and sandbox settings were not changed.');
3626
- }
3797
+ (0, ScheduleCapabilities_1.assertHostScheduleBackend)(backend);
3798
+ const bindingEpoch = this.requireHostBinding(owner);
3799
+ const executor = this.threadPool.getExecutor(threadId);
3800
+ const cwd = this.directoryGuard.resolveWorkingDirectory(context?.cwd ?? this.threadManager.getThread(threadId).workingDirectory);
3801
+ const sessionId = executor.getSessionId?.();
3802
+ if (!sessionId)
3803
+ throw new Error('Send an ordinary message in this thread to establish its native conversation, then retry scheduling.');
3804
+ (0, WorkingDirectory_1.assertWorkingDirectoryExists)(cwd);
3805
+ this.checkHostSession(executor, sessionId, cwd);
3806
+ captured = { executor, sessionId, cwd, bindingEpoch };
3627
3807
  }
3628
- const nativeCancellation = !nativeBound && (backend === 'claude' || backend === 'agy') && command.kind === 'cancel'
3629
- && (await this.initializeSchedules()).canCancel(owner, command.id);
3808
+ const service = await this.initializeSchedules();
3809
+ const records = await service.list(owner);
3630
3810
  check();
3631
- if (!nativeBound && (backend === 'claude' || backend === 'agy') && (command.kind === 'create' || nativeCancellation
3632
- || command.kind !== 'cancel' && this.schedules?.hasActiveSchedules(owner.threadId))) {
3633
- const executor = this.threadPool.getExecutor(owner.threadId);
3811
+ if (command.kind === 'cancel') {
3812
+ const manage = async () => {
3813
+ check();
3814
+ const occurrence = this.hostOccurrences.get(threadId);
3815
+ if (occurrence?.record.id === command.id && occurrence.record.openId === owner.openId
3816
+ && occurrence.record.generation === owner.generation)
3817
+ occurrence.cancelled = true;
3818
+ return [await service.cancel(owner, command.id)];
3819
+ };
3820
+ const native = (backend === 'claude' || backend === 'agy') && records.some(record => record.engine !== 'host' && record.backend === backend && record.id === command.id && service.canCancel(owner, record.id));
3821
+ if (!native)
3822
+ return await manage();
3823
+ const executor = this.threadPool.getExecutor(threadId);
3634
3824
  if (!executor.withNativeScheduleOperation)
3635
3825
  throw new Error('Shared native session scheduling is unavailable.');
3636
- if (!context && command.kind === 'create' && executor.configureManagedTools) {
3637
- // Install the same bridge the next ordinary turn will use before a
3638
- // slash-created native job exists. That turn must not recycle its host.
3639
- const bridge = this.delegationBridges.get(owner.threadId) ?? new DelegationBridge_1.DelegationBridge();
3640
- this.delegationBridges.set(owner.threadId, bridge);
3641
- const thread = this.threadManager.getThread(owner.threadId);
3642
- const connection = await bridge.start(thread && (0, DelegationSettings_1.isDelegationEnabled)(thread) ? ['delegation', 'scheduling'] : ['scheduling']);
3643
- check();
3644
- await executor.configureManagedTools(connection);
3645
- check();
3646
- }
3647
- const records = await executor.withNativeScheduleOperation(id, current, () => this.runScheduleOperation(owner, command, id, context, true), !!context);
3648
- if (command.kind === 'create' && !current()) {
3649
- const cleanupCurrent = () => {
3650
- try {
3651
- return !this.isDestroyed && this.scheduleGeneration(owner.threadId) === owner.generation
3652
- && this.threadPool.getExistingExecutor(owner.threadId) === executor;
3653
- }
3654
- catch {
3655
- return false;
3656
- }
3657
- };
3658
- const service = await this.initializeSchedules();
3659
- try {
3660
- if (!executor.reconcileNativeSchedule) {
3661
- throw new Error(`Schedule ${id} requires explicit cancellation; native cleanup admission is unavailable.`);
3662
- }
3663
- await executor.reconcileNativeSchedule(id, cleanupCurrent, () => service.cancel(owner, id));
3664
- }
3665
- catch (error) {
3666
- await service.retainCleanupError(owner, id, error);
3667
- throw error;
3668
- }
3669
- throw new Error('Scheduling context retired during creation. Inspect /schedule list for the final task state.');
3670
- }
3671
- return records;
3826
+ allowNativeAction?.();
3827
+ return await executor.withNativeScheduleOperation(id, current, manage, !!context);
3672
3828
  }
3673
- const service = await this.initializeSchedules();
3674
- check();
3675
- if (command.kind === 'list') {
3676
- await service.refresh(owner);
3677
- check();
3678
- void service.retryDeliveries().catch(() => { });
3679
- return service.list(owner);
3680
- }
3681
- if (command.kind === 'cancel')
3682
- return [await service.cancel(owner, command.id)];
3683
- (0, ScheduleCapabilities_1.assertNativeScheduleBackend)(backend);
3684
- // A durable record fences retries after lost in-memory receipts or a process restart.
3685
- if ((await service.list(owner)).some(record => record.id === id))
3829
+ (0, ScheduleCapabilities_1.assertHostScheduleBackend)(backend);
3830
+ if (records.some(record => record.id === id))
3686
3831
  throw new Error(`Schedule ${id} already has a durable record. Use /schedule list; it was not recreated.`);
3687
- check();
3688
- const thread = this.threadManager.getThread(owner.threadId);
3689
- const cwd = this.directoryGuard.resolveWorkingDirectory(context?.cwd ?? thread.workingDirectory);
3690
- (0, WorkingDirectory_1.assertWorkingDirectoryExists)(cwd);
3691
- const existingOwner = this.scheduleOwners.get(owner.threadId);
3692
- if (existingOwner && existingOwner.openId !== owner.openId && (await this.activeSchedules(owner.threadId)).length)
3832
+ const existingOwner = this.scheduleOwners.get(threadId);
3833
+ if (existingOwner && existingOwner.openId !== owner.openId && (await this.activeSchedules(threadId)).length)
3693
3834
  throw new Error('This thread has schedules belonging to a different owner.');
3694
3835
  check();
3695
- this.scheduleOwners.set(owner.threadId, owner);
3696
- if (!context && backend !== 'claude') {
3697
- const executor = this.threadPool.getExecutor(owner.threadId);
3698
- if (executor.configureManagedTools) {
3699
- const bridge = this.delegationBridges.get(owner.threadId) ?? new DelegationBridge_1.DelegationBridge();
3700
- this.delegationBridges.set(owner.threadId, bridge);
3701
- const connection = await bridge.start((0, DelegationSettings_1.isDelegationEnabled)(thread) ? ['delegation', 'scheduling'] : ['scheduling']);
3702
- check();
3703
- await executor.configureManagedTools(connection);
3704
- check();
3705
- }
3706
- }
3707
- const record = await service.create(owner, { id, threadId: owner.threadId, backend, cwd, rule: command.rule, prompt: command.prompt,
3708
- command: config[backend]?.command,
3836
+ const thread = this.threadManager.getThread(threadId);
3837
+ const { executor, sessionId, cwd, bindingEpoch } = captured;
3838
+ this.requireHostBinding(owner, bindingEpoch);
3839
+ if (this.threadPool.getExistingExecutor(threadId) !== executor)
3840
+ throw new Error('Scheduling executor changed.');
3841
+ this.checkHostSession(executor, sessionId, cwd);
3842
+ this.scheduleOwners.set(threadId, owner);
3843
+ const config = context?.config ?? this.executorConfiguration();
3844
+ const input = { id, threadId, backend, cwd, engine: 'host', sessionId, bindingEpoch,
3845
+ rule: command.rule, prompt: command.prompt, command: config[backend]?.command,
3709
3846
  model: context ? context.model : thread.models?.[backend] ?? (backend === 'claude' ? thread.model || undefined : config[backend]?.model),
3710
- effort: context ? context.effort : thread.efforts?.[backend] });
3711
- if (!current() && !nativeBound) {
3847
+ effort: context ? context.effort : thread.efforts?.[backend] };
3848
+ const record = await service.create(owner, input);
3849
+ try {
3850
+ check();
3851
+ this.checkHostRecordBinding(record);
3852
+ if (this.threadPool.getExistingExecutor(threadId) !== executor)
3853
+ throw new Error('Scheduling executor changed.');
3854
+ this.checkHostSession(executor, sessionId, cwd);
3855
+ }
3856
+ catch (error) {
3712
3857
  await service.cancel(owner, record.id);
3713
- throw new Error('Scheduling context retired during creation; the native task was cancelled.');
3858
+ throw error;
3714
3859
  }
3715
3860
  return [record];
3716
3861
  }
3717
3862
  finally {
3718
- if (!nativeBound) {
3719
- this.scheduleManagement.delete(owner.threadId);
3720
- await this.activeSchedules(owner.threadId).catch(() => undefined);
3721
- }
3863
+ this.scheduleManagement.delete(threadId);
3864
+ await this.activeSchedules(threadId).catch(() => undefined);
3865
+ }
3866
+ }
3867
+ checkHostSession(executor, sessionId, cwd) {
3868
+ if (!sessionId || executor.getSessionId?.() !== sessionId || executor.getCurrentWorkingDirectory() !== cwd) {
3869
+ throw new Error('Scheduled task requires the original native session and working directory.');
3722
3870
  }
3871
+ executor.checkHostScheduleSession?.(sessionId);
3723
3872
  }
3724
3873
  /** Purge shares native operation admission with cancellation; only the service
3725
3874
  * decides whether verified retirement permits history removal. */
@@ -3733,7 +3882,7 @@ You can also use natural language commands to control Claude Code CLI.`,
3733
3882
  const current = () => {
3734
3883
  try {
3735
3884
  return !this.isDestroyed && !this.automaticUpdateInProgress && this.wsClient.isConnected()
3736
- && epoch === this.imageConnectionEpoch && this.scheduleGeneration(owner.threadId) === owner.generation && !this.abortOperations.has(owner.threadId)
3885
+ && epoch === this.imageConnectionEpoch && this.scheduleOwnerCurrent(owner) && !this.abortOperations.has(owner.threadId)
3737
3886
  && this.threadPool.getBackendKey(owner.threadId) === backend
3738
3887
  && this.threadPool.getExistingExecutor(owner.threadId) === executor
3739
3888
  && capturedSettings === settings() && (!inTurnCurrent || inTurnCurrent());
@@ -3768,9 +3917,9 @@ You can also use natural language commands to control Claude Code CLI.`,
3768
3917
  return await run();
3769
3918
  const records = await service.list(owner);
3770
3919
  const needsVerification = backend === 'claude' && !!executor.withReviewedNativeCleanup && (cleanup.some(item => ids.includes(item.id) && item.backend === 'claude' && !!item.attribution && !!item.nativeId) || records.some(record => ids.includes(record.id)
3771
- && record.backend === 'claude' && !!record.recovery && !!record.nativeId && !record.cleanupConfirmed && !record.creationRefused && !['active', 'running', 'creating'].includes(record.state)));
3920
+ && record.engine !== 'host' && record.backend === 'claude' && !!record.recovery && !!record.nativeId && !record.cleanupConfirmed && !record.creationRefused && !['active', 'running', 'creating'].includes(record.state)));
3772
3921
  const needsNative = needsVerification || ['claude', 'agy'].includes(backend) && records.some(record => ids.includes(record.id)
3773
- && record.backend === backend && (service.canCancel(owner, record.id)
3922
+ && record.engine !== 'host' && record.backend === backend && (service.canCancel(owner, record.id)
3774
3923
  || backend === 'agy' && service.needsNativePurge(owner, record.id)));
3775
3924
  if (!needsNative)
3776
3925
  return await run();
@@ -3820,7 +3969,7 @@ You can also use natural language commands to control Claude Code CLI.`,
3820
3969
  try {
3821
3970
  return !this.isDestroyed && !this.automaticUpdateInProgress
3822
3971
  && !this.abortOperations.has(threadId) && this.wsClient.isConnected() && epoch === this.imageConnectionEpoch
3823
- && this.scheduleGeneration(threadId) === owner.generation && this.threadPool.getExistingExecutor(threadId) === executor
3972
+ && this.scheduleOwnerCurrent(owner) && this.threadPool.getExistingExecutor(threadId) === executor
3824
3973
  && this.threadPool.getBackendKey(threadId) === 'claude' && config === settings() && (!inTurnCurrent || inTurnCurrent());
3825
3974
  }
3826
3975
  catch {
@@ -3911,7 +4060,9 @@ You can also use natural language commands to control Claude Code CLI.`,
3911
4060
  if (message.attachments?.length || message.fileIds?.length || message.workingDirectory) {
3912
4061
  throw new Error('Use /cd first and include a self-contained text prompt. Schedule commands do not accept attachments or directory overrides.');
3913
4062
  }
3914
- const owner = { threadId, openId: message.openId, generation: this.scheduleGeneration(threadId) };
4063
+ const owner = this.scheduleOwner(threadId, message.openId);
4064
+ if (!this.scheduleOwnerCurrent(owner))
4065
+ throw new Error('Scheduled task owner does not match this device binding.');
3915
4066
  if (command.kind === 'cleanup-review' || command.kind === 'cleanup-confirm') {
3916
4067
  const result = await this.runReviewedNativeCleanup(owner, command, (0, crypto_1.createHash)('sha256').update(message.messageId ?? (0, uuid_1.v4)()).digest('hex'));
3917
4068
  let output;
@@ -3954,8 +4105,7 @@ You can also use natural language commands to control Claude Code CLI.`,
3954
4105
  else if (command.kind === 'cancel')
3955
4106
  output = `Schedule ${record.id}: ${record.state}.`;
3956
4107
  else {
3957
- const lifecycle = 'Schedules run only while their native host remains live. After host loss they are interrupted and never automatically restored. Native history and exact cleanup obligations are retained.';
3958
- output = `Schedule ${record.id}: ${record.state}.\n${record.rule.kind === 'once' ? record.rule.at : `${record.rule.expression} (${record.rule.timezone})`}\n\nRuns in this thread's foreground ${ScheduleCapabilities_1.NATIVE_SCHEDULE_CAPABILITIES[record.backend].label} conversation and returns results here. Keep the CLI running; native timing is approximate. ${lifecycle}\nUse /schedule list or /schedule cancel ${record.id}.`;
4108
+ output = `Schedule ${record.id}: ${record.state}.\n${record.rule.kind === 'once' ? record.rule.at : `${record.rule.expression} (${record.rule.timezone})`}\n\nThe CLI stores the schedule across restarts and runs it in this thread's original ${ScheduleCapabilities_1.HOST_SCHEDULE_CAPABILITIES[record.backend].label} conversation. Results return here when connected.\nUse /schedule list or /schedule cancel ${record.id}.`;
3959
4109
  }
3960
4110
  if (command.kind === 'list') {
3961
4111
  const cleanup = await this.schedules?.listCleanup(owner) ?? [];
@@ -4290,6 +4440,7 @@ You can also use natural language commands to control Claude Code CLI.`,
4290
4440
  */
4291
4441
  async destroy() {
4292
4442
  this.isDestroyed = true;
4443
+ const scheduledTurns = [...this.hostOccurrences.keys()].map(id => this.activeThreadOperations.get(id)?.done);
4293
4444
  this.directoryBrowser.destroy();
4294
4445
  this.settingsService.destroy();
4295
4446
  this.scheduleCards.destroy();
@@ -4313,6 +4464,7 @@ You can also use natural language commands to control Claude Code CLI.`,
4313
4464
  this.delegation.destroy(),
4314
4465
  ...[...this.delegationBridges.values()].map(bridge => bridge.close()),
4315
4466
  this.threadPool.destroyAll({ deleteData: false, shutdown: true }),
4467
+ ...scheduledTurns,
4316
4468
  ]);
4317
4469
  const failure = results.find((result) => result.status === 'rejected');
4318
4470
  if (failure)