@yu_robotics/remote-cli 1.6.237 → 1.6.238

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 (64) 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 +1 -0
  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 +17 -7
  13. package/dist/executor/ClaudePersistentExecutor.d.ts.map +1 -1
  14. package/dist/executor/ClaudePersistentExecutor.js +362 -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/maintenance/release-notes.json +1 -1
  23. package/dist/scheduling/ScheduleCapabilities.d.ts +1 -1
  24. package/dist/scheduling/ScheduleCapabilities.d.ts.map +1 -1
  25. package/dist/scheduling/ScheduleCapabilities.js +3 -2
  26. package/dist/scheduling/ScheduleCapabilities.js.map +1 -1
  27. package/dist/scheduling/ScheduleService.d.ts +26 -0
  28. package/dist/scheduling/ScheduleService.d.ts.map +1 -1
  29. package/dist/scheduling/ScheduleService.js +549 -17
  30. package/dist/scheduling/ScheduleService.js.map +1 -1
  31. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts +25 -2
  32. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts.map +1 -1
  33. package/dist/scheduling/claude/ClaudeSessionSchedules.js +126 -17
  34. package/dist/scheduling/claude/ClaudeSessionSchedules.js.map +1 -1
  35. package/dist/scheduling/dsh/SessionScheduleBridge.d.ts.map +1 -1
  36. package/dist/scheduling/dsh/SessionScheduleBridge.js +21 -0
  37. package/dist/scheduling/dsh/SessionScheduleBridge.js.map +1 -1
  38. package/dist/scheduling/dsh/SessionScheduleClient.d.ts.map +1 -1
  39. package/dist/scheduling/dsh/SessionScheduleClient.js +8 -0
  40. package/dist/scheduling/dsh/SessionScheduleClient.js.map +1 -1
  41. package/dist/scheduling/types.d.ts +84 -0
  42. package/dist/scheduling/types.d.ts.map +1 -1
  43. package/dist/scheduling/types.js.map +1 -1
  44. package/dist/settings/SettingsService.d.ts +1 -1
  45. package/dist/settings/SettingsService.d.ts.map +1 -1
  46. package/dist/settings/SettingsService.js +3 -3
  47. package/dist/settings/SettingsService.js.map +1 -1
  48. package/dist/thread/ThreadExecutorPool.d.ts +1 -1
  49. package/dist/thread/ThreadExecutorPool.d.ts.map +1 -1
  50. package/dist/thread/ThreadExecutorPool.js +5 -3
  51. package/dist/thread/ThreadExecutorPool.js.map +1 -1
  52. package/dist/update/AutomaticUpdater.d.ts +2 -1
  53. package/dist/update/AutomaticUpdater.d.ts.map +1 -1
  54. package/dist/update/AutomaticUpdater.js +11 -3
  55. package/dist/update/AutomaticUpdater.js.map +1 -1
  56. package/native/prebuilds/darwin-arm64/managed_native.node +0 -0
  57. package/native/prebuilds/darwin-arm64/manifest.json +1 -1
  58. package/native/prebuilds/darwin-x64/managed_native.node +0 -0
  59. package/native/prebuilds/darwin-x64/manifest.json +1 -1
  60. package/native/prebuilds/win32-arm64/managed_native.node +0 -0
  61. package/native/prebuilds/win32-arm64/manifest.json +1 -1
  62. package/native/prebuilds/win32-x64/managed_native.node +0 -0
  63. package/native/prebuilds/win32-x64/manifest.json +1 -1
  64. package/package.json +1 -1
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.ClaudePersistentExecutor = void 0;
7
7
  const ClaudeSessionSchedules_1 = require("../scheduling/claude/ClaudeSessionSchedules");
8
8
  const TurnLedger_1 = require("./claude/TurnLedger");
9
+ const types_1 = require("../scheduling/types");
9
10
  const tools_1 = require("../managed/tools");
10
11
  const ManagedSpawn_1 = require("./ManagedSpawn");
11
12
  const OwnershipRuntime_1 = require("../delegation/OwnershipRuntime");
@@ -62,6 +63,14 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
62
63
  model;
63
64
  effort;
64
65
  reportedModel;
66
+ /** Native session selection, not a claim about the model serving an in-flight response. */
67
+ acknowledgedModel;
68
+ modelSelectionForeground;
69
+ modelChange;
70
+ hasPendingSettingsChange() { return !!this.modelChange; }
71
+ canRetrySettingsChange(setting) {
72
+ return setting === 'model' && this.modelChange?.retryable === true && !this.isWorkBusy() && !this.sessionSchedules?.hasPendingMutation;
73
+ }
65
74
  // Native control catalog cache & control request state
66
75
  cachedModelCatalog = null;
67
76
  cachedRawEntries = null;
