@yu_robotics/remote-cli 1.6.237 → 1.6.239

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 (75) hide show
  1. package/dist/client/MessageHandler.d.ts +9 -2
  2. package/dist/client/MessageHandler.d.ts.map +1 -1
  3. package/dist/client/MessageHandler.js +202 -21
  4. package/dist/client/MessageHandler.js.map +1 -1
  5. package/dist/commands/start.d.ts.map +1 -1
  6. package/dist/commands/start.js +5 -1
  7. package/dist/commands/start.js.map +1 -1
  8. package/dist/executor/AcpExecutor.d.ts +2 -0
  9. package/dist/executor/AcpExecutor.d.ts.map +1 -1
  10. package/dist/executor/AcpExecutor.js +9 -0
  11. package/dist/executor/AcpExecutor.js.map +1 -1
  12. package/dist/executor/ClaudePersistentExecutor.d.ts +20 -7
  13. package/dist/executor/ClaudePersistentExecutor.d.ts.map +1 -1
  14. package/dist/executor/ClaudePersistentExecutor.js +393 -58
  15. package/dist/executor/ClaudePersistentExecutor.js.map +1 -1
  16. package/dist/executor/DshExecutor.d.ts +13 -1
  17. package/dist/executor/DshExecutor.d.ts.map +1 -1
  18. package/dist/executor/DshExecutor.js +39 -1
  19. package/dist/executor/DshExecutor.js.map +1 -1
  20. package/dist/executor/IExecutor.d.ts +6 -0
  21. package/dist/executor/IExecutor.d.ts.map +1 -1
  22. package/dist/executor/claude/TurnLedger.js +1 -1
  23. package/dist/executor/claude/TurnLedger.js.map +1 -1
  24. package/dist/maintenance/release-notes.json +1 -1
  25. package/dist/scheduling/ScheduleCapabilities.d.ts +1 -1
  26. package/dist/scheduling/ScheduleCapabilities.d.ts.map +1 -1
  27. package/dist/scheduling/ScheduleCapabilities.js +3 -2
  28. package/dist/scheduling/ScheduleCapabilities.js.map +1 -1
  29. package/dist/scheduling/ScheduleService.d.ts +27 -0
  30. package/dist/scheduling/ScheduleService.d.ts.map +1 -1
  31. package/dist/scheduling/ScheduleService.js +564 -17
  32. package/dist/scheduling/ScheduleService.js.map +1 -1
  33. package/dist/scheduling/claude/ClaudeScheduleOwnership.d.ts +27 -0
  34. package/dist/scheduling/claude/ClaudeScheduleOwnership.d.ts.map +1 -0
  35. package/dist/scheduling/claude/ClaudeScheduleOwnership.js +122 -0
  36. package/dist/scheduling/claude/ClaudeScheduleOwnership.js.map +1 -0
  37. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts +30 -2
  38. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts.map +1 -1
  39. package/dist/scheduling/claude/ClaudeSessionSchedules.js +170 -20
  40. package/dist/scheduling/claude/ClaudeSessionSchedules.js.map +1 -1
  41. package/dist/scheduling/dsh/SessionScheduleBridge.d.ts.map +1 -1
  42. package/dist/scheduling/dsh/SessionScheduleBridge.js +21 -0
  43. package/dist/scheduling/dsh/SessionScheduleBridge.js.map +1 -1
  44. package/dist/scheduling/dsh/SessionScheduleClient.d.ts.map +1 -1
  45. package/dist/scheduling/dsh/SessionScheduleClient.js +8 -0
  46. package/dist/scheduling/dsh/SessionScheduleClient.js.map +1 -1
  47. package/dist/scheduling/types.d.ts +90 -0
  48. package/dist/scheduling/types.d.ts.map +1 -1
  49. package/dist/scheduling/types.js +5 -1
  50. package/dist/scheduling/types.js.map +1 -1
  51. package/dist/service/ServiceManager.d.ts +5 -0
  52. package/dist/service/ServiceManager.d.ts.map +1 -1
  53. package/dist/service/ServiceManager.js +86 -9
  54. package/dist/service/ServiceManager.js.map +1 -1
  55. package/dist/settings/SettingsService.d.ts +1 -1
  56. package/dist/settings/SettingsService.d.ts.map +1 -1
  57. package/dist/settings/SettingsService.js +3 -3
  58. package/dist/settings/SettingsService.js.map +1 -1
  59. package/dist/thread/ThreadExecutorPool.d.ts +1 -1
  60. package/dist/thread/ThreadExecutorPool.d.ts.map +1 -1
  61. package/dist/thread/ThreadExecutorPool.js +5 -3
  62. package/dist/thread/ThreadExecutorPool.js.map +1 -1
  63. package/dist/update/AutomaticUpdater.d.ts +2 -1
  64. package/dist/update/AutomaticUpdater.d.ts.map +1 -1
  65. package/dist/update/AutomaticUpdater.js +11 -3
  66. package/dist/update/AutomaticUpdater.js.map +1 -1
  67. package/native/prebuilds/darwin-arm64/managed_native.node +0 -0
  68. package/native/prebuilds/darwin-arm64/manifest.json +1 -1
  69. package/native/prebuilds/darwin-x64/managed_native.node +0 -0
  70. package/native/prebuilds/darwin-x64/manifest.json +1 -1
  71. package/native/prebuilds/win32-arm64/managed_native.node +0 -0
  72. package/native/prebuilds/win32-arm64/manifest.json +1 -1
  73. package/native/prebuilds/win32-x64/managed_native.node +0 -0
  74. package/native/prebuilds/win32-x64/manifest.json +1 -1
  75. package/package.json +1 -1
