@yu_robotics/remote-cli 1.6.264 → 1.6.266

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +41 -0
  2. package/dist/client/MessageHandler.d.ts +13 -2
  3. package/dist/client/MessageHandler.d.ts.map +1 -1
  4. package/dist/client/MessageHandler.js +393 -172
  5. package/dist/client/MessageHandler.js.map +1 -1
  6. package/dist/client/WebSocketClient.d.ts.map +1 -1
  7. package/dist/client/WebSocketClient.js +1 -0
  8. package/dist/client/WebSocketClient.js.map +1 -1
  9. package/dist/delegation/piExtension.js +1 -1
  10. package/dist/delegation/piExtension.js.map +1 -1
  11. package/dist/executor/AcpExecutor.d.ts +11 -4
  12. package/dist/executor/AcpExecutor.d.ts.map +1 -1
  13. package/dist/executor/AcpExecutor.js +64 -11
  14. package/dist/executor/AcpExecutor.js.map +1 -1
  15. package/dist/executor/AgyExecutor.d.ts +6 -0
  16. package/dist/executor/AgyExecutor.d.ts.map +1 -1
  17. package/dist/executor/AgyExecutor.js +126 -9
  18. package/dist/executor/AgyExecutor.js.map +1 -1
  19. package/dist/executor/ClaudePersistentExecutor.d.ts +5 -1
  20. package/dist/executor/ClaudePersistentExecutor.d.ts.map +1 -1
  21. package/dist/executor/ClaudePersistentExecutor.js +81 -17
  22. package/dist/executor/ClaudePersistentExecutor.js.map +1 -1
  23. package/dist/executor/CodexAppServerClient.d.ts +1 -1
  24. package/dist/executor/CodexAppServerClient.d.ts.map +1 -1
  25. package/dist/executor/CodexAppServerClient.js +8 -2
  26. package/dist/executor/CodexAppServerClient.js.map +1 -1
  27. package/dist/executor/CodexAppServerExecutor.d.ts +3 -1
  28. package/dist/executor/CodexAppServerExecutor.d.ts.map +1 -1
  29. package/dist/executor/CodexAppServerExecutor.js +67 -22
  30. package/dist/executor/CodexAppServerExecutor.js.map +1 -1
  31. package/dist/executor/DshExecutor.d.ts +2 -0
  32. package/dist/executor/DshExecutor.d.ts.map +1 -1
  33. package/dist/executor/DshExecutor.js +26 -6
  34. package/dist/executor/DshExecutor.js.map +1 -1
  35. package/dist/executor/IExecutor.d.ts +4 -0
  36. package/dist/executor/IExecutor.d.ts.map +1 -1
  37. package/dist/executor/PiExecutor.d.ts +2 -0
  38. package/dist/executor/PiExecutor.d.ts.map +1 -1
  39. package/dist/executor/PiExecutor.js +96 -23
  40. package/dist/executor/PiExecutor.js.map +1 -1
  41. package/dist/executor/acp/AcpClient.d.ts +4 -3
  42. package/dist/executor/acp/AcpClient.d.ts.map +1 -1
  43. package/dist/executor/acp/AcpClient.js +18 -2
  44. package/dist/executor/acp/AcpClient.js.map +1 -1
  45. package/dist/executor/agy/AgyAcpRuntime.d.ts +8 -1
  46. package/dist/executor/agy/AgyAcpRuntime.d.ts.map +1 -1
  47. package/dist/executor/agy/AgyAcpRuntime.js +47 -3
  48. package/dist/executor/agy/AgyAcpRuntime.js.map +1 -1
  49. package/dist/executor/agy/AgySessionSelection.d.ts +3 -0
  50. package/dist/executor/agy/AgySessionSelection.d.ts.map +1 -1
  51. package/dist/executor/agy/AgySessionSelection.js +24 -0
  52. package/dist/executor/agy/AgySessionSelection.js.map +1 -1
  53. package/dist/executor/dsh/DshAcpClient.d.ts +1 -1
  54. package/dist/executor/dsh/DshAcpClient.d.ts.map +1 -1
  55. package/dist/executor/dsh/DshAcpClient.js +2 -2
  56. package/dist/executor/dsh/DshAcpClient.js.map +1 -1
  57. package/dist/executor/pi/PiClient.d.ts +3 -1
  58. package/dist/executor/pi/PiClient.d.ts.map +1 -1
  59. package/dist/executor/pi/PiClient.js +15 -1
  60. package/dist/executor/pi/PiClient.js.map +1 -1
  61. package/dist/executor/pi/PiTypes.d.ts +3 -1
  62. package/dist/executor/pi/PiTypes.d.ts.map +1 -1
  63. package/dist/executor/pi/PiTypes.js.map +1 -1
  64. package/dist/executor/zcode/ZCodeClient.d.ts +2 -2
  65. package/dist/executor/zcode/ZCodeClient.d.ts.map +1 -1
  66. package/dist/executor/zcode/ZCodeClient.js +26 -7
  67. package/dist/executor/zcode/ZCodeClient.js.map +1 -1
  68. package/dist/maintenance/release-notes.json +1 -1
  69. package/dist/managed/tools.d.ts +6 -6
  70. package/dist/scheduling/ScheduleCapabilities.d.ts +59 -14
  71. package/dist/scheduling/ScheduleCapabilities.d.ts.map +1 -1
  72. package/dist/scheduling/ScheduleCapabilities.js +33 -29
  73. package/dist/scheduling/ScheduleCapabilities.js.map +1 -1
  74. package/dist/scheduling/ScheduleCardService.d.ts.map +1 -1
  75. package/dist/scheduling/ScheduleCardService.js +3 -1
  76. package/dist/scheduling/ScheduleCardService.js.map +1 -1
  77. package/dist/scheduling/ScheduleCleanup.d.ts +3 -2
  78. package/dist/scheduling/ScheduleCleanup.d.ts.map +1 -1
  79. package/dist/scheduling/ScheduleCleanup.js +3 -0
  80. package/dist/scheduling/ScheduleCleanup.js.map +1 -1
  81. package/dist/scheduling/ScheduleCommand.d.ts +1 -3
  82. package/dist/scheduling/ScheduleCommand.d.ts.map +1 -1
  83. package/dist/scheduling/ScheduleCommand.js +10 -62
  84. package/dist/scheduling/ScheduleCommand.js.map +1 -1
  85. package/dist/scheduling/ScheduleDeliveryClient.d.ts +2 -1
  86. package/dist/scheduling/ScheduleDeliveryClient.d.ts.map +1 -1
  87. package/dist/scheduling/ScheduleDeliveryClient.js +20 -8
  88. package/dist/scheduling/ScheduleDeliveryClient.js.map +1 -1
  89. package/dist/scheduling/ScheduleService.d.ts +48 -4
  90. package/dist/scheduling/ScheduleService.d.ts.map +1 -1
  91. package/dist/scheduling/ScheduleService.js +582 -73
  92. package/dist/scheduling/ScheduleService.js.map +1 -1
  93. package/dist/scheduling/ScheduleToolScope.d.ts +4 -1
  94. package/dist/scheduling/ScheduleToolScope.d.ts.map +1 -1
  95. package/dist/scheduling/ScheduleToolScope.js +14 -13
  96. package/dist/scheduling/ScheduleToolScope.js.map +1 -1
  97. package/dist/scheduling/agy/AgyHookRelay.d.ts +3 -0
  98. package/dist/scheduling/agy/AgyHookRelay.d.ts.map +1 -1
  99. package/dist/scheduling/agy/AgyHookRelay.js +15 -1
  100. package/dist/scheduling/agy/AgyHookRelay.js.map +1 -1
  101. package/dist/scheduling/claude/ClaudeScheduleOwnership.d.ts +2 -0
  102. package/dist/scheduling/claude/ClaudeScheduleOwnership.d.ts.map +1 -1
  103. package/dist/scheduling/claude/ClaudeScheduleOwnership.js +11 -0
  104. package/dist/scheduling/claude/ClaudeScheduleOwnership.js.map +1 -1
  105. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts +3 -2
  106. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts.map +1 -1
  107. package/dist/scheduling/claude/ClaudeSessionSchedules.js +12 -4
  108. package/dist/scheduling/claude/ClaudeSessionSchedules.js.map +1 -1
  109. package/dist/scheduling/dsh/ScheduledSessionGuard.js +1 -1
  110. package/dist/scheduling/dsh/ScheduledSessionGuard.js.map +1 -1
  111. package/dist/scheduling/host/HostScheduleRule.d.ts +6 -0
  112. package/dist/scheduling/host/HostScheduleRule.d.ts.map +1 -0
  113. package/dist/scheduling/host/HostScheduleRule.js +144 -0
  114. package/dist/scheduling/host/HostScheduleRule.js.map +1 -0
  115. package/dist/scheduling/toolContract.d.ts +3 -3
  116. package/dist/scheduling/toolContract.js +4 -4
  117. package/dist/scheduling/toolContract.js.map +1 -1
  118. package/dist/scheduling/types.d.ts +20 -2
  119. package/dist/scheduling/types.d.ts.map +1 -1
  120. package/dist/scheduling/types.js.map +1 -1
  121. package/dist/types/ScheduleCards.d.ts +2 -1
  122. package/dist/types/ScheduleCards.d.ts.map +1 -1
  123. package/dist/types/index.d.ts +2 -0
  124. package/dist/types/index.d.ts.map +1 -1
  125. package/native/prebuilds/darwin-arm64/managed_native.node +0 -0
  126. package/native/prebuilds/darwin-arm64/manifest.json +1 -1
  127. package/native/prebuilds/darwin-x64/managed_native.node +0 -0
  128. package/native/prebuilds/darwin-x64/manifest.json +1 -1
  129. package/native/prebuilds/win32-arm64/managed_native.node +0 -0
  130. package/native/prebuilds/win32-arm64/manifest.json +1 -1
  131. package/native/prebuilds/win32-x64/managed_native.node +0 -0
  132. package/native/prebuilds/win32-x64/manifest.json +1 -1
  133. package/package.json +1 -1
