@yu_robotics/remote-cli 1.6.236 → 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 (72) 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 +266 -34
  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 +52 -12
  13. package/dist/executor/ClaudePersistentExecutor.d.ts.map +1 -1
  14. package/dist/executor/ClaudePersistentExecutor.js +795 -123
  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 +14 -0
  21. package/dist/executor/IExecutor.d.ts.map +1 -1
  22. package/dist/executor/claude/TurnLedger.d.ts +33 -0
  23. package/dist/executor/claude/TurnLedger.d.ts.map +1 -0
  24. package/dist/executor/claude/TurnLedger.js +126 -0
  25. package/dist/executor/claude/TurnLedger.js.map +1 -0
  26. package/dist/maintenance/release-notes.json +1 -1
  27. package/dist/managed/ManagedToolBridge.d.ts +4 -1
  28. package/dist/managed/ManagedToolBridge.d.ts.map +1 -1
  29. package/dist/managed/ManagedToolBridge.js +17 -2
  30. package/dist/managed/ManagedToolBridge.js.map +1 -1
  31. package/dist/scheduling/ScheduleCapabilities.d.ts +1 -1
  32. package/dist/scheduling/ScheduleCapabilities.d.ts.map +1 -1
  33. package/dist/scheduling/ScheduleCapabilities.js +3 -2
  34. package/dist/scheduling/ScheduleCapabilities.js.map +1 -1
  35. package/dist/scheduling/ScheduleService.d.ts +28 -0
  36. package/dist/scheduling/ScheduleService.d.ts.map +1 -1
  37. package/dist/scheduling/ScheduleService.js +562 -17
  38. package/dist/scheduling/ScheduleService.js.map +1 -1
  39. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts +28 -2
  40. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts.map +1 -1
  41. package/dist/scheduling/claude/ClaudeSessionSchedules.js +158 -18
  42. package/dist/scheduling/claude/ClaudeSessionSchedules.js.map +1 -1
  43. package/dist/scheduling/dsh/SessionScheduleBridge.d.ts.map +1 -1
  44. package/dist/scheduling/dsh/SessionScheduleBridge.js +21 -0
  45. package/dist/scheduling/dsh/SessionScheduleBridge.js.map +1 -1
  46. package/dist/scheduling/dsh/SessionScheduleClient.d.ts.map +1 -1
  47. package/dist/scheduling/dsh/SessionScheduleClient.js +8 -0
  48. package/dist/scheduling/dsh/SessionScheduleClient.js.map +1 -1
  49. package/dist/scheduling/types.d.ts +84 -0
  50. package/dist/scheduling/types.d.ts.map +1 -1
  51. package/dist/scheduling/types.js.map +1 -1
  52. package/dist/settings/SettingsService.d.ts +1 -1
  53. package/dist/settings/SettingsService.d.ts.map +1 -1
  54. package/dist/settings/SettingsService.js +3 -3
  55. package/dist/settings/SettingsService.js.map +1 -1
  56. package/dist/thread/ThreadExecutorPool.d.ts +1 -1
  57. package/dist/thread/ThreadExecutorPool.d.ts.map +1 -1
  58. package/dist/thread/ThreadExecutorPool.js +5 -3
  59. package/dist/thread/ThreadExecutorPool.js.map +1 -1
  60. package/dist/update/AutomaticUpdater.d.ts +2 -1
  61. package/dist/update/AutomaticUpdater.d.ts.map +1 -1
  62. package/dist/update/AutomaticUpdater.js +11 -3
  63. package/dist/update/AutomaticUpdater.js.map +1 -1
  64. package/native/prebuilds/darwin-arm64/managed_native.node +0 -0
  65. package/native/prebuilds/darwin-arm64/manifest.json +1 -1
  66. package/native/prebuilds/darwin-x64/managed_native.node +0 -0
  67. package/native/prebuilds/darwin-x64/manifest.json +1 -1
  68. package/native/prebuilds/win32-arm64/managed_native.node +0 -0
  69. package/native/prebuilds/win32-arm64/manifest.json +1 -1
  70. package/native/prebuilds/win32-x64/managed_native.node +0 -0
  71. package/native/prebuilds/win32-x64/manifest.json +1 -1
  72. package/package.json +1 -1
@@ -5,6 +5,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.ClaudePersistentExecutor = void 0;
7
7
  const ClaudeSessionSchedules_1 = require("../scheduling/claude/ClaudeSessionSchedules");
8
+ const TurnLedger_1 = require("./claude/TurnLedger");
9
+ const types_1 = require("../scheduling/types");
8
10
  const tools_1 = require("../managed/tools");
9
11
  const ManagedSpawn_1 = require("./ManagedSpawn");
10
12
  const OwnershipRuntime_1 = require("../delegation/OwnershipRuntime");
@@ -61,6 +63,14 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
61
63
  model;
62
64
  effort;
63
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
+ }
64
74
  // Native control catalog cache & control request state
65
75
  cachedModelCatalog = null;
66
76
  cachedRawEntries = null;
@@ -70,6 +80,27 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
70
80
  claudeProcess = null;
71
81
  workerGroups = new ManagedProcessGroups_1.ManagedProcessGroups();
72
82
  isStarting = false;
83
+ startup;
84
+ stopOperation;
85
+ stopEpoch = 0;
86
+ destruction;
87
+ abortOperation;
88
+ shutdownUncertain = false;
89
+ commandEpoch = 0;
90
+ scheduleCleanupHost;
91
+ turnLedger = new TurnLedger_1.TurnLedger();
92
+ retainedAbort;
93
+ lastAbortMessage;
94
+ cleanupAdmission() {
95
+ return !!this.retainedAbort?.lease && this.scheduleCleanupHost === this.retainedAbort.child
96
+ && this.claudeProcess === this.retainedAbort.child && !this.isStopping && !this.isDestroyed;
97
+ }
98
+ preservesProcessOnAbort() {
99
+ return !!this.retainedAbort || (this.turnLedger.invalid && !!this.sessionSchedules?.hasJobs) || (!this.delegationWorker && !this.isStarting && !this.hasUncertainShutdown()
100
+ && this.turnLedger.supported(this.claudeProcess?.pid));
101
+ }
102
+ abortStatusMessage() { return this.lastAbortMessage; }
103
+ hasPendingCancellation() { return !!this.retainedAbort; }
73
104
  isStopping = false; // Flag to indicate intentional process stop
74
105
  isSessionError = false; // Flag to suppress auto-restart on session-not-found errors
75
106
  sessionResumeFailure = false;
@@ -103,7 +134,16 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
103
134
  currentTaskStartTime = 0;
104
135
  // Interactive input handling
105
136
  isWaitingForInput = false;
106
- inputRequestCallbacks = [];
137
+ inputGeneration = 0;
138
+ inputWaiters = new Set();
139
+ cancelInputWaiters() {
140
+ this.inputGeneration++;
141
+ clearTimeout(this.inputDetectionTimer);
142
+ this.inputDetectionTimer = undefined;
143
+ for (const waiter of [...this.inputWaiters])
144
+ waiter.finish(null);
145
+ this.isWaitingForInput = false;
146
+ }
107
147
  inputDetectionTimer;
108
148
  lastOutputTime = 0;
109
149
  // Sandbox and approval state