@@ -4,8 +4,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.ClaudePersistentExecutor = void 0;
7
+ const ClaudeScheduleOwnership_1 = require("../scheduling/claude/ClaudeScheduleOwnership");
7
8
  const ClaudeSessionSchedules_1 = require("../scheduling/claude/ClaudeSessionSchedules");
8
9
  const TurnLedger_1 = require("./claude/TurnLedger");
10
+ const types_1 = require("../scheduling/types");
9
11
  const tools_1 = require("../managed/tools");
10
12
  const ManagedSpawn_1 = require("./ManagedSpawn");
11
13
  const OwnershipRuntime_1 = require("../delegation/OwnershipRuntime");
@@ -62,6 +64,14 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
62
64
  model;
63
65
  effort;
64
66
  reportedModel;
67
+ /** Native session selection, not a claim about the model serving an in-flight response. */
68
+ acknowledgedModel;
69
+ modelSelectionForeground;
70
+ modelChange;
71
+ hasPendingSettingsChange() { return !!this.modelChange; }
72
+ canRetrySettingsChange(setting) {
73
+ return setting === 'model' && this.modelChange?.retryable === true && !this.isWorkBusy() && !this.sessionSchedules?.hasPendingMutation;
74
+ }
65
75
  // Native control catalog cache & control request state
66
76
  cachedModelCatalog = null;
67
77
  cachedRawEntries = null;