@@ -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);
@@ -1035,6 +1041,40 @@ class MessageHandler {
1035
1041
  * Handle /abort command for a specific thread executor
1036
1042
  */
1037
1043
  async handleAbortCommand(messageId, threadId, executor) {
1044
+ const occurrence = this.hostOccurrences.get(threadId);
1045
+ if (occurrence) {
1046
+ const operation = this.activeThreadOperations.get(threadId);
1047
+ if (!operation || this.isDestroyed || occurrence.record.openId !== this.messageOpenIds.get(messageId)
1048
+ || !this.hostBindingCurrent(occurrence.record)) {
1049
+ this.sendResponse(messageId, threadId, { success: false, error: 'Scheduled occurrence ownership changed.' });
1050
+ return;
1051
+ }
1052
+ if (!occurrence.executor) {
1053
+ this.sendResponse(messageId, threadId, { success: true, output: 'The scheduled occurrence has not started executing.' });
1054
+ return;
1055
+ }
1056
+ if (executor !== occurrence.executor) {
1057
+ this.sendResponse(messageId, threadId, { success: false, error: 'Scheduled executor changed.' });
1058
+ return;
1059
+ }
1060
+ try {
1061
+ occurrence.abort ??= executor.abort().then(accepted => {
1062
+ if (executor.hasPendingCancellation?.() || executor.hasUncertainShutdown?.()) {
1063
+ throw new Error('Scheduled occurrence interruption is unconfirmed. Retry /abort.');
1064
+ }
1065
+ return accepted;
1066
+ });
1067
+ if (!await occurrence.abort)
1068
+ throw new Error('The executor did not confirm interruption of this occurrence.');
1069
+ await operation.done;
1070
+ this.sendResponse(messageId, threadId, { success: true, output: 'The scheduled occurrence was interrupted by /abort.' });
1071
+ }
1072
+ catch (error) {
1073
+ occurrence.abort = undefined;
1074
+ this.sendResponse(messageId, threadId, { success: false, error: error instanceof Error ? error.message : 'Failed to interrupt the scheduled occurrence.' });
1075
+ }
1076
+ return;
1077
+ }
1038
1078
  if (executor?.hasPendingSettingsChange?.()) {
1039
1079
  this.sendResponse(messageId, threadId, { success: false,
1040
1080
  error: 'Native settings change is pending or unconfirmed. Wait for its reply or retry the setting after a terminal error. /clear is destructive recovery and loses session-only schedules.' });
@@ -1198,11 +1238,39 @@ class MessageHandler {
1198
1238
  async clearThreadConversation(messageId, threadId) {
1199
1239
  if (this.abortOperations.has(threadId))
1200
1240
  throw new Error('Direct backend abort is still pending; retry /clear after it settles.');
1241
+ if (this.scheduleManagement.has(threadId))
1242
+ throw new Error('Schedule management is in progress. Retry the conversation reset after it settles.');
1243
+ this.scheduleManagement.add(threadId);
1244
+ try {
1245
+ await this.resetThreadConversation(messageId, threadId);
1246
+ }
1247
+ finally {
1248
+ this.scheduleManagement.delete(threadId);
1249
+ }
1250
+ }
1251
+ async resetThreadConversation(messageId, threadId) {
1201
1252
  const existing = this.threadPool.getExistingExecutor(threadId);
1202
1253
  const destructiveRecovery = existing?.hasPendingCancellation?.() === true || existing?.hasPendingSettingsChange?.() === true;
1254
+ const openId = this.messageOpenIds.get(messageId);
1255
+ const binding = this.scheduleBinding;
1256
+ const connectionEpoch = this.imageConnectionEpoch;
1203
1257
  await this.assertScheduleCleanupContext(threadId);
1204
- if (!destructiveRecovery)
1205
- await this.assertSchedulesIdle(threadId);
1258
+ const removed = await this.schedules?.clearHostContext(threadId, () => {
1259
+ // A previous clear committed schedule erasure before writing its pending reset marker.
1260
+ if (this.threadManager.contextResets.isPending(threadId))
1261
+ return undefined;
1262
+ if (!openId || !binding || connectionEpoch !== this.imageConnectionEpoch)
1263
+ throw new Error('Conversation reset requires the original schedule binding.');
1264
+ const owner = this.scheduleOwner(threadId, openId);
1265
+ this.requireHostBinding(owner, binding.epoch);
1266
+ return owner;
1267
+ }, destructiveRecovery);
1268
+ const scheduleNotice = removed ? `Removed ${removed} host ${removed === 1 ? 'schedule' : 'schedules'} and associated history. ` : '';
1269
+ if (removed) {
1270
+ this.scheduleOwners.delete(threadId);
1271
+ if (connectionEpoch !== this.imageConnectionEpoch)
1272
+ throw new Error(`${scheduleNotice}Device binding changed during conversation reset. Retry in the original thread.`);
1273
+ }
1206
1274
  this.conversationRevisions.set(threadId, (this.conversationRevisions.get(threadId) ?? 0) + 1);
1207
1275
  this.settingsService.invalidate(threadId);
1208
1276
  this.directoryBrowser.invalidate(threadId);
@@ -1246,11 +1314,11 @@ class MessageHandler {
1246
1314
  this.threadPool.setThreadBusy(threadId, false);
1247
1315
  await workers;
1248
1316
  this.sendResponse(messageId, threadId, { success: true,
1249
- output: `${destructiveRecovery ? 'Explicit reset stopped the Claude host; its session-only schedules were lost. ' : ''}Started a fresh conversation for direct backends and managed workers. Permanent deletion of old managed child native sessions is queued. Verified Codex, Kimi, Pi, and Claude child sessions are supported on Linux; unsupported versions, layouts, backends, platforms, and unconfirmed targets remain pending. Task artifacts and recovery evidence are retained. Pending native writers still block conflicting execution.` }, true);
1317
+ output: `${scheduleNotice}${destructiveRecovery ? 'Explicit reset stopped the Claude host; its session-only schedules were lost. ' : ''}Started a fresh conversation for direct backends and managed workers. Permanent deletion of old managed child native sessions is queued. Verified Codex, Kimi, Pi, and Claude child sessions are supported on Linux; unsupported versions, layouts, backends, platforms, and unconfirmed targets remain pending. Task artifacts and recovery evidence are retained. Pending native writers still block conflicting execution.` }, true);
1250
1318
  }
1251
1319
  catch (error) {
1252
1320
  const detail = error instanceof Error ? error.message : 'Local context storage is unavailable';
1253
- throw new Error(`Could not clear thread conversation: ${detail}. Check local CLI storage and retry /clear or /new.`);
1321
+ throw new Error(`${scheduleNotice}Could not clear thread conversation: ${detail}. Check local CLI storage and retry /clear or /new.`);
1254
1322
  }
1255
1323
  finally {
1256
1324
  if (active)
@@ -1462,7 +1530,7 @@ Use /compact to reduce conversation context or /clear to start a fresh context.`
1462
1530
  - /effort [auto|level] - Open effort settings, or set a native supported level with a text argument
1463
1531
  - /goal [objective|pause|resume|clear] - Manage a native Codex goal; optional --budget <tokens> on start or resume
1464
1532
  - /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
1533
+ - /schedule [capabilities|list|cancel <id>|after|at|cron] - Manage scheduled tasks; /schedule shows examples
1466
1534
  - /delegation [on|off|reset [backend]] - Delegate tasks between installed agent backends; reset saved worker context when needed
1467
1535
  - /backend - Open backend settings (Current thread by default; Confirm applies)
1468
1536
  - /backend <index> - Switch all threads and clear per-thread backend overrides
@@ -2570,7 +2638,7 @@ You can also use natural language commands to control Claude Code CLI.`,
2570
2638
  if (this.isDestroyed || this.abortOperations.has(threadId))
2571
2639
  throw new Error('Attachment task cancelled.');
2572
2640
  }
2573
- const openId = this.getMessageOpenId(messageId);
2641
+ const openId = this.messageOpenIds.get(messageId);
2574
2642
  const thread = this.threadManager.getThread(threadId);
2575
2643
  const outputGeneration = thread?.delegationWorkspaceGeneration ?? 0;
2576
2644
  if (goalRequest && thread && (0, DelegationSettings_1.isDelegationEnabled)(thread)) {
@@ -2644,7 +2712,7 @@ You can also use natural language commands to control Claude Code CLI.`,
2644
2712
  await executor.configureDelegation(undefined);
2645
2713
  }
2646
2714
  if (thread && openId && !goalRequest && executor.configureManagedTools) {
2647
- const owner = { threadId, openId, generation: this.scheduleGeneration(threadId) };
2715
+ const owner = this.scheduleOwner(threadId, openId);
2648
2716
  const epoch = this.imageConnectionEpoch;
2649
2717
  const backend = this.threadPool.getBackendKey(threadId);
2650
2718
  const config = structuredClone(this.executorConfiguration());
@@ -2656,8 +2724,8 @@ You can also use natural language commands to control Claude Code CLI.`,
2656
2724
  try {
2657
2725
  const latest = this.threadManager.getThread(threadId);
2658
2726
  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
2727
+ && epoch === this.imageConnectionEpoch && this.scheduleOwnerCurrent(owner)
2728
+ && this.threadPool.getBackendKey(threadId) === backend && this.threadPool.getExistingExecutor(threadId) === executor && !!latest
2661
2729
  && JSON.stringify({ config: this.executorConfiguration(), models: latest.models, model: latest.model, efforts: latest.efforts }) === settings;
2662
2730
  }
2663
2731
  catch {
@@ -2681,13 +2749,13 @@ You can also use natural language commands to control Claude Code CLI.`,
2681
2749
  await executor.configureManagedTools(connection);
2682
2750
  assertCurrent();
2683
2751
  }
2684
- scheduleScope = this.scheduleToolOperations.scope({ owner, messageId, backend, current: context.current,
2752
+ scheduleScope = this.scheduleToolOperations.scope({ owner, messageId, backend, bindingEpoch: this.scheduleBinding?.epoch, current: context.current,
2685
2753
  nativeAction: id => executor.nativeScheduleAction?.(id),
2686
2754
  deleteCleanup: (command, id) => this.runReviewedNativeCleanup(owner, command, id, context.current),
2687
2755
  listCleanup: async () => (await (await this.initializeSchedules()).listCleanup(owner)).map(ScheduleCleanup_1.cleanupSummary),
2688
2756
  purge: (selection, id) => this.runSchedulePurge(owner, selection, id, context.current),
2689
2757
  reviewCleanup: id => this.runReviewedNativeCleanup(owner, { kind: 'cleanup-review' }, id, context.current),
2690
- run: (command, id) => this.runScheduleOperation(owner, command, id, context),
2758
+ run: (command, id, allowNativeAction) => this.runScheduleOperation(owner, command, id, context, allowNativeAction),
2691
2759
  present: async (records, operationId) => {
2692
2760
  if (!context.current() || !this.scheduleToolCardsSupported)
2693
2761
  return 'Management card unavailable. Use /schedule list; do not recreate the task.';
@@ -3146,8 +3214,9 @@ You can also use natural language commands to control Claude Code CLI.`,
3146
3214
  }
3147
3215
  handleApprovalResponse(message) {
3148
3216
  const pending = this.pendingApprovalCards.get(message.messageId);
3217
+ const occurrence = this.hostOccurrences.get(message.threadId);
3149
3218
  if (!pending || pending.request.threadId !== message.threadId || pending.request.openId !== message.openId
3150
- || pending.request.taskMessageId !== message.taskMessageId) {
3219
+ || pending.request.taskMessageId !== message.taskMessageId || occurrence && !this.hostBindingCurrent(occurrence.record)) {
3151
3220
  this.sendApprovalMessage({ type: 'approval_resolved', messageId: message.messageId,
3152
3221
  openId: message.openId, threadId: message.threadId, status: 'expired', timestamp: Date.now() });
3153
3222
  return;
@@ -3400,6 +3469,41 @@ You can also use natural language commands to control Claude Code CLI.`,
3400
3469
  })).digest('hex');
3401
3470
  return path_1.default.join(directory, 'schedules', namespace);
3402
3471
  }
3472
+ scheduleOwner(threadId, openId) {
3473
+ return { threadId, openId, generation: this.scheduleGeneration(threadId),
3474
+ ...(this.scheduleBinding?.openId === openId && { bindingEpoch: this.scheduleBinding.epoch }) };
3475
+ }
3476
+ scheduleOwnerCurrent(owner) {
3477
+ const configuredOwner = this.config.get('openId');
3478
+ return (!configuredOwner || configuredOwner === owner.openId)
3479
+ && (!this.scheduleBinding || this.scheduleBinding.openId === owner.openId)
3480
+ && (!this.scheduleBinding || !owner.bindingEpoch || this.scheduleBinding.epoch === owner.bindingEpoch)
3481
+ && this.scheduleGeneration(owner.threadId) === owner.generation;
3482
+ }
3483
+ requireHostBinding(owner, expectedEpoch) {
3484
+ const binding = this.scheduleBinding;
3485
+ if (!this.wsClient.isConnected() || !binding)
3486
+ throw new Error('Host scheduling requires a connected Router with hostSchedulesV1 binding support. Upgrade or reconnect the Router.');
3487
+ if (binding.deviceId !== this.config.get('deviceId') || binding.openId !== owner.openId
3488
+ || !this.scheduleOwnerCurrent(owner) || expectedEpoch !== undefined && binding.epoch !== expectedEpoch) {
3489
+ throw new Error('Scheduled task no longer belongs to the current device binding and thread.');
3490
+ }
3491
+ return binding.epoch;
3492
+ }
3493
+ checkHostRecordBinding(record) {
3494
+ if (!record.bindingEpoch)
3495
+ throw new Error('Scheduled task has no original device binding receipt.');
3496
+ this.requireHostBinding(record, record.bindingEpoch);
3497
+ }
3498
+ hostBindingCurrent(record) {
3499
+ try {
3500
+ this.checkHostRecordBinding(record);
3501
+ return true;
3502
+ }
3503
+ catch {
3504
+ return false;
3505
+ }
3506
+ }
3403
3507
  /** Fence the updater before connection/version callbacks can race catalog loading. */
3404
3508
  async prepareScheduleStartup() {
3405
3509
  this.threadPool.setScheduleCatalog?.(() => {
@@ -3411,17 +3515,26 @@ You can also use natural language commands to control Claude Code CLI.`,
3411
3515
  return;
3412
3516
  this.scheduleCatalogPending = true;
3413
3517
  try {
3414
- await fs_1.default.promises.lstat(path_1.default.join(directory, ScheduleService_1.SCHEDULE_CATALOG_FILE));
3518
+ await this.loadScheduleCatalog();
3415
3519
  }
3416
- catch (error) {
3417
- if (['ENOENT', 'ENOTDIR'].includes(error.code ?? '')) {
3418
- this.scheduleCatalogPending = false;
3419
- return;
3520
+ catch {
3521
+ console.warn('[Schedules] Local schedule catalog is unavailable. Use /schedule list for details.');
3522
+ }
3523
+ }
3524
+ async hasScheduleCatalog(directory) {
3525
+ for (const file of [ScheduleService_1.SCHEDULE_CATALOG_FILE, ScheduleService_1.HOST_SCHEDULE_CATALOG_FILE]) {
3526
+ try {
3527
+ await fs_1.default.promises.lstat(path_1.default.join(directory, file));
3528
+ return true;
3529
+ }
3530
+ catch (error) {
3531
+ if (!['ENOENT', 'ENOTDIR'].includes(error.code ?? ''))
3532
+ throw error;
3420
3533
  }
3421
- throw error;
3422
3534
  }
3535
+ return false;
3423
3536
  }
3424
- /** Catalog loading waits for transport readiness and never creates an absent catalog. */
3537
+ /** Recover the local catalog before Router registration confirms the binding. */
3425
3538
  async loadScheduleCatalog() {
3426
3539
  if (this.isDestroyed)
3427
3540
  return;
@@ -3429,13 +3542,9 @@ You can also use natural language commands to control Claude Code CLI.`,
3429
3542
  const directory = this.scheduleDirectory();
3430
3543
  if (!directory)
3431
3544
  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;
3545
+ if (!await this.hasScheduleCatalog(directory) && !this.scheduleInitialization) {
3546
+ this.scheduleCatalogPending = false;
3547
+ return;
3439
3548
  }
3440
3549
  }
3441
3550
  // A disconnect or shutdown can happen while storage is being checked. Never
@@ -3461,9 +3570,12 @@ You can also use natural language commands to control Claude Code CLI.`,
3461
3570
  throw new Error('Local schedule storage is unavailable.');
3462
3571
  const service = new ScheduleService_1.ScheduleService({
3463
3572
  directory,
3573
+ hostDispatch: (record, occurrenceId, admit) => this.dispatchHostOccurrence(record, occurrenceId, admit),
3464
3574
  isNativeMutationPending: owner => this.threadPool.getExistingExecutor(owner.threadId)?.hasPendingScheduleMutation?.() ?? false,
3465
3575
  withPurgeVerification: (record, context, accept) => (0, SchedulePurgeVerification_1.verifySchedulePurge)(record, this.schedulePurgeHosts.get(record.threadId), context.isCurrent, accept),
3466
3576
  provider: { cleanupFor: input => {
3577
+ if (input.engine === 'host')
3578
+ return undefined;
3467
3579
  if (!input.threadId || this.threadPool.getBackendKey(input.threadId) !== input.backend)
3468
3580
  return undefined;
3469
3581
  return this.threadPool.getExecutor(input.threadId).nativeScheduleCleanup;
@@ -3472,6 +3584,8 @@ You can also use natural language commands to control Claude Code CLI.`,
3472
3584
  let executor;
3473
3585
  let generation;
3474
3586
  try {
3587
+ if (input.engine === 'host')
3588
+ throw new Error('Host schedules cannot create native timer definitions.');
3475
3589
  (0, ScheduleCapabilities_1.assertNativeScheduleBackend)(backend);
3476
3590
  if (!input.threadId)
3477
3591
  throw new Error('Native scheduling requires the original thread.');
@@ -3507,8 +3621,10 @@ You can also use natural language commands to control Claude Code CLI.`,
3507
3621
  } },
3508
3622
  isOwnerCurrent: owner => {
3509
3623
  // Shutdown blocks delivery separately; it does not invalidate persisted ownership.
3624
+ if (owner.bindingEpoch !== undefined && (!this.wsClient.isConnected() || !this.scheduleBinding))
3625
+ return undefined;
3510
3626
  try {
3511
- return this.scheduleGeneration(owner.threadId) === owner.generation;
3627
+ return this.scheduleOwnerCurrent(owner);
3512
3628
  }
3513
3629
  catch {
3514
3630
  return false;
@@ -3517,6 +3633,10 @@ You can also use natural language commands to control Claude Code CLI.`,
3517
3633
  deliver: async (delivery) => {
3518
3634
  if (!this.scheduleResultsSupported || this.isDestroyed)
3519
3635
  throw new Error('Scheduled result delivery is unavailable.');
3636
+ if (delivery.schedule.engine === 'host')
3637
+ this.checkHostRecordBinding(delivery.schedule);
3638
+ else if (!this.scheduleOwnerCurrent(delivery.schedule))
3639
+ throw new Error('Scheduled result owner changed.');
3520
3640
  const thread = this.threadManager.getThread(delivery.schedule.threadId);
3521
3641
  if (!thread)
3522
3642
  throw new Error('The original thread no longer exists.');
@@ -3525,12 +3645,138 @@ You can also use natural language commands to control Claude Code CLI.`,
3525
3645
  });
3526
3646
  await service.initialize();
3527
3647
  if (!this.isDestroyed)
3528
- this.scheduleDelivery = new ScheduleDeliveryClient_1.ScheduleDeliveryClient(this.wsClient);
3648
+ this.scheduleDelivery = new ScheduleDeliveryClient_1.ScheduleDeliveryClient(this.wsClient, record => record.engine === 'host' ? this.hostBindingCurrent(record) : this.scheduleOwnerCurrent(record));
3529
3649
  this.schedules = service;
3530
3650
  return service;
3531
3651
  })();
3532
3652
  return this.scheduleInitialization;
3533
3653
  }
3654
+ async dispatchHostOccurrence(record, occurrenceId, admit) {
3655
+ const { threadId, openId, sessionId, cwd } = record;
3656
+ if (!this.scheduleBinding || !this.wsClient.isConnected())
3657
+ return undefined;
3658
+ if (this.settingsBusy(threadId) || this.settingsAdmission.isBlocked(threadId)
3659
+ || this.scheduleManagement.has(threadId) || this.activeThreadOperations.has(threadId)
3660
+ || this.pendingGoalActivations.has(threadId))
3661
+ return undefined;
3662
+ const messageId = `${record.id}:${occurrenceId}`;
3663
+ return this.settingsAdmission.command(threadId, messageId, async () => {
3664
+ const token = this.beginThreadOperation(threadId);
3665
+ const occurrence = { record, cancelled: false };
3666
+ this.hostOccurrences.set(threadId, occurrence);
3667
+ this.messageOpenIds.set(messageId, openId);
3668
+ try {
3669
+ const checkOwner = (allowDisconnectedResult = false) => {
3670
+ // A completed response can enter its original owner's outbox while offline.
3671
+ // Admission, approvals and transport still require a confirmed live binding.
3672
+ if (!allowDisconnectedResult || this.scheduleBinding)
3673
+ this.checkHostRecordBinding(record);
3674
+ else if (!this.scheduleOwnerCurrent(record))
3675
+ throw new Error('Scheduled result owner changed.');
3676
+ if (this.isDestroyed || this.cancelledOperations.has(token) || this.activeThreadOperations.get(threadId)?.token !== token
3677
+ || !openId || record.engine !== 'host' || this.threadPool.getBackendKey(threadId) !== record.backend
3678
+ || this.directoryGuard.resolveWorkingDirectory(this.threadManager.getThread(threadId).workingDirectory) !== cwd) {
3679
+ throw new Error('Scheduled occurrence lost its original conversation or owner.');
3680
+ }
3681
+ };
3682
+ checkOwner();
3683
+ if (!sessionId)
3684
+ throw new Error('Scheduled task has no native conversation identity.');
3685
+ const executor = this.threadPool.getExecutor(threadId);
3686
+ if (executor.hasPendingCancellation?.() || executor.hasPendingScheduleMutation?.()
3687
+ || executor.hasPendingSettingsChange?.() || executor.isGoalRunning?.() || executor.isBusy?.())
3688
+ return undefined;
3689
+ const check = (allowDisconnectedResult = false) => {
3690
+ checkOwner(allowDisconnectedResult);
3691
+ if (this.threadPool.getExistingExecutor(threadId) !== executor)
3692
+ throw new Error('Scheduled executor changed.');
3693
+ this.checkHostSession(executor, sessionId, cwd);
3694
+ };
3695
+ check();
3696
+ (0, WorkingDirectory_1.assertWorkingDirectoryExists)(cwd);
3697
+ if (this.delegation.blocksWorkspace(cwd, threadId))
3698
+ return undefined;
3699
+ await this.delegation.assertExecutionSafe(cwd, threadId);
3700
+ check();
3701
+ if (occurrence.cancelled || !await admit())
3702
+ return undefined;
3703
+ const beforePrompt = () => {
3704
+ check();
3705
+ if (occurrence.cancelled)
3706
+ throw new Error('Scheduled occurrence was cancelled before prompt dispatch.');
3707
+ };
3708
+ beforePrompt();
3709
+ let display = '';
3710
+ occurrence.executor = executor;
3711
+ const result = await executor.execute(record.prompt, {
3712
+ hostScheduleSessionId: sessionId,
3713
+ // Claude checks queued authorization before process startup and again before stdin.
3714
+ ...(record.backend === 'claude' && { nativeScheduleCurrent: () => {
3715
+ try {
3716
+ beforePrompt();
3717
+ return true;
3718
+ }
3719
+ catch {
3720
+ return false;
3721
+ }
3722
+ } }),
3723
+ resolvePrompt: actual => {
3724
+ beforePrompt();
3725
+ if (actual !== sessionId)
3726
+ throw new Error('Scheduled task could not resume its original native session.');
3727
+ return record.prompt;
3728
+ },
3729
+ onDisplayText: chunk => { if (display.length < 65537)
3730
+ display += chunk.slice(0, 65537 - display.length); },
3731
+ onApprovalRequest: approval => {
3732
+ try {
3733
+ check();
3734
+ }
3735
+ catch {
3736
+ return false;
3737
+ }
3738
+ return this.forwardApproval(approval, executor, messageId, threadId);
3739
+ },
3740
+ onApprovalResolved: (id, status) => this.resolveApprovalCard(id, status),
3741
+ onStream: chunk => {
3742
+ if (!executor.isWaitingInput?.())
3743
+ return;
3744
+ try {
3745
+ check();
3746
+ }
3747
+ catch {
3748
+ return;
3749
+ }
3750
+ this.sendStreamChunk(messageId, threadId, chunk);
3751
+ },
3752
+ }).catch((error) => ({ success: false, output: undefined,
3753
+ error: error instanceof Error ? error.message : 'Scheduled execution failed.' }));
3754
+ const aborted = occurrence.abort && await occurrence.abort;
3755
+ check(true);
3756
+ if (aborted)
3757
+ return { success: false, abortedByUser: true, output: display || result.output,
3758
+ error: 'Scheduled occurrence interrupted by /abort.' };
3759
+ // Prefer the public display stream, but preserve the executor's final
3760
+ // output when a backend only returns its answer at turn completion.
3761
+ return { success: result.success, output: display || result.output, error: result.error };
3762
+ }
3763
+ catch (error) {
3764
+ return { success: false, error: error instanceof Error ? error.message : 'Scheduled execution failed.' };
3765
+ }
3766
+ finally {
3767
+ for (const [id, pending] of this.pendingApprovalCards) {
3768
+ if (pending.request.taskMessageId === messageId)
3769
+ this.resolveApprovalCard(id, 'expired');
3770
+ }
3771
+ this.messageOpenIds.delete(messageId);
3772
+ if (this.hostOccurrences.get(threadId) === occurrence)
3773
+ this.hostOccurrences.delete(threadId);
3774
+ this.cancelledOperations.delete(token);
3775
+ if (this.finishThreadOperation(threadId, token) && !this.isDestroyed)
3776
+ void this.startNextQueuedCommand(threadId);
3777
+ }
3778
+ }, true);
3779
+ }
3534
3780
  async activeSchedules(threadId) {
3535
3781
  const owner = this.scheduleOwners.get(threadId);
3536
3782
  if (!owner || !this.schedules)
@@ -3546,14 +3792,8 @@ You can also use natural language commands to control Claude Code CLI.`,
3546
3792
  const directory = this.scheduleDirectory();
3547
3793
  if (!directory)
3548
3794
  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
- }
3795
+ if (!await this.hasScheduleCatalog(directory))
3796
+ return;
3557
3797
  await this.initializeSchedules();
3558
3798
  }
3559
3799
  if (this.schedules?.hasCleanupContext(threadId)) {
@@ -3593,133 +3833,111 @@ You can also use natural language commands to control Claude Code CLI.`,
3593
3833
  resolve('Management card unavailable. Use /schedule list; do not recreate the task.');
3594
3834
  });
3595
3835
  }
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) {
3836
+ /** Slash commands, management cards and in-turn tools share record-specific admission. */
3837
+ async runScheduleOperation(owner, command, id = (0, uuid_1.v4)(), context, allowNativeAction) {
3838
+ const { threadId } = owner;
3839
+ const epoch = this.imageConnectionEpoch;
3840
+ const backend = context?.backend ?? this.threadPool.getBackendKey(threadId);
3598
3841
  const current = () => {
3599
3842
  try {
3600
- return !this.isDestroyed && this.scheduleGeneration(owner.threadId) === owner.generation && (!context || context.current());
3843
+ return !this.isDestroyed && !this.automaticUpdateInProgress && epoch === this.imageConnectionEpoch
3844
+ && this.scheduleOwnerCurrent(owner) && this.threadPool.getBackendKey(threadId) === backend
3845
+ && (!context || context.current());
3601
3846
  }
3602
3847
  catch {
3603
3848
  return false;
3604
3849
  }
3605
3850
  };
3606
- const check = () => { if (!current() || this.automaticUpdateInProgress)
3851
+ const check = () => { if (!current())
3607
3852
  throw new Error('Scheduling context changed or client is shutting down/updating.'); };
3608
3853
  check();
3609
- if (command.kind === 'list' && this.threadPool.getExistingExecutor(owner.threadId)?.hasPendingCancellation?.()) {
3854
+ if (command.kind === 'list') {
3610
3855
  const service = await this.initializeSchedules();
3856
+ const records = await service.list(owner);
3611
3857
  check();
3612
- return service.list(owner); // Catalog-only recovery visibility; never acquire native management admission.
3858
+ return records;
3613
3859
  }
3614
- if (!nativeBound && this.scheduleManagement.has(owner.threadId))
3860
+ if (this.scheduleManagement.has(threadId))
3615
3861
  throw new Error('A schedule operation is already in progress for this thread.');
3616
- this.scheduleManagement.add(owner.threadId);
3862
+ this.scheduleManagement.add(threadId);
3617
3863
  try {
3618
- const backend = context?.backend ?? this.threadPool.getBackendKey(owner.threadId);
3619
- const config = context?.config ?? this.executorConfiguration();
3864
+ let captured;
3620
3865
  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
- }
3866
+ (0, ScheduleCapabilities_1.assertHostScheduleBackend)(backend);
3867
+ const bindingEpoch = this.requireHostBinding(owner);
3868
+ const executor = this.threadPool.getExecutor(threadId);
3869
+ const cwd = this.directoryGuard.resolveWorkingDirectory(context?.cwd ?? this.threadManager.getThread(threadId).workingDirectory);
3870
+ const sessionId = executor.getSessionId?.();
3871
+ if (!sessionId)
3872
+ throw new Error('Send an ordinary message in this thread to establish its native conversation, then retry scheduling.');
3873
+ (0, WorkingDirectory_1.assertWorkingDirectoryExists)(cwd);
3874
+ this.checkHostSession(executor, sessionId, cwd);
3875
+ captured = { executor, sessionId, cwd, bindingEpoch };
3627
3876
  }
3628
- const nativeCancellation = !nativeBound && (backend === 'claude' || backend === 'agy') && command.kind === 'cancel'
3629
- && (await this.initializeSchedules()).canCancel(owner, command.id);
3877
+ const service = await this.initializeSchedules();
3878
+ const records = await service.list(owner);
3630
3879
  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);
3880
+ if (command.kind === 'cancel') {
3881
+ const manage = async () => {
3882
+ check();
3883
+ const occurrence = this.hostOccurrences.get(threadId);
3884
+ if (occurrence?.record.id === command.id && occurrence.record.openId === owner.openId
3885
+ && occurrence.record.generation === owner.generation)
3886
+ occurrence.cancelled = true;
3887
+ return [await service.cancel(owner, command.id)];
3888
+ };
3889
+ const native = (backend === 'claude' || backend === 'agy') && records.some(record => record.engine !== 'host' && record.backend === backend && record.id === command.id && service.canCancel(owner, record.id));
3890
+ if (!native)
3891
+ return await manage();
3892
+ const executor = this.threadPool.getExecutor(threadId);
3634
3893
  if (!executor.withNativeScheduleOperation)
3635
3894
  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;
3895
+ allowNativeAction?.();
3896
+ return await executor.withNativeScheduleOperation(id, current, manage, !!context);
3672
3897
  }
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))
3898
+ (0, ScheduleCapabilities_1.assertHostScheduleBackend)(backend);
3899
+ if (records.some(record => record.id === id))
3686
3900
  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)
3901
+ const existingOwner = this.scheduleOwners.get(threadId);
3902
+ if (existingOwner && existingOwner.openId !== owner.openId && (await this.activeSchedules(threadId)).length)
3693
3903
  throw new Error('This thread has schedules belonging to a different owner.');
3694
3904
  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,
3905
+ const thread = this.threadManager.getThread(threadId);
3906
+ const { executor, sessionId, cwd, bindingEpoch } = captured;
3907
+ this.requireHostBinding(owner, bindingEpoch);
3908
+ if (this.threadPool.getExistingExecutor(threadId) !== executor)
3909
+ throw new Error('Scheduling executor changed.');
3910
+ this.checkHostSession(executor, sessionId, cwd);
3911
+ this.scheduleOwners.set(threadId, owner);
3912
+ const config = context?.config ?? this.executorConfiguration();
3913
+ const input = { id, threadId, backend, cwd, engine: 'host', sessionId, bindingEpoch,
3914
+ rule: command.rule, prompt: command.prompt, command: config[backend]?.command,
3709
3915
  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) {
3916
+ effort: context ? context.effort : thread.efforts?.[backend] };
3917
+ const record = await service.create(owner, input);
3918
+ try {
3919
+ check();
3920
+ this.checkHostRecordBinding(record);
3921
+ if (this.threadPool.getExistingExecutor(threadId) !== executor)
3922
+ throw new Error('Scheduling executor changed.');
3923
+ this.checkHostSession(executor, sessionId, cwd);
3924
+ }
3925
+ catch (error) {
3712
3926
  await service.cancel(owner, record.id);
3713
- throw new Error('Scheduling context retired during creation; the native task was cancelled.');
3927
+ throw error;
3714
3928
  }
3715
3929
  return [record];
3716
3930
  }
3717
3931
  finally {
3718
- if (!nativeBound) {
3719
- this.scheduleManagement.delete(owner.threadId);
3720
- await this.activeSchedules(owner.threadId).catch(() => undefined);
3721
- }
3932
+ this.scheduleManagement.delete(threadId);
3933
+ await this.activeSchedules(threadId).catch(() => undefined);
3934
+ }
3935
+ }
3936
+ checkHostSession(executor, sessionId, cwd) {
3937
+ if (!sessionId || executor.getSessionId?.() !== sessionId || executor.getCurrentWorkingDirectory() !== cwd) {
3938
+ throw new Error('Scheduled task requires the original native session and working directory.');
3722
3939
  }
3940
+ executor.checkHostScheduleSession?.(sessionId);
3723
3941
  }
3724
3942
  /** Purge shares native operation admission with cancellation; only the service
3725
3943
  * decides whether verified retirement permits history removal. */
@@ -3733,7 +3951,7 @@ You can also use natural language commands to control Claude Code CLI.`,
3733
3951
  const current = () => {
3734
3952
  try {
3735
3953
  return !this.isDestroyed && !this.automaticUpdateInProgress && this.wsClient.isConnected()
3736
- && epoch === this.imageConnectionEpoch && this.scheduleGeneration(owner.threadId) === owner.generation && !this.abortOperations.has(owner.threadId)
3954
+ && epoch === this.imageConnectionEpoch && this.scheduleOwnerCurrent(owner) && !this.abortOperations.has(owner.threadId)
3737
3955
  && this.threadPool.getBackendKey(owner.threadId) === backend
3738
3956
  && this.threadPool.getExistingExecutor(owner.threadId) === executor
3739
3957
  && capturedSettings === settings() && (!inTurnCurrent || inTurnCurrent());
@@ -3768,9 +3986,9 @@ You can also use natural language commands to control Claude Code CLI.`,
3768
3986
  return await run();
3769
3987
  const records = await service.list(owner);
3770
3988
  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)));