@@ -254,7 +294,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
254
294
  getExecutionMetadata() {
255
295
  let effectiveEffort = this.effort;
256
296
  if (this.effort && this.cachedRawEntries) {
257
- const activeModel = this.reportedModel || this.model;
297
+ const activeModel = this.reportedModel || this.acknowledgedModel || this.model;
258
298
  const entry = activeModel
259
299
  ? this.cachedRawEntries.find(e => e.value === activeModel || (e.resolvedModel !== undefined && e.resolvedModel === activeModel))
260
300
  : this.cachedRawEntries.find(e => e.value === 'default');
@@ -266,12 +306,174 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
266
306
  if (!effectiveEffort) {
267
307
  data.effortSource = 'unknown';
268
308
  }
269
- if (this.isProcessRunning() && this.reportedModel) {
270
- data.model = this.reportedModel;
309
+ if (this.isProcessRunning() && (this.acknowledgedModel || this.reportedModel)) {
310
+ data.model = this.reportedModel || this.acknowledgedModel;
271
311
  data.modelSource = 'reported';
272
312
  }
313
+ if (this.modelChange) {
314
+ data.model = undefined;
315
+ data.modelSource = 'unknown';
316
+ }
273
317
  return data;
274
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
+ }
275
477
  sessionSchedules;
276
478
  scheduleHooksReady = false;
277
479
  currentScheduleManagement = false;
@@ -284,30 +486,61 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
284
486
  this.claudeProcess.stdin.write(JSON.stringify(frame) + '\n');
285
487
  },
286
488
  manage: async (prompt, current) => {
287
- await this.listModels();
489
+ if (this.scheduleCleanupHost) {
490
+ if (!current() || this.claudeProcess !== this.scheduleCleanupHost || this.isStopping || (this.abortOperation && !this.cleanupAdmission())) {
491
+ throw new Error('Native cleanup admission expired; retry explicit schedule cancellation.');
492
+ }
493
+ }
494
+ else
495
+ await this.listModels();
288
496
  return this.execute(prompt, { nativeScheduleManagement: true, nativeScheduleCurrent: current });
289
497
  },
290
- wake: () => { void this.processQueue(); },
498
+ wake: () => { this.turnLedger.changed(); void this.processQueue(); },
291
499
  });
292
500
  }
293
501
  async withNativeScheduleOperation(id, current, run, inTurn) {
294
- if (this.delegationWorker || this.isDestroyed || this.isStopping || this.sandbox.isRestricted())
502
+ if (this.modelChange || this.retainedAbort || this.delegationWorker || this.isDestroyed || this.isStopping || this.sandbox.isRestricted())
295
503
  throw new Error('Native schedule owner or sandbox is unavailable.');
296
504
  if (!inTurn)
297
505
  await this.listModels();
506
+ if (this.modelChange)
507
+ throw new Error('Native model change is pending or unconfirmed.');
298
508
  if (!this.scheduleHooksReady)
299
509
  throw new Error('Native scheduling hooks are not initialized.');
300
510
  return this.schedules().inToolOperation(id, current, run, inTurn);
301
511
  }
512
+ async reconcileNativeSchedule(id, current, run) {
513
+ if (!current() || this.isDestroyed || this.hasUncertainShutdown() || this.abortOperation
514
+ || this.isBusy() || this.scheduleCleanupHost) {
515
+ throw new Error(`Schedule ${id} cleanup is pending; retry explicit cancellation when the native session is idle.`);
516
+ }
517
+ // A confirmed close already retired the old handle. Never initialize a replacement host here.
518
+ if (!this.claudeProcess)
519
+ return run();
520
+ if (!this.sessionSchedules || !this.scheduleHooksReady)
521
+ throw new Error('Native cleanup ownership is unavailable.');
522
+ const child = this.claudeProcess;
523
+ this.scheduleCleanupHost = child;
524
+ try {
525
+ return await this.sessionSchedules.inToolOperation(id, () => current() && this.claudeProcess === child && !this.isStopping && !this.abortOperation, run, false);
526
+ }
527
+ finally {
528
+ this.scheduleCleanupHost = undefined;
529
+ }
530
+ }
302
531
  nativeScheduleAction(id) { return this.sessionSchedules?.action(id); }
303
532
  async createNativeSchedule(input, onEvent, isOwnerCurrent) {
304
- 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()
305
534
  || input.cwd !== this.currentWorkingDirectory)
306
535
  throw new Error('Native schedule context or sandbox is unavailable.');
307
536
  if (!this.scheduleHooksReady)
308
537
  throw new Error('Native scheduling hooks are not initialized.');
309
538
  const timezone = await this.readNativeScheduleTimezone();
310
- 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);
311
544
  }
312
545
  /** Inspect only the effective TZ; never log, retain, or expose settings to a model. */