@@ -285,7 +294,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
285
294
  getExecutionMetadata() {
286
295
  let effectiveEffort = this.effort;
287
296
  if (this.effort && this.cachedRawEntries) {
288
- const activeModel = this.reportedModel || this.model;
297
+ const activeModel = this.reportedModel || this.acknowledgedModel || this.model;
289
298
  const entry = activeModel
290
299
  ? this.cachedRawEntries.find(e => e.value === activeModel || (e.resolvedModel !== undefined && e.resolvedModel === activeModel))
291
300
  : this.cachedRawEntries.find(e => e.value === 'default');
@@ -297,12 +306,174 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
297
306
  if (!effectiveEffort) {
298
307
  data.effortSource = 'unknown';
299
308
  }
300
- if (this.isProcessRunning() && this.reportedModel) {
301
- data.model = this.reportedModel;
309
+ if (this.isProcessRunning() && (this.acknowledgedModel || this.reportedModel)) {
310
+ data.model = this.reportedModel || this.acknowledgedModel;
302
311
  data.modelSource = 'reported';
303
312
  }
313
+ if (this.modelChange) {
314
+ data.model = undefined;
315
+ data.modelSource = 'unknown';
316
+ }
304
317
  return data;
305
318
  }
319
+ scheduleRestart;
320
+ scheduleRestoring;
321
+ get nativeScheduleRecovery() {
322
+ if (this.delegationWorker || process.platform !== 'linux' || process.arch !== 'x64'
323
+ || this.sandbox.isRestricted() || this.turnLedger.version && this.turnLedger.version !== '2.1.311')
324
+ return undefined;
325
+ return {
326
+ provider: 'claude-session-skip-unadmitted-v1', strategy: 'reconstruct', orderlyOnly: true,
327
+ handoffPolicy: 'skip-unadmitted',
328
+ describe: input => JSON.stringify({ marker: (0, crypto_1.randomUUID)(), sessionId: this.sessionId,
329
+ cwd: input.cwd, threadId: this.threadId, model: this.model, effort: this.effort,
330
+ effectiveModel: this.acknowledgedModel || this.reportedModel || this.model }),
331
+ finishRestart: () => this.finishScheduleRestart(),
332
+ releaseRestartAdmission: () => {
333
+ const state = this.scheduleRestart;
334
+ if (state?.exit?.code === 0 && !state.exit.signal && state.endRequested
335
+ && state.epoch === this.stopEpoch && !this.claudeProcess)
336
+ this.scheduleRestart = undefined;
337
+ },
338
+ reconcile: async (record, context, emit) => {
339
+ const identity = JSON.parse(record.recovery.identity);
340
+ if (record.recovery?.handoff !== 'clean' || !record.recovery.nativeDefinitionAbsent
341
+ || record.recovery.handoffPolicy !== 'skip-unadmitted' || !context.isCurrent()
342
+ || context.signal.aborted || !identity.sessionId || identity.sessionId !== this.sessionId
343
+ || identity.cwd !== this.currentWorkingDirectory || identity.threadId !== this.threadId
344
+ || identity.model !== this.model || identity.effort !== this.effort) {
345
+ throw new Error('Original Claude context or clean handoff evidence changed.');
346
+ }
347
+ if (this.scheduleRestart && !this.scheduleRestart.exit)
348
+ throw new Error('Claude predecessor exit is unconfirmed.');
349
+ this.scheduleRestart = undefined;
350
+ const restoration = {};
351
+ this.scheduleRestoring = restoration;
352
+ const epoch = this.stopEpoch;
353
+ const current = () => this.scheduleRestoring === restoration && this.stopEpoch === epoch
354
+ && !this.isDestroyed && context.isCurrent() && !context.signal.aborted && this.sessionId === identity.sessionId;
355
+ const input = { id: record.id, threadId: record.threadId, backend: 'claude',
356
+ cwd: record.cwd, prompt: record.prompt, rule: record.rule, ...record.execution, recovery: record.recovery };
357
+ let handle;
358
+ try {
359
+ await this.listModels();
360
+ if (!current())
361
+ throw new Error('Claude recovery owner changed.');
362
+ if (this.turnLedger.version !== '2.1.311' || this.turnLedger.pid !== this.claudeProcess?.pid
363
+ || typeof identity.effectiveModel !== 'string' || !identity.effectiveModel)
364
+ throw new Error('Original Claude model or supported host is unavailable.');
365
+ const child = this.claudeProcess;
366
+ if (this.model !== identity.effectiveModel) {
367
+ const response = await this.nativeControl('set_model', { model: identity.effectiveModel });
368
+ if (!current() || this.claudeProcess !== child)
369
+ throw new Error('Claude recovery model owner changed.');
370
+ if (!response || typeof response !== 'object' || response.model !== identity.effectiveModel) {
371
+ throw new Error('Claude recovery model selection is unconfirmed.');
372
+ }
373
+ this.recordModelSelection(identity.effectiveModel);
374
+ }
375
+ const adapter = this.schedules();
376
+ const timezone = await this.readNativeScheduleTimezone();
377
+ if (!current() || this.claudeProcess !== child)
378
+ throw new Error('Claude recovery host changed.');
379
+ handle = await adapter.inToolOperation(`restore-${record.id}`, current, () => adapter.create(input, emit, context.isOwnerCurrent ?? context.isCurrent, timezone, true), false);
380
+ if (!current() || this.claudeProcess !== child || !this.turnLedger.supported(child?.pid))
381
+ throw new types_1.NativeScheduleCleanupError('Claude recovery host or protocol changed.', handle);
382
+ const recovered = this.recoverableScheduleHandle(handle, input, restoration);
383
+ this.scheduleRestoring = undefined;
384
+ return recovered;
385
+ }
386
+ catch (error) {
387
+ const cleanup = error instanceof types_1.NativeScheduleCleanupError ? error.handle : handle;
388
+ if (cleanup)
389
+ throw new types_1.NativeScheduleCleanupError(error instanceof Error ? error.message : 'Claude recovery failed after native creation.', this.recoverableScheduleHandle(cleanup, input, restoration));
390
+ throw error; // Keep direct input fenced until cleanup or explicit context reset.
391
+ }
392
+ },
393
+ };
394
+ }
395
+ recoverableScheduleHandle(handle, input, restoration) {
396
+ if (!input.recovery)
397
+ return handle;
398
+ const identity = JSON.parse(input.recovery.identity);
399
+ const executor = this;
400
+ return { ...handle,
401
+ get nativeId() { return handle.nativeId; },
402
+ get recoveryIdentity() {
403
+ return JSON.stringify({ ...identity, sessionId: executor.sessionId,
404
+ model: executor.model, effort: executor.effort,
405
+ effectiveModel: executor.acknowledgedModel || executor.reportedModel || executor.model });
406
+ },
407
+ releaseForRestart: async () => ({ ...await this.releaseScheduleDefinitions(),
408
+ ...(handle.onceDefinitionAlreadyAbsent && { onceDefinitionAlreadyAbsent: true }) }),
409
+ stop: async () => {
410
+ await handle.stop();
411
+ if (restoration && this.scheduleRestoring === restoration && !this.sessionSchedules?.hasPendingMutation)
412
+ this.scheduleRestoring = undefined;
413
+ }, };
414
+ }
415
+ releaseScheduleDefinitions() {
416
+ if (this.scheduleRestart?.release)
417
+ return this.scheduleRestart.release;
418
+ const child = this.claudeProcess;
419
+ if (!child || !this.turnLedger.supported(child.pid) || !this.scheduleHooksReady || this.modelChange
420
+ || this.retainedAbort || this.abortOperation || this.hasUncertainShutdown() || this.commandQueue.length
421
+ || this.isProcessing || this.isStarting || this.scheduleRestoring)
422
+ return Promise.reject(new Error('Claude handoff admission is unavailable.'));
423
+ const adapter = this.schedules();
424
+ const state = this.scheduleRestart ??= { child, epoch: this.stopEpoch, adapter };
425
+ const current = () => !this.isDestroyed && this.claudeProcess === child && this.stopEpoch === state.epoch && !this.abortOperation;
426
+ // Synchronous: after this point, a wake must pass the hook fence or be skipped.
427
+ adapter.beginRestart();
428
+ state.release = (async () => {
429
+ await adapter.removeFutureDefinitionsForRestart({ isCurrent: current });
430
+ await this.turnLedger.wait(() => current() && !adapter.admittedWork && !this.isProcessing
431
+ && !this.turnLedger.active && !this.pendingApprovals.size && !this.pendingControlRequests.size, 25_000, 'Admitted schedule execution drain');
432
+ if (!current())
433
+ throw new Error('Claude handoff host changed.');
434
+ return { nativeDefinitionAbsent: true, policy: 'skip-unadmitted' };
435
+ })();
436
+ return state.release;
437
+ }
438
+ async finishScheduleRestart() {
439
+ const state = this.scheduleRestart;
440
+ if (!state?.release)
441
+ throw new Error('Claude handoff was not prepared.');
442
+ await state.release;
443
+ if (state.exit) {
444
+ if (state.exit.code === 0 && !state.exit.signal && this.stopEpoch === state.epoch)
445
+ return;
446
+ throw new Error('Claude handoff exited unsuccessfully.');
447
+ }
448
+ const child = state.child;
449
+ const current = () => this.claudeProcess === child && this.stopEpoch === state.epoch && !this.isDestroyed;
450
+ if (!current())
451
+ throw new Error('Claude handoff host changed.');
452
+ // A new initialize response includes a fresh authoritative native task snapshot.
453
+ this.turnLedger.inventory = undefined;
454
+ await this.nativeControl('initialize', { hooks: ClaudeSessionSchedules_1.SCHEDULE_HOOKS });
455
+ await this.turnLedger.wait(() => current() && this.turnLedger.inventory?.size === 0
456
+ && [...this.turnLedger.tasks.values()].every(task => task.terminal)
457
+ && !state.adapter.admittedWork && !this.turnLedger.active && !this.isProcessing
458
+ && !this.pendingApprovals.size && !this.pendingControlRequests.size, 25_000, 'Native background drain');
459
+ if (!current())
460
+ throw new Error('Claude handoff host changed.');
461
+ // No signals, process-tree stop or timeout escalation: timeout retains the fence.
462
+ const exit = new Promise((resolve, reject) => {
463
+ const closed = (code, signal) => {
464
+ clearTimeout(timer);
465
+ if (code === 0 && !signal && this.stopEpoch === state.epoch)
466
+ resolve();
467
+ else
468
+ reject(new Error('Claude orderly exit was not confirmed.'));
469
+ };
470
+ const timer = setTimeout(() => { child.removeListener('close', closed); reject(new Error('Claude orderly exit remains unconfirmed; ownership retained.')); }, 20_000);
471
+ child.once('close', closed);
472
+ });
473
+ state.endRequested = true;
474
+ child.stdin.end();
475
+ await exit;
476
+ }
306
477
  sessionSchedules;
307
478
  scheduleHooksReady = false;
308
479
  currentScheduleManagement = false;
@@ -324,14 +495,16 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
324
495
  await this.listModels();
325
496
  return this.execute(prompt, { nativeScheduleManagement: true, nativeScheduleCurrent: current });
326
497
  },
327
- wake: () => { void this.processQueue(); },
498
+ wake: () => { this.turnLedger.changed(); void this.processQueue(); },
328
499
  });