@@ -285,7 +295,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
285
295
  getExecutionMetadata() {
286
296
  let effectiveEffort = this.effort;
287
297
  if (this.effort && this.cachedRawEntries) {
288
- const activeModel = this.reportedModel || this.model;
298
+ const activeModel = this.reportedModel || this.acknowledgedModel || this.model;
289
299
  const entry = activeModel
290
300
  ? this.cachedRawEntries.find(e => e.value === activeModel || (e.resolvedModel !== undefined && e.resolvedModel === activeModel))
291
301
  : this.cachedRawEntries.find(e => e.value === 'default');
@@ -297,12 +307,201 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
297
307
  if (!effectiveEffort) {
298
308
  data.effortSource = 'unknown';
299
309
  }
300
- if (this.isProcessRunning() && this.reportedModel) {
301
- data.model = this.reportedModel;
310
+ if (this.isProcessRunning() && (this.acknowledgedModel || this.reportedModel)) {
311
+ data.model = this.reportedModel || this.acknowledgedModel;
302
312
  data.modelSource = 'reported';
303
313
  }
314
+ if (this.modelChange) {
315
+ data.model = undefined;
316
+ data.modelSource = 'unknown';
317
+ }
304
318
  return data;
305
319
  }
320
+ scheduleRestart;
321
+ scheduleRestoring;
322
+ scheduleOwnership;
323
+ scheduleOwnershipSession;
324
+ scheduleHostOwnership() {
325
+ if (!this.sessionId)
326
+ throw new Error('Native schedule session identity is unavailable.');
327
+ if (this.scheduleOwnershipSession !== this.sessionId) {
328
+ this.scheduleOwnership?.close();
329
+ this.scheduleOwnership = new ClaudeScheduleOwnership_1.ClaudeScheduleOwnership(this.sessionFilePath, this.sessionId);
330
+ this.scheduleOwnershipSession = this.sessionId;
331
+ }
332
+ return this.scheduleOwnership;
333
+ }
334
+ get nativeScheduleRecovery() {
335
+ // Advertise the adapter before cold startup; native operations still require
336
+ // the current host's tools, hooks, lifecycle evidence and confirmed receipts.
337
+ if (this.delegationWorker || this.sandbox.isRestricted())
338
+ return undefined;
339
+ return {
340
+ provider: 'claude-session-skip-unadmitted-v1', strategy: 'reconstruct', orderlyOnly: true, futureOnly: true,
341
+ handoffPolicy: 'skip-unadmitted',
342
+ describe: input => JSON.stringify({ marker: (0, crypto_1.randomUUID)(), sessionId: this.sessionId,
343
+ cwd: input.cwd, threadId: this.threadId, model: this.model, effort: this.effort,
344
+ effectiveModel: this.acknowledgedModel || this.reportedModel || this.model }),
345
+ finishRestart: () => this.finishScheduleRestart(),
346
+ releaseRestartAdmission: () => {
347
+ const state = this.scheduleRestart;
348
+ if (state?.exit?.code === 0 && !state.exit.signal && state.endRequested
349
+ && state.epoch === this.stopEpoch && !this.claudeProcess)
350
+ this.scheduleRestart = undefined;
351
+ },
352
+ reconcile: async (record, context, emit) => {
353
+ const identity = JSON.parse(record.recovery.identity);
354
+ const clean = record.recovery?.handoff === 'clean' && record.recovery.nativeDefinitionAbsent;
355
+ if ((!clean && (!record.recovery?.futureOnly || record.rule.kind !== 'cron'))
356
+ || record.recovery?.handoffPolicy !== 'skip-unadmitted' || !context.isCurrent()
357
+ || context.signal.aborted || !identity.sessionId || identity.sessionId !== this.sessionId
358
+ || identity.cwd !== this.currentWorkingDirectory || identity.threadId !== this.threadId
359
+ || identity.model !== this.model || identity.effort !== this.effort) {
360
+ throw new Error('Original Claude context or recovery evidence changed.');
361
+ }
362
+ if (this.scheduleRestart && !this.scheduleRestart.exit)
363
+ throw new Error('Claude predecessor exit is unconfirmed.');
364
+ this.scheduleRestart = undefined;
365
+ const ownership = this.scheduleHostOwnership();
366
+ ownership.reserve(!!clean);
367
+ if (!clean)
368
+ ownership.assertRebootRecovery();
369
+ const restoration = {};
370
+ this.scheduleRestoring = restoration;
371
+ const epoch = this.stopEpoch;
372
+ const current = () => this.scheduleRestoring === restoration && this.stopEpoch === epoch
373
+ && !this.isDestroyed && context.isCurrent() && !context.signal.aborted && this.sessionId === identity.sessionId;
374
+ const input = { id: record.id, threadId: record.threadId, backend: 'claude',
375
+ cwd: record.cwd, prompt: record.prompt, rule: record.rule, ...record.execution, recovery: record.recovery };
376
+ let handle;
377
+ try {
378
+ await this.listModels();
379
+ if (!current())
380
+ throw new Error('Claude recovery owner changed.');
381
+ if (!this.claudeProcess?.pid || this.turnLedger.invalid || this.turnLedger.pid !== this.claudeProcess.pid
382
+ || this.turnLedger.session && !this.turnLedger.supported(this.claudeProcess.pid)
383
+ || typeof identity.effectiveModel !== 'string' || !identity.effectiveModel)
384
+ throw new Error('Original Claude model or supported host is unavailable.');
385
+ const child = this.claudeProcess;
386
+ if (this.model !== identity.effectiveModel) {
387
+ const response = await this.nativeControl('set_model', { model: identity.effectiveModel });
388
+ if (!current() || this.claudeProcess !== child)
389
+ throw new Error('Claude recovery model owner changed.');
390
+ if (!response || typeof response !== 'object' || response.model !== identity.effectiveModel) {
391
+ throw new Error('Claude recovery model selection is unconfirmed.');
392
+ }
393
+ this.recordModelSelection(identity.effectiveModel);
394
+ }
395
+ const adapter = this.schedules();
396
+ const timezone = await this.readNativeScheduleTimezone();
397
+ if (!current() || this.claudeProcess !== child)
398
+ throw new Error('Claude recovery host changed.');
399
+ handle = await adapter.inToolOperation(`restore-${record.id}`, current, () => adapter.create(input, emit, context.isOwnerCurrent ?? context.isCurrent, timezone, clean ? 'adopt' : 'adopt-existing', record.nativeId), false);
400
+ if (!current() || this.claudeProcess !== child || !this.turnLedger.supported(child?.pid))
401
+ throw new types_1.NativeScheduleCleanupError('Claude recovery host or protocol changed.', handle);
402
+ const recovered = this.recoverableScheduleHandle(handle, input, restoration);
403
+ this.scheduleRestoring = undefined;
404
+ return recovered;
405
+ }
406
+ catch (error) {
407
+ if (error instanceof types_1.NativeScheduleAbsentError && this.scheduleRestoring === restoration)
408
+ this.scheduleRestoring = undefined;
409
+ const cleanup = error instanceof types_1.NativeScheduleCleanupError ? error.handle : handle;
410
+ if (cleanup)
411
+ throw new types_1.NativeScheduleCleanupError(error instanceof Error ? error.message : 'Claude recovery failed after native creation.', this.recoverableScheduleHandle(cleanup, input, restoration));
412
+ throw error; // Keep direct input fenced until cleanup or explicit context reset.
413
+ }
414
+ },
415
+ };
416
+ }
417
+ recoverableScheduleHandle(handle, input, restoration) {
418
+ if (!input.recovery)
419
+ return handle;
420
+ const identity = JSON.parse(input.recovery.identity);
421
+ const executor = this;
422
+ return { ...handle,
423
+ get nativeId() { return handle.nativeId; },
424
+ get recoveryIdentity() {
425
+ return JSON.stringify({ ...identity, sessionId: executor.sessionId,
426
+ model: executor.model, effort: executor.effort,
427
+ effectiveModel: executor.acknowledgedModel || executor.reportedModel || executor.model });
428
+ },
429
+ releaseForRestart: async () => ({ ...await this.releaseScheduleDefinitions(),
430
+ ...(handle.onceDefinitionAlreadyAbsent && { onceDefinitionAlreadyAbsent: true }) }),
431
+ stop: async () => {
432
+ await handle.stop();
433
+ if (restoration && this.scheduleRestoring === restoration && !this.sessionSchedules?.hasPendingMutation)
434
+ this.scheduleRestoring = undefined;
435
+ }, };
436
+ }
437
+ releaseScheduleDefinitions() {
438
+ if (this.scheduleRestart?.release)
439
+ return this.scheduleRestart.release;
440
+ const child = this.claudeProcess;
441
+ if (!child || !this.turnLedger.supported(child.pid) || !this.scheduleHooksReady || this.modelChange
442
+ || this.retainedAbort || this.abortOperation || this.hasUncertainShutdown() || this.commandQueue.length
443
+ || this.isProcessing || this.isStarting || this.scheduleRestoring)
444
+ return Promise.reject(new Error('Claude handoff admission is unavailable.'));
445
+ const adapter = this.schedules();
446
+ const state = this.scheduleRestart ??= { child, epoch: this.stopEpoch, adapter };
447
+ const current = () => !this.isDestroyed && this.claudeProcess === child && this.stopEpoch === state.epoch && !this.abortOperation;
448
+ // Synchronous: after this point, a wake must pass the hook fence or be skipped.
449
+ adapter.beginRestart();
450
+ state.release = (async () => {
451
+ await adapter.removeFutureDefinitionsForRestart({ isCurrent: current });
452
+ await this.turnLedger.wait(() => current() && !adapter.admittedWork && !this.isProcessing
453
+ && !this.turnLedger.active && !this.pendingApprovals.size && !this.pendingControlRequests.size, 25_000, 'Admitted schedule execution drain');
454
+ if (!current())
455
+ throw new Error('Claude handoff host changed.');
456
+ return { nativeDefinitionAbsent: true, policy: 'skip-unadmitted' };
457
+ })();
458
+ return state.release;
459
+ }
460
+ async finishScheduleRestart() {
461
+ const state = this.scheduleRestart;
462
+ if (!state?.release)
463
+ throw new Error('Claude handoff was not prepared.');
464
+ await state.release;
465
+ if (state.exit) {
466
+ if (state.exit.code === 0 && !state.exit.signal && state.endRequested
467
+ && this.stopEpoch === state.epoch && !this.claudeProcess) {
468
+ // A timeout or failed receipt publication can precede a confirmed close.
469
+ // Retrying must durably publish that proof before reporting success.
470
+ this.scheduleOwnership?.confirmClean();
471
+ return;
472
+ }
473
+ throw new Error('Claude handoff exited unsuccessfully.');
474
+ }
475
+ const child = state.child;
476
+ const current = () => this.claudeProcess === child && this.stopEpoch === state.epoch && !this.isDestroyed;
477
+ if (!current())
478
+ throw new Error('Claude handoff host changed.');
479
+ // A new initialize response includes a fresh authoritative native task snapshot.
480
+ this.turnLedger.inventory = undefined;
481
+ await this.nativeControl('initialize', { hooks: ClaudeSessionSchedules_1.SCHEDULE_HOOKS });
482
+ await this.turnLedger.wait(() => current() && this.turnLedger.inventory?.size === 0
483
+ && [...this.turnLedger.tasks.values()].every(task => task.terminal)
484
+ && !state.adapter.admittedWork && !this.turnLedger.active && !this.isProcessing
485
+ && !this.pendingApprovals.size && !this.pendingControlRequests.size, 25_000, 'Native background drain');
486
+ if (!current())
487
+ throw new Error('Claude handoff host changed.');
488
+ // No signals, process-tree stop or timeout escalation: timeout retains the fence.
489
+ const exit = new Promise((resolve, reject) => {
490
+ const closed = (code, signal) => {
491
+ clearTimeout(timer);
492
+ if (code === 0 && !signal && this.stopEpoch === state.epoch)
493
+ resolve();
494
+ else
495
+ reject(new Error('Claude orderly exit was not confirmed.'));
496
+ };
497
+ const timer = setTimeout(() => { child.removeListener('close', closed); reject(new Error('Claude orderly exit remains unconfirmed; ownership retained.')); }, 20_000);
498
+ child.once('close', closed);
499
+ });
500
+ state.endRequested = true;
501
+ child.stdin.end();
502
+ await exit;
503
+ this.scheduleOwnership?.confirmClean();
504
+ }
306
505
  sessionSchedules;
307
506
  scheduleHooksReady = false;
308
507
  currentScheduleManagement = false;
@@ -324,14 +523,16 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
324
523
  await this.listModels();
325
524
  return this.execute(prompt, { nativeScheduleManagement: true, nativeScheduleCurrent: current });
326
525
  },
327
- wake: () => { void this.processQueue(); },
526
+ wake: () => { this.turnLedger.changed(); void this.processQueue(); },
328
527
  });
