@yu_robotics/remote-cli 1.6.194 → 1.6.195
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/README.md +22 -2
- package/dist/client/MessageHandler.d.ts +9 -0
- package/dist/client/MessageHandler.d.ts.map +1 -1
- package/dist/client/MessageHandler.js +243 -83
- package/dist/client/MessageHandler.js.map +1 -1
- package/dist/delegation/DelegatedWorkerSessionStore.d.ts +7 -2
- package/dist/delegation/DelegatedWorkerSessionStore.d.ts.map +1 -1
- package/dist/delegation/DelegatedWorkerSessionStore.js +77 -12
- package/dist/delegation/DelegatedWorkerSessionStore.js.map +1 -1
- package/dist/delegation/DelegationManager.d.ts +8 -1
- package/dist/delegation/DelegationManager.d.ts.map +1 -1
- package/dist/delegation/DelegationManager.js +112 -30
- package/dist/delegation/DelegationManager.js.map +1 -1
- package/dist/delegation/DelegationOwnership.d.ts +2 -0
- package/dist/delegation/DelegationOwnership.d.ts.map +1 -1
- package/dist/delegation/DelegationOwnership.js +35 -0
- package/dist/delegation/DelegationOwnership.js.map +1 -1
- package/dist/maintenance/release-notes.json +1 -1
- package/dist/settings/SettingsAdmission.d.ts +5 -1
- package/dist/settings/SettingsAdmission.d.ts.map +1 -1
- package/dist/settings/SettingsAdmission.js +26 -5
- package/dist/settings/SettingsAdmission.js.map +1 -1
- package/dist/thread/ThreadContextReset.d.ts +5 -0
- package/dist/thread/ThreadContextReset.d.ts.map +1 -1
- package/dist/thread/ThreadContextReset.js +64 -1
- package/dist/thread/ThreadContextReset.js.map +1 -1
- package/dist/thread/ThreadExecutorPool.d.ts +2 -0
- package/dist/thread/ThreadExecutorPool.d.ts.map +1 -1
- package/dist/thread/ThreadExecutorPool.js +9 -10
- package/dist/thread/ThreadExecutorPool.js.map +1 -1
- package/dist/thread/ThreadManager.d.ts.map +1 -1
- package/dist/thread/ThreadManager.js +8 -3
- package/dist/thread/ThreadManager.js.map +1 -1
- package/dist/thread/types.d.ts +1 -1
- package/package.json +1 -1
|
@@ -169,6 +169,9 @@ class MessageHandler {
|
|
|
169
169
|
piBinding: threadId => readPiBinding(threadId),
|
|
170
170
|
});
|
|
171
171
|
activeThreadOperations = new Map();
|
|
172
|
+
conversationRevisions = new Map();
|
|
173
|
+
cancelledOperations = new Set();
|
|
174
|
+
coordinatorPreparations = new Map();
|
|
172
175
|
abortOperations = new Map();
|
|
173
176
|
pendingGoalActivations = new Map();
|
|
174
177
|
automaticUpdateInProgress = false;
|
|
@@ -412,10 +415,14 @@ class MessageHandler {
|
|
|
412
415
|
const threadId = message.threadId ?? this.threadManager.getDefaultThread().id;
|
|
413
416
|
const content = message.content?.trim() ?? '';
|
|
414
417
|
const clearing = content === '/clear' || content === '/new';
|
|
418
|
+
const management = content === '/abort' || /^\/thread(?:\s+list)?$/.test(content) || /^\/thread\s+new(?:\s|$)/.test(content);
|
|
419
|
+
let admissionCurrent = () => true;
|
|
415
420
|
const body = () => {
|
|
416
|
-
if (!
|
|
421
|
+
if (!admissionCurrent())
|
|
422
|
+
return Promise.resolve();
|
|
423
|
+
if (!clearing && !management)
|
|
417
424
|
this.threadManager.contextResets.assertReady(threadId);
|
|
418
|
-
return this.handleAdmittedCommandMessage(message, fileOrder);
|
|
425
|
+
return this.handleAdmittedCommandMessage(message, fileOrder, () => admissionCurrent());
|
|
419
426
|
};
|
|
420
427
|
this.messageOpenIds.set(message.messageId, message.openId);
|
|
421
428
|
if ((0, SessionResumeService_1.isSessionControl)(content)) {
|
|
@@ -456,10 +463,16 @@ class MessageHandler {
|
|
|
456
463
|
return;
|
|
457
464
|
}
|
|
458
465
|
try {
|
|
466
|
+
if (management)
|
|
467
|
+
return await body();
|
|
468
|
+
if (clearing) {
|
|
469
|
+
await this.settingsAdmission.recovery(threadId, body);
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
459
472
|
// Abort and addressed human replies must remain available during native work.
|
|
460
473
|
if (content === '/abort' || /^(?:yes|no)(?:\s|$)/.test(content) || content.startsWith('/input '))
|
|
461
474
|
return await body();
|
|
462
|
-
if (
|
|
475
|
+
if (/^\/(?:backend|model|effort|cd)\s+\S/.test(content)) {
|
|
463
476
|
const global = /^\/backend\s/.test(content) && !/\s@$/.test(content);
|
|
464
477
|
await this.settingsAdmission.mutation(global ? '*' : threadId, async () => {
|
|
465
478
|
this.settingsService.invalidate(global ? undefined : threadId);
|
|
@@ -469,18 +482,19 @@ class MessageHandler {
|
|
|
469
482
|
});
|
|
470
483
|
}
|
|
471
484
|
else {
|
|
472
|
-
await this.settingsAdmission.command(threadId, message.messageId, async () => {
|
|
485
|
+
await this.settingsAdmission.command(threadId, message.messageId, async (isCurrent) => {
|
|
486
|
+
admissionCurrent = isCurrent;
|
|
473
487
|
if (/^\/(?:clear|new|sandbox)(?:\s|$)/.test(content) || /^\/thread\s+delete(?:\s|$)/.test(content))
|
|
474
488
|
this.settingsService.invalidate(threadId);
|
|
475
489
|
await body();
|
|
476
|
-
});
|
|
490
|
+
}, !content.startsWith('/') && !message.workingDirectory && !this.pendingReplaces.has(message.openId || message.messageId));
|
|
477
491
|
}
|
|
478
492
|
}
|
|
479
493
|
catch (error) {
|
|
480
494
|
this.sendResponse(message.messageId, threadId, { success: false, error: error instanceof Error ? error.message : 'Command admission failed.' }, clearing);
|
|
481
495
|
}
|
|
482
496
|
}
|
|
483
|
-
async handleAdmittedCommandMessage(message, fileOrder) {
|
|
497
|
+
async handleAdmittedCommandMessage(message, fileOrder, admissionCurrent = () => true) {
|
|
484
498
|
const { messageId, content, attachments, workingDirectory, openId, isSlashCommand, threadId } = message;
|
|
485
499
|
this.currentOpenId = openId;
|
|
486
500
|
this.messageOpenIds.set(message.messageId, openId);
|
|
@@ -509,6 +523,14 @@ class MessageHandler {
|
|
|
509
523
|
await this.clearThreadConversation(messageId, resolvedThreadId);
|
|
510
524
|
return;
|
|
511
525
|
}
|
|
526
|
+
if (/^\/thread(?:\s+list)?$/.test(settingsCommand) || /^\/thread\s+new(?:\s|$)/.test(settingsCommand)) {
|
|
527
|
+
await this.handleThreadCommand(messageId, resolvedThreadId, settingsCommand);
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
if (settingsCommand === '/abort') {
|
|
531
|
+
await this.handleAbortCommand(messageId, resolvedThreadId, this.threadPool.getExistingExecutor(resolvedThreadId));
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
512
534
|
if (this.directoryCardsSupported && openId && settingsCommand === '/cd') {
|
|
513
535
|
try {
|
|
514
536
|
const menu = await this.directoryBrowser.open(resolvedThreadId, openId, messageId);
|
|
@@ -546,7 +568,7 @@ class MessageHandler {
|
|
|
546
568
|
}
|
|
547
569
|
return;
|
|
548
570
|
}
|
|
549
|
-
|
|
571
|
+
let executor = this.threadPool.getExecutor(resolvedThreadId);
|
|
550
572
|
this.sendStreamContext(messageId, resolvedThreadId, executor);
|
|
551
573
|
const goalCommand = (0, GoalCommand_1.parseGoalCommand)(settingsCommand);
|
|
552
574
|
let goalRequest;
|
|
@@ -595,11 +617,6 @@ class MessageHandler {
|
|
|
595
617
|
}
|
|
596
618
|
goalRequest = goalCommand.request;
|
|
597
619
|
}
|
|
598
|
-
// Handle /abort for this specific thread (bypasses busy check)
|
|
599
|
-
if (content?.trim() === '/abort') {
|
|
600
|
-
await this.handleAbortCommand(messageId, resolvedThreadId, executor);
|
|
601
|
-
return;
|
|
602
|
-
}
|
|
603
620
|
const abortOperation = this.abortOperations.get(resolvedThreadId);
|
|
604
621
|
if (abortOperation) {
|
|
605
622
|
this.sendStreamChunk(messageId, resolvedThreadId, '⏳ Waiting for the current abort to finish...\n');
|
|
@@ -612,21 +629,12 @@ class MessageHandler {
|
|
|
612
629
|
return;
|
|
613
630
|
}
|
|
614
631
|
}
|
|
632
|
+
if (!admissionCurrent())
|
|
633
|
+
return;
|
|
615
634
|
if (content?.trim() === '/queue' || content?.trim().startsWith('/queue ')) {
|
|
616
635
|
await this.handleQueueCommand(messageId, resolvedThreadId, content.trim());
|
|
617
636
|
return;
|
|
618
637
|
}
|
|
619
|
-
// /thread (list) and /thread new never touch the caller thread's execution
|
|
620
|
-
// context, so they bypass the busy check (like /abort and /queue). This also
|
|
621
|
-
// covers the router's "+ New" card button, which always arrives without a
|
|
622
|
-
// threadId and would otherwise be rejected whenever the default thread is busy.
|
|
623
|
-
// /thread delete is intentionally NOT exempted: it keeps its own busy/queue guards.
|
|
624
|
-
const trimmedForThreadCmd = content?.trim() ?? '';
|
|
625
|
-
if (/^\/thread(?:\s+list)?$/.test(trimmedForThreadCmd)
|
|
626
|
-
|| /^\/thread\s+new(?:\s|$)/.test(trimmedForThreadCmd)) {
|
|
627
|
-
await this.handleThreadCommand(messageId, resolvedThreadId, trimmedForThreadCmd);
|
|
628
|
-
return;
|
|
629
|
-
}
|
|
630
638
|
// Backend switching has its own lifecycle handling and must run before the
|
|
631
639
|
// normal command busy flag is acquired.
|
|
632
640
|
if (content?.trim() === '/backend' || content?.trim().startsWith('/backend ')) {
|
|
@@ -702,6 +710,8 @@ class MessageHandler {
|
|
|
702
710
|
return;
|
|
703
711
|
}
|
|
704
712
|
}
|
|
713
|
+
if (!admissionCurrent())
|
|
714
|
+
return;
|
|
705
715
|
const threadBusy = this.threadPool.isThreadBusy(resolvedThreadId);
|
|
706
716
|
const queuedCount = this.threadQueues.get(resolvedThreadId)?.length ?? 0;
|
|
707
717
|
if (!threadBusy && !this.hasThreadQueueState(resolvedThreadId))
|
|
@@ -755,7 +765,7 @@ class MessageHandler {
|
|
|
755
765
|
const goalActivation = goalRequest ? { cancelled: false } : undefined;
|
|
756
766
|
if (goalActivation)
|
|
757
767
|
this.pendingGoalActivations.set(resolvedThreadId, goalActivation);
|
|
758
|
-
const operationToken = this.beginThreadOperation(resolvedThreadId);
|
|
768
|
+
const operationToken = this.beginThreadOperation(resolvedThreadId, messageId, !content?.trim().startsWith('/') && !workingDirectory && !this.pendingReplaces.has(openId || messageId));
|
|
759
769
|
try {
|
|
760
770
|
this.trackTask(messageId, resolvedThreadId, content || '');
|
|
761
771
|
// Validate and set working directory if provided
|
|
@@ -773,16 +783,14 @@ class MessageHandler {
|
|
|
773
783
|
if (this.delegation.hasActiveTasks(resolvedThreadId)) {
|
|
774
784
|
throw new Error('Cannot change working directory while a delegated worker is running. Wait for it to finish or send /abort first.');
|
|
775
785
|
}
|
|
776
|
-
const generation = this.threadManager.getThread(resolvedThreadId)?.delegationWorkspaceGeneration ?? 0;
|
|
777
786
|
const changedDirectory = await this.threadPool.setWorkingDirectory(resolvedThreadId, workingDirectory);
|
|
778
|
-
if (changedDirectory.changed)
|
|
779
|
-
|
|
780
|
-
if (cleanup.failed)
|
|
781
|
-
this.sendStreamChunk(messageId, resolvedThreadId, `Working directory changed, but ${cleanup.failed} delegated worker lane(s) could not be cleaned up. Retry with /delegation reset after checking filesystem permissions.\n`);
|
|
782
|
-
}
|
|
787
|
+
if (changedDirectory.changed)
|
|
788
|
+
executor = this.threadPool.getExecutor(resolvedThreadId);
|
|
783
789
|
}
|
|
784
790
|
// Update thread activity timestamp
|
|
785
791
|
await this.threadManager.updateThread(resolvedThreadId, { lastActiveAt: Date.now() });
|
|
792
|
+
if (this.cancelledOperations.has(operationToken) || this.activeThreadOperations.get(resolvedThreadId)?.token !== operationToken)
|
|
793
|
+
return;
|
|
786
794
|
// Check for pending replace state (user sending file content)
|
|
787
795
|
const pendingKey = openId || messageId;
|
|
788
796
|
if (this.pendingReplaces.has(pendingKey) && content && !content.startsWith('/')) {
|
|
@@ -794,7 +802,7 @@ class MessageHandler {
|
|
|
794
802
|
return;
|
|
795
803
|
}
|
|
796
804
|
const builtInResult = await this.handleBuiltInCommand(messageId, resolvedThreadId, content, executor);
|
|
797
|
-
if (builtInResult)
|
|
805
|
+
if (builtInResult || this.cancelledOperations.has(operationToken) || this.activeThreadOperations.get(resolvedThreadId)?.token !== operationToken)
|
|
798
806
|
return;
|
|
799
807
|
if (isSlashCommand) {
|
|
800
808
|
console.log(`[MessageHandler] Executing passthrough slash command: ${content}`);
|
|
@@ -806,6 +814,8 @@ class MessageHandler {
|
|
|
806
814
|
await this.executeCommand(messageId, resolvedThreadId, processedContent, executor, attachments);
|
|
807
815
|
}
|
|
808
816
|
catch (error) {
|
|
817
|
+
if (this.cancelledOperations.has(operationToken) || this.activeThreadOperations.get(resolvedThreadId)?.token !== operationToken)
|
|
818
|
+
return;
|
|
809
819
|
this.threadPool.setThreadError(resolvedThreadId, true);
|
|
810
820
|
this.sendResponse(messageId, resolvedThreadId, {
|
|
811
821
|
success: false,
|
|
@@ -813,6 +823,7 @@ class MessageHandler {
|
|
|
813
823
|
});
|
|
814
824
|
}
|
|
815
825
|
finally {
|
|
826
|
+
this.cancelledOperations.delete(operationToken);
|
|
816
827
|
if (goalActivation && this.pendingGoalActivations.get(resolvedThreadId) === goalActivation) {
|
|
817
828
|
this.pendingGoalActivations.delete(resolvedThreadId);
|
|
818
829
|
}
|
|
@@ -825,6 +836,8 @@ class MessageHandler {
|
|
|
825
836
|
* Handle /abort command for a specific thread executor
|
|
826
837
|
*/
|
|
827
838
|
async handleAbortCommand(messageId, threadId, executor) {
|
|
839
|
+
this.conversationRevisions.set(threadId, (this.conversationRevisions.get(threadId) ?? 0) + 1);
|
|
840
|
+
this.settingsAdmission.cancelRecoverable(threadId);
|
|
828
841
|
this.fileInbox?.cancelThread(threadId);
|
|
829
842
|
this.imageDeliveries.get(threadId)?.cancel();
|
|
830
843
|
const pendingGoal = this.pendingGoalActivations.get(threadId);
|
|
@@ -833,14 +846,14 @@ class MessageHandler {
|
|
|
833
846
|
const existingAbort = this.abortOperations.get(threadId);
|
|
834
847
|
if (existingAbort) {
|
|
835
848
|
await existingAbort;
|
|
836
|
-
if (executor
|
|
849
|
+
if (executor?.hasUncertainShutdown?.()) {
|
|
837
850
|
this.sendResponse(messageId, threadId, {
|
|
838
851
|
success: false,
|
|
839
852
|
error: 'Executor shutdown could not be confirmed. This thread remains busy; retry /abort before changing context or sending more work.',
|
|
840
853
|
});
|
|
841
854
|
return;
|
|
842
855
|
}
|
|
843
|
-
if (executor
|
|
856
|
+
if (executor?.isGoalRunning?.()) {
|
|
844
857
|
this.sendResponse(messageId, threadId, {
|
|
845
858
|
success: false,
|
|
846
859
|
error: 'Native goal stop could not be confirmed. This thread remains busy; retry /goal pause or /abort.',
|
|
@@ -855,20 +868,29 @@ class MessageHandler {
|
|
|
855
868
|
}
|
|
856
869
|
const wasExecuting = this.threadPool.isThreadBusy(threadId);
|
|
857
870
|
const clearedCount = this.clearThreadQueue(threadId);
|
|
858
|
-
const activeOperation = this.
|
|
871
|
+
const activeOperation = this.cancelThreadOperation(threadId);
|
|
872
|
+
this.detachDelegationBridge(threadId);
|
|
873
|
+
for (const [id, approval] of this.pendingApprovalCards) {
|
|
874
|
+
if (approval.request.threadId === threadId)
|
|
875
|
+
this.resolveApprovalCard(id, 'expired');
|
|
876
|
+
}
|
|
859
877
|
let aborted = false;
|
|
860
878
|
const operation = (async () => {
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
aborted = await executor.abort();
|
|
864
|
-
if (executor
|
|
879
|
+
const workers = this.delegation.cancelThread(threadId);
|
|
880
|
+
// Parent cancellation starts concurrently with worker cleanup.
|
|
881
|
+
[aborted] = await Promise.all([executor ? executor.abort() : Promise.resolve(false), workers]);
|
|
882
|
+
if (executor?.hasUncertainShutdown?.()) {
|
|
865
883
|
throw new Error('Executor shutdown could not be confirmed. This thread remains busy; retry /abort before changing context or sending more work.');
|
|
866
884
|
}
|
|
867
|
-
if (!aborted && executor
|
|
885
|
+
if (!aborted && executor?.isGoalRunning?.()) {
|
|
868
886
|
throw new Error('Native goal stop could not be confirmed. This thread remains busy; retry /goal pause or /abort.');
|
|
869
887
|
}
|
|
870
|
-
if (activeOperation)
|
|
888
|
+
if (activeOperation && !activeOperation.recoverable)
|
|
871
889
|
await activeOperation.done;
|
|
890
|
+
if (activeOperation)
|
|
891
|
+
this.finishThreadOperation(threadId, activeOperation.token);
|
|
892
|
+
else
|
|
893
|
+
this.threadPool.setThreadBusy(threadId, false);
|
|
872
894
|
})();
|
|
873
895
|
const barrier = operation.then(() => undefined, () => undefined);
|
|
874
896
|
this.abortOperations.set(threadId, barrier);
|
|
@@ -954,28 +976,62 @@ class MessageHandler {
|
|
|
954
976
|
this.wsClient.send({ type: 'worker_context_reset_result', messageId: request.messageId,
|
|
955
977
|
success: !error, ...(error ? { error } : {}), timestamp: Date.now() });
|
|
956
978
|
}
|
|
979
|
+
detachDelegationBridge(threadId) {
|
|
980
|
+
const bridge = this.delegationBridges.get(threadId);
|
|
981
|
+
if (!bridge)
|
|
982
|
+
return;
|
|
983
|
+
bridge.activate(undefined);
|
|
984
|
+
this.delegationBridges.delete(threadId);
|
|
985
|
+
void bridge.close().catch(() => undefined);
|
|
986
|
+
}
|
|
957
987
|
async clearThreadConversation(messageId, threadId) {
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
this.
|
|
963
|
-
|
|
988
|
+
this.conversationRevisions.set(threadId, (this.conversationRevisions.get(threadId) ?? 0) + 1);
|
|
989
|
+
this.settingsService.invalidate(threadId);
|
|
990
|
+
this.directoryBrowser.invalidate(threadId);
|
|
991
|
+
this.clearThreadQueue(threadId);
|
|
992
|
+
this.fileInbox?.cancelThread(threadId);
|
|
993
|
+
this.imageDeliveries.get(threadId)?.cancel();
|
|
994
|
+
for (const [id, approval] of this.pendingApprovalCards) {
|
|
995
|
+
if (approval.request.threadId === threadId)
|
|
996
|
+
this.resolveApprovalCard(id, 'expired');
|
|
997
|
+
}
|
|
998
|
+
const active = this.cancelThreadOperation(threadId);
|
|
999
|
+
this.detachDelegationBridge(threadId);
|
|
1000
|
+
// Closing the worker scope is synchronous; its cleanup remains manager-owned.
|
|
1001
|
+
const workers = this.delegation.cancelThread(threadId);
|
|
1002
|
+
void workers.catch(() => undefined);
|
|
964
1003
|
try {
|
|
965
|
-
await this.delegation.assertThreadContextResettable(threadId);
|
|
966
1004
|
await this.threadManager.contextResets.begin(threadId);
|
|
1005
|
+
const thread = this.threadManager.getThread(threadId);
|
|
1006
|
+
await this.threadManager.contextResets.advanceGeneration(threadId, thread.delegationWorkspaceGeneration);
|
|
1007
|
+
const aborting = this.abortOperations.get(threadId);
|
|
1008
|
+
if (aborting)
|
|
1009
|
+
throw new Error('Direct backend abort is still pending; retry after it settles');
|
|
1010
|
+
const executor = this.threadPool.getExistingExecutor(threadId);
|
|
1011
|
+
if (executor) {
|
|
1012
|
+
await executor.abort();
|
|
1013
|
+
if (executor.hasUncertainShutdown?.())
|
|
1014
|
+
throw new Error('Direct backend shutdown is unconfirmed');
|
|
1015
|
+
}
|
|
1016
|
+
if (this.coordinatorPreparations.has(threadId))
|
|
1017
|
+
throw new Error('Direct backend preparation is still pending; retry after it settles');
|
|
1018
|
+
this.threadPool.assertContextResettable(threadId);
|
|
967
1019
|
await this.threadPool.clearThreadContext(threadId);
|
|
968
|
-
|
|
1020
|
+
if (this.abortOperations.has(threadId))
|
|
1021
|
+
throw new Error('Direct backend abort is still pending; retry after it settles');
|
|
969
1022
|
await this.threadManager.contextResets.complete(threadId);
|
|
1023
|
+
this.threadPool.setThreadBusy(threadId, false);
|
|
1024
|
+
await workers;
|
|
970
1025
|
this.sendResponse(messageId, threadId, { success: true,
|
|
971
|
-
output: '
|
|
1026
|
+
output: 'Started a fresh conversation for direct backends and managed workers. Historical worker contexts and artifacts are retained for explicit recovery. Pending native writers still block conflicting execution.' }, true);
|
|
972
1027
|
}
|
|
973
1028
|
catch (error) {
|
|
974
1029
|
const detail = error instanceof Error ? error.message : 'Local context storage is unavailable';
|
|
975
1030
|
throw new Error(`Could not clear thread conversation: ${detail}. Check local CLI storage and retry /clear or /new.`);
|
|
976
1031
|
}
|
|
977
1032
|
finally {
|
|
978
|
-
|
|
1033
|
+
if (active)
|
|
1034
|
+
this.finishThreadOperation(threadId, active.token);
|
|
979
1035
|
}
|
|
980
1036
|
}
|
|
981
1037
|
/**
|
|
@@ -1219,6 +1275,7 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
1219
1275
|
});
|
|
1220
1276
|
return true;
|
|
1221
1277
|
}
|
|
1278
|
+
await this.assertNativeCommandReady(threadId, executor);
|
|
1222
1279
|
this.sendStreamChunk(messageId, threadId, '🗜️ Compressing conversation history...\n');
|
|
1223
1280
|
const result = await executor.compactWhenFull((chunk) => {
|
|
1224
1281
|
this.sendStreamChunk(messageId, threadId, chunk);
|
|
@@ -1507,12 +1564,14 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
1507
1564
|
this.currentOpenId = command.openId;
|
|
1508
1565
|
this.messageOpenIds.set(command.messageId, command.openId);
|
|
1509
1566
|
this.notificationAdapter.setCurrentOpenId(command.openId);
|
|
1510
|
-
const operationToken = this.beginThreadOperation(threadId);
|
|
1567
|
+
const operationToken = this.beginThreadOperation(threadId, command.messageId, true);
|
|
1511
1568
|
console.log(`[MessageHandler] Starting queued message ${command.messageId} in thread ${threadId}: remaining=${this.threadQueues.get(threadId)?.length ?? 0}`);
|
|
1512
1569
|
try {
|
|
1513
1570
|
const executor = this.threadPool.getExecutor(threadId);
|
|
1514
1571
|
this.trackTask(command.messageId, threadId, command.content);
|
|
1515
1572
|
await this.threadManager.updateThread(threadId, { lastActiveAt: Date.now() });
|
|
1573
|
+
if (this.cancelledOperations.has(operationToken) || this.activeThreadOperations.get(threadId)?.token !== operationToken)
|
|
1574
|
+
return;
|
|
1516
1575
|
this.wsClient.send({
|
|
1517
1576
|
type: 'queue_started',
|
|
1518
1577
|
messageId: command.messageId,
|
|
@@ -1532,12 +1591,15 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
1532
1591
|
await this.executeCommand(command.messageId, threadId, processedContent, executor, command.attachments, true);
|
|
1533
1592
|
}
|
|
1534
1593
|
catch (error) {
|
|
1594
|
+
if (this.cancelledOperations.has(operationToken) || this.activeThreadOperations.get(threadId)?.token !== operationToken)
|
|
1595
|
+
return;
|
|
1535
1596
|
this.sendResponse(command.messageId, threadId, {
|
|
1536
1597
|
success: false,
|
|
1537
1598
|
error: this.pauseQueueAfterFailure(threadId, error instanceof Error ? error.message : 'Queued command failed'),
|
|
1538
1599
|
});
|
|
1539
1600
|
}
|
|
1540
1601
|
finally {
|
|
1602
|
+
this.cancelledOperations.delete(operationToken);
|
|
1541
1603
|
if (this.finishThreadOperation(threadId, operationToken) && !this.pausedQueues.has(threadId)) {
|
|
1542
1604
|
void this.startNextQueuedCommand(threadId);
|
|
1543
1605
|
}
|
|
@@ -1553,11 +1615,21 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
1553
1615
|
console.warn(`[MessageHandler] Queue paused in thread ${threadId}: confirmed=${count}, awaiting_confirmation=${pending}`);
|
|
1554
1616
|
return `${error}\n\n⏸️ Queue paused after a failed task. Waiting: ${count} confirmed, ${pending} awaiting confirmation. Use /queue continue to resume, or /queue clear to discard pending messages.`;
|
|
1555
1617
|
}
|
|
1556
|
-
|
|
1618
|
+
cancelThreadOperation(threadId, reason = 'Request cancelled by conversation recovery. Worker cleanup may continue in the background.') {
|
|
1619
|
+
const active = this.activeThreadOperations.get(threadId);
|
|
1620
|
+
if (active && !this.cancelledOperations.has(active.token)) {
|
|
1621
|
+
this.cancelledOperations.add(active.token);
|
|
1622
|
+
// Complete task-recovery bookkeeping before a newer request can be admitted.
|
|
1623
|
+
if (active.messageId)
|
|
1624
|
+
this.sendResponse(active.messageId, threadId, { success: false, error: reason }, true);
|
|
1625
|
+
}
|
|
1626
|
+
return active;
|
|
1627
|
+
}
|
|
1628
|
+
beginThreadOperation(threadId, messageId, recoverable = false) {
|
|
1557
1629
|
const token = Symbol(threadId);
|
|
1558
1630
|
let resolveDone;
|
|
1559
1631
|
const done = new Promise((resolve) => { resolveDone = resolve; });
|
|
1560
|
-
this.activeThreadOperations.set(threadId, { token, done, resolveDone });
|
|
1632
|
+
this.activeThreadOperations.set(threadId, { token, done, resolveDone, messageId, recoverable });
|
|
1561
1633
|
this.threadPool.setThreadBusy(threadId, true);
|
|
1562
1634
|
return token;
|
|
1563
1635
|
}
|
|
@@ -1644,8 +1716,7 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
1644
1716
|
if (sub === 'new') {
|
|
1645
1717
|
const name = parts[2];
|
|
1646
1718
|
const callerThread = this.threadManager.getThread(callerThreadId) || this.threadManager.getDefaultThread();
|
|
1647
|
-
const
|
|
1648
|
-
const cwd = callerExecutor.getCurrentWorkingDirectory();
|
|
1719
|
+
const cwd = callerThread.workingDirectory;
|
|
1649
1720
|
try {
|
|
1650
1721
|
const newThread = await this.threadManager.createThread(name || this.generateThreadName(), cwd, this.threadPool.getBackendKey(callerThread.id));
|
|
1651
1722
|
// Use newThread.id so the router maps this card to the new thread,
|
|
@@ -1997,6 +2068,20 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
1997
2068
|
resolveSlashBackend(threadId) {
|
|
1998
2069
|
return this.threadPool.getBackendKey(threadId);
|
|
1999
2070
|
}
|
|
2071
|
+
/** Native commands can execute model tools and must honor the same recovery barriers as chat. */
|
|
2072
|
+
async assertNativeCommandReady(threadId, executor) {
|
|
2073
|
+
const token = this.activeThreadOperations.get(threadId)?.token;
|
|
2074
|
+
if (this.coordinatorPreparations.has(threadId)) {
|
|
2075
|
+
throw new Error('Previous backend preparation is still pending. Wait for it to settle, then retry /clear before sending more work.');
|
|
2076
|
+
}
|
|
2077
|
+
if (executor.hasUncertainShutdown?.())
|
|
2078
|
+
throw new Error('Direct backend shutdown is unconfirmed. Retry /abort or /clear before sending more work.');
|
|
2079
|
+
await this.delegation.assertExecutionSafe(executor.getCurrentWorkingDirectory(), threadId);
|
|
2080
|
+
if (this.isDestroyed || this.abortOperations.has(threadId) || (token &&
|
|
2081
|
+
(this.cancelledOperations.has(token) || this.activeThreadOperations.get(threadId)?.token !== token))) {
|
|
2082
|
+
throw new Error('Conversation request was cancelled');
|
|
2083
|
+
}
|
|
2084
|
+
}
|
|
2000
2085
|
/**
|
|
2001
2086
|
* Execute passthrough slash command on the active backend's CLI.
|
|
2002
2087
|
*
|
|
@@ -2022,6 +2107,7 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
2022
2107
|
// ZCode names its native skill-list command /skill, while remote-cli
|
|
2023
2108
|
// exposes the cross-backend command as /skills.
|
|
2024
2109
|
const backendCommand = backend === 'zcode' && command.trim() === '/skills' ? '/skill' : command;
|
|
2110
|
+
await this.assertNativeCommandReady(threadId, executor);
|
|
2025
2111
|
const result = await executor.execute(backendCommand, {
|
|
2026
2112
|
onStream: (chunk) => this.sendStreamChunk(messageId, threadId, chunk),
|
|
2027
2113
|
onToolUse: (toolUse) => this.sendToolUse(messageId, threadId, toolUse),
|
|
@@ -2068,7 +2154,8 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
2068
2154
|
* Spawn a one-shot CLI process for a passthrough slash command and relay
|
|
2069
2155
|
* its output back to the user.
|
|
2070
2156
|
*/
|
|
2071
|
-
spawnPassthroughCommand(messageId, threadId, bin, args, executor, backend, extraEnv = {}) {
|
|
2157
|
+
async spawnPassthroughCommand(messageId, threadId, bin, args, executor, backend, extraEnv = {}) {
|
|
2158
|
+
await this.assertNativeCommandReady(threadId, executor);
|
|
2072
2159
|
return new Promise((resolve) => {
|
|
2073
2160
|
const label = backend === 'agy' ? 'AGY CLI' : 'Claude CLI';
|
|
2074
2161
|
const chunks = [];
|
|
@@ -2132,6 +2219,25 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
2132
2219
|
* Execute AI command on a specific executor
|
|
2133
2220
|
*/
|
|
2134
2221
|
async executeCommand(messageId, threadId, content, executor, attachments, fromQueue = false, goalRequest, goalActivation) {
|
|
2222
|
+
if (this.coordinatorPreparations.has(threadId)) {
|
|
2223
|
+
throw new Error('Previous backend preparation is still pending. Wait for it to settle, then retry /clear before sending more work.');
|
|
2224
|
+
}
|
|
2225
|
+
if (executor.hasUncertainShutdown?.())
|
|
2226
|
+
throw new Error('Direct backend shutdown is unconfirmed. Retry /abort or /clear before sending more work.');
|
|
2227
|
+
const conversationRevision = this.conversationRevisions.get(threadId) ?? 0;
|
|
2228
|
+
const operationToken = this.activeThreadOperations.get(threadId)?.token;
|
|
2229
|
+
const isCurrent = () => !this.isDestroyed && (!operationToken ||
|
|
2230
|
+
(!this.cancelledOperations.has(operationToken) && this.activeThreadOperations.get(threadId)?.token === operationToken));
|
|
2231
|
+
let prepared;
|
|
2232
|
+
const preparation = new Promise(resolve => { prepared = resolve; });
|
|
2233
|
+
this.coordinatorPreparations.set(threadId, preparation);
|
|
2234
|
+
const finishPreparation = () => {
|
|
2235
|
+
prepared();
|
|
2236
|
+
if (this.coordinatorPreparations.get(threadId) === preparation)
|
|
2237
|
+
this.coordinatorPreparations.delete(threadId);
|
|
2238
|
+
};
|
|
2239
|
+
const assertCurrent = () => { if (!isCurrent())
|
|
2240
|
+
throw new Error('Conversation request was cancelled'); };
|
|
2135
2241
|
this.sendStreamContext(messageId, threadId, executor);
|
|
2136
2242
|
let delegationScope;
|
|
2137
2243
|
let delegationBridge;
|
|
@@ -2141,7 +2247,7 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
2141
2247
|
let executionActive = false;
|
|
2142
2248
|
let lastProgramState;
|
|
2143
2249
|
const activity = new ActivityProgress_1.ActivityProgress(snapshot => {
|
|
2144
|
-
if (requestFinished || this.isDestroyed || this.abortOperations.has(threadId)
|
|
2250
|
+
if (!isCurrent() || requestFinished || this.isDestroyed || this.abortOperations.has(threadId)
|
|
2145
2251
|
|| !this.activityProgressSupported || delegationScope?.isClosed())
|
|
2146
2252
|
return false;
|
|
2147
2253
|
if (executor.isWaitingInput?.()) {
|
|
@@ -2155,13 +2261,20 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
2155
2261
|
});
|
|
2156
2262
|
const showState = (text) => {
|
|
2157
2263
|
activity.clear();
|
|
2158
|
-
if (text === lastProgramState || requestFinished || this.isDestroyed || this.abortOperations.has(threadId)
|
|
2264
|
+
if (!isCurrent() || text === lastProgramState || requestFinished || this.isDestroyed || this.abortOperations.has(threadId)
|
|
2159
2265
|
|| !this.activityProgressSupported || delegationScope?.isClosed())
|
|
2160
2266
|
return;
|
|
2161
2267
|
if (this.sendActivity(messageId, threadId, { source: 'state', text }))
|
|
2162
2268
|
lastProgramState = text;
|
|
2163
2269
|
};
|
|
2164
2270
|
const complete = async (success, error) => {
|
|
2271
|
+
finishPreparation();
|
|
2272
|
+
if (!isCurrent()) {
|
|
2273
|
+
imageDelivery?.cancel();
|
|
2274
|
+
activity.dispose();
|
|
2275
|
+
void delegationScope?.close().catch(() => undefined);
|
|
2276
|
+
return false;
|
|
2277
|
+
}
|
|
2165
2278
|
await imageDelivery?.finish();
|
|
2166
2279
|
if (this.imageDeliveries.get(threadId) === imageDelivery)
|
|
2167
2280
|
this.imageDeliveries.delete(threadId);
|
|
@@ -2173,6 +2286,8 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
2173
2286
|
? delegationScope.getRetainedResults() : [];
|
|
2174
2287
|
if (delegationScope)
|
|
2175
2288
|
await delegationScope.close();
|
|
2289
|
+
if (!isCurrent())
|
|
2290
|
+
return false;
|
|
2176
2291
|
if (retained.length && !this.isDestroyed && !this.abortOperations.has(threadId)) {
|
|
2177
2292
|
const details = retained.map(task => [
|
|
2178
2293
|
`${task.backend}: ${task.state} (${task.taskId})`, task.output,
|
|
@@ -2207,14 +2322,14 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
2207
2322
|
if (goalRequest && thread && (0, DelegationSettings_1.isDelegationEnabled)(thread)) {
|
|
2208
2323
|
throw new Error('Turn managed delegation off before starting a native goal.');
|
|
2209
2324
|
}
|
|
2325
|
+
await this.delegation.assertExecutionSafe(executor.getCurrentWorkingDirectory(), threadId);
|
|
2326
|
+
assertCurrent();
|
|
2210
2327
|
if (thread && (0, DelegationSettings_1.isDelegationEnabled)(thread) && executor.configureDelegation) {
|
|
2211
|
-
if (this.delegation.blocksWorkspace(executor.getCurrentWorkingDirectory(), threadId)) {
|
|
2212
|
-
throw new Error('A delegated worker holds this workspace. Wait for it to finish; if worker cleanup failed, stop the worker and restart the CLI.');
|
|
2213
|
-
}
|
|
2214
2328
|
const backend = this.threadPool.getBackendKey(threadId);
|
|
2215
2329
|
if (!thread.delegationBackends?.includes(backend)) {
|
|
2216
2330
|
await this.threadManager.updateThread(threadId, { delegationBackends: [...(thread.delegationBackends ?? []), backend] });
|
|
2217
2331
|
}
|
|
2332
|
+
assertCurrent();
|
|
2218
2333
|
delegationScope = this.delegation.begin({ thread, messageId,
|
|
2219
2334
|
backend: this.threadPool.getBackendKey(threadId),
|
|
2220
2335
|
config: this.config.get('executor') ?? { type: 'auto' },
|
|
@@ -2232,10 +2347,11 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
2232
2347
|
onActivityProgress: this.delegationProgressSupported && this.activityProgressSupported
|
|
2233
2348
|
? progress => this.sendDelegationProgress(messageId, threadId, progress)
|
|
2234
2349
|
: undefined,
|
|
2235
|
-
onApproval: (request, child) => this.forwardApproval(request, child, messageId, threadId, true),
|
|
2236
|
-
onApprovalResolved: (id, status) =>
|
|
2350
|
+
onApproval: (request, child) => isCurrent() && this.forwardApproval(request, child, messageId, threadId, true),
|
|
2351
|
+
onApprovalResolved: (id, status) => { if (isCurrent())
|
|
2352
|
+
this.resolveApprovalCard(id, status); },
|
|
2237
2353
|
isWorkspaceBusy: cwd => this.threadManager.listThreads().some(other => {
|
|
2238
|
-
if (other.id === threadId || !this.threadPool.isThreadBusy(other.id))
|
|
2354
|
+
if (other.id === threadId && isCurrent() || !this.threadPool.isThreadBusy(other.id))
|
|
2239
2355
|
return false;
|
|
2240
2356
|
try {
|
|
2241
2357
|
return (0, DelegationManager_1.workspacesOverlap)((0, fs_2.realpathSync)(this.threadPool.getExecutor(other.id).getCurrentWorkingDirectory()), cwd);
|
|
@@ -2247,18 +2363,21 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
2247
2363
|
delegationBridge = this.delegationBridges.get(threadId) ?? new DelegationBridge_1.DelegationBridge();
|
|
2248
2364
|
this.delegationBridges.set(threadId, delegationBridge);
|
|
2249
2365
|
const connection = await delegationBridge.start();
|
|
2366
|
+
assertCurrent();
|
|
2250
2367
|
await executor.configureDelegation(connection);
|
|
2368
|
+
assertCurrent();
|
|
2251
2369
|
if (delegationScope.isClosed() || this.isDestroyed || this.abortOperations.has(threadId)) {
|
|
2252
2370
|
throw new Error('Delegation was cancelled before the coordinator started');
|
|
2253
2371
|
}
|
|
2254
|
-
|
|
2255
|
-
content = `${contract_1.DELEGATION_INSTRUCTIONS}${pendingArtifacts ? `\n\n${pendingArtifacts}` : ''}\n\nUser request:\n${content}`;
|
|
2372
|
+
content = `${contract_1.DELEGATION_INSTRUCTIONS}\n\nUser request:\n${content}`;
|
|
2256
2373
|
}
|
|
2257
2374
|
else if (thread?.delegationBackends?.includes(this.threadPool.getBackendKey(threadId)) && executor.configureDelegation) {
|
|
2258
2375
|
await executor.configureDelegation(undefined);
|
|
2259
2376
|
}
|
|
2260
2377
|
const onTaskNotification = (notification) => {
|
|
2261
|
-
if (this.isDestroyed || !this.threadManager.getThread(threadId)
|
|
2378
|
+
if (this.isDestroyed || !this.threadManager.getThread(threadId)
|
|
2379
|
+
|| (this.conversationRevisions.get(threadId) ?? 0) !== conversationRevision
|
|
2380
|
+
|| (this.threadManager.getThread(threadId)?.delegationWorkspaceGeneration ?? 0) !== (thread?.delegationWorkspaceGeneration ?? 0))
|
|
2262
2381
|
return;
|
|
2263
2382
|
this.notificationAdapter.sendTaskNotification({ ...notification, threadId }, openId);
|
|
2264
2383
|
};
|
|
@@ -2301,10 +2420,13 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
2301
2420
|
const executeOptions = {
|
|
2302
2421
|
onActivity: this.activityProgressSupported ? (snapshot) => activity.offer(snapshot) : undefined,
|
|
2303
2422
|
onApprovalRequest: (approval) => {
|
|
2423
|
+
if (!isCurrent())
|
|
2424
|
+
return false;
|
|
2304
2425
|
showState('Waiting for approval');
|
|
2305
2426
|
return this.forwardApproval(approval, executor, messageId, threadId);
|
|
2306
2427
|
},
|
|
2307
|
-
onApprovalResolved: (requestId, status) =>
|
|
2428
|
+
onApprovalResolved: (requestId, status) => { if (isCurrent())
|
|
2429
|
+
this.resolveApprovalCard(requestId, status); },
|
|
2308
2430
|
onTaskNotification,
|
|
2309
2431
|
onStream: (chunk) => {
|
|
2310
2432
|
streamedAny = true;
|
|
@@ -2354,6 +2476,7 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
2354
2476
|
attachments,
|
|
2355
2477
|
};
|
|
2356
2478
|
const assertCoordinatorActive = () => {
|
|
2479
|
+
assertCurrent();
|
|
2357
2480
|
if (delegationScope && (delegationScope.isClosed() || this.isDestroyed || this.abortOperations.has(threadId))) {
|
|
2358
2481
|
throw new Error('Delegation was cancelled');
|
|
2359
2482
|
}
|
|
@@ -2381,11 +2504,11 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
2381
2504
|
return Promise.reject(new Error('The coordinator execution has ended'));
|
|
2382
2505
|
return scope.invoke(...args);
|
|
2383
2506
|
});
|
|
2384
|
-
const canPublish = () => active && (!scope || (!scope.isClosed() && !scope.hasPendingResults()));
|
|
2507
|
+
const canPublish = () => isCurrent() && active && (!scope || (!scope.isClosed() && !scope.hasPendingResults()));
|
|
2385
2508
|
const guardedOptions = {
|
|
2386
2509
|
...options,
|
|
2387
2510
|
onActivity: options.onActivity ? snapshot => {
|
|
2388
|
-
if (!active || requestFinished || this.isDestroyed || this.abortOperations.has(threadId))
|
|
2511
|
+
if (!isCurrent() || !active || requestFinished || this.isDestroyed || this.abortOperations.has(threadId))
|
|
2389
2512
|
return;
|
|
2390
2513
|
if (executor.isWaitingInput?.()) {
|
|
2391
2514
|
showState('Waiting for your input');
|
|
@@ -2396,10 +2519,10 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
2396
2519
|
showState('Waiting for worker results');
|
|
2397
2520
|
} : undefined,
|
|
2398
2521
|
onStream: chunk => {
|
|
2399
|
-
if (!active || scope?.isClosed())
|
|
2522
|
+
if (!isCurrent() || !active || scope?.isClosed())
|
|
2400
2523
|
return;
|
|
2401
2524
|
queueMicrotask(() => {
|
|
2402
|
-
if (active && !requestFinished && executor.isWaitingInput?.())
|
|
2525
|
+
if (isCurrent() && active && !requestFinished && executor.isWaitingInput?.())
|
|
2403
2526
|
showState('Waiting for your input');
|
|
2404
2527
|
});
|
|
2405
2528
|
if (canPublish())
|
|
@@ -2409,7 +2532,7 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
2409
2532
|
// ACP and Pi may set their pending-input flag just after emitting
|
|
2410
2533
|
// the prompt. Keep real questions/approvals visible, not stale prose.
|
|
2411
2534
|
queueMicrotask(() => {
|
|
2412
|
-
if (active && !scope?.isClosed() && executor.isWaitingInput?.())
|
|
2535
|
+
if (isCurrent() && active && !scope?.isClosed() && executor.isWaitingInput?.())
|
|
2413
2536
|
options.onStream?.(chunk);
|
|
2414
2537
|
});
|
|
2415
2538
|
}
|
|
@@ -2428,9 +2551,9 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
2428
2551
|
suppressed = true; },
|
|
2429
2552
|
onRedactedThinking: () => { if (canPublish())
|
|
2430
2553
|
options.onRedactedThinking?.(); },
|
|
2431
|
-
onToolUse: tool => { if (active && !scope?.isClosed())
|
|
2554
|
+
onToolUse: tool => { if (isCurrent() && active && !scope?.isClosed())
|
|
2432
2555
|
options.onToolUse?.(tool); },
|
|
2433
|
-
onToolResult: tool => { if (active && !scope?.isClosed())
|
|
2556
|
+
onToolResult: tool => { if (isCurrent() && active && !scope?.isClosed())
|
|
2434
2557
|
options.onToolResult?.(tool); },
|
|
2435
2558
|
};
|
|
2436
2559
|
const backend = this.threadPool.getBackendKey(threadId);
|
|
@@ -2483,14 +2606,20 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
2483
2606
|
mayRetry = !goalRequest && (!scope || scope.getLaunchRevision() === launchRevision);
|
|
2484
2607
|
}
|
|
2485
2608
|
};
|
|
2609
|
+
finishPreparation();
|
|
2610
|
+
assertCurrent();
|
|
2486
2611
|
let prompt = content;
|
|
2487
2612
|
let options = executeOptions;
|
|
2488
2613
|
let closeoutRounds = 0;
|
|
2489
2614
|
for (;;) {
|
|
2490
2615
|
let result = await executeOnce(prompt, options);
|
|
2616
|
+
assertCoordinatorActive();
|
|
2491
2617
|
// Retry only an execution that accepted no new worker launch. Historical
|
|
2492
2618
|
// completed tasks must not disable recovery of the result continuation.
|
|
2493
|
-
if (mayRetry && await this.
|
|
2619
|
+
if (mayRetry && await this.withCoordinatorPreparation(threadId, () => {
|
|
2620
|
+
assertCoordinatorActive();
|
|
2621
|
+
return this.clearInvalidCodexModel(threadId, executor, result.error);
|
|
2622
|
+
})) {
|
|
2494
2623
|
assertCoordinatorActive();
|
|
2495
2624
|
this.sendStreamChunk(messageId, threadId, '⚠️ The saved Codex model is unavailable for this account. Cleared it and retrying with the backend default...\n');
|
|
2496
2625
|
// Retain the ordinary path's existing image-flush timing on model retry.
|
|
@@ -2500,8 +2629,12 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
2500
2629
|
if ('compactWhenFull' in executor && typeof executor.compactWhenFull === 'function') {
|
|
2501
2630
|
this.sendStreamChunk(messageId, threadId, '🔄 Context window full. Compacting conversation history, please wait...\n');
|
|
2502
2631
|
showState('Compacting context');
|
|
2503
|
-
const compactResult = await
|
|
2504
|
-
|
|
2632
|
+
const compactResult = await this.withCoordinatorPreparation(threadId, () => {
|
|
2633
|
+
assertCoordinatorActive();
|
|
2634
|
+
return executor.compactWhenFull((chunk) => {
|
|
2635
|
+
if (isCurrent())
|
|
2636
|
+
this.sendStreamChunk(messageId, threadId, chunk);
|
|
2637
|
+
});
|
|
2505
2638
|
});
|
|
2506
2639
|
assertCoordinatorActive();
|
|
2507
2640
|
if (!compactResult.success) {
|
|
@@ -2560,6 +2693,25 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
2560
2693
|
catch (error) {
|
|
2561
2694
|
return complete(false, error instanceof Error ? error.message : 'Execution error');
|
|
2562
2695
|
}
|
|
2696
|
+
finally {
|
|
2697
|
+
finishPreparation();
|
|
2698
|
+
if (delegationBridge && this.delegationBridges.get(threadId) !== delegationBridge) {
|
|
2699
|
+
void delegationBridge.close().catch(() => undefined);
|
|
2700
|
+
}
|
|
2701
|
+
}
|
|
2702
|
+
}
|
|
2703
|
+
/** Native retry/configuration work may outlive cancellation and still write stable pointers. */
|
|
2704
|
+
async withCoordinatorPreparation(threadId, operation) {
|
|
2705
|
+
const pending = Promise.resolve().then(operation);
|
|
2706
|
+
const barrier = pending.then(() => undefined, () => undefined);
|
|
2707
|
+
this.coordinatorPreparations.set(threadId, barrier);
|
|
2708
|
+
try {
|
|
2709
|
+
return await pending;
|
|
2710
|
+
}
|
|
2711
|
+
finally {
|
|
2712
|
+
if (this.coordinatorPreparations.get(threadId) === barrier)
|
|
2713
|
+
this.coordinatorPreparations.delete(threadId);
|
|
2714
|
+
}
|
|
2563
2715
|
}
|
|
2564
2716
|
async clearInvalidCodexModel(threadId, executor, error) {
|
|
2565
2717
|
if (!error || !this.isUnavailableCodexModelError(error))
|
|
@@ -2817,6 +2969,12 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
2817
2969
|
}
|
|
2818
2970
|
}
|
|
2819
2971
|
sendResponse(messageId, threadId, result, metadataOnly = false) {
|
|
2972
|
+
const operation = threadId ? this.activeThreadOperations.get(threadId) : undefined;
|
|
2973
|
+
if (operation && operation.messageId === messageId && !result.queueConfirmation) {
|
|
2974
|
+
if (operation.responseSent)
|
|
2975
|
+
return;
|
|
2976
|
+
operation.responseSent = true;
|
|
2977
|
+
}
|
|
2820
2978
|
if (!result.queueConfirmation)
|
|
2821
2979
|
this.fileInbox?.release(messageId, !result.success);
|
|
2822
2980
|
try {
|
|
@@ -2862,18 +3020,16 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
2862
3020
|
/** Shared card/text Apply path. Callers hold exclusive settings admission. */
|
|
2863
3021
|
async changeWorkingDirectory(threadId, targetDir) {
|
|
2864
3022
|
if (this.isDestroyed || this.automaticUpdateInProgress || this.abortOperations.has(threadId)
|
|
2865
|
-
|| this.threadPool.isThreadBusy(threadId) || this.hasThreadQueueState(threadId)) {
|
|
3023
|
+
|| this.threadPool.isThreadBusy(threadId) || this.coordinatorPreparations.has(threadId) || this.hasThreadQueueState(threadId)) {
|
|
2866
3024
|
throw new Error('Cannot change working directory while the thread has active or queued work. Retry when it is idle.');
|
|
2867
3025
|
}
|
|
2868
3026
|
if (this.delegation.hasActiveTasks(threadId)) {
|
|
2869
3027
|
throw new Error('Cannot change working directory while a delegated worker is running. Wait for it to finish or send /abort first.');
|
|
2870
3028
|
}
|
|
2871
3029
|
this.settingsService.invalidate(threadId);
|
|
2872
|
-
const generation = this.threadManager.getThread(threadId)?.delegationWorkspaceGeneration ?? 0;
|
|
2873
3030
|
const { cwd, changed } = await this.threadPool.setWorkingDirectory(threadId, targetDir);
|
|
2874
|
-
const cleanup = changed ? await this.delegation.invalidateWorkspaceGeneration(threadId, generation + 1) : { removed: 0, failed: 0 };
|
|
2875
3031
|
this.directoryBrowser.invalidate(threadId);
|
|
2876
|
-
return { success: true, output: `✅ Changed working directory to: ${cwd}${changed ? '\nConversation context cleared for all direct and delegated backends in this thread.' : ''}
|
|
3032
|
+
return { success: true, output: `✅ Changed working directory to: ${cwd}${changed ? '\nConversation context cleared for all direct and delegated backends in this thread.' : ''}` };
|
|
2877
3033
|
}
|
|
2878
3034
|
settingsState(threadId) {
|
|
2879
3035
|
this.threadManager.contextResets.assertReady(threadId);
|
|
@@ -2894,7 +3050,7 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
2894
3050
|
settingsBusy(threadId, exceptRequest, includeQueue = true) {
|
|
2895
3051
|
return this.isDestroyed || this.automaticUpdateInProgress || this.threadPool.isThreadBusy(threadId)
|
|
2896
3052
|
|| this.delegation.hasActiveTasks(threadId) || this.abortOperations.has(threadId)
|
|
2897
|
-
|| this.settingsAdmission.hasCommand(threadId, exceptRequest) || (includeQueue && this.hasThreadQueueState(threadId));
|
|
3053
|
+
|| this.coordinatorPreparations.has(threadId) || this.settingsAdmission.hasCommand(threadId, exceptRequest) || (includeQueue && this.hasThreadQueueState(threadId));
|
|
2898
3054
|
}
|
|
2899
3055
|
settingsFallback(menu) {
|
|
2900
3056
|
const lines = [`${menu.kind === 'backend' ? 'Backend' : menu.kind === 'model' ? 'Model' : menu.kind === 'delegation' ? 'Delegation' : 'Reasoning effort'} settings`,
|
|
@@ -3178,6 +3334,10 @@ You can also use natural language commands to control Claude Code CLI.`,
|
|
|
3178
3334
|
this.directoryBrowser.destroy();
|
|
3179
3335
|
this.settingsService.destroy();
|
|
3180
3336
|
this.isDestroyed = true;
|
|
3337
|
+
for (const threadId of this.activeThreadOperations.keys()) {
|
|
3338
|
+
this.settingsAdmission.cancelRecoverable(threadId);
|
|
3339
|
+
this.cancelThreadOperation(threadId, 'Request cancelled because the CLI is shutting down.');
|
|
3340
|
+
}
|
|
3181
3341
|
for (const delivery of this.imageDeliveries.values())
|
|
3182
3342
|
delivery.cancel();
|
|
3183
3343
|
this.imageDeliveries.clear();
|