329
500
  }
330
501
  async withNativeScheduleOperation(id, current, run, inTurn) {
331
- if (this.retainedAbort || this.delegationWorker || this.isDestroyed || this.isStopping || this.sandbox.isRestricted())
502
+ if (this.modelChange || this.retainedAbort || this.delegationWorker || this.isDestroyed || this.isStopping || this.sandbox.isRestricted())
332
503
  throw new Error('Native schedule owner or sandbox is unavailable.');
333
504
  if (!inTurn)
334
505
  await this.listModels();
506
+ if (this.modelChange)
507
+ throw new Error('Native model change is pending or unconfirmed.');
335
508
  if (!this.scheduleHooksReady)
336
509
  throw new Error('Native scheduling hooks are not initialized.');
337
510
  return this.schedules().inToolOperation(id, current, run, inTurn);
@@ -357,13 +530,17 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
357
530
  }
358
531
  nativeScheduleAction(id) { return this.sessionSchedules?.action(id); }
359
532
  async createNativeSchedule(input, onEvent, isOwnerCurrent) {
360
- if (this.delegationWorker || this.isDestroyed || this.isStopping || this.sandbox.isRestricted()
533
+ if (this.scheduleRestart || this.modelChange || this.delegationWorker || this.isDestroyed || this.isStopping || this.sandbox.isRestricted()
361
534
  || input.cwd !== this.currentWorkingDirectory)
362
535
  throw new Error('Native schedule context or sandbox is unavailable.');
363
536
  if (!this.scheduleHooksReady)
364
537
  throw new Error('Native scheduling hooks are not initialized.');
365
538
  const timezone = await this.readNativeScheduleTimezone();
366
- return this.schedules().create(input, onEvent, isOwnerCurrent, timezone);
539
+ if (this.modelChange)
540
+ throw new Error('Native model change is pending or unconfirmed.');
541
+ if (input.recovery && !this.turnLedger.supported(this.claudeProcess?.pid))
542
+ throw new Error('Claude recovery protocol is unsupported.');
543
+ return this.recoverableScheduleHandle(await this.schedules().create(input, onEvent, isOwnerCurrent, timezone), input);
367
544
  }
368
545
  /** Inspect only the effective TZ; never log, retain, or expose settings to a model. */
369
546
  readNativeScheduleTimezone() {
@@ -442,8 +619,10 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
442
619
  * directories that may have their own .claude-session files.
443
620
  */
444
621
  hasUncertainShutdown() { return this.shutdownUncertain || this.isStopping || !!this.stopOperation; }
445
- isBusy() {
446
- if (this.retainedAbort || this.abortOperation || this.hasUncertainShutdown() || this.scheduleCleanupHost)
622
+ isBusy() { return !!this.modelChange || this.isWorkBusy(); }
623
+ isWorkBusy() {
624
+ if (this.scheduleRestoring || this.retainedAbort || this.abortOperation || this.hasUncertainShutdown() || this.scheduleCleanupHost
625
+ || this.scheduleRestart && this.claudeProcess === this.scheduleRestart.child)
447
626
  return true;
448
627
  if (this.sessionSchedules?.busy)
449
628
  return true;
@@ -732,8 +911,12 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
732
911
  // Use 'close' event (fires after all I/O streams are closed, i.e. after all stdout
733
912
  // data events have been processed) instead of 'exit' for command completion logic.
734
913
  child.on('close', (code, signal) => {
914
+ const restart = this.scheduleRestart;
915
+ const released = restart?.child === child && restart.endRequested && restart.epoch === this.stopEpoch && code === 0 && !signal;
735
916
  if (this.claudeProcess === child) {
736
- this.sessionSchedules?.processClosed();
917
+ if (restart?.child === child)
918
+ restart.exit = { code, signal };
919
+ this.sessionSchedules?.processClosed(!!released);
737
920
  this.sessionSchedules = undefined;
738
921
  this.scheduleHooksReady = false;
739
922
  }
@@ -742,11 +925,13 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
742
925
  flushStderr();
743
926
  this.clearApprovals('Claude process exited');
744
927
  this.rejectPendingControlRequests('Claude process exited before control response');
928
+ this.modelChange = undefined;
929
+ this.acknowledgedModel = undefined;
745
930
  this.clearCatalogCache();
746
931
  this.claudeProcess = null;
747
932
  this.turnLedger.retire();
748
933
  // Check if this was an intentional stop (abort/reset)
749
- const wasIntentionalStop = this.isStopping;
934
+ const wasIntentionalStop = this.isStopping || !!released;
750
935
  this.isStopping = false; // Reset the flag
751
936
  // Reject current command if any (only for unexpected exits)
752
937
  if (this.currentCommandReject && !wasIntentionalStop) {
@@ -924,6 +1109,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
924
1109
  if (this.claudeProcess === child) {
925
1110
  this.claudeProcess = null;
926
1111
  this.turnLedger.retire();
1112
+ this.modelChange = undefined;
1113
+ this.acknowledgedModel = undefined;
927
1114
  }
928
1115
  this.isStopping = false;
929
1116
  console.log('[ClaudePersistent] Process stopped');
@@ -1298,7 +1485,9 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1298
1485
  pending.resolve(response ?? {});
1299
1486
  }
1300
1487
  else {
1301
- pending.reject(new Error(error || `Claude control request failed with status: ${subtype}`));
1488
+ pending.reject(Object.assign(new Error(error || `Claude control request failed with status: ${subtype}`), {
1489
+ nativeCode: message.response.error_code, nativeModel: message.response.model,
1490
+ }));
1302
1491
  }
1303
1492
  }
1304
1493
  rejectPendingControlRequests(reason) {
@@ -1411,7 +1600,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1411
1600
  break;
1412
1601
  case 'system':
1413
1602
  // System messages (e.g., init)
1414
- if (message.subtype === 'init' && typeof message.model === 'string' && message.model.trim()) {
1603
+ if (message.subtype === 'init' && !this.acknowledgedModel && typeof message.model === 'string' && message.model.trim()) {
1415
1604
  this.reportedModel = message.model;
1416
1605
  }
1417
1606
  if (message.subtype === 'init' && message.session_id) {
@@ -1504,7 +1693,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1504
1693
  }
1505
1694
  break;
1506
1695
  case 'assistant':
1507
- if (!message.parent_tool_use_id && typeof message.message?.model === 'string' && message.message.model.trim()) {
1696
+ if (!message.parent_tool_use_id && typeof message.message?.model === 'string' && message.message.model.trim()
1697
+ && (!this.acknowledgedModel || (this.isProcessing && this.turnLedger.foreground !== this.modelSelectionForeground))) {
1508
1698
  this.reportedModel = message.message.model;
1509
1699
  }
1510
1700
  // Assistant messages contain the actual response content
@@ -1896,7 +2086,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1896
2086
  */
1897
2087
  async processQueue() {
1898
2088
  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) {
2089
+ if (this.isDestroyed || this.modelChange || ((this.abortOperation || this.retainedAbort) && !cleanup) || this.hasUncertainShutdown() || this.isProcessing || this.isStarting || this.sessionSchedules?.busy || this.commandQueue.length === 0) {
1900
2090
  return;
1901
2091
  }
1902
2092
  if (this.turnLedger.supported(this.claudeProcess?.pid) && this.turnLedger.foreground
@@ -1956,7 +2146,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1956
2146
  this.isStarting = false;
1957
2147
  }
1958
2148
  }
1959
- if (epoch !== this.commandEpoch || ((this.abortOperation || this.retainedAbort) && !cleanup) || this.hasUncertainShutdown() || this.sessionSchedules?.busy)
2149
+ if (epoch !== this.commandEpoch || this.modelChange || ((this.abortOperation || this.retainedAbort) && !cleanup) || this.hasUncertainShutdown() || this.sessionSchedules?.busy)
1960
2150
  return;
1961
2151
  const command = this.commandQueue.shift();
1962
2152
  if (!command) {
@@ -2070,6 +2260,10 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2070
2260
  async execute(prompt, options = {}) {
2071
2261
  if (this.isDestroyed)
2072
2262
  return { success: false, error: 'Executor has been destroyed' };
2263
+ if ((this.scheduleRestart || this.scheduleRestoring) && !(options.nativeScheduleManagement && options.nativeScheduleCurrent?.()))
2264
+ return { success: false, error: 'Native schedule handoff or restoration is pending.' };
2265
+ if (this.modelChange)
2266
+ 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
2267
  if (((this.abortOperation || this.retainedAbort) && !(this.cleanupAdmission() && options.nativeScheduleManagement && options.nativeScheduleCurrent?.()))
2074
2268
  || this.hasUncertainShutdown() || (this.scheduleCleanupHost && !options.nativeScheduleManagement)) {
2075
2269
  return { success: false, error: 'Native cleanup is still pending. Retry after cleanup.' };
@@ -2106,6 +2300,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2106
2300
  return operation;
2107
2301
  }
2108
2302
  async abortCurrent() {
2303
+ if (this.modelChange)
2304
+ 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
2305
  if (this.retainedAbort || (this.preservesProcessOnAbort() && (this.isProcessing || this.isWaitingInput() || this.sessionSchedules?.hasPendingMutation))) {
2110
2306
  return this.interruptForeground();
2111
2307
  }
@@ -2308,6 +2504,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2308
2504
  await this.stopProcess();
2309
2505
  this.retainedAbort = undefined;
2310
2506
  this.shutdownUncertain = false;
2507
+ this.scheduleRestart = undefined;
2508
+ this.scheduleRestoring = undefined;
2311
2509
  }
2312
2510
  /**
2313
2511
  * Reset execution context
@@ -2318,6 +2516,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2318
2516
  * prompts interrupted during startup are not replayed into the fresh context.
2319
2517
  */
2320
2518
  resetContext() {
2519
+ this.scheduleRestart = undefined;
2520
+ this.scheduleRestoring = undefined;
2321
2521
  this.cancelInputWaiters();
2322
2522
  this.nativeCreationEpoch++;
2323
2523
  console.log('[ClaudePersistent] Resetting session context');
@@ -2336,53 +2536,148 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2336
2536
  // so clearing it in memory is not enough. The process must be restarted fresh.
2337
2537
  this.stopProcess().catch((err) => console.error('[ClaudePersistent] Failed to stop process on reset:', err));
2338
2538
  }
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
- */
2539
+ /** Switch only the session selection. Never recycle a live host to change a model. */
2345
2540
  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' };
2541
+ return this.changeModel(model);
2542
+ }
2543
+ async clearModel() {
2544
+ const result = await this.changeModel(undefined);
2545
+ if (!result.success)
2546
+ throw new Error(result.error);
2547
+ }
2548
+ async changeModel(model) {
2549
+ const failure = (error) => ({ success: false, error });
2550
+ if (this.isDestroyed)
2551
+ return failure('Executor has been destroyed');
2552
+ if (model !== undefined && (!model.trim() || model.length > 512 || /[\x00-\x1f\x7f]/.test(model)))
2553
+ return failure('Invalid model identifier.');
2554
+ if (this.isWorkBusy() || (this.modelChange && !this.modelChange.retryable) || this.sessionSchedules?.hasPendingMutation) {
2555
+ return failure('Cannot change model while Claude work or a model change is pending.');
2556
+ }
2557
+ const validateEffort = () => {
2558
+ if (!this.effort)
2559
+ return;
2560
+ const entry = this.cachedRawEntries?.find(e => e.value === (model ?? 'default') || (model !== undefined && e.resolvedModel === model));
2561
+ if (!entry)
2562
+ return 'Cannot validate the saved reasoning effort. Reset /effort auto before changing models.';
2563
+ if (!entry.supportsEffort || !entry.supportedEffortLevels?.includes(this.effort)) {
2564
+ return 'The saved reasoning effort is incompatible with this model. Reset /effort auto before changing models.';
2565
+ }
2566
+ };
2567
+ const child = this.claudeProcess;
2568
+ if (!child) {
2569
+ // Cold preferences never start a model process just to validate or change a setting.
2570
+ const error = validateEffort();
2571
+ if (error)
2572
+ return failure(error);
2573
+ this.model = model;
2574
+ this.reportedModel = undefined;
2575
+ this.acknowledgedModel = undefined;
2576
+ return { success: true, output: model === undefined ? 'Model restored to default.' : `Model set to ${model}.` };
2577
+ }
2578
+ const previous = this.modelChange;
2579
+ const operation = { child, epoch: this.stopEpoch, session: this.sessionId, retryable: false };
2580
+ this.modelChange = operation;
2581
+ const current = (initialized = true) => this.modelChange === operation && this.claudeProcess === child
2582
+ && this.stopEpoch === operation.epoch && this.sessionId === operation.session && !this.turnLedger.invalid
2583
+ && (!initialized || (this.turnLedger.pid === child.pid && this.turnLedger.version === '2.1.311'))
2584
+ && (!this.turnLedger.session || this.turnLedger.session === operation.session) && !this.isDestroyed && !this.hasUncertainShutdown();
2585
+ try {
2586
+ await this.listModels();
2587
+ if (!current(false))
2588
+ throw new Error('Native model host changed before the request.');
2589
+ // The public SDK supports set_model, but receipt/error semantics below have
2590
+ // only been inspected for this build. No process-stop fallback on other hosts.
2591
+ if (process.platform !== 'linux' || process.arch !== 'x64' || this.turnLedger.version !== '2.1.311'
2592
+ || !child.pid || this.turnLedger.pid !== child.pid || !child.stdin?.writable || child.killed) {
2593
+ throw new Error('In-process model changes require the inspected Linux x64 Claude 2.1.311 host. The current host and schedules were retained.');
2594
+ }
2595
+ const error = validateEffort();
2596
+ if (error)
2597
+ throw new Error(error);
2351
2598
  }
2352
- if (this.effort && !this.cachedRawEntries) {
2599
+ catch (error) {
2600
+ if (this.modelChange === operation)
2601
+ this.modelChange = previous;
2602
+ return failure(error instanceof Error ? error.message : 'Cannot prepare native model change.');
2603
+ }
2604
+ return new Promise(resolve => {
2605
+ const requestId = `model-${(0, crypto_1.randomUUID)()}`;
2606
+ let returned = false;
2607
+ const finish = (result) => { if (!returned) {
2608
+ returned = true;
2609
+ resolve(result);
2610
+ } };
2611
+ const uncertain = (reason, retryable = false) => {
2612
+ if (this.modelChange === operation)
2613
+ operation.retryable = retryable;
2614
+ 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.`));
2615
+ };
2616
+ const validModel = (value) => typeof value === 'string' && value.trim().length > 0
2617
+ && value.length <= 512 && !/[\x00-\x1f\x7f]/.test(value);
2618
+ // Keep the correlated receiver after the user-facing deadline. A late ACK
2619
+ // can settle admission, but must never save a preference or emit success.
2620
+ const timer = setTimeout(() => uncertain('Native model change timed out after 10000ms.'), 10_000);
2621
+ this.pendingControlRequests.set(requestId, {
2622
+ timer,
2623
+ resolve: response => {
2624
+ if (!current()) {
2625
+ uncertain('Native model host changed before acknowledgement.');
2626
+ return;
2627
+ }
2628
+ const selected = response?.model;
2629
+ if (!validModel(selected)) {
2630
+ uncertain('Native model acknowledgement omitted a valid selection.', true);
2631
+ return;
2632
+ }
2633
+ this.recordModelSelection(selected);
2634
+ if (!returned)
2635
+ this.model = model;
2636
+ this.modelChange = undefined;
2637
+ finish({ success: true, output: model === undefined ? 'Model restored to default.' : `Model set to ${model}.` });
2638
+ void this.processQueue();
2639
+ },
2640
+ reject: error => {
2641
+ if (!current()) {
2642
+ uncertain('Native model host changed before acknowledgement.');
2643
+ return;
2644
+ }
2645
+ const { nativeCode, nativeModel } = error;
2646
+ // A terminal response may report a changed selection even on failure.
2647
+ // verdict_pending is explicitly not a refusal and may still apply later.
2648
+ if (nativeCode !== 'verdict_pending' && validModel(nativeModel)) {
2649
+ this.recordModelSelection(nativeModel);
2650
+ }
2651
+ const refused = ['invalid_request', 'catalog_unknown', 'not_found', 'restricted_by_org', 'unavailable_for_account',
2652
+ 'not_offered', 'alias_1m_disabled', 'alias_1m_unsupported', 'blocked_by_hook', 'check_failed',
2653
+ 'check_rejected', 'credits_required', 'rate_limit', 'auth_failed', 'model_not_current'].includes(nativeCode ?? '');
2654
+ if (refused && validModel(nativeModel)) {
2655
+ this.modelChange = undefined;
2656
+ finish(failure(`Native model change refused (${nativeCode}); no preference was saved.`));
2657
+ void this.processQueue();
2658
+ }
2659
+ else
2660
+ uncertain('Native model change did not return a confirmed outcome.', nativeCode === 'internal_error');
2661
+ },
2662
+ });
2353
2663
  try {
2354
- await this.listModels();
2664
+ child.stdin.write(JSON.stringify({ type: 'control_request', request_id: requestId,
2665
+ request: { subtype: 'set_model', ...(model === undefined ? {} : { model }) } }) + '\n', error => {
2666
+ if (error && this.pendingControlRequests.has(requestId))
2667
+ uncertain('Native model request write failed.');
2668
+ });
2355
2669
  }
2356
2670
  catch {
2357
- return { success: false, error: 'Cannot validate the saved reasoning effort. Reset /effort auto before changing models.' };
2671
+ uncertain('Native model request write failed.');
2358
2672
  }
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.' };
2367
- }
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
- };
2673
+ });
2376
2674
  }
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;
2675
+ recordModelSelection(model) {
2676
+ this.acknowledgedModel = model;
2677
+ this.modelSelectionForeground = this.turnLedger.foreground;
2678
+ // Old in-flight responses cannot shadow a newly acknowledged session selection.
2679
+ // A later foreground can report the actual served model (including fallback).
2384
2680
  this.reportedModel = undefined;
2385
- await this.stopProcess();
2386
2681
  }
2387
2682
  /**
2388
2683
  * Query models available to the authenticated Claude backend using native control initialization.
@@ -2393,7 +2688,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2393
2688
  throw new Error('Executor has been destroyed');
2394
2689
  }
2395
2690
  if (this.cachedModelCatalog) {
2396
- return (0, ClaudeSettings_1.parseClaudeModelsCatalog)(this.cachedRawEntries, this.reportedModel || this.model).models;
2691
+ return (0, ClaudeSettings_1.parseClaudeModelsCatalog)(this.cachedRawEntries, this.reportedModel || this.acknowledgedModel || this.model).models;
2397
2692
  }
2398
2693
  if (this.catalogInitPromise) {
2399
2694
  return this.catalogInitPromise;
@@ -2449,7 +2744,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2449
2744
  const rawResponse = response || {};
2450
2745
  this.turnLedger.version = typeof rawResponse.claude_code_version === 'string' ? rawResponse.claude_code_version : undefined;
2451
2746
  this.turnLedger.pid = typeof rawResponse.pid === 'number' ? rawResponse.pid : undefined;
2452
- const { models, rawEntries } = (0, ClaudeSettings_1.parseClaudeModelsCatalog)(rawResponse.models, this.reportedModel || this.model);
2747
+ const { models, rawEntries } = (0, ClaudeSettings_1.parseClaudeModelsCatalog)(rawResponse.models, this.reportedModel || this.acknowledgedModel || this.model);
2453
2748
  if (scheduleHooks && this.sessionId && this.delegation?.groups?.includes('scheduling')) {
2454
2749
  await this.readNativeScheduleTimezone();
2455
2750
  }
@@ -2519,7 +2814,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2519
2814
  unavailableReason: 'Reasoning effort is not supported for Claude Code.',
2520
2815
  };
2521
2816
  }
2522
- const activeModel = this.reportedModel || this.model;
2817
+ const activeModel = this.reportedModel || this.acknowledgedModel || this.model;
2523
2818
  return (0, ClaudeSettings_1.resolveClaudeEfforts)(this.cachedRawEntries, activeModel, this.effort);
2524
2819
  }
2525
2820
  /**
@@ -2534,6 +2829,9 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2534
2829
  if (this.isBusy()) {
2535
2830
  return { success: false, error: 'Cannot change reasoning effort while Claude is busy' };
2536
2831
  }
2832
+ if (this.sessionSchedules?.hasJobs || this.sessionSchedules?.hasPendingMutation) {
2833
+ 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.' };
2834
+ }
2537
2835
  const normalized = effort.trim().toLowerCase();
2538
2836
  if (normalized === 'auto' || normalized === '') {
2539
2837
  await this.stopProcess();
@@ -2566,6 +2864,10 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2566
2864
  error: `Unsupported reasoning effort: ${effort}. Supported values: auto, ${effortInfo.choices.map(c => c.value).join(', ')}.`,
2567
2865
  };
2568
2866
  }
2867
+ // Catalog lookup yields: a schedule or settings request may have arrived.
2868
+ if (this.isBusy() || this.sessionSchedules?.hasJobs || this.sessionSchedules?.hasPendingMutation) {
2869
+ return { success: false, error: 'Claude work or native schedules arrived while checking effort. Retry after explicitly retiring schedules.' };
2870
+ }
2569
2871
  await this.stopProcess();
2570
2872
  this.effort = match.value;
2571
2873
  return {
@@ -2579,6 +2881,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2579
2881
  * Returns a promise that resolves when compaction is complete.
2580
2882
  */
2581
2883
  compact(onStream) {
2884
+ if (this.modelChange)
2885
+ return Promise.resolve({ success: false, error: 'Native model change is pending or unconfirmed.' });
2582
2886
  if (this.retainedAbort || this.abortOperation)
2583
2887
  return Promise.resolve({ success: false, error: 'Native cancellation cleanup is pending.' });
2584
2888
  console.log('[ClaudePersistent] Sending /compact slash command');