313
546
  readNativeScheduleTimezone() {
@@ -373,7 +606,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
373
606
  async configureDelegation(connection) {
374
607
  if ((0, contract_1.sameConnection)(this.delegation, connection))
375
608
  return;
376
- if (this.isProcessing || this.isStarting || this.commandQueue.length)
609
+ if (this.isBusy())
377
610
  throw new Error('Cannot change delegation while Claude is busy');
378
611
  await this.stopProcess();
379
612
  this.delegation = connection;
@@ -385,7 +618,12 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
385
618
  * the previous session. This prevents session conflicts when switching between
386
619
  * directories that may have their own .claude-session files.
387
620
  */
388
- isBusy() {
621
+ hasUncertainShutdown() { return this.shutdownUncertain || this.isStopping || !!this.stopOperation; }
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)
626
+ return true;
389
627
  if (this.sessionSchedules?.busy)
390
628
  return true;
391
629
  return this.isProcessing || this.isStarting || this.commandQueue.length > 0;
@@ -422,14 +660,24 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
422
660
  this.nativeObserver = observer;
423
661
  this.nativeCaptureFailure = onFailure;
424
662
  }
425
- async startProcess() {
426
- if (this.isDestroyed || (this.isStopping && this.claudeProcess))
663
+ startProcess() {
664
+ if (this.startup)
665
+ return this.startup;
666
+ const startup = this.startProcessImpl();
667
+ this.startup = startup;
668
+ void startup.finally(() => { if (this.startup === startup)
669
+ this.startup = undefined; }).catch(() => { });
670
+ return startup;
671
+ }
672
+ async startProcessImpl() {
673
+ if (this.isDestroyed || this.abortOperation || this.retainedAbort || this.hasUncertainShutdown())
427
674
  throw new Error('Claude process is unavailable or its exit is unconfirmed');
428
675
  if (this.claudeProcess || this.isStarting) {
429
676
  return;
430
677
  }
431
678
  this.isStarting = true;
432
679
  const creationEpoch = this.nativeCreationEpoch;
680
+ const stopEpoch = this.stopEpoch;
433
681
  this.reportedModel = undefined;
434
682
  try {
435
683
  (0, WorkingDirectory_1.assertWorkingDirectoryExists)(this.currentWorkingDirectory);
@@ -561,6 +809,10 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
561
809
  ? '[redacted configuration]' : arg);
562
810
  console.log(`[ClaudePersistent] Starting: ${this.claudeCommand} ${loggedArgs.join(' ')}`);
563
811
  console.log(`[ClaudePersistent] Working directory: ${this.currentWorkingDirectory}`);
812
+ // Startup may have awaited approval-channel setup while abort retired its queue.
813
+ if (this.isDestroyed || this.abortOperation || this.hasUncertainShutdown() || stopEpoch !== this.stopEpoch) {
814
+ throw new Error('Claude startup was cancelled before process creation');
815
+ }
564
816
  // Spawn the process
565
817
  const child = (0, ManagedSpawn_1.spawnManaged)(this.delegationWorker, this.claudeCommand, args, {
566
818
  ...(this.delegationWorker && process.platform !== 'win32' ? { detached: true } : {}),
@@ -575,6 +827,14 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
575
827
  },
576
828
  });
577
829
  this.claudeProcess = child;
830
+ this.turnLedger = new TurnLedger_1.TurnLedger();
831
+ child.stdin?.on?.('error', () => {
832
+ if (this.claudeProcess !== child)
833
+ return;
834
+ this.turnLedger.invalid = true;
835
+ this.rejectPendingControlRequests('Native input transport failed; cancellation remains unconfirmed.');
836
+ this.turnLedger.changed();
837
+ });
578
838
  this.nativeScheduleTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
579
839
  if (this.delegation?.groups?.includes('scheduling') && !this.delegationWorker && !restricted)
580
840
  this.schedules();
@@ -587,6 +847,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
587
847
  // Handle stdout (JSON stream)
588
848
  let buffer = '';
589
849
  child.stdout?.on('data', (data) => {
850
+ if (this.claudeProcess !== child)
851
+ return;
590
852
  buffer += data.toString();
591
853
  // Process complete JSON lines
592
854
  const lines = buffer.split('\n');
@@ -649,8 +911,12 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
649
911
  // Use 'close' event (fires after all I/O streams are closed, i.e. after all stdout
650
912
  // data events have been processed) instead of 'exit' for command completion logic.
651
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;
652
916
  if (this.claudeProcess === child) {
653
- this.sessionSchedules?.processClosed();
917
+ if (restart?.child === child)
918
+ restart.exit = { code, signal };
919
+ this.sessionSchedules?.processClosed(!!released);
654
920
  this.sessionSchedules = undefined;
655
921
  this.scheduleHooksReady = false;
656
922
  }
@@ -659,10 +925,13 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
659
925
  flushStderr();
660
926
  this.clearApprovals('Claude process exited');
661
927
  this.rejectPendingControlRequests('Claude process exited before control response');
928
+ this.modelChange = undefined;
929
+ this.acknowledgedModel = undefined;
662
930
  this.clearCatalogCache();
663
931
  this.claudeProcess = null;
932
+ this.turnLedger.retire();
664
933
  // Check if this was an intentional stop (abort/reset)
665
- const wasIntentionalStop = this.isStopping;
934
+ const wasIntentionalStop = this.isStopping || !!released;
666
935
  this.isStopping = false; // Reset the flag
667
936
  // Reject current command if any (only for unexpected exits)
668
937
  if (this.currentCommandReject && !wasIntentionalStop) {
@@ -685,7 +954,11 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
685
954
  this.isSessionError = false; // Reset session error flag
686
955
  if (!this.isDestroyed && !wasIntentionalStop && !hasSessionError && this.commandQueue.length > 0) {
687
956
  console.log('[ClaudePersistent] Auto-restarting process...');
688
- setTimeout(() => this.startProcess(), 1000);
957
+ const epoch = this.commandEpoch;
958
+ setTimeout(() => {
959
+ if (epoch === this.commandEpoch && !this.abortOperation && !this.hasUncertainShutdown())
960
+ void this.startProcess().catch(() => { });
961
+ }, 1000);
689
962
  }
690
963
  else if (hasSessionError && this.commandQueue.length > 0) {
691
964
  // Session is invalid - drain the queue with a friendly error rather than restarting
@@ -720,7 +993,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
720
993
  }, 1000);
721
994
  });
722
995
  if (earlyError) {
723
- this.claudeProcess = null;
996
+ if (this.claudeProcess === child)
997
+ this.claudeProcess = null;
724
998
  this.isStarting = false;
725
999
  const err = earlyError;
726
1000
  if (err.message.includes('ENOENT') || err.code === 'ENOENT') {
@@ -728,6 +1002,12 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
728
1002
  }
729
1003
  throw err;
730
1004
  }
1005
+ // A stop may finish while the startup readiness wait is still settling.
1006
+ // Do not attach fresh callbacks or dispatch work on that retired child.
1007
+ if (this.isDestroyed || this.abortOperation || this.hasUncertainShutdown()
1008
+ || stopEpoch !== this.stopEpoch || this.claudeProcess !== child) {
1009
+ throw new Error('Claude startup was cancelled after process creation');
1010
+ }
731
1011
  if (this.filePolicyToken) {
732
1012
  try {
733
1013
  // SessionStart runs before stdin is consumed. Do not send a user task
@@ -745,7 +1025,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
745
1025
  this.clearApprovals('Claude process failed');
746
1026
  // An error is not exit evidence for a session that owns native jobs.
747
1027
  // Retain the process until close (or an explicit bounded stop) confirms it.
748
- if (this.sessionSchedules?.hasJobs)
1028
+ if (this.sessionSchedules?.hasJobs || this.retainedAbort)
749
1029
  this.isStopping = true;
750
1030
  else
751
1031
  this.claudeProcess = null;
@@ -778,19 +1058,38 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
778
1058
  /**
779
1059
  * Stop the persistent Claude process
780
1060
  */
781
- async stopProcess() {
1061
+ stopProcess() {
1062
+ if (this.stopOperation)
1063
+ return this.stopOperation;
1064
+ const child = this.claudeProcess;
1065
+ this.stopEpoch++;
1066
+ this.isStopping = true;
1067
+ // Publish the barrier before stdin.end can synchronously emit close or invoke
1068
+ // a processExit listener. All callers join this captured child's stop.
1069
+ let resolve;
1070
+ let reject;
1071
+ const operation = new Promise((done, fail) => { resolve = done; reject = fail; });
1072
+ this.stopOperation = operation;
1073
+ void operation.finally(() => {
1074
+ if (this.stopOperation === operation)
1075
+ this.stopOperation = undefined;
1076
+ }).catch(() => { });
1077
+ void this.stopCapturedProcess(child).then(resolve, reject);
1078
+ return operation;
1079
+ }
1080
+ async stopCapturedProcess(child) {
782
1081
  this.filePolicyToken = undefined;
783
1082
  this.filePolicyRoots = [];
784
1083
  this.filePolicyStarted = false;
785
1084
  this.clearApprovals('Claude process stopped');
786
1085
  this.rejectPendingControlRequests('Claude process stopped before control response');
787
1086
  this.clearCatalogCache();
788
- if (!this.claudeProcess) {
1087
+ if (!child) {
1088
+ this.isStopping = false;
789
1089
  return;
790
1090
  }
791
1091
  console.log('[ClaudePersistent] Stopping process...');
792
1092
  this.isStopping = true;
793
- const child = this.claudeProcess;
794
1093
  // A signal is not evidence of exit. Bound the wait and retain the child on
795
1094
  // failure so the caller cannot silently launch a replacement over it.
796
1095
  await new Promise((resolve, reject) => {
@@ -807,8 +1106,12 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
807
1106
  child.kill('SIGTERM');
808
1107
  }
809
1108
  });
810
- if (this.claudeProcess === child)
1109
+ if (this.claudeProcess === child) {
811
1110
  this.claudeProcess = null;
1111
+ this.turnLedger.retire();
1112
+ this.modelChange = undefined;
1113
+ this.acknowledgedModel = undefined;
1114
+ }
812
1115
  this.isStopping = false;
813
1116
  console.log('[ClaudePersistent] Process stopped');
814
1117
  }
@@ -1048,7 +1351,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1048
1351
  return this.sandbox.describe(this.currentWorkingDirectory);
1049
1352
  }
1050
1353
  async configureSandbox(command) {
1051
- if (this.isProcessing || this.commandQueue.length > 0) {
1354
+ if (this.isDestroyed || this.isBusy()) {
1052
1355
  return { success: false, error: 'Wait for the running task before changing sandbox settings.' };
1053
1356
  }
1054
1357
  try {
@@ -1182,7 +1485,9 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1182
1485
  pending.resolve(response ?? {});
1183
1486
  }
1184
1487
  else {
1185
- 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
+ }));
1186
1491
  }
1187
1492
  }
1188
1493
  rejectPendingControlRequests(reason) {
@@ -1204,16 +1509,45 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1204
1509
  try {
1205
1510
  // Parse message first to check type
1206
1511
  const parsedMessage = JSON.parse(line);
1512
+ this.turnLedger.observe(parsedMessage);
1513
+ const cancellation = this.retainedAbort;
1514
+ if (cancellation?.requestId && parsedMessage.type === 'control_response'
1515
+ && parsedMessage.response?.request_id === cancellation.requestId) {
1516
+ const receipt = parsedMessage.response.response;
1517
+ cancellation.ack = parsedMessage.response.subtype === 'success' && ['stopped', 'idle', 'spared'].includes(receipt?.turn ?? '');
1518
+ this.turnLedger.changed();
1519
+ }
1207
1520
  // Handle native Claude Control response packets (models catalog, etc.).
1208
1521
  // These bypass raw stdout logging to prevent any potential account/credential leakage.
1209
1522
  if (this.sessionSchedules?.accept(parsedMessage))
1210
1523
  return;
1524
+ if (this.turnLedger.supported(this.claudeProcess?.pid) && parsedMessage.type === 'result'
1525
+ && !parsedMessage.parent_tool_use_id && !this.turnLedger.joined(parsedMessage, this.turnLedger.foreground))
1526
+ return;
1211
1527
  if (parsedMessage.type === 'result' && !parsedMessage.parent_tool_use_id)
1212
1528
  this.sessionSchedules?.foregroundEnded();
1213
1529
  if (parsedMessage.type === 'control_response' || parsedMessage.type === 'control_request') {
1214
1530
  this.handleControlMessage(parsedMessage);
1215
1531
  return;
1216
1532
  }
1533
+ if (parsedMessage.type === 'command_lifecycle') {
1534
+ void this.processQueue();
1535
+ return;
1536
+ }
1537
+ // Keep native controls and schedule receipts alive, but retire old foreground display authority.
1538
+ if (cancellation && !this.cleanupAdmission()) {
1539
+ // A timed-out cleanup lease does not erase its in-flight native management turn.
1540
+ // Consume its matched terminal internally so an explicit retry can acquire the same host.
1541
+ if (parsedMessage.type === 'result' && this.currentScheduleManagement
1542
+ && this.turnLedger.joined(parsedMessage, this.turnLedger.foreground)) {
1543
+ this.completeCurrentCommand(!parsedMessage.is_error, 'Native cancellation management turn failed.');
1544
+ }
1545
+ return;
1546
+ }
1547
+ const lineage = parsedMessage;
1548
+ if (this.turnLedger.supported(this.claudeProcess?.pid) && (lineage.user_message_uuid || lineage.user_message_uuids?.length)
1549
+ && !this.turnLedger.joined(lineage, this.turnLedger.foreground))
1550
+ return;
1217
1551
  const nativeContent = parsedMessage.message?.content ?? parsedMessage.content;
1218
1552
  const containsToolResult = Array.isArray(nativeContent) && nativeContent.some(block => (block !== null && typeof block === 'object' && block.type === 'tool_result'));
1219
1553
  // Token deltas are noisy; tool results may contain private media or metadata.
@@ -1266,7 +1600,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1266
1600
  break;
1267
1601
  case 'system':
1268
1602
  // System messages (e.g., init)
1269
- 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()) {
1270
1604
  this.reportedModel = message.model;
1271
1605
  }
1272
1606
  if (message.subtype === 'init' && message.session_id) {
@@ -1359,7 +1693,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1359
1693
  }
1360
1694
  break;
1361
1695
  case 'assistant':
1362
- 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))) {
1363
1698
  this.reportedModel = message.message.model;
1364
1699
  }