329
528
  }
330
529
  async withNativeScheduleOperation(id, current, run, inTurn) {
331
- if (this.retainedAbort || this.delegationWorker || this.isDestroyed || this.isStopping || this.sandbox.isRestricted())
530
+ if (this.modelChange || this.retainedAbort || this.delegationWorker || this.isDestroyed || this.isStopping || this.sandbox.isRestricted())
332
531
  throw new Error('Native schedule owner or sandbox is unavailable.');
333
532
  if (!inTurn)
334
533
  await this.listModels();
534
+ if (this.modelChange)
535
+ throw new Error('Native model change is pending or unconfirmed.');
335
536
  if (!this.scheduleHooksReady)
336
537
  throw new Error('Native scheduling hooks are not initialized.');
337
538
  return this.schedules().inToolOperation(id, current, run, inTurn);
@@ -357,13 +558,19 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
357
558
  }
358
559
  nativeScheduleAction(id) { return this.sessionSchedules?.action(id); }
359
560
  async createNativeSchedule(input, onEvent, isOwnerCurrent) {
360
- if (this.delegationWorker || this.isDestroyed || this.isStopping || this.sandbox.isRestricted()
561
+ if (this.scheduleRestart || this.modelChange || this.delegationWorker || this.isDestroyed || this.isStopping || this.sandbox.isRestricted()
361
562
  || input.cwd !== this.currentWorkingDirectory)
362
563
  throw new Error('Native schedule context or sandbox is unavailable.');
363
564
  if (!this.scheduleHooksReady)
364
565
  throw new Error('Native scheduling hooks are not initialized.');
365
566
  const timezone = await this.readNativeScheduleTimezone();
366
- return this.schedules().create(input, onEvent, isOwnerCurrent, timezone);
567
+ if (this.modelChange)
568
+ throw new Error('Native model change is pending or unconfirmed.');
569
+ if (input.recovery && !this.turnLedger.supported(this.claudeProcess?.pid))
570
+ throw new Error('Claude recovery protocol is unsupported.');
571
+ if (input.recovery)
572
+ this.scheduleHostOwnership().reserve(true);
573
+ return this.recoverableScheduleHandle(await this.schedules().create(input, onEvent, isOwnerCurrent, timezone), input);
367
574
  }
368
575
  /** Inspect only the effective TZ; never log, retain, or expose settings to a model. */
369
576
  readNativeScheduleTimezone() {
@@ -442,8 +649,10 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
442
649
  * directories that may have their own .claude-session files.
443
650
  */
444
651
  hasUncertainShutdown() { return this.shutdownUncertain || this.isStopping || !!this.stopOperation; }
445
- isBusy() {
446
- if (this.retainedAbort || this.abortOperation || this.hasUncertainShutdown() || this.scheduleCleanupHost)
652
+ isBusy() { return !!this.modelChange || this.isWorkBusy(); }
653
+ isWorkBusy() {
654
+ if (this.scheduleRestoring || this.retainedAbort || this.abortOperation || this.hasUncertainShutdown() || this.scheduleCleanupHost
655
+ || this.scheduleRestart && this.claudeProcess === this.scheduleRestart.child)
447
656
  return true;
448
657
  if (this.sessionSchedules?.busy)
449
658
  return true;
@@ -732,8 +941,13 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
732
941
  // Use 'close' event (fires after all I/O streams are closed, i.e. after all stdout
733
942
  // data events have been processed) instead of 'exit' for command completion logic.
734
943
  child.on('close', (code, signal) => {
944
+ const restart = this.scheduleRestart;
945
+ const released = restart?.child === child && restart.endRequested && restart.epoch === this.stopEpoch && code === 0 && !signal;
735
946
  if (this.claudeProcess === child) {
736
- this.sessionSchedules?.processClosed();
947
+ if (restart?.child === child)
948
+ restart.exit = { code, signal };
949
+ this.scheduleOwnership?.hostClosed();
950
+ this.sessionSchedules?.processClosed(!!released);
737
951
  this.sessionSchedules = undefined;
738
952
  this.scheduleHooksReady = false;
739
953
  }
@@ -742,11 +956,13 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
742
956
  flushStderr();
743
957
  this.clearApprovals('Claude process exited');
744
958
  this.rejectPendingControlRequests('Claude process exited before control response');
959
+ this.modelChange = undefined;
960
+ this.acknowledgedModel = undefined;
745
961
  this.clearCatalogCache();
746
962
  this.claudeProcess = null;
747
963
  this.turnLedger.retire();
748
964
  // Check if this was an intentional stop (abort/reset)
749
- const wasIntentionalStop = this.isStopping;
965
+ const wasIntentionalStop = this.isStopping || !!released;
750
966
  this.isStopping = false; // Reset the flag
751
967
  // Reject current command if any (only for unexpected exits)
752
968
  if (this.currentCommandReject && !wasIntentionalStop) {
@@ -924,6 +1140,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
924
1140
  if (this.claudeProcess === child) {
925
1141
  this.claudeProcess = null;
926
1142
  this.turnLedger.retire();
1143
+ this.modelChange = undefined;
1144
+ this.acknowledgedModel = undefined;
927
1145
  }
928
1146
  this.isStopping = false;
929
1147
  console.log('[ClaudePersistent] Process stopped');
@@ -1298,7 +1516,9 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1298
1516
  pending.resolve(response ?? {});
1299
1517
  }
1300
1518
  else {
1301
- pending.reject(new Error(error || `Claude control request failed with status: ${subtype}`));
1519
+ pending.reject(Object.assign(new Error(error || `Claude control request failed with status: ${subtype}`), {
1520
+ nativeCode: message.response.error_code, nativeModel: message.response.model,
1521
+ }));
1302
1522
  }
1303
1523
  }
1304
1524
  rejectPendingControlRequests(reason) {
@@ -1411,7 +1631,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1411
1631
  break;
1412
1632
  case 'system':
1413
1633
  // System messages (e.g., init)
1414
- if (message.subtype === 'init' && typeof message.model === 'string' && message.model.trim()) {
1634
+ if (message.subtype === 'init' && !this.acknowledgedModel && typeof message.model === 'string' && message.model.trim()) {
1415
1635
  this.reportedModel = message.model;
1416
1636
  }
1417
1637
  if (message.subtype === 'init' && message.session_id) {
@@ -1504,7 +1724,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1504
1724
  }
1505
1725
  break;
1506
1726
  case 'assistant':
1507
- if (!message.parent_tool_use_id && typeof message.message?.model === 'string' && message.message.model.trim()) {
1727
+ if (!message.parent_tool_use_id && typeof message.message?.model === 'string' && message.message.model.trim()
1728
+ && (!this.acknowledgedModel || (this.isProcessing && this.turnLedger.foreground !== this.modelSelectionForeground))) {
1508
1729
  this.reportedModel = message.message.model;
1509
1730
  }
1510
1731
  // Assistant messages contain the actual response content
@@ -1896,7 +2117,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1896
2117
  */
1897
2118
  async processQueue() {
1898
2119
  const cleanup = this.cleanupAdmission() && this.commandQueue[0]?.options.nativeScheduleManagement;
1899
- if (this.isDestroyed || ((this.abortOperation || this.retainedAbort) && !cleanup) || this.hasUncertainShutdown() || this.isProcessing || this.isStarting || this.sessionSchedules?.busy || this.commandQueue.length === 0) {
2120
+ if (this.isDestroyed || this.modelChange || ((this.abortOperation || this.retainedAbort) && !cleanup) || this.hasUncertainShutdown() || this.isProcessing || this.isStarting || this.sessionSchedules?.busy || this.commandQueue.length === 0) {
1900
2121
  return;
1901
2122
  }
1902
2123
  if (this.turnLedger.supported(this.claudeProcess?.pid) && this.turnLedger.foreground
@@ -1956,7 +2177,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1956
2177
  this.isStarting = false;
1957
2178
  }
1958
2179
  }
1959
- if (epoch !== this.commandEpoch || ((this.abortOperation || this.retainedAbort) && !cleanup) || this.hasUncertainShutdown() || this.sessionSchedules?.busy)
2180
+ if (epoch !== this.commandEpoch || this.modelChange || ((this.abortOperation || this.retainedAbort) && !cleanup) || this.hasUncertainShutdown() || this.sessionSchedules?.busy)
1960
2181
  return;
1961
2182
  const command = this.commandQueue.shift();
1962
2183
  if (!command) {
@@ -2070,6 +2291,10 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2070
2291
  async execute(prompt, options = {}) {
2071
2292
  if (this.isDestroyed)
2072
2293
  return { success: false, error: 'Executor has been destroyed' };
2294
+ if ((this.scheduleRestart || this.scheduleRestoring) && !(options.nativeScheduleManagement && options.nativeScheduleCurrent?.()))
2295
+ return { success: false, error: 'Native schedule handoff or restoration is pending.' };
2296
+ if (this.modelChange)
2297
+ return { success: false, error: 'Native model change is pending or unconfirmed. Retry /model after its reply, or use /clear (session-only schedules will be lost).' };
2073
2298
  if (((this.abortOperation || this.retainedAbort) && !(this.cleanupAdmission() && options.nativeScheduleManagement && options.nativeScheduleCurrent?.()))
2074
2299
  || this.hasUncertainShutdown() || (this.scheduleCleanupHost && !options.nativeScheduleManagement)) {
2075
2300
  return { success: false, error: 'Native cleanup is still pending. Retry after cleanup.' };
@@ -2106,6 +2331,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2106
2331
  return operation;
2107
2332
  }
2108
2333
  async abortCurrent() {
2334
+ if (this.modelChange)
2335
+ throw new Error('Native model change is pending or unconfirmed. /abort cannot cancel a settings request; wait for its reply or explicitly /clear (session-only schedules will be lost).');
2109
2336
  if (this.retainedAbort || (this.preservesProcessOnAbort() && (this.isProcessing || this.isWaitingInput() || this.sessionSchedules?.hasPendingMutation))) {
2110
2337
  return this.interruptForeground();
2111
2338
  }
@@ -2308,6 +2535,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2308
2535
  await this.stopProcess();
2309
2536
  this.retainedAbort = undefined;
2310
2537
  this.shutdownUncertain = false;
2538
+ this.scheduleRestart = undefined;
2539
+ this.scheduleRestoring = undefined;
2311
2540
  }
2312
2541
  /**
2313
2542
  * Reset execution context
@@ -2318,6 +2547,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2318
2547
  * prompts interrupted during startup are not replayed into the fresh context.
2319
2548
  */
2320
2549
  resetContext() {
2550
+ this.scheduleRestart = undefined;
2551
+ this.scheduleRestoring = undefined;
2321
2552
  this.cancelInputWaiters();
2322
2553
  this.nativeCreationEpoch++;
2323
2554
  console.log('[ClaudePersistent] Resetting session context');
@@ -2336,53 +2567,147 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2336
2567
  // so clearing it in memory is not enough. The process must be restarted fresh.
2337
2568
  this.stopProcess().catch((err) => console.error('[ClaudePersistent] Failed to stop process on reset:', err));
2338
2569
  }
2339
- /**
2340
- * Switch the model for future commands.
2341
- * Restarts the process if running, preserving the session via --resume.
2342
- * Rejects known incompatible effort rather than silently changing a second preference.
2343
- * Retains a deliberate text-argument full-model path if not found in catalog.
2344
- */
2570
+ /** Switch only the session selection. Never recycle a live host to change a model. */
2345
2571
  async setModel(model, _onStream) {
2346
- if (this.isDestroyed) {
2347
- return { success: false, error: 'Executor has been destroyed' };
2348
- }
2349
- if (this.isBusy()) {
2350
- return { success: false, error: 'Cannot change model while Claude is busy' };
2572
+ return this.changeModel(model);
2573
+ }
2574
+ async clearModel() {
2575
+ const result = await this.changeModel(undefined);
2576
+ if (!result.success)
2577
+ throw new Error(result.error);
2578
+ }
2579
+ async changeModel(model) {
2580
+ const failure = (error) => ({ success: false, error });
2581
+ if (this.isDestroyed)
2582
+ return failure('Executor has been destroyed');
2583
+ if (model !== undefined && (!model.trim() || model.length > 512 || /[\x00-\x1f\x7f]/.test(model)))
2584
+ return failure('Invalid model identifier.');
2585
+ if (this.isWorkBusy() || (this.modelChange && !this.modelChange.retryable) || this.sessionSchedules?.hasPendingMutation) {
2586
+ return failure('Cannot change model while Claude work or a model change is pending.');
2587
+ }
2588
+ const validateEffort = () => {
2589
+ if (!this.effort)
2590
+ return;
2591
+ const entry = this.cachedRawEntries?.find(e => e.value === (model ?? 'default') || (model !== undefined && e.resolvedModel === model));
2592
+ if (!entry)
2593
+ return 'Cannot validate the saved reasoning effort. Reset /effort auto before changing models.';
2594
+ if (!entry.supportsEffort || !entry.supportedEffortLevels?.includes(this.effort)) {
2595
+ return 'The saved reasoning effort is incompatible with this model. Reset /effort auto before changing models.';
2596
+ }
2597
+ };
2598
+ const child = this.claudeProcess;
2599
+ if (!child) {
2600
+ // Cold preferences never start a model process just to validate or change a setting.
2601
+ const error = validateEffort();
2602
+ if (error)
2603
+ return failure(error);
2604
+ this.model = model;
2605
+ this.reportedModel = undefined;
2606
+ this.acknowledgedModel = undefined;
2607
+ return { success: true, output: model === undefined ? 'Model restored to default.' : `Model set to ${model}.` };
2608
+ }
2609
+ const previous = this.modelChange;
2610
+ const operation = { child, epoch: this.stopEpoch, session: this.sessionId, retryable: false };
2611
+ this.modelChange = operation;
2612
+ const current = (initialized = true) => this.modelChange === operation && this.claudeProcess === child
2613
+ && this.stopEpoch === operation.epoch && this.sessionId === operation.session && !this.turnLedger.invalid
2614
+ && (!initialized || (!!child.pid && this.turnLedger.pid === child.pid))
2615
+ && (!this.turnLedger.session || this.turnLedger.session === operation.session) && !this.isDestroyed && !this.hasUncertainShutdown();
2616
+ try {
2617
+ await this.listModels();
2618
+ if (!current(false))
2619
+ throw new Error('Native model host changed before the request.');
2620
+ // set_model has no advertised capability bit in the public SDK. Probe the
2621
+ // initialized host and require its correlated, explicit model receipt.
2622
+ if (!child.pid || this.turnLedger.pid !== child.pid || !child.stdin?.writable || child.killed) {
2623
+ throw new Error('In-process model changes require a matching initialized, writable native host. The current host and schedules were retained.');
2624
+ }
2625
+ const error = validateEffort();
2626
+ if (error)
2627
+ throw new Error(error);
2351
2628
  }
2352
- if (this.effort && !this.cachedRawEntries) {
2629
+ catch (error) {
2630
+ if (this.modelChange === operation)
2631
+ this.modelChange = previous;
2632
+ return failure(error instanceof Error ? error.message : 'Cannot prepare native model change.');
2633
+ }
2634
+ return new Promise(resolve => {
2635
+ const requestId = `model-${(0, crypto_1.randomUUID)()}`;
2636
+ let returned = false;
2637
+ const finish = (result) => { if (!returned) {
2638
+ returned = true;
2639
+ resolve(result);
2640
+ } };
2641
+ const uncertain = (reason, retryable = false) => {
2642
+ if (this.modelChange === operation)
2643
+ operation.retryable = retryable;
2644
+ finish(failure(`${reason} Model selection is unconfirmed; no preference was saved. Native jobs were not stopped. Wait for the pending reply or retry /model after a terminal error; /clear is destructive recovery and loses session-only schedules.`));
2645
+ };
2646
+ const validModel = (value) => typeof value === 'string' && value.trim().length > 0
2647
+ && value.length <= 512 && !/[\x00-\x1f\x7f]/.test(value);
2648
+ // Keep the correlated receiver after the user-facing deadline. A late ACK
2649
+ // can settle admission, but must never save a preference or emit success.
2650
+ const timer = setTimeout(() => uncertain('Native model change timed out after 10000ms.'), 10_000);
2651
+ this.pendingControlRequests.set(requestId, {
2652
+ timer,
2653
+ resolve: response => {
2654
+ if (!current()) {
2655
+ uncertain('Native model host changed before acknowledgement.');
2656
+ return;
2657
+ }
2658
+ const selected = response?.model;
2659
+ if (!validModel(selected)) {
2660
+ uncertain('Native model acknowledgement omitted a valid selection.', true);
2661
+ return;
2662
+ }
2663
+ this.recordModelSelection(selected);
2664
+ if (!returned)
2665
+ this.model = model;
2666
+ this.modelChange = undefined;
2667
+ finish({ success: true, output: model === undefined ? 'Model restored to default.' : `Model set to ${model}.` });
2668
+ void this.processQueue();
2669
+ },
2670
+ reject: error => {
2671
+ if (!current()) {
2672
+ uncertain('Native model host changed before acknowledgement.');
2673
+ return;
2674
+ }
2675
+ const { nativeCode, nativeModel } = error;
2676
+ // A terminal response may report a changed selection even on failure.
2677
+ // verdict_pending is explicitly not a refusal and may still apply later.
2678
+ if (nativeCode !== 'verdict_pending' && validModel(nativeModel)) {
2679
+ this.recordModelSelection(nativeModel);
2680
+ }
2681
+ const refused = ['invalid_request', 'catalog_unknown', 'not_found', 'restricted_by_org', 'unavailable_for_account',
2682
+ 'not_offered', 'alias_1m_disabled', 'alias_1m_unsupported', 'blocked_by_hook', 'check_failed',
2683
+ 'check_rejected', 'credits_required', 'rate_limit', 'auth_failed', 'model_not_current'].includes(nativeCode ?? '');
2684
+ if (refused && validModel(nativeModel)) {
2685
+ this.modelChange = undefined;
2686
+ finish(failure(`Native model change refused (${nativeCode}); no preference was saved.`));
2687
+ void this.processQueue();
2688
+ }
2689
+ else
2690
+ uncertain('Native model change did not return a confirmed outcome.', nativeCode === 'internal_error');
2691
+ },
2692
+ });
2353
2693
  try {
2354
- await this.listModels();
2694
+ child.stdin.write(JSON.stringify({ type: 'control_request', request_id: requestId,
2695
+ request: { subtype: 'set_model', ...(model === undefined ? {} : { model }) } }) + '\n', error => {
2696
+ if (error && this.pendingControlRequests.has(requestId))
2697
+ uncertain('Native model request write failed.');
2698
+ });
2355
2699
  }
2356
2700
  catch {
2357
- return { success: false, error: 'Cannot validate the saved reasoning effort. Reset /effort auto before changing models.' };
2358
- }
2359
- }
2360
- let matchedEntry;
2361
- if (this.cachedRawEntries) {
2362
- matchedEntry = this.cachedRawEntries.find(e => e.value === model || (e.resolvedModel !== undefined && e.resolvedModel === model));
2363
- }
2364
- if (this.effort && matchedEntry) {
2365
- if (!matchedEntry.supportsEffort || !matchedEntry.supportedEffortLevels?.includes(this.effort)) {
2366
- return { success: false, error: 'The saved reasoning effort is incompatible with this model. Reset /effort auto before changing models.' };
2701
+ uncertain('Native model request write failed.');
2367
2702
  }
2368
- }
2369
- await this.stopProcess();
2370
- this.model = model;
2371
- this.reportedModel = undefined;
2372
- return {
2373
- success: true,
2374
- output: `Model set to ${this.model}.`,
2375
- };
2703
+ });
2376
2704
  }
2377
- async clearModel() {
2378
- if (this.isDestroyed)
2379
- return;
2380
- if (this.isBusy()) {
2381
- throw new Error('Cannot clear model while Claude is busy');
2382
- }
2383
- this.model = undefined;
2705
+ recordModelSelection(model) {
2706
+ this.acknowledgedModel = model;
2707
+ this.modelSelectionForeground = this.turnLedger.foreground;
2708
+ // Old in-flight responses cannot shadow a newly acknowledged session selection.
2709
+ // A later foreground can report the actual served model (including fallback).
2384
2710
  this.reportedModel = undefined;
2385
- await this.stopProcess();
2386
2711
  }
2387
2712
  /**
2388
2713
  * Query models available to the authenticated Claude backend using native control initialization.
@@ -2393,7 +2718,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2393
2718
  throw new Error('Executor has been destroyed');
2394
2719
  }
2395
2720
  if (this.cachedModelCatalog) {
2396
- return (0, ClaudeSettings_1.parseClaudeModelsCatalog)(this.cachedRawEntries, this.reportedModel || this.model).models;
2721
+ return (0, ClaudeSettings_1.parseClaudeModelsCatalog)(this.cachedRawEntries, this.reportedModel || this.acknowledgedModel || this.model).models;
2397
2722
  }
2398
2723
  if (this.catalogInitPromise) {
2399
2724
  return this.catalogInitPromise;
@@ -2449,7 +2774,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2449
2774
  const rawResponse = response || {};
2450
2775
  this.turnLedger.version = typeof rawResponse.claude_code_version === 'string' ? rawResponse.claude_code_version : undefined;
2451
2776
  this.turnLedger.pid = typeof rawResponse.pid === 'number' ? rawResponse.pid : undefined;
2452
- const { models, rawEntries } = (0, ClaudeSettings_1.parseClaudeModelsCatalog)(rawResponse.models, this.reportedModel || this.model);
2777
+ const { models, rawEntries } = (0, ClaudeSettings_1.parseClaudeModelsCatalog)(rawResponse.models, this.reportedModel || this.acknowledgedModel || this.model);
2453
2778
  if (scheduleHooks && this.sessionId && this.delegation?.groups?.includes('scheduling')) {
2454
2779
  await this.readNativeScheduleTimezone();
2455
2780
  }
@@ -2519,7 +2844,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2519
2844
  unavailableReason: 'Reasoning effort is not supported for Claude Code.',
2520
2845
  };
2521
2846
  }
2522
- const activeModel = this.reportedModel || this.model;
2847
+ const activeModel = this.reportedModel || this.acknowledgedModel || this.model;
2523
2848
  return (0, ClaudeSettings_1.resolveClaudeEfforts)(this.cachedRawEntries, activeModel, this.effort);
2524
2849
  }
2525
2850
  /**
@@ -2534,6 +2859,9 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2534
2859
  if (this.isBusy()) {
2535
2860
  return { success: false, error: 'Cannot change reasoning effort while Claude is busy' };
2536
2861
  }
2862
+ if (this.sessionSchedules?.hasJobs || this.sessionSchedules?.hasPendingMutation) {
2863
+ return { success: false, error: 'Reasoning effort changes require a process restart and are unavailable while native schedules exist. Cancel schedules explicitly first; they will not be stopped to change a preference.' };
2864
+ }
2537
2865
  const normalized = effort.trim().toLowerCase();
2538
2866
  if (normalized === 'auto' || normalized === '') {
2539
2867
  await this.stopProcess();
@@ -2566,6 +2894,10 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2566
2894
  error: `Unsupported reasoning effort: ${effort}. Supported values: auto, ${effortInfo.choices.map(c => c.value).join(', ')}.`,
2567
2895
  };
2568
2896
  }
2897
+ // Catalog lookup yields: a schedule or settings request may have arrived.
2898
+ if (this.isBusy() || this.sessionSchedules?.hasJobs || this.sessionSchedules?.hasPendingMutation) {
2899
+ return { success: false, error: 'Claude work or native schedules arrived while checking effort. Retry after explicitly retiring schedules.' };
2900
+ }
2569
2901
  await this.stopProcess();
2570
2902
  this.effort = match.value;
2571
2903
  return {
@@ -2579,6 +2911,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2579
2911
  * Returns a promise that resolves when compaction is complete.
2580
2912
  */
2581
2913
  compact(onStream) {
2914
+ if (this.modelChange)
2915
+ return Promise.resolve({ success: false, error: 'Native model change is pending or unconfirmed.' });
2582
2916
  if (this.retainedAbort || this.abortOperation)
2583
2917
  return Promise.resolve({ success: false, error: 'Native cancellation cleanup is pending.' });
2584
2918
  console.log('[ClaudePersistent] Sending /compact slash command');
@@ -2733,6 +3067,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2733
3067
  fs_1.default.rmSync(this.approvalSocketDirectory, { recursive: true, force: true });
2734
3068
  this.approvalSocketDirectory = undefined;
2735
3069
  }
3070
+ this.scheduleOwnership?.close();
2736
3071
  // Remove all listeners
2737
3072
  this.removeAllListeners();
2738
3073
  }