@yu_robotics/remote-cli 1.6.236 → 1.6.237
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.
- package/dist/client/MessageHandler.d.ts.map +1 -1
- package/dist/client/MessageHandler.js +65 -14
- package/dist/client/MessageHandler.js.map +1 -1
- package/dist/executor/ClaudePersistentExecutor.d.ts +35 -5
- package/dist/executor/ClaudePersistentExecutor.d.ts.map +1 -1
- package/dist/executor/ClaudePersistentExecutor.js +437 -69
- package/dist/executor/ClaudePersistentExecutor.js.map +1 -1
- package/dist/executor/IExecutor.d.ts +8 -0
- package/dist/executor/IExecutor.d.ts.map +1 -1
- package/dist/executor/claude/TurnLedger.d.ts +33 -0
- package/dist/executor/claude/TurnLedger.d.ts.map +1 -0
- package/dist/executor/claude/TurnLedger.js +126 -0
- package/dist/executor/claude/TurnLedger.js.map +1 -0
- package/dist/maintenance/release-notes.json +1 -1
- package/dist/managed/ManagedToolBridge.d.ts +4 -1
- package/dist/managed/ManagedToolBridge.d.ts.map +1 -1
- package/dist/managed/ManagedToolBridge.js +17 -2
- package/dist/managed/ManagedToolBridge.js.map +1 -1
- package/dist/scheduling/ScheduleService.d.ts +2 -0
- package/dist/scheduling/ScheduleService.d.ts.map +1 -1
- package/dist/scheduling/ScheduleService.js +13 -0
- package/dist/scheduling/ScheduleService.js.map +1 -1
- package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts +3 -0
- package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts.map +1 -1
- package/dist/scheduling/claude/ClaudeSessionSchedules.js +32 -1
- package/dist/scheduling/claude/ClaudeSessionSchedules.js.map +1 -1
- package/native/prebuilds/darwin-arm64/managed_native.node +0 -0
- package/native/prebuilds/darwin-arm64/manifest.json +1 -1
- package/native/prebuilds/darwin-x64/managed_native.node +0 -0
- package/native/prebuilds/darwin-x64/manifest.json +1 -1
- package/native/prebuilds/win32-arm64/managed_native.node +0 -0
- package/native/prebuilds/win32-arm64/manifest.json +1 -1
- package/native/prebuilds/win32-x64/managed_native.node +0 -0
- package/native/prebuilds/win32-x64/manifest.json +1 -1
- package/package.json +1 -1
|
@@ -5,6 +5,7 @@ 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");
|
|
8
9
|
const tools_1 = require("../managed/tools");
|
|
9
10
|
const ManagedSpawn_1 = require("./ManagedSpawn");
|
|
10
11
|
const OwnershipRuntime_1 = require("../delegation/OwnershipRuntime");
|
|
@@ -70,6 +71,27 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
70
71
|
claudeProcess = null;
|
|
71
72
|
workerGroups = new ManagedProcessGroups_1.ManagedProcessGroups();
|
|
72
73
|
isStarting = false;
|
|
74
|
+
startup;
|
|
75
|
+
stopOperation;
|
|
76
|
+
stopEpoch = 0;
|
|
77
|
+
destruction;
|
|
78
|
+
abortOperation;
|
|
79
|
+
shutdownUncertain = false;
|
|
80
|
+
commandEpoch = 0;
|
|
81
|
+
scheduleCleanupHost;
|
|
82
|
+
turnLedger = new TurnLedger_1.TurnLedger();
|
|
83
|
+
retainedAbort;
|
|
84
|
+
lastAbortMessage;
|
|
85
|
+
cleanupAdmission() {
|
|
86
|
+
return !!this.retainedAbort?.lease && this.scheduleCleanupHost === this.retainedAbort.child
|
|
87
|
+
&& this.claudeProcess === this.retainedAbort.child && !this.isStopping && !this.isDestroyed;
|
|
88
|
+
}
|
|
89
|
+
preservesProcessOnAbort() {
|
|
90
|
+
return !!this.retainedAbort || (this.turnLedger.invalid && !!this.sessionSchedules?.hasJobs) || (!this.delegationWorker && !this.isStarting && !this.hasUncertainShutdown()
|
|
91
|
+
&& this.turnLedger.supported(this.claudeProcess?.pid));
|
|
92
|
+
}
|
|
93
|
+
abortStatusMessage() { return this.lastAbortMessage; }
|
|
94
|
+
hasPendingCancellation() { return !!this.retainedAbort; }
|
|
73
95
|
isStopping = false; // Flag to indicate intentional process stop
|
|
74
96
|
isSessionError = false; // Flag to suppress auto-restart on session-not-found errors
|
|
75
97
|
sessionResumeFailure = false;
|
|
@@ -103,7 +125,16 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
103
125
|
currentTaskStartTime = 0;
|
|
104
126
|
// Interactive input handling
|
|
105
127
|
isWaitingForInput = false;
|
|
106
|
-
|
|
128
|
+
inputGeneration = 0;
|
|
129
|
+
inputWaiters = new Set();
|
|
130
|
+
cancelInputWaiters() {
|
|
131
|
+
this.inputGeneration++;
|
|
132
|
+
clearTimeout(this.inputDetectionTimer);
|
|
133
|
+
this.inputDetectionTimer = undefined;
|
|
134
|
+
for (const waiter of [...this.inputWaiters])
|
|
135
|
+
waiter.finish(null);
|
|
136
|
+
this.isWaitingForInput = false;
|
|
137
|
+
}
|
|
107
138
|
inputDetectionTimer;
|
|
108
139
|
lastOutputTime = 0;
|
|
109
140
|
// Sandbox and approval state
|
|
@@ -284,14 +315,20 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
284
315
|
this.claudeProcess.stdin.write(JSON.stringify(frame) + '\n');
|
|
285
316
|
},
|
|
286
317
|
manage: async (prompt, current) => {
|
|
287
|
-
|
|
318
|
+
if (this.scheduleCleanupHost) {
|
|
319
|
+
if (!current() || this.claudeProcess !== this.scheduleCleanupHost || this.isStopping || (this.abortOperation && !this.cleanupAdmission())) {
|
|
320
|
+
throw new Error('Native cleanup admission expired; retry explicit schedule cancellation.');
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
else
|
|
324
|
+
await this.listModels();
|
|
288
325
|
return this.execute(prompt, { nativeScheduleManagement: true, nativeScheduleCurrent: current });
|
|
289
326
|
},
|
|
290
327
|
wake: () => { void this.processQueue(); },
|
|
291
328
|
});
|
|
292
329
|
}
|
|
293
330
|
async withNativeScheduleOperation(id, current, run, inTurn) {
|
|
294
|
-
if (this.delegationWorker || this.isDestroyed || this.isStopping || this.sandbox.isRestricted())
|
|
331
|
+
if (this.retainedAbort || this.delegationWorker || this.isDestroyed || this.isStopping || this.sandbox.isRestricted())
|
|
295
332
|
throw new Error('Native schedule owner or sandbox is unavailable.');
|
|
296
333
|
if (!inTurn)
|
|
297
334
|
await this.listModels();
|
|
@@ -299,6 +336,25 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
299
336
|
throw new Error('Native scheduling hooks are not initialized.');
|
|
300
337
|
return this.schedules().inToolOperation(id, current, run, inTurn);
|
|
301
338
|
}
|
|
339
|
+
async reconcileNativeSchedule(id, current, run) {
|
|
340
|
+
if (!current() || this.isDestroyed || this.hasUncertainShutdown() || this.abortOperation
|
|
341
|
+
|| this.isBusy() || this.scheduleCleanupHost) {
|
|
342
|
+
throw new Error(`Schedule ${id} cleanup is pending; retry explicit cancellation when the native session is idle.`);
|
|
343
|
+
}
|
|
344
|
+
// A confirmed close already retired the old handle. Never initialize a replacement host here.
|
|
345
|
+
if (!this.claudeProcess)
|
|
346
|
+
return run();
|
|
347
|
+
if (!this.sessionSchedules || !this.scheduleHooksReady)
|
|
348
|
+
throw new Error('Native cleanup ownership is unavailable.');
|
|
349
|
+
const child = this.claudeProcess;
|
|
350
|
+
this.scheduleCleanupHost = child;
|
|
351
|
+
try {
|
|
352
|
+
return await this.sessionSchedules.inToolOperation(id, () => current() && this.claudeProcess === child && !this.isStopping && !this.abortOperation, run, false);
|
|
353
|
+
}
|
|
354
|
+
finally {
|
|
355
|
+
this.scheduleCleanupHost = undefined;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
302
358
|
nativeScheduleAction(id) { return this.sessionSchedules?.action(id); }
|
|
303
359
|
async createNativeSchedule(input, onEvent, isOwnerCurrent) {
|
|
304
360
|
if (this.delegationWorker || this.isDestroyed || this.isStopping || this.sandbox.isRestricted()
|
|
@@ -373,7 +429,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
373
429
|
async configureDelegation(connection) {
|
|
374
430
|
if ((0, contract_1.sameConnection)(this.delegation, connection))
|
|
375
431
|
return;
|
|
376
|
-
if (this.
|
|
432
|
+
if (this.isBusy())
|
|
377
433
|
throw new Error('Cannot change delegation while Claude is busy');
|
|
378
434
|
await this.stopProcess();
|
|
379
435
|
this.delegation = connection;
|
|
@@ -385,7 +441,10 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
385
441
|
* the previous session. This prevents session conflicts when switching between
|
|
386
442
|
* directories that may have their own .claude-session files.
|
|
387
443
|
*/
|
|
444
|
+
hasUncertainShutdown() { return this.shutdownUncertain || this.isStopping || !!this.stopOperation; }
|
|
388
445
|
isBusy() {
|
|
446
|
+
if (this.retainedAbort || this.abortOperation || this.hasUncertainShutdown() || this.scheduleCleanupHost)
|
|
447
|
+
return true;
|
|
389
448
|
if (this.sessionSchedules?.busy)
|
|
390
449
|
return true;
|
|
391
450
|
return this.isProcessing || this.isStarting || this.commandQueue.length > 0;
|
|
@@ -422,14 +481,24 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
422
481
|
this.nativeObserver = observer;
|
|
423
482
|
this.nativeCaptureFailure = onFailure;
|
|
424
483
|
}
|
|
425
|
-
|
|
426
|
-
if (this.
|
|
484
|
+
startProcess() {
|
|
485
|
+
if (this.startup)
|
|
486
|
+
return this.startup;
|
|
487
|
+
const startup = this.startProcessImpl();
|
|
488
|
+
this.startup = startup;
|
|
489
|
+
void startup.finally(() => { if (this.startup === startup)
|
|
490
|
+
this.startup = undefined; }).catch(() => { });
|
|
491
|
+
return startup;
|
|
492
|
+
}
|
|
493
|
+
async startProcessImpl() {
|
|
494
|
+
if (this.isDestroyed || this.abortOperation || this.retainedAbort || this.hasUncertainShutdown())
|
|
427
495
|
throw new Error('Claude process is unavailable or its exit is unconfirmed');
|
|
428
496
|
if (this.claudeProcess || this.isStarting) {
|
|
429
497
|
return;
|
|
430
498
|
}
|
|
431
499
|
this.isStarting = true;
|
|
432
500
|
const creationEpoch = this.nativeCreationEpoch;
|
|
501
|
+
const stopEpoch = this.stopEpoch;
|
|
433
502
|
this.reportedModel = undefined;
|
|
434
503
|
try {
|
|
435
504
|
(0, WorkingDirectory_1.assertWorkingDirectoryExists)(this.currentWorkingDirectory);
|
|
@@ -561,6 +630,10 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
561
630
|
? '[redacted configuration]' : arg);
|
|
562
631
|
console.log(`[ClaudePersistent] Starting: ${this.claudeCommand} ${loggedArgs.join(' ')}`);
|
|
563
632
|
console.log(`[ClaudePersistent] Working directory: ${this.currentWorkingDirectory}`);
|
|
633
|
+
// Startup may have awaited approval-channel setup while abort retired its queue.
|
|
634
|
+
if (this.isDestroyed || this.abortOperation || this.hasUncertainShutdown() || stopEpoch !== this.stopEpoch) {
|
|
635
|
+
throw new Error('Claude startup was cancelled before process creation');
|
|
636
|
+
}
|
|
564
637
|
// Spawn the process
|
|
565
638
|
const child = (0, ManagedSpawn_1.spawnManaged)(this.delegationWorker, this.claudeCommand, args, {
|
|
566
639
|
...(this.delegationWorker && process.platform !== 'win32' ? { detached: true } : {}),
|
|
@@ -575,6 +648,14 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
575
648
|
},
|
|
576
649
|
});
|
|
577
650
|
this.claudeProcess = child;
|
|
651
|
+
this.turnLedger = new TurnLedger_1.TurnLedger();
|
|
652
|
+
child.stdin?.on?.('error', () => {
|
|
653
|
+
if (this.claudeProcess !== child)
|
|
654
|
+
return;
|
|
655
|
+
this.turnLedger.invalid = true;
|
|
656
|
+
this.rejectPendingControlRequests('Native input transport failed; cancellation remains unconfirmed.');
|
|
657
|
+
this.turnLedger.changed();
|
|
658
|
+
});
|
|
578
659
|
this.nativeScheduleTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
579
660
|
if (this.delegation?.groups?.includes('scheduling') && !this.delegationWorker && !restricted)
|
|
580
661
|
this.schedules();
|
|
@@ -587,6 +668,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
587
668
|
// Handle stdout (JSON stream)
|
|
588
669
|
let buffer = '';
|
|
589
670
|
child.stdout?.on('data', (data) => {
|
|
671
|
+
if (this.claudeProcess !== child)
|
|
672
|
+
return;
|
|
590
673
|
buffer += data.toString();
|
|
591
674
|
// Process complete JSON lines
|
|
592
675
|
const lines = buffer.split('\n');
|
|
@@ -661,6 +744,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
661
744
|
this.rejectPendingControlRequests('Claude process exited before control response');
|
|
662
745
|
this.clearCatalogCache();
|
|
663
746
|
this.claudeProcess = null;
|
|
747
|
+
this.turnLedger.retire();
|
|
664
748
|
// Check if this was an intentional stop (abort/reset)
|
|
665
749
|
const wasIntentionalStop = this.isStopping;
|
|
666
750
|
this.isStopping = false; // Reset the flag
|
|
@@ -685,7 +769,11 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
685
769
|
this.isSessionError = false; // Reset session error flag
|
|
686
770
|
if (!this.isDestroyed && !wasIntentionalStop && !hasSessionError && this.commandQueue.length > 0) {
|
|
687
771
|
console.log('[ClaudePersistent] Auto-restarting process...');
|
|
688
|
-
|
|
772
|
+
const epoch = this.commandEpoch;
|
|
773
|
+
setTimeout(() => {
|
|
774
|
+
if (epoch === this.commandEpoch && !this.abortOperation && !this.hasUncertainShutdown())
|
|
775
|
+
void this.startProcess().catch(() => { });
|
|
776
|
+
}, 1000);
|
|
689
777
|
}
|
|
690
778
|
else if (hasSessionError && this.commandQueue.length > 0) {
|
|
691
779
|
// Session is invalid - drain the queue with a friendly error rather than restarting
|
|
@@ -720,7 +808,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
720
808
|
}, 1000);
|
|
721
809
|
});
|
|
722
810
|
if (earlyError) {
|
|
723
|
-
this.claudeProcess
|
|
811
|
+
if (this.claudeProcess === child)
|
|
812
|
+
this.claudeProcess = null;
|
|
724
813
|
this.isStarting = false;
|
|
725
814
|
const err = earlyError;
|
|
726
815
|
if (err.message.includes('ENOENT') || err.code === 'ENOENT') {
|
|
@@ -728,6 +817,12 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
728
817
|
}
|
|
729
818
|
throw err;
|
|
730
819
|
}
|
|
820
|
+
// A stop may finish while the startup readiness wait is still settling.
|
|
821
|
+
// Do not attach fresh callbacks or dispatch work on that retired child.
|
|
822
|
+
if (this.isDestroyed || this.abortOperation || this.hasUncertainShutdown()
|
|
823
|
+
|| stopEpoch !== this.stopEpoch || this.claudeProcess !== child) {
|
|
824
|
+
throw new Error('Claude startup was cancelled after process creation');
|
|
825
|
+
}
|
|
731
826
|
if (this.filePolicyToken) {
|
|
732
827
|
try {
|
|
733
828
|
// SessionStart runs before stdin is consumed. Do not send a user task
|
|
@@ -745,7 +840,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
745
840
|
this.clearApprovals('Claude process failed');
|
|
746
841
|
// An error is not exit evidence for a session that owns native jobs.
|
|
747
842
|
// Retain the process until close (or an explicit bounded stop) confirms it.
|
|
748
|
-
if (this.sessionSchedules?.hasJobs)
|
|
843
|
+
if (this.sessionSchedules?.hasJobs || this.retainedAbort)
|
|
749
844
|
this.isStopping = true;
|
|
750
845
|
else
|
|
751
846
|
this.claudeProcess = null;
|
|
@@ -778,19 +873,38 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
778
873
|
/**
|
|
779
874
|
* Stop the persistent Claude process
|
|
780
875
|
*/
|
|
781
|
-
|
|
876
|
+
stopProcess() {
|
|
877
|
+
if (this.stopOperation)
|
|
878
|
+
return this.stopOperation;
|
|
879
|
+
const child = this.claudeProcess;
|
|
880
|
+
this.stopEpoch++;
|
|
881
|
+
this.isStopping = true;
|
|
882
|
+
// Publish the barrier before stdin.end can synchronously emit close or invoke
|
|
883
|
+
// a processExit listener. All callers join this captured child's stop.
|
|
884
|
+
let resolve;
|
|
885
|
+
let reject;
|
|
886
|
+
const operation = new Promise((done, fail) => { resolve = done; reject = fail; });
|
|
887
|
+
this.stopOperation = operation;
|
|
888
|
+
void operation.finally(() => {
|
|
889
|
+
if (this.stopOperation === operation)
|
|
890
|
+
this.stopOperation = undefined;
|
|
891
|
+
}).catch(() => { });
|
|
892
|
+
void this.stopCapturedProcess(child).then(resolve, reject);
|
|
893
|
+
return operation;
|
|
894
|
+
}
|
|
895
|
+
async stopCapturedProcess(child) {
|
|
782
896
|
this.filePolicyToken = undefined;
|
|
783
897
|
this.filePolicyRoots = [];
|
|
784
898
|
this.filePolicyStarted = false;
|
|
785
899
|
this.clearApprovals('Claude process stopped');
|
|
786
900
|
this.rejectPendingControlRequests('Claude process stopped before control response');
|
|
787
901
|
this.clearCatalogCache();
|
|
788
|
-
if (!
|
|
902
|
+
if (!child) {
|
|
903
|
+
this.isStopping = false;
|
|
789
904
|
return;
|
|
790
905
|
}
|
|
791
906
|
console.log('[ClaudePersistent] Stopping process...');
|
|
792
907
|
this.isStopping = true;
|
|
793
|
-
const child = this.claudeProcess;
|
|
794
908
|
// A signal is not evidence of exit. Bound the wait and retain the child on
|
|
795
909
|
// failure so the caller cannot silently launch a replacement over it.
|
|
796
910
|
await new Promise((resolve, reject) => {
|
|
@@ -807,8 +921,10 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
807
921
|
child.kill('SIGTERM');
|
|
808
922
|
}
|
|
809
923
|
});
|
|
810
|
-
if (this.claudeProcess === child)
|
|
924
|
+
if (this.claudeProcess === child) {
|
|
811
925
|
this.claudeProcess = null;
|
|
926
|
+
this.turnLedger.retire();
|
|
927
|
+
}
|
|
812
928
|
this.isStopping = false;
|
|
813
929
|
console.log('[ClaudePersistent] Process stopped');
|
|
814
930
|
}
|
|
@@ -1048,7 +1164,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
1048
1164
|
return this.sandbox.describe(this.currentWorkingDirectory);
|
|
1049
1165
|
}
|
|
1050
1166
|
async configureSandbox(command) {
|
|
1051
|
-
if (this.
|
|
1167
|
+
if (this.isDestroyed || this.isBusy()) {
|
|
1052
1168
|
return { success: false, error: 'Wait for the running task before changing sandbox settings.' };
|
|
1053
1169
|
}
|
|
1054
1170
|
try {
|
|
@@ -1204,16 +1320,45 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
1204
1320
|
try {
|
|
1205
1321
|
// Parse message first to check type
|
|
1206
1322
|
const parsedMessage = JSON.parse(line);
|
|
1323
|
+
this.turnLedger.observe(parsedMessage);
|
|
1324
|
+
const cancellation = this.retainedAbort;
|
|
1325
|
+
if (cancellation?.requestId && parsedMessage.type === 'control_response'
|
|
1326
|
+
&& parsedMessage.response?.request_id === cancellation.requestId) {
|
|
1327
|
+
const receipt = parsedMessage.response.response;
|
|
1328
|
+
cancellation.ack = parsedMessage.response.subtype === 'success' && ['stopped', 'idle', 'spared'].includes(receipt?.turn ?? '');
|
|
1329
|
+
this.turnLedger.changed();
|
|
1330
|
+
}
|
|
1207
1331
|
// Handle native Claude Control response packets (models catalog, etc.).
|
|
1208
1332
|
// These bypass raw stdout logging to prevent any potential account/credential leakage.
|
|
1209
1333
|
if (this.sessionSchedules?.accept(parsedMessage))
|
|
1210
1334
|
return;
|
|
1335
|
+
if (this.turnLedger.supported(this.claudeProcess?.pid) && parsedMessage.type === 'result'
|
|
1336
|
+
&& !parsedMessage.parent_tool_use_id && !this.turnLedger.joined(parsedMessage, this.turnLedger.foreground))
|
|
1337
|
+
return;
|
|
1211
1338
|
if (parsedMessage.type === 'result' && !parsedMessage.parent_tool_use_id)
|
|
1212
1339
|
this.sessionSchedules?.foregroundEnded();
|
|
1213
1340
|
if (parsedMessage.type === 'control_response' || parsedMessage.type === 'control_request') {
|
|
1214
1341
|
this.handleControlMessage(parsedMessage);
|
|
1215
1342
|
return;
|
|
1216
1343
|
}
|
|
1344
|
+
if (parsedMessage.type === 'command_lifecycle') {
|
|
1345
|
+
void this.processQueue();
|
|
1346
|
+
return;
|
|
1347
|
+
}
|
|
1348
|
+
// Keep native controls and schedule receipts alive, but retire old foreground display authority.
|
|
1349
|
+
if (cancellation && !this.cleanupAdmission()) {
|
|
1350
|
+
// A timed-out cleanup lease does not erase its in-flight native management turn.
|
|
1351
|
+
// Consume its matched terminal internally so an explicit retry can acquire the same host.
|
|
1352
|
+
if (parsedMessage.type === 'result' && this.currentScheduleManagement
|
|
1353
|
+
&& this.turnLedger.joined(parsedMessage, this.turnLedger.foreground)) {
|
|
1354
|
+
this.completeCurrentCommand(!parsedMessage.is_error, 'Native cancellation management turn failed.');
|
|
1355
|
+
}
|
|
1356
|
+
return;
|
|
1357
|
+
}
|
|
1358
|
+
const lineage = parsedMessage;
|
|
1359
|
+
if (this.turnLedger.supported(this.claudeProcess?.pid) && (lineage.user_message_uuid || lineage.user_message_uuids?.length)
|
|
1360
|
+
&& !this.turnLedger.joined(lineage, this.turnLedger.foreground))
|
|
1361
|
+
return;
|
|
1217
1362
|
const nativeContent = parsedMessage.message?.content ?? parsedMessage.content;
|
|
1218
1363
|
const containsToolResult = Array.isArray(nativeContent) && nativeContent.some(block => (block !== null && typeof block === 'object' && block.type === 'tool_result'));
|
|
1219
1364
|
// Token deltas are noisy; tool results may contain private media or metadata.
|
|
@@ -1541,7 +1686,10 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
1541
1686
|
// Pause processing state
|
|
1542
1687
|
this.isWaitingForInput = true;
|
|
1543
1688
|
// Notify through hooks
|
|
1689
|
+
const generation = this.inputGeneration;
|
|
1544
1690
|
const userInput = await this.requestInteractiveInput(lastLine);
|
|
1691
|
+
if (generation !== this.inputGeneration)
|
|
1692
|
+
return;
|
|
1545
1693
|
if (userInput !== null) {
|
|
1546
1694
|
this.sendInput(userInput);
|
|
1547
1695
|
}
|
|
@@ -1589,17 +1737,18 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
1589
1737
|
else
|
|
1590
1738
|
this.currentStreamCallback?.(`\n${prompt}\n`);
|
|
1591
1739
|
// Wait for input via sendInput() or timeout
|
|
1740
|
+
const generation = this.inputGeneration;
|
|
1592
1741
|
return new Promise((resolve) => {
|
|
1593
|
-
const
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1742
|
+
const waiter = { finish: (input) => {
|
|
1743
|
+
if (!this.inputWaiters.delete(waiter))
|
|
1744
|
+
return;
|
|
1745
|
+
clearTimeout(timer);
|
|
1746
|
+
if (generation === this.inputGeneration)
|
|
1747
|
+
this.isWaitingForInput = false;
|
|
1748
|
+
resolve(input);
|
|
1749
|
+
} };
|
|
1750
|
+
const timer = setTimeout(() => waiter.finish(null), 300000);
|
|
1751
|
+
this.inputWaiters.add(waiter);
|
|
1603
1752
|
});
|
|
1604
1753
|
}
|
|
1605
1754
|
/**
|
|
@@ -1607,6 +1756,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
1607
1756
|
* This is called by MessageHandler when user sends a message while waiting for input
|
|
1608
1757
|
*/
|
|
1609
1758
|
sendInput(input) {
|
|
1759
|
+
if (this.retainedAbort || this.abortOperation)
|
|
1760
|
+
return false;
|
|
1610
1761
|
if (this.pendingApprovals.size > 0) {
|
|
1611
1762
|
const match = /^(yes|y|approve|accept|no|n|deny|decline|cancel)(?:\s+(\S+))?$/i.exec(input.trim());
|
|
1612
1763
|
const requestId = match?.[2] ?? (this.pendingApprovals.size === 1 ? this.pendingApprovals.keys().next().value : undefined);
|
|
@@ -1629,16 +1780,15 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
1629
1780
|
},
|
|
1630
1781
|
};
|
|
1631
1782
|
inputMessage.uuid = (0, crypto_1.randomUUID)();
|
|
1783
|
+
this.turnLedger.dispatched(inputMessage.uuid, true);
|
|
1632
1784
|
this.sessionSchedules?.foregroundDispatched(inputMessage.uuid);
|
|
1633
1785
|
const inputLine = JSON.stringify(inputMessage);
|
|
1634
1786
|
console.log(`[ClaudePersistent] Sending user input: ${input}`);
|
|
1635
1787
|
this.claudeProcess.stdin?.write(inputLine + '\n');
|
|
1636
1788
|
this.isWaitingForInput = false;
|
|
1637
1789
|
// Notify any waiting callbacks (for requestInteractiveInput)
|
|
1638
|
-
for (const
|
|
1639
|
-
|
|
1640
|
-
}
|
|
1641
|
-
this.inputRequestCallbacks = [];
|
|
1790
|
+
for (const waiter of [...this.inputWaiters])
|
|
1791
|
+
waiter.finish(input);
|
|
1642
1792
|
return true;
|
|
1643
1793
|
}
|
|
1644
1794
|
/**
|
|
@@ -1705,12 +1855,14 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
1705
1855
|
this.resetCurrentCommand();
|
|
1706
1856
|
// Process next command in queue
|
|
1707
1857
|
this.isProcessing = false;
|
|
1858
|
+
this.turnLedger.changed();
|
|
1708
1859
|
this.processQueue();
|
|
1709
1860
|
}
|
|
1710
1861
|
/**
|
|
1711
1862
|
* Reset current command state
|
|
1712
1863
|
*/
|
|
1713
1864
|
resetCurrentCommand() {
|
|
1865
|
+
this.cancelInputWaiters();
|
|
1714
1866
|
this.currentScheduleManagement = false;
|
|
1715
1867
|
this.clearApprovals('Task is no longer active');
|
|
1716
1868
|
this.currentOutputBuffer = [];
|
|
@@ -1743,15 +1895,28 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
1743
1895
|
* Process the command queue
|
|
1744
1896
|
*/
|
|
1745
1897
|
async processQueue() {
|
|
1746
|
-
|
|
1898
|
+
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) {
|
|
1747
1900
|
return;
|
|
1748
1901
|
}
|
|
1902
|
+
if (this.turnLedger.supported(this.claudeProcess?.pid) && this.turnLedger.foreground
|
|
1903
|
+
&& !this.turnLedger.settled(this.turnLedger.foreground))
|
|
1904
|
+
return;
|
|
1905
|
+
const epoch = this.commandEpoch;
|
|
1906
|
+
// Expired management work must not start a replacement host.
|
|
1907
|
+
while (this.commandQueue[0]?.options.nativeScheduleCurrent && !this.commandQueue[0].options.nativeScheduleCurrent()) {
|
|
1908
|
+
this.commandQueue.shift().resolve({ success: false, error: 'Native schedule management authorization expired before dispatch.' });
|
|
1909
|
+
}
|
|
1910
|
+
if (!this.commandQueue.length)
|
|
1911
|
+
return;
|
|
1749
1912
|
// Ensure process is running
|
|
1750
1913
|
if (!this.claudeProcess) {
|
|
1751
1914
|
try {
|
|
1752
1915
|
await this.startProcess();
|
|
1753
1916
|
}
|
|
1754
1917
|
catch (error) {
|
|
1918
|
+
if (epoch !== this.commandEpoch)
|
|
1919
|
+
return;
|
|
1755
1920
|
// Failed to start process (e.g., working directory doesn't exist)
|
|
1756
1921
|
// Return error result to caller without crashing the process
|
|
1757
1922
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
@@ -1777,6 +1942,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
1777
1942
|
await this.listModels();
|
|
1778
1943
|
}
|
|
1779
1944
|
catch {
|
|
1945
|
+
if (epoch !== this.commandEpoch)
|
|
1946
|
+
return;
|
|
1780
1947
|
const failed = this.commandQueue.shift();
|
|
1781
1948
|
// A resumed native scheduler can fire before a later command. If hook
|
|
1782
1949
|
// registration or policy validation failed, retire that process before
|
|
@@ -1789,7 +1956,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
1789
1956
|
this.isStarting = false;
|
|
1790
1957
|
}
|
|
1791
1958
|
}
|
|
1792
|
-
if (this.sessionSchedules?.busy)
|
|
1959
|
+
if (epoch !== this.commandEpoch || ((this.abortOperation || this.retainedAbort) && !cleanup) || this.hasUncertainShutdown() || this.sessionSchedules?.busy)
|
|
1793
1960
|
return;
|
|
1794
1961
|
const command = this.commandQueue.shift();
|
|
1795
1962
|
if (!command) {
|
|
@@ -1890,6 +2057,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
1890
2057
|
...(command.isSlashCommand ? { isSlashCommand: true } : {}),
|
|
1891
2058
|
};
|
|
1892
2059
|
inputMessage.uuid = (0, crypto_1.randomUUID)();
|
|
2060
|
+
this.turnLedger.dispatched(inputMessage.uuid);
|
|
1893
2061
|
this.sessionSchedules?.foregroundDispatched(inputMessage.uuid, command.options.nativeScheduleManagement);
|
|
1894
2062
|
const inputLine = JSON.stringify(inputMessage);
|
|
1895
2063
|
console.log(`[ClaudePersistent] Sending command${command.isSlashCommand ? ' (slash)' : ''}: ${command.prompt.substring(0, 100)}...`);
|
|
@@ -1900,11 +2068,11 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
1900
2068
|
* Execute a command through the persistent Claude process
|
|
1901
2069
|
*/
|
|
1902
2070
|
async execute(prompt, options = {}) {
|
|
1903
|
-
if (this.isDestroyed)
|
|
1904
|
-
return {
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
};
|
|
2071
|
+
if (this.isDestroyed)
|
|
2072
|
+
return { success: false, error: 'Executor has been destroyed' };
|
|
2073
|
+
if (((this.abortOperation || this.retainedAbort) && !(this.cleanupAdmission() && options.nativeScheduleManagement && options.nativeScheduleCurrent?.()))
|
|
2074
|
+
|| this.hasUncertainShutdown() || (this.scheduleCleanupHost && !options.nativeScheduleManagement)) {
|
|
2075
|
+
return { success: false, error: 'Native cleanup is still pending. Retry after cleanup.' };
|
|
1908
2076
|
}
|
|
1909
2077
|
try {
|
|
1910
2078
|
(0, WorkingDirectory_1.assertWorkingDirectoryExists)(this.currentWorkingDirectory);
|
|
@@ -1925,14 +2093,38 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
1925
2093
|
});
|
|
1926
2094
|
}
|
|
1927
2095
|
/**
|
|
1928
|
-
*
|
|
1929
|
-
*
|
|
2096
|
+
* Interrupt a verified native foreground, or retain the legacy stop path for unsupported/startup hosts.
|
|
2097
|
+
* A retained cancellation owns its unresolved evidence until retry or explicit destructive reset.
|
|
1930
2098
|
*/
|
|
1931
|
-
|
|
1932
|
-
if (
|
|
2099
|
+
abort() {
|
|
2100
|
+
if (this.abortOperation)
|
|
2101
|
+
return this.abortOperation;
|
|
2102
|
+
const operation = Promise.resolve().then(() => this.abortCurrent());
|
|
2103
|
+
this.abortOperation = operation;
|
|
2104
|
+
void operation.finally(() => { if (this.abortOperation === operation)
|
|
2105
|
+
this.abortOperation = undefined; }).catch(() => { });
|
|
2106
|
+
return operation;
|
|
2107
|
+
}
|
|
2108
|
+
async abortCurrent() {
|
|
2109
|
+
if (this.retainedAbort || (this.preservesProcessOnAbort() && (this.isProcessing || this.isWaitingInput() || this.sessionSchedules?.hasPendingMutation))) {
|
|
2110
|
+
return this.interruptForeground();
|
|
2111
|
+
}
|
|
2112
|
+
if (this.preservesProcessOnAbort() && this.commandQueue.length) {
|
|
2113
|
+
this.commandEpoch++;
|
|
2114
|
+
for (const command of this.commandQueue.splice(0))
|
|
2115
|
+
command.reject(new Error('Command aborted by user'));
|
|
2116
|
+
this.lastAbortMessage = 'Queued foreground work cancelled; Claude and future native schedules retained.';
|
|
2117
|
+
return true;
|
|
2118
|
+
}
|
|
2119
|
+
this.lastAbortMessage = undefined;
|
|
2120
|
+
if (!this.isProcessing && !this.isWaitingInput() && !this.isStarting && !this.commandQueue.length && !this.hasUncertainShutdown()) {
|
|
1933
2121
|
console.log('[ClaudePersistent] No command is currently executing');
|
|
1934
2122
|
return false;
|
|
1935
2123
|
}
|
|
2124
|
+
this.commandEpoch++;
|
|
2125
|
+
const queued = this.commandQueue.splice(0);
|
|
2126
|
+
for (const command of queued)
|
|
2127
|
+
command.reject(new Error('Command aborted by user'));
|
|
1936
2128
|
// If waiting for input, cancel the input request
|
|
1937
2129
|
if (this.isWaitingForInput) {
|
|
1938
2130
|
console.log('[ClaudePersistent] Cancelling input request...');
|
|
@@ -1944,16 +2136,7 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
1944
2136
|
}
|
|
1945
2137
|
console.log('[ClaudePersistent] Aborting current command...');
|
|
1946
2138
|
this.denyAllPendingApprovals('Task aborted by user');
|
|
1947
|
-
|
|
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
|
-
}
|
|
2139
|
+
this.notifyForegroundAborted();
|
|
1957
2140
|
// Mark as intentional stop before rejecting and stopping
|
|
1958
2141
|
this.isStopping = true;
|
|
1959
2142
|
// Reject current command if any
|
|
@@ -1965,26 +2148,177 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
1965
2148
|
this.isProcessing = false;
|
|
1966
2149
|
this.currentTaskId = null;
|
|
1967
2150
|
this.currentTaskStartTime = 0;
|
|
1968
|
-
//
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
2151
|
+
// Startup may not have published its child yet. Keep admission fenced until
|
|
2152
|
+
// that continuation settles, then stop its owned process with close evidence.
|
|
2153
|
+
try {
|
|
2154
|
+
if (this.startup) {
|
|
2155
|
+
let timer;
|
|
2156
|
+
try {
|
|
2157
|
+
await Promise.race([this.startup.catch(() => { }), new Promise((_, reject) => {
|
|
2158
|
+
timer = setTimeout(() => reject(new Error('Claude startup cancellation could not be confirmed')), 10000);
|
|
2159
|
+
})]);
|
|
2160
|
+
}
|
|
2161
|
+
finally {
|
|
2162
|
+
clearTimeout(timer);
|
|
2163
|
+
}
|
|
1976
2164
|
}
|
|
1977
|
-
this.
|
|
2165
|
+
await this.stopProcess();
|
|
2166
|
+
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).';
|
|
2167
|
+
this.shutdownUncertain = false;
|
|
2168
|
+
this.isStopping = false;
|
|
2169
|
+
}
|
|
2170
|
+
catch (error) {
|
|
2171
|
+
this.shutdownUncertain = true;
|
|
2172
|
+
throw error;
|
|
1978
2173
|
}
|
|
1979
2174
|
return true;
|
|
1980
2175
|
}
|
|
2176
|
+
nativeControl(subtype, fields) {
|
|
2177
|
+
const child = this.claudeProcess;
|
|
2178
|
+
const requestId = `abort-control-${(0, crypto_1.randomUUID)()}`;
|
|
2179
|
+
return new Promise((resolve, reject) => {
|
|
2180
|
+
const timer = setTimeout(() => { this.pendingControlRequests.delete(requestId); reject(new Error('Native task cleanup acknowledgement timed out.')); }, 10_000);
|
|
2181
|
+
this.pendingControlRequests.set(requestId, { timer, resolve, reject });
|
|
2182
|
+
try {
|
|
2183
|
+
if (!child?.stdin?.writable)
|
|
2184
|
+
throw new Error('Native cancellation host is unavailable.');
|
|
2185
|
+
child.stdin.write(JSON.stringify({ type: 'control_request', request_id: requestId, request: { subtype, ...fields } }) + '\n');
|
|
2186
|
+
}
|
|
2187
|
+
catch (error) {
|
|
2188
|
+
clearTimeout(timer);
|
|
2189
|
+
this.pendingControlRequests.delete(requestId);
|
|
2190
|
+
reject(error);
|
|
2191
|
+
}
|
|
2192
|
+
});
|
|
2193
|
+
}
|
|
2194
|
+
notifyForegroundAborted() {
|
|
2195
|
+
if (this.lifecycleHooks && !this.currentScheduleManagement && this.currentTaskId) {
|
|
2196
|
+
ClaudeCodeHooks_1.claudeCodeHooks.notifyTaskAborted({ taskId: this.currentTaskId, description: '',
|
|
2197
|
+
workingDirectory: this.currentWorkingDirectory, sessionId: this.sessionId || undefined,
|
|
2198
|
+
startTime: this.currentTaskStartTime }, 'Command aborted by user via /abort');
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
async interruptForeground() {
|
|
2202
|
+
let state = this.retainedAbort;
|
|
2203
|
+
if (!state) {
|
|
2204
|
+
const id = this.turnLedger.foreground, child = this.claudeProcess;
|
|
2205
|
+
if (!id || !child)
|
|
2206
|
+
throw new Error('Native foreground identity is unconfirmed; retry /abort or use /clear (session-only schedules will be lost).');
|
|
2207
|
+
state = { child, id, inputs: new Set(this.turnLedger.inputs), session: this.turnLedger.session, ack: false, lease: false,
|
|
2208
|
+
cleanup: this.sessionSchedules?.captureCancellation() ?? (async () => { }) };
|
|
2209
|
+
this.retainedAbort = state;
|
|
2210
|
+
this.commandEpoch++;
|
|
2211
|
+
for (const command of this.commandQueue.splice(0))
|
|
2212
|
+
command.reject(new Error('Command aborted by user'));
|
|
2213
|
+
this.denyAllPendingApprovals('Task aborted by user');
|
|
2214
|
+
this.notifyForegroundAborted();
|
|
2215
|
+
this.currentCommandReject?.(new Error('Command aborted by user'));
|
|
2216
|
+
this.resetCurrentCommand();
|
|
2217
|
+
this.isProcessing = false;
|
|
2218
|
+
this.currentTaskId = null;
|
|
2219
|
+
this.currentTaskStartTime = 0;
|
|
2220
|
+
}
|
|
2221
|
+
const captured = state;
|
|
2222
|
+
const current = () => this.retainedAbort === captured && this.claudeProcess === captured.child
|
|
2223
|
+
&& this.turnLedger.session === captured.session && !this.turnLedger.invalid && !this.isDestroyed && !this.isStopping;
|
|
2224
|
+
if (!current())
|
|
2225
|
+
throw new Error('Native cancellation host identity changed. Use /clear for explicit destructive recovery.');
|
|
2226
|
+
await this.turnLedger.wait(() => current() && !!this.turnLedger.turns.get(captured.id)?.started, 15_000, 'Native foreground start identity');
|
|
2227
|
+
if (!state.requestId) {
|
|
2228
|
+
if (this.turnLedger.settled(state.id))
|
|
2229
|
+
state.ack = true; // Natural completion: do not interrupt a later autonomous turn.
|
|
2230
|
+
else {
|
|
2231
|
+
state.requestId = `interrupt-${(0, crypto_1.randomUUID)()}`;
|
|
2232
|
+
// Native targeting accepts at most eight UUIDs; oversized lists silently
|
|
2233
|
+
// become unscoped interrupts. Target recent lineage but join every input.
|
|
2234
|
+
state.child.stdin.write(JSON.stringify({ type: 'control_request', request_id: state.requestId,
|
|
2235
|
+
request: { subtype: 'interrupt', for_user_message_uuids: [...state.inputs].slice(-8) } }) + '\n');
|
|
2236
|
+
}
|
|
2237
|
+
}
|
|
2238
|
+
await this.turnLedger.wait(() => current() && captured.ack && [...captured.inputs].every(id => this.turnLedger.settled(id)), 15_000, 'Native foreground cancellation');
|
|
2239
|
+
// A previous failed cleanup may still have a native management turn. Do not overlap or replay it.
|
|
2240
|
+
await this.turnLedger.wait(() => current() && !this.isProcessing && !this.sessionSchedules?.busy, 15_000, 'Native cleanup admission');
|
|
2241
|
+
if (!state.work) {
|
|
2242
|
+
state.lease = true;
|
|
2243
|
+
this.scheduleCleanupHost = state.child;
|
|
2244
|
+
state.work = (async () => {
|
|
2245
|
+
const lease = () => current() && captured.lease;
|
|
2246
|
+
await captured.cleanup(lease);
|
|
2247
|
+
await this.turnLedger.wait(() => lease() && !this.isProcessing
|
|
2248
|
+
&& (!this.turnLedger.foreground || this.turnLedger.settled(this.turnLedger.foreground)), 15_000, 'Native management terminal');
|
|
2249
|
+
for (const [id, task] of this.turnLedger.tasks) {
|
|
2250
|
+
if (!task.owner || !captured.inputs.has(task.owner) || task.terminal)
|
|
2251
|
+
continue;
|
|
2252
|
+
if (!lease())
|
|
2253
|
+
throw new Error('Native task cleanup lease expired.');
|
|
2254
|
+
// Only a snapshot observed after this stop request can prove retirement.
|
|
2255
|
+
this.turnLedger.inventory = undefined;
|
|
2256
|
+
await this.nativeControl('stop_task', { task_id: id });
|
|
2257
|
+
await this.turnLedger.wait(() => lease() && (task.terminal || !!this.turnLedger.inventory && !this.turnLedger.inventory.has(id)), 10_000, 'Owned native task retirement');
|
|
2258
|
+
}
|
|
2259
|
+
})();
|
|
2260
|
+
void state.work.catch(() => { });
|
|
2261
|
+
}
|
|
2262
|
+
let timer;
|
|
2263
|
+
let closed;
|
|
2264
|
+
try {
|
|
2265
|
+
await Promise.race([state.work, new Promise((_, reject) => {
|
|
2266
|
+
closed = () => reject(new Error('Native cancellation host closed; session-only schedules were lost. Use /clear to recover.'));
|
|
2267
|
+
captured.child.once('close', closed);
|
|
2268
|
+
timer = setTimeout(() => reject(new Error('Native mutation cleanup remains pending. Retry /abort or use /clear; /clear loses session-only schedules.')), 75_000);
|
|
2269
|
+
})]);
|
|
2270
|
+
if (!current())
|
|
2271
|
+
throw new Error('Native cancellation host changed during cleanup.');
|
|
2272
|
+
this.retainedAbort = undefined;
|
|
2273
|
+
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.';
|
|
2274
|
+
return true;
|
|
2275
|
+
}
|
|
2276
|
+
catch (error) {
|
|
2277
|
+
// Keep the handle/catalog and host fenced. Retry only after the previous cleanup unwinds.
|
|
2278
|
+
const work = state.work;
|
|
2279
|
+
void work?.finally(() => { if (captured.work === work)
|
|
2280
|
+
captured.work = undefined; }).catch(() => { });
|
|
2281
|
+
throw error;
|
|
2282
|
+
}
|
|
2283
|
+
finally {
|
|
2284
|
+
clearTimeout(timer);
|
|
2285
|
+
state.lease = false;
|
|
2286
|
+
this.scheduleCleanupHost = undefined;
|
|
2287
|
+
if (closed)
|
|
2288
|
+
captured.child.removeListener('close', closed);
|
|
2289
|
+
}
|
|
2290
|
+
}
|
|
2291
|
+
/** Explicit /clear recovery is destructive; never used as an interrupt timeout fallback. */
|
|
2292
|
+
async stopForContextReset() {
|
|
2293
|
+
if (this.abortOperation)
|
|
2294
|
+
throw new Error('Cancellation is still settling; retry /clear after it returns.');
|
|
2295
|
+
if (this.startup || this.isStarting) {
|
|
2296
|
+
await this.abort();
|
|
2297
|
+
return;
|
|
2298
|
+
}
|
|
2299
|
+
this.commandEpoch++;
|
|
2300
|
+
for (const command of this.commandQueue.splice(0))
|
|
2301
|
+
command.reject(new Error('Conversation cleared'));
|
|
2302
|
+
this.notifyForegroundAborted();
|
|
2303
|
+
this.currentCommandReject?.(new Error('Conversation cleared'));
|
|
2304
|
+
this.resetCurrentCommand();
|
|
2305
|
+
this.isProcessing = false;
|
|
2306
|
+
this.currentTaskId = null;
|
|
2307
|
+
this.currentTaskStartTime = 0;
|
|
2308
|
+
await this.stopProcess();
|
|
2309
|
+
this.retainedAbort = undefined;
|
|
2310
|
+
this.shutdownUncertain = false;
|
|
2311
|
+
}
|
|
1981
2312
|
/**
|
|
1982
2313
|
* Reset execution context
|
|
1983
2314
|
* Clears the session ID to start a fresh conversation on next command.
|
|
1984
|
-
*
|
|
1985
|
-
*
|
|
2315
|
+
* Initiates a process stop; this void API is not a shutdown acknowledgement.
|
|
2316
|
+
* Production callers cancel work and await destroy/waitForExit before resetting.
|
|
2317
|
+
* Concurrent execute calls remain fenced until the captured stop settles;
|
|
2318
|
+
* prompts interrupted during startup are not replayed into the fresh context.
|
|
1986
2319
|
*/
|
|
1987
2320
|
resetContext() {
|
|
2321
|
+
this.cancelInputWaiters();
|
|
1988
2322
|
this.nativeCreationEpoch++;
|
|
1989
2323
|
console.log('[ClaudePersistent] Resetting session context');
|
|
1990
2324
|
this.sessionId = null;
|
|
@@ -2113,6 +2447,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
2113
2447
|
}
|
|
2114
2448
|
try {
|
|
2115
2449
|
const rawResponse = response || {};
|
|
2450
|
+
this.turnLedger.version = typeof rawResponse.claude_code_version === 'string' ? rawResponse.claude_code_version : undefined;
|
|
2451
|
+
this.turnLedger.pid = typeof rawResponse.pid === 'number' ? rawResponse.pid : undefined;
|
|
2116
2452
|
const { models, rawEntries } = (0, ClaudeSettings_1.parseClaudeModelsCatalog)(rawResponse.models, this.reportedModel || this.model);
|
|
2117
2453
|
if (scheduleHooks && this.sessionId && this.delegation?.groups?.includes('scheduling')) {
|
|
2118
2454
|
await this.readNativeScheduleTimezone();
|
|
@@ -2243,6 +2579,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
2243
2579
|
* Returns a promise that resolves when compaction is complete.
|
|
2244
2580
|
*/
|
|
2245
2581
|
compact(onStream) {
|
|
2582
|
+
if (this.retainedAbort || this.abortOperation)
|
|
2583
|
+
return Promise.resolve({ success: false, error: 'Native cancellation cleanup is pending.' });
|
|
2246
2584
|
console.log('[ClaudePersistent] Sending /compact slash command');
|
|
2247
2585
|
return new Promise((resolve, reject) => {
|
|
2248
2586
|
if (this.isDestroyed) {
|
|
@@ -2277,6 +2615,8 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
2277
2615
|
* 4. Restart the persistent process with the new session ID
|
|
2278
2616
|
*/
|
|
2279
2617
|
async compactWhenFull(onStream) {
|
|
2618
|
+
if (this.retainedAbort || this.abortOperation)
|
|
2619
|
+
return { success: false, error: 'Native cancellation cleanup is pending.' };
|
|
2280
2620
|
console.log('[ClaudePersistent] Context full - running external compact');
|
|
2281
2621
|
if (this.isDestroyed) {
|
|
2282
2622
|
return { success: false, error: 'Executor has been destroyed' };
|
|
@@ -2337,7 +2677,19 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
2337
2677
|
/**
|
|
2338
2678
|
* Destroy executor and cleanup
|
|
2339
2679
|
*/
|
|
2340
|
-
|
|
2680
|
+
destroy() {
|
|
2681
|
+
if (this.destruction)
|
|
2682
|
+
return this.destruction;
|
|
2683
|
+
const operation = this.destroyOwnedResources();
|
|
2684
|
+
this.destruction = operation;
|
|
2685
|
+
void operation.finally(() => {
|
|
2686
|
+
if (this.destruction === operation)
|
|
2687
|
+
this.destruction = undefined;
|
|
2688
|
+
}).catch(() => { });
|
|
2689
|
+
return operation;
|
|
2690
|
+
}
|
|
2691
|
+
async destroyOwnedResources() {
|
|
2692
|
+
this.cancelInputWaiters();
|
|
2341
2693
|
this.isDestroyed = true;
|
|
2342
2694
|
// Clear queue and reject pending commands
|
|
2343
2695
|
for (const command of this.commandQueue) {
|
|
@@ -2347,8 +2699,30 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
2347
2699
|
this.clearApprovals('Executor destroyed');
|
|
2348
2700
|
this.rejectPendingControlRequests('Executor has been destroyed');
|
|
2349
2701
|
this.clearCatalogCache();
|
|
2350
|
-
|
|
2351
|
-
|
|
2702
|
+
if (this.currentCommandReject) {
|
|
2703
|
+
this.currentCommandReject(new Error('Executor has been destroyed'));
|
|
2704
|
+
this.resetCurrentCommand();
|
|
2705
|
+
}
|
|
2706
|
+
// Stop the published child first: startup may itself be waiting for that
|
|
2707
|
+
// child's close. Then join unpublished resource ownership before reporting
|
|
2708
|
+
// destruction complete. A timeout retains a retryable destroyed executor.
|
|
2709
|
+
await this.stopProcess();
|
|
2710
|
+
let startupDeadline;
|
|
2711
|
+
try {
|
|
2712
|
+
await Promise.race([
|
|
2713
|
+
Promise.allSettled([this.startup, this.approvalStartup]),
|
|
2714
|
+
new Promise((_, reject) => {
|
|
2715
|
+
startupDeadline = setTimeout(() => reject(new Error('Claude startup destruction could not be confirmed')), 10000);
|
|
2716
|
+
}),
|
|
2717
|
+
]);
|
|
2718
|
+
}
|
|
2719
|
+
catch (error) {
|
|
2720
|
+
this.shutdownUncertain = true;
|
|
2721
|
+
throw error;
|
|
2722
|
+
}
|
|
2723
|
+
finally {
|
|
2724
|
+
clearTimeout(startupDeadline);
|
|
2725
|
+
}
|
|
2352
2726
|
if (this.approvalServer) {
|
|
2353
2727
|
const server = this.approvalServer;
|
|
2354
2728
|
this.approvalServer = null;
|
|
@@ -2359,12 +2733,6 @@ class ClaudePersistentExecutor extends events_1.EventEmitter {
|
|
|
2359
2733
|
fs_1.default.rmSync(this.approvalSocketDirectory, { recursive: true, force: true });
|
|
2360
2734
|
this.approvalSocketDirectory = undefined;
|
|
2361
2735
|
}
|
|
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
2736
|
// Remove all listeners
|
|
2369
2737
|
this.removeAllListeners();
|
|
2370
2738
|
}
|