1365
1700
  // Assistant messages contain the actual response content
@@ -1541,7 +1876,10 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1541
1876
  // Pause processing state
1542
1877
  this.isWaitingForInput = true;
1543
1878
  // Notify through hooks
1879
+ const generation = this.inputGeneration;
1544
1880
  const userInput = await this.requestInteractiveInput(lastLine);
1881
+ if (generation !== this.inputGeneration)
1882
+ return;
1545
1883
  if (userInput !== null) {
1546
1884
  this.sendInput(userInput);
1547
1885
  }
@@ -1589,17 +1927,18 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1589
1927
  else
1590
1928
  this.currentStreamCallback?.(`\n${prompt}\n`);
1591
1929
  // Wait for input via sendInput() or timeout
1930
+ const generation = this.inputGeneration;
1592
1931
  return new Promise((resolve) => {
1593
- const timeoutId = setTimeout(() => {
1594
- console.log('[ClaudePersistent] Input request timed out');
1595
- this.isWaitingForInput = false;
1596
- resolve(null);
1597
- }, 300000); // 5 minutes timeout
1598
- // Store callback to be called when sendInput is invoked
1599
- this.inputRequestCallbacks.push((input) => {
1600
- clearTimeout(timeoutId);
1601
- resolve(input);
1602
- });
1932
+ const waiter = { finish: (input) => {
1933
+ if (!this.inputWaiters.delete(waiter))
1934
+ return;
1935
+ clearTimeout(timer);
1936
+ if (generation === this.inputGeneration)
1937
+ this.isWaitingForInput = false;
1938
+ resolve(input);
1939
+ } };
1940
+ const timer = setTimeout(() => waiter.finish(null), 300000);
1941
+ this.inputWaiters.add(waiter);
1603
1942
  });
1604
1943
  }
1605
1944
  /**
@@ -1607,6 +1946,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1607
1946
  * This is called by MessageHandler when user sends a message while waiting for input
1608
1947
  */
1609
1948
  sendInput(input) {
1949
+ if (this.retainedAbort || this.abortOperation)
1950
+ return false;
1610
1951
  if (this.pendingApprovals.size > 0) {
1611
1952
  const match = /^(yes|y|approve|accept|no|n|deny|decline|cancel)(?:\s+(\S+))?$/i.exec(input.trim());
1612
1953
  const requestId = match?.[2] ?? (this.pendingApprovals.size === 1 ? this.pendingApprovals.keys().next().value : undefined);
@@ -1629,16 +1970,15 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1629
1970
  },
1630
1971
  };