3989
+ && record.engine !== 'host' && record.backend === 'claude' && !!record.recovery && !!record.nativeId && !record.cleanupConfirmed && !record.creationRefused && !['active', 'running', 'creating'].includes(record.state)));
3772
3990
  const needsNative = needsVerification || ['claude', 'agy'].includes(backend) && records.some(record => ids.includes(record.id)
3773
- && record.backend === backend && (service.canCancel(owner, record.id)
3991
+ && record.engine !== 'host' && record.backend === backend && (service.canCancel(owner, record.id)
3774
3992
  || backend === 'agy' && service.needsNativePurge(owner, record.id)));
3775
3993
  if (!needsNative)
3776
3994
  return await run();
@@ -3820,7 +4038,7 @@ You can also use natural language commands to control Claude Code CLI.`,
3820
4038
  try {
3821
4039
  return !this.isDestroyed && !this.automaticUpdateInProgress
3822
4040
  && !this.abortOperations.has(threadId) && this.wsClient.isConnected() && epoch === this.imageConnectionEpoch
3823
- && this.scheduleGeneration(threadId) === owner.generation && this.threadPool.getExistingExecutor(threadId) === executor
4041
+ && this.scheduleOwnerCurrent(owner) && this.threadPool.getExistingExecutor(threadId) === executor
3824
4042
  && this.threadPool.getBackendKey(threadId) === 'claude' && config === settings() && (!inTurnCurrent || inTurnCurrent());
3825
4043
  }
3826
4044
  catch {
@@ -3911,7 +4129,9 @@ You can also use natural language commands to control Claude Code CLI.`,
3911
4129
  if (message.attachments?.length || message.fileIds?.length || message.workingDirectory) {
3912
4130
  throw new Error('Use /cd first and include a self-contained text prompt. Schedule commands do not accept attachments or directory overrides.');
3913
4131
  }
3914
- const owner = { threadId, openId: message.openId, generation: this.scheduleGeneration(threadId) };
4132
+ const owner = this.scheduleOwner(threadId, message.openId);
4133
+ if (!this.scheduleOwnerCurrent(owner))
4134
+ throw new Error('Scheduled task owner does not match this device binding.');
3915
4135
  if (command.kind === 'cleanup-review' || command.kind === 'cleanup-confirm') {
3916
4136
  const result = await this.runReviewedNativeCleanup(owner, command, (0, crypto_1.createHash)('sha256').update(message.messageId ?? (0, uuid_1.v4)()).digest('hex'));
3917
4137
  let output;
@@ -3954,8 +4174,7 @@ You can also use natural language commands to control Claude Code CLI.`,
3954
4174
  else if (command.kind === 'cancel')
3955
4175
  output = `Schedule ${record.id}: ${record.state}.`;
3956
4176
  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}.`;
4177
+ 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
4178
  }
3960
4179
  if (command.kind === 'list') {
3961
4180
  const cleanup = await this.schedules?.listCleanup(owner) ?? [];
@@ -4290,6 +4509,7 @@ You can also use natural language commands to control Claude Code CLI.`,
4290
4509
  */
4291
4510
  async destroy() {
4292
4511
  this.isDestroyed = true;
4512
+ const scheduledTurns = [...this.hostOccurrences.keys()].map(id => this.activeThreadOperations.get(id)?.done);
4293
4513
  this.directoryBrowser.destroy();
4294
4514
  this.settingsService.destroy();
4295
4515
  this.scheduleCards.destroy();
@@ -4313,6 +4533,7 @@ You can also use natural language commands to control Claude Code CLI.`,
4313
4533
  this.delegation.destroy(),
4314
4534
  ...[...this.delegationBridges.values()].map(bridge => bridge.close()),
4315
4535
  this.threadPool.destroyAll({ deleteData: false, shutdown: true }),
4536
+ ...scheduledTurns,
4316
4537
  ]);
4317
4538
  const failure = results.find((result) => result.status === 'rejected');
4318
4539
  if (failure)