1631
1972
  inputMessage.uuid = (0, crypto_1.randomUUID)();
1973
+ this.turnLedger.dispatched(inputMessage.uuid, true);
1632
1974
  this.sessionSchedules?.foregroundDispatched(inputMessage.uuid);
1633
1975
  const inputLine = JSON.stringify(inputMessage);
1634
1976
  console.log(`[ClaudePersistent] Sending user input: ${input}`);
1635
1977
  this.claudeProcess.stdin?.write(inputLine + '\n');
1636
1978
  this.isWaitingForInput = false;
1637
1979
  // Notify any waiting callbacks (for requestInteractiveInput)
1638
- for (const callback of this.inputRequestCallbacks) {
1639
- callback(input);
1640
- }
1641
- this.inputRequestCallbacks = [];
1980
+ for (const waiter of [...this.inputWaiters])
1981
+ waiter.finish(input);
1642
1982
  return true;
1643
1983
  }
1644
1984
  /**
@@ -1705,12 +2045,14 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1705
2045
  this.resetCurrentCommand();
1706
2046
  // Process next command in queue
1707
2047
  this.isProcessing = false;
2048
+ this.turnLedger.changed();
1708
2049
  this.processQueue();
1709
2050
  }
1710
2051
  /**
1711
2052
  * Reset current command state
1712
2053
  */
1713
2054
  resetCurrentCommand() {
2055
+ this.cancelInputWaiters();
1714
2056
  this.currentScheduleManagement = false;
1715
2057
  this.clearApprovals('Task is no longer active');
1716
2058
  this.currentOutputBuffer = [];
@@ -1743,15 +2085,28 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1743
2085
  * Process the command queue
1744
2086
  */
1745
2087
  async processQueue() {
1746
- if (this.isProcessing || this.isStarting || this.sessionSchedules?.busy || this.commandQueue.length === 0) {
2088
+ const cleanup = this.cleanupAdmission() && this.commandQueue[0]?.options.nativeScheduleManagement;
2089
+ if (this.isDestroyed || this.modelChange || ((this.abortOperation || this.retainedAbort) && !cleanup) || this.hasUncertainShutdown() || this.isProcessing || this.isStarting || this.sessionSchedules?.busy || this.commandQueue.length === 0) {
1747
2090
  return;
1748
2091
  }
2092
+ if (this.turnLedger.supported(this.claudeProcess?.pid) && this.turnLedger.foreground
2093
+ && !this.turnLedger.settled(this.turnLedger.foreground))
2094
+ return;
2095
+ const epoch = this.commandEpoch;
2096
+ // Expired management work must not start a replacement host.
2097
+ while (this.commandQueue[0]?.options.nativeScheduleCurrent && !this.commandQueue[0].options.nativeScheduleCurrent()) {
2098
+ this.commandQueue.shift().resolve({ success: false, error: 'Native schedule management authorization expired before dispatch.' });
2099
+ }
2100
+ if (!this.commandQueue.length)
2101
+ return;
1749
2102
  // Ensure process is running
1750
2103
  if (!this.claudeProcess) {
1751
2104
  try {
1752
2105
  await this.startProcess();
1753
2106
  }
1754
2107
  catch (error) {
2108
+ if (epoch !== this.commandEpoch)
2109
+ return;
1755
2110
  // Failed to start process (e.g., working directory doesn't exist)
1756
2111
  // Return error result to caller without crashing the process
1757
2112
  const errorMessage = error instanceof Error ? error.message : String(error);
@@ -1777,6 +2132,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1777
2132
  await this.listModels();
1778
2133
  }
1779
2134
  catch {
2135
+ if (epoch !== this.commandEpoch)
2136
+ return;
1780
2137
  const failed = this.commandQueue.shift();
1781
2138
  // A resumed native scheduler can fire before a later command. If hook
1782
2139
  // registration or policy validation failed, retire that process before
@@ -1789,7 +2146,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1789
2146
  this.isStarting = false;
1790
2147
  }
1791
2148
  }
1792
- if (this.sessionSchedules?.busy)
2149
+ if (epoch !== this.commandEpoch || this.modelChange || ((this.abortOperation || this.retainedAbort) && !cleanup) || this.hasUncertainShutdown() || this.sessionSchedules?.busy)
1793
2150
  return;
1794
2151
  const command = this.commandQueue.shift();
1795
2152
  if (!command) {
@@ -1890,6 +2247,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1890
2247
  ...(command.isSlashCommand ? { isSlashCommand: true } : {}),
1891
2248
  };
1892
2249
  inputMessage.uuid = (0, crypto_1.randomUUID)();
2250
+ this.turnLedger.dispatched(inputMessage.uuid);
1893
2251
  this.sessionSchedules?.foregroundDispatched(inputMessage.uuid, command.options.nativeScheduleManagement);
1894
2252
  const inputLine = JSON.stringify(inputMessage);
1895
2253
  console.log(`[ClaudePersistent] Sending command${command.isSlashCommand ? ' (slash)' : ''}: ${command.prompt.substring(0, 100)}...`);
@@ -1900,11 +2258,15 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1900
2258
  * Execute a command through the persistent Claude process
1901
2259
  */
1902
2260
  async execute(prompt, options = {}) {
1903
- if (this.isDestroyed) {
1904
- return {
1905
- success: false,
1906
- error: 'Executor has been destroyed',
1907
- };
2261
+ if (this.isDestroyed)
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).' };
2267
+ if (((this.abortOperation || this.retainedAbort) && !(this.cleanupAdmission() && options.nativeScheduleManagement && options.nativeScheduleCurrent?.()))
2268
+ || this.hasUncertainShutdown() || (this.scheduleCleanupHost && !options.nativeScheduleManagement)) {
2269
+ return { success: false, error: 'Native cleanup is still pending. Retry after cleanup.' };
1908
2270
  }
1909
2271
  try {
1910
2272
  (0, WorkingDirectory_1.assertWorkingDirectoryExists)(this.currentWorkingDirectory);
@@ -1925,14 +2287,40 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1925
2287
  });
1926
2288
  }
1927
2289
  /**
1928
- * Abort current command execution
1929
- * Stops the current process and rejects the pending command
2290
+ * Interrupt a verified native foreground, or retain the legacy stop path for unsupported/startup hosts.
2291
+ * A retained cancellation owns its unresolved evidence until retry or explicit destructive reset.
1930
2292
  */
1931
- async abort() {
1932
- if (!this.isProcessing && !this.isWaitingInput()) {
2293
+ abort() {
2294
+ if (this.abortOperation)
2295
+ return this.abortOperation;
2296
+ const operation = Promise.resolve().then(() => this.abortCurrent());
2297
+ this.abortOperation = operation;
2298
+ void operation.finally(() => { if (this.abortOperation === operation)
2299
+ this.abortOperation = undefined; }).catch(() => { });
2300
+ return operation;
2301
+ }
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).');
2305
+ if (this.retainedAbort || (this.preservesProcessOnAbort() && (this.isProcessing || this.isWaitingInput() || this.sessionSchedules?.hasPendingMutation))) {
2306
+ return this.interruptForeground();
2307
+ }
2308
+ if (this.preservesProcessOnAbort() && this.commandQueue.length) {
2309
+ this.commandEpoch++;
2310
+ for (const command of this.commandQueue.splice(0))
2311
+ command.reject(new Error('Command aborted by user'));
2312
+ this.lastAbortMessage = 'Queued foreground work cancelled; Claude and future native schedules retained.';
2313
+ return true;
2314
+ }
2315
+ this.lastAbortMessage = undefined;
2316
+ if (!this.isProcessing && !this.isWaitingInput() && !this.isStarting && !this.commandQueue.length && !this.hasUncertainShutdown()) {
1933
2317
  console.log('[ClaudePersistent] No command is currently executing');
1934
2318
  return false;
1935
2319
  }
2320
+ this.commandEpoch++;
2321
+ const queued = this.commandQueue.splice(0);
2322
+ for (const command of queued)
2323
+ command.reject(new Error('Command aborted by user'));
1936
2324
  // If waiting for input, cancel the input request
1937
2325
  if (this.isWaitingForInput) {
1938
2326
  console.log('[ClaudePersistent] Cancelling input request...');
@@ -1944,16 +2332,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1944
2332
  }
1945
2333
  console.log('[ClaudePersistent] Aborting current command...');
1946
2334
  this.denyAllPendingApprovals('Task aborted by user');
1947
- // Emit task aborted hook before stopping
1948
- if (this.lifecycleHooks && !this.currentScheduleManagement && this.currentTaskId) {
1949
- ClaudeCodeHooks_1.claudeCodeHooks.notifyTaskAborted({
1950
- taskId: this.currentTaskId,
1951
- description: '',
1952
- workingDirectory: this.currentWorkingDirectory,
1953
- sessionId: this.sessionId || undefined,
1954
- startTime: this.currentTaskStartTime,
1955
- }, 'Command aborted by user via /abort');
1956
- }
2335
+ this.notifyForegroundAborted();
1957
2336
  // Mark as intentional stop before rejecting and stopping
1958
2337
  this.isStopping = true;
1959
2338
  // Reject current command if any
@@ -1965,26 +2344,181 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
1965
2344
  this.isProcessing = false;
1966
2345
  this.currentTaskId = null;
1967
2346
  this.currentTaskStartTime = 0;
1968
- // Stop the process to ensure clean state
1969
- await this.stopProcess();
1970
- console.log('[ClaudePersistent] Process stopped after abort');
1971
- // Clear any pending commands in queue
1972
- if (this.commandQueue.length > 0) {
1973
- console.log(`[ClaudePersistent] Clearing ${this.commandQueue.length} pending commands from queue`);
1974
- for (const command of this.commandQueue) {
1975
- command.reject(new Error('Command aborted by user'));
2347
+ // Startup may not have published its child yet. Keep admission fenced until
2348
+ // that continuation settles, then stop its owned process with close evidence.
2349
+ try {
2350
+ if (this.startup) {
2351
+ let timer;
2352
+ try {
2353
+ await Promise.race([this.startup.catch(() => { }), new Promise((_, reject) => {
2354
+ timer = setTimeout(() => reject(new Error('Claude startup cancellation could not be confirmed')), 10000);
2355
+ })]);
2356
+ }
2357
+ finally {
2358
+ clearTimeout(timer);
2359
+ }
1976
2360
  }
1977
- this.commandQueue = [];
2361
+ await this.stopProcess();
2362
+ this.lastAbortMessage = 'Current work stopped by closing the Claude host. Session-only native schedules on that host were lost (native retained interruption was unavailable or startup was still pending).';
2363
+ this.shutdownUncertain = false;
2364
+ this.isStopping = false;
2365
+ }
2366
+ catch (error) {
2367
+ this.shutdownUncertain = true;
2368
+ throw error;
1978
2369
  }
1979
2370
  return true;
1980
2371
  }
2372
+ nativeControl(subtype, fields) {
2373
+ const child = this.claudeProcess;
2374
+ const requestId = `abort-control-${(0, crypto_1.randomUUID)()}`;
2375
+ return new Promise((resolve, reject) => {
2376
+ const timer = setTimeout(() => { this.pendingControlRequests.delete(requestId); reject(new Error('Native task cleanup acknowledgement timed out.')); }, 10_000);
2377
+ this.pendingControlRequests.set(requestId, { timer, resolve, reject });
2378
+ try {
2379
+ if (!child?.stdin?.writable)
2380
+ throw new Error('Native cancellation host is unavailable.');
2381
+ child.stdin.write(JSON.stringify({ type: 'control_request', request_id: requestId, request: { subtype, ...fields } }) + '\n');
2382
+ }
2383
+ catch (error) {
2384
+ clearTimeout(timer);
2385
+ this.pendingControlRequests.delete(requestId);
2386
+ reject(error);
2387
+ }
2388
+ });
2389
+ }
2390
+ notifyForegroundAborted() {
2391
+ if (this.lifecycleHooks && !this.currentScheduleManagement && this.currentTaskId) {
2392
+ ClaudeCodeHooks_1.claudeCodeHooks.notifyTaskAborted({ taskId: this.currentTaskId, description: '',
2393
+ workingDirectory: this.currentWorkingDirectory, sessionId: this.sessionId || undefined,
2394
+ startTime: this.currentTaskStartTime }, 'Command aborted by user via /abort');
2395
+ }
2396
+ }
2397
+ async interruptForeground() {
2398
+ let state = this.retainedAbort;
2399
+ if (!state) {
2400
+ const id = this.turnLedger.foreground, child = this.claudeProcess;
2401
+ if (!id || !child)
2402
+ throw new Error('Native foreground identity is unconfirmed; retry /abort or use /clear (session-only schedules will be lost).');
2403
+ state = { child, id, inputs: new Set(this.turnLedger.inputs), session: this.turnLedger.session, ack: false, lease: false,
2404
+ cleanup: this.sessionSchedules?.captureCancellation() ?? (async () => { }) };
2405
+ this.retainedAbort = state;
2406
+ this.commandEpoch++;
2407
+ for (const command of this.commandQueue.splice(0))
2408
+ command.reject(new Error('Command aborted by user'));
2409
+ this.denyAllPendingApprovals('Task aborted by user');
2410
+ this.notifyForegroundAborted();
2411
+ this.currentCommandReject?.(new Error('Command aborted by user'));
2412
+ this.resetCurrentCommand();
2413
+ this.isProcessing = false;
2414
+ this.currentTaskId = null;
2415
+ this.currentTaskStartTime = 0;
2416
+ }
2417
+ const captured = state;
2418
+ const current = () => this.retainedAbort === captured && this.claudeProcess === captured.child
2419
+ && this.turnLedger.session === captured.session && !this.turnLedger.invalid && !this.isDestroyed && !this.isStopping;
2420
+ if (!current())
2421
+ throw new Error('Native cancellation host identity changed. Use /clear for explicit destructive recovery.');
2422
+ await this.turnLedger.wait(() => current() && !!this.turnLedger.turns.get(captured.id)?.started, 15_000, 'Native foreground start identity');
2423
+ if (!state.requestId) {
2424
+ if (this.turnLedger.settled(state.id))
2425
+ state.ack = true; // Natural completion: do not interrupt a later autonomous turn.
2426
+ else {
2427
+ state.requestId = `interrupt-${(0, crypto_1.randomUUID)()}`;
2428
+ // Native targeting accepts at most eight UUIDs; oversized lists silently
2429
+ // become unscoped interrupts. Target recent lineage but join every input.
2430
+ state.child.stdin.write(JSON.stringify({ type: 'control_request', request_id: state.requestId,
2431
+ request: { subtype: 'interrupt', for_user_message_uuids: [...state.inputs].slice(-8) } }) + '\n');
2432
+ }
2433
+ }
2434
+ await this.turnLedger.wait(() => current() && captured.ack && [...captured.inputs].every(id => this.turnLedger.settled(id)), 15_000, 'Native foreground cancellation');
2435
+ // A previous failed cleanup may still have a native management turn. Do not overlap or replay it.
2436
+ await this.turnLedger.wait(() => current() && !this.isProcessing && !this.sessionSchedules?.busy, 15_000, 'Native cleanup admission');
2437
+ if (!state.work) {
2438
+ state.lease = true;
2439
+ this.scheduleCleanupHost = state.child;
2440
+ state.work = (async () => {
2441
+ const lease = () => current() && captured.lease;
2442
+ await captured.cleanup(lease);
2443
+ await this.turnLedger.wait(() => lease() && !this.isProcessing
2444
+ && (!this.turnLedger.foreground || this.turnLedger.settled(this.turnLedger.foreground)), 15_000, 'Native management terminal');
2445
+ for (const [id, task] of this.turnLedger.tasks) {
2446
+ if (!task.owner || !captured.inputs.has(task.owner) || task.terminal)
2447
+ continue;
2448
+ if (!lease())
2449
+ throw new Error('Native task cleanup lease expired.');
2450
+ // Only a snapshot observed after this stop request can prove retirement.
2451
+ this.turnLedger.inventory = undefined;
2452
+ await this.nativeControl('stop_task', { task_id: id });
2453
+ await this.turnLedger.wait(() => lease() && (task.terminal || !!this.turnLedger.inventory && !this.turnLedger.inventory.has(id)), 10_000, 'Owned native task retirement');
2454
+ }
2455
+ })();
2456
+ void state.work.catch(() => { });
2457
+ }
2458
+ let timer;
2459
+ let closed;
2460
+ try {
2461
+ await Promise.race([state.work, new Promise((_, reject) => {
2462
+ closed = () => reject(new Error('Native cancellation host closed; session-only schedules were lost. Use /clear to recover.'));
2463
+ captured.child.once('close', closed);
2464
+ timer = setTimeout(() => reject(new Error('Native mutation cleanup remains pending. Retry /abort or use /clear; /clear loses session-only schedules.')), 75_000);
2465
+ })]);
2466
+ if (!current())
2467
+ throw new Error('Native cancellation host changed during cleanup.');
2468
+ this.retainedAbort = undefined;
2469
+ this.lastAbortMessage = 'Current foreground work interrupted. Claude conversation and future native schedules were retained. Already-fired shared-session work may also have been interrupted; native task retirement does not prove all external effects stopped.';
2470
+ return true;
2471
+ }
2472
+ catch (error) {
2473
+ // Keep the handle/catalog and host fenced. Retry only after the previous cleanup unwinds.
2474
+ const work = state.work;
2475
+ void work?.finally(() => { if (captured.work === work)
2476
+ captured.work = undefined; }).catch(() => { });
2477
+ throw error;
2478
+ }
2479
+ finally {
2480
+ clearTimeout(timer);
2481
+ state.lease = false;
2482
+ this.scheduleCleanupHost = undefined;
2483
+ if (closed)
2484
+ captured.child.removeListener('close', closed);
2485
+ }
2486
+ }
2487
+ /** Explicit /clear recovery is destructive; never used as an interrupt timeout fallback. */
2488
+ async stopForContextReset() {
2489
+ if (this.abortOperation)
2490
+ throw new Error('Cancellation is still settling; retry /clear after it returns.');
2491
+ if (this.startup || this.isStarting) {
2492
+ await this.abort();
2493
+ return;
2494
+ }
2495
+ this.commandEpoch++;
2496
+ for (const command of this.commandQueue.splice(0))
2497
+ command.reject(new Error('Conversation cleared'));
2498
+ this.notifyForegroundAborted();
2499
+ this.currentCommandReject?.(new Error('Conversation cleared'));
2500
+ this.resetCurrentCommand();
2501
+ this.isProcessing = false;
2502
+ this.currentTaskId = null;
2503
+ this.currentTaskStartTime = 0;
2504
+ await this.stopProcess();
2505
+ this.retainedAbort = undefined;
2506
+ this.shutdownUncertain = false;
2507
+ this.scheduleRestart = undefined;
2508
+ this.scheduleRestoring = undefined;
2509
+ }
1981
2510
  /**
1982
2511
  * Reset execution context
1983
2512
  * Clears the session ID to start a fresh conversation on next command.
1984
- * Does NOT stop the process - the process continues running and will
1985
- * create a new session automatically when the next command is executed.
2513
+ * Initiates a process stop; this void API is not a shutdown acknowledgement.
2514
+ * Production callers cancel work and await destroy/waitForExit before resetting.
2515
+ * Concurrent execute calls remain fenced until the captured stop settles;
2516
+ * prompts interrupted during startup are not replayed into the fresh context.
1986
2517
  */
1987
2518
  resetContext() {
2519
+ this.scheduleRestart = undefined;
2520
+ this.scheduleRestoring = undefined;
2521
+ this.cancelInputWaiters();
1988
2522
  this.nativeCreationEpoch++;
1989
2523
  console.log('[ClaudePersistent] Resetting session context');
1990
2524
  this.sessionId = null;
@@ -2002,53 +2536,148 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2002
2536
  // so clearing it in memory is not enough. The process must be restarted fresh.
2003
2537
  this.stopProcess().catch((err) => console.error('[ClaudePersistent] Failed to stop process on reset:', err));
2004
2538
  }
2005
- /**
2006
- * Switch the model for future commands.
2007
- * Restarts the process if running, preserving the session via --resume.
2008
- * Rejects known incompatible effort rather than silently changing a second preference.
2009
- * Retains a deliberate text-argument full-model path if not found in catalog.
2010
- */
2539
+ /** Switch only the session selection. Never recycle a live host to change a model. */
2011
2540
  async setModel(model, _onStream) {
2012
- if (this.isDestroyed) {
2013
- return { success: false, error: 'Executor has been destroyed' };
2014
- }
2015
- if (this.isBusy()) {
2016
- 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);
2017
2598
  }
2018
- 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
+ });
2019
2663
  try {
2020
- 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
+ });
2021
2669
  }
2022
2670
  catch {
2023
- return { success: false, error: 'Cannot validate the saved reasoning effort. Reset /effort auto before changing models.' };
2671
+ uncertain('Native model request write failed.');
2024
2672
  }
2025
- }
2026
- let matchedEntry;
2027
- if (this.cachedRawEntries) {
2028
- matchedEntry = this.cachedRawEntries.find(e => e.value === model || (e.resolvedModel !== undefined && e.resolvedModel === model));
2029
- }
2030
- if (this.effort && matchedEntry) {
2031
- if (!matchedEntry.supportsEffort || !matchedEntry.supportedEffortLevels?.includes(this.effort)) {
2032
- return { success: false, error: 'The saved reasoning effort is incompatible with this model. Reset /effort auto before changing models.' };
2033
- }
2034
- }
2035
- await this.stopProcess();
2036
- this.model = model;
2037
- this.reportedModel = undefined;
2038
- return {
2039
- success: true,
2040
- output: `Model set to ${this.model}.`,
2041
- };
2673
+ });
2042
2674
  }
2043
- async clearModel() {
2044
- if (this.isDestroyed)
2045
- return;
2046
- if (this.isBusy()) {
2047
- throw new Error('Cannot clear model while Claude is busy');
2048
- }
2049
- 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).
2050
2680
  this.reportedModel = undefined;
2051
- await this.stopProcess();
2052
2681
  }
2053
2682
  /**
2054
2683
  * Query models available to the authenticated Claude backend using native control initialization.
@@ -2059,7 +2688,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2059
2688
  throw new Error('Executor has been destroyed');
2060
2689
  }
2061
2690
  if (this.cachedModelCatalog) {
2062
- 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;
2063
2692
  }
2064
2693
  if (this.catalogInitPromise) {
2065
2694
  return this.catalogInitPromise;
@@ -2113,7 +2742,9 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2113
2742
  }
2114
2743
  try {
2115
2744
  const rawResponse = response || {};
2116
- const { models, rawEntries } = (0, ClaudeSettings_1.parseClaudeModelsCatalog)(rawResponse.models, this.reportedModel || this.model);
2745
+ this.turnLedger.version = typeof rawResponse.claude_code_version === 'string' ? rawResponse.claude_code_version : undefined;
2746
+ this.turnLedger.pid = typeof rawResponse.pid === 'number' ? rawResponse.pid : undefined;
2747
+ const { models, rawEntries } = (0, ClaudeSettings_1.parseClaudeModelsCatalog)(rawResponse.models, this.reportedModel || this.acknowledgedModel || this.model);
2117
2748
  if (scheduleHooks && this.sessionId && this.delegation?.groups?.includes('scheduling')) {
2118
2749
  await this.readNativeScheduleTimezone();
2119
2750
  }
@@ -2183,7 +2814,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2183
2814
  unavailableReason: 'Reasoning effort is not supported for Claude Code.',
2184
2815
  };
2185
2816
  }
2186
- const activeModel = this.reportedModel || this.model;
2817
+ const activeModel = this.reportedModel || this.acknowledgedModel || this.model;
2187
2818
  return (0, ClaudeSettings_1.resolveClaudeEfforts)(this.cachedRawEntries, activeModel, this.effort);
2188
2819
  }
2189
2820
  /**
@@ -2198,6 +2829,9 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2198
2829
  if (this.isBusy()) {
2199
2830
  return { success: false, error: 'Cannot change reasoning effort while Claude is busy' };
2200
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
+ }
2201
2835
  const normalized = effort.trim().toLowerCase();
2202
2836
  if (normalized === 'auto' || normalized === '') {
2203
2837
  await this.stopProcess();
@@ -2230,6 +2864,10 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2230
2864
  error: `Unsupported reasoning effort: ${effort}. Supported values: auto, ${effortInfo.choices.map(c => c.value).join(', ')}.`,
2231
2865
  };
2232
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
+ }
2233
2871
  await this.stopProcess();
2234
2872
  this.effort = match.value;
2235
2873
  return {
@@ -2243,6 +2881,10 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2243
2881
  * Returns a promise that resolves when compaction is complete.
2244
2882
  */
2245
2883
  compact(onStream) {
2884
+ if (this.modelChange)
2885
+ return Promise.resolve({ success: false, error: 'Native model change is pending or unconfirmed.' });
2886
+ if (this.retainedAbort || this.abortOperation)
2887
+ return Promise.resolve({ success: false, error: 'Native cancellation cleanup is pending.' });
2246
2888
  console.log('[ClaudePersistent] Sending /compact slash command');
2247
2889
  return new Promise((resolve, reject) => {
2248
2890
  if (this.isDestroyed) {
@@ -2277,6 +2919,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2277
2919
  * 4. Restart the persistent process with the new session ID
2278
2920
  */
2279
2921
  async compactWhenFull(onStream) {
2922
+ if (this.retainedAbort || this.abortOperation)
2923
+ return { success: false, error: 'Native cancellation cleanup is pending.' };
2280
2924
  console.log('[ClaudePersistent] Context full - running external compact');
2281
2925
  if (this.isDestroyed) {
2282
2926
  return { success: false, error: 'Executor has been destroyed' };
@@ -2337,7 +2981,19 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2337
2981
  /**
2338
2982
  * Destroy executor and cleanup
2339
2983
  */
2340
- async destroy() {
2984
+ destroy() {
2985
+ if (this.destruction)
2986
+ return this.destruction;
2987
+ const operation = this.destroyOwnedResources();
2988
+ this.destruction = operation;
2989
+ void operation.finally(() => {
2990
+ if (this.destruction === operation)
2991
+ this.destruction = undefined;
2992
+ }).catch(() => { });
2993
+ return operation;
2994
+ }
2995
+ async destroyOwnedResources() {
2996
+ this.cancelInputWaiters();
2341
2997
  this.isDestroyed = true;
2342
2998
  // Clear queue and reject pending commands
2343
2999
  for (const command of this.commandQueue) {
@@ -2347,8 +3003,30 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2347
3003
  this.clearApprovals('Executor destroyed');
2348
3004
  this.rejectPendingControlRequests('Executor has been destroyed');
2349
3005
  this.clearCatalogCache();
2350
- // Startup owns its unpublished listener until it has completed or cleaned up.
2351
- await this.approvalStartup?.catch(() => undefined);
3006
+ if (this.currentCommandReject) {
3007
+ this.currentCommandReject(new Error('Executor has been destroyed'));
3008
+ this.resetCurrentCommand();
3009
+ }
3010
+ // Stop the published child first: startup may itself be waiting for that
3011
+ // child's close. Then join unpublished resource ownership before reporting
3012
+ // destruction complete. A timeout retains a retryable destroyed executor.
3013
+ await this.stopProcess();
3014
+ let startupDeadline;
3015
+ try {
3016
+ await Promise.race([
3017
+ Promise.allSettled([this.startup, this.approvalStartup]),
3018
+ new Promise((_, reject) => {
3019
+ startupDeadline = setTimeout(() => reject(new Error('Claude startup destruction could not be confirmed')), 10000);
3020
+ }),
3021
+ ]);
3022
+ }
3023
+ catch (error) {
3024
+ this.shutdownUncertain = true;
3025
+ throw error;
3026
+ }
3027
+ finally {
3028
+ clearTimeout(startupDeadline);
3029
+ }
2352
3030
  if (this.approvalServer) {
2353
3031
  const server = this.approvalServer;
2354
3032
  this.approvalServer = null;
@@ -2359,12 +3037,6 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
2359
3037
  fs_1.default.rmSync(this.approvalSocketDirectory, { recursive: true, force: true });
2360
3038
  this.approvalSocketDirectory = undefined;
2361
3039
  }
2362
- if (this.currentCommandReject) {
2363
- this.currentCommandReject(new Error('Executor has been destroyed'));
2364
- this.resetCurrentCommand();
2365
- }
2366
- // Stop process
2367
- await this.stopProcess();
2368
3040
  // Remove all listeners
2369
3041
  this.removeAllListeners();
2370
3042
  }