@shumkov/orchestra 0.10.5 → 0.10.7
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.
|
@@ -383,7 +383,9 @@ mcp.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
|
383
383
|
'renders rich, an edited checklist/table/heading is re-rendered rich rather ' +
|
|
384
384
|
'than flattened. Canonical use: send a plan as `- [ ] step` items, then edit ' +
|
|
385
385
|
'that same message_id with the WHOLE list again and `- [x]` on completed ' +
|
|
386
|
-
'steps — check items off as you go and the user watches one bubble update
|
|
386
|
+
'steps — check items off as you go and the user watches one bubble update, ' +
|
|
387
|
+
'and one final time when the work ends, every item resolved and the ' +
|
|
388
|
+
'hourglass gone. ' +
|
|
387
389
|
'Also fine for a short one-line status. An edit REPLACES the body, so always ' +
|
|
388
390
|
're-send the full text. An edit is TEXT-ONLY: image markdown degrades to its ' +
|
|
389
391
|
'caption and cannot add media to a bubble (send media with `reply(files:)`). ' +
|
|
@@ -505,7 +505,16 @@ class CliProcess extends Process {
|
|
|
505
505
|
// While non-empty, the keep-alive interval resets the turn's idle ceiling (an
|
|
506
506
|
// idle `ask` fires no tool hooks, so _extendQuietOnToolActivity wouldn't run).
|
|
507
507
|
this._openQuestions = new Set();
|
|
508
|
+
this._openApprovals = new Set();
|
|
508
509
|
this._questionKeepAliveTimer = null;
|
|
510
|
+
this._cleanRestartOutputFenced = false;
|
|
511
|
+
this._cleanRestartEvidenceLost = false;
|
|
512
|
+
this._resumeAttestation = null;
|
|
513
|
+
Object.defineProperty(this, 'resumeAttestation', {
|
|
514
|
+
enumerable: true,
|
|
515
|
+
configurable: false,
|
|
516
|
+
get: () => this._resumeAttestation,
|
|
517
|
+
});
|
|
509
518
|
|
|
510
519
|
// File-send outbound cap (bot → user). Safe cloud default; overwritten in
|
|
511
520
|
// _spawnTmuxClaude with the backend/chat-resolved value before any turn.
|
|
@@ -552,6 +561,11 @@ class CliProcess extends Process {
|
|
|
552
561
|
async start(opts = {}) {
|
|
553
562
|
if (this.closed) throw new Error('CliProcess: cannot start a closed instance');
|
|
554
563
|
|
|
564
|
+
this._resumeAttestation = null;
|
|
565
|
+
this._pendingResumeAttestation = null;
|
|
566
|
+
this._strictExpectedSessionId = opts.resumePolicy === 'require-existing-session'
|
|
567
|
+
? opts.expectedSessionId
|
|
568
|
+
: null;
|
|
555
569
|
this.claudeSessionId = opts.existingSessionId || crypto.randomUUID();
|
|
556
570
|
// Save cwd so the tool dispatcher's file-attachment allowlist (P0 #2) can
|
|
557
571
|
// permit files under the agent's workspace.
|
|
@@ -593,6 +607,15 @@ class CliProcess extends Process {
|
|
|
593
607
|
await this._createSocketServer();
|
|
594
608
|
await this._spawnTmuxClaude({ tmuxName, opts });
|
|
595
609
|
await this._waitForBridgeHandshake();
|
|
610
|
+
if (this._strictExpectedSessionId != null) {
|
|
611
|
+
if (this.claudeSessionId !== this._strictExpectedSessionId) {
|
|
612
|
+
throw Object.assign(
|
|
613
|
+
new Error('strict resume reported a different session identity'),
|
|
614
|
+
{ code: 'REQUIRED_SESSION_MISMATCH' },
|
|
615
|
+
);
|
|
616
|
+
}
|
|
617
|
+
this._resumeAttestation = this._pendingResumeAttestation;
|
|
618
|
+
}
|
|
596
619
|
this._stopStartupPingLoop();
|
|
597
620
|
// Phase 1.3: arm hook tail AFTER spawn so this._hookNdjsonPath is
|
|
598
621
|
// populated (set inside _spawnTmuxClaude when writeHookFiles runs).
|
|
@@ -670,6 +693,7 @@ class CliProcess extends Process {
|
|
|
670
693
|
});
|
|
671
694
|
|
|
672
695
|
this.bridgeServer.on('session-init', msg => {
|
|
696
|
+
if (!this._acceptBridgeSessionId(msg.claude_session_id)) return;
|
|
673
697
|
// Adopt the canonical claude session_id the bridge reports (claude may
|
|
674
698
|
// have ignored our --session-id; the bridge tells us what claude is
|
|
675
699
|
// actually running).
|
|
@@ -705,6 +729,22 @@ class CliProcess extends Process {
|
|
|
705
729
|
await this.bridgeServer.listen();
|
|
706
730
|
}
|
|
707
731
|
|
|
732
|
+
_acceptBridgeSessionId(sessionId) {
|
|
733
|
+
if (
|
|
734
|
+
this._strictExpectedSessionId != null
|
|
735
|
+
&& sessionId !== this._strictExpectedSessionId
|
|
736
|
+
) {
|
|
737
|
+
this._resumeAttestation = null;
|
|
738
|
+
this._pendingResumeAttestation = null;
|
|
739
|
+
this._cancelPendingBridgeHandshake(
|
|
740
|
+
'REQUIRED_SESSION_MISMATCH',
|
|
741
|
+
'strict resume reported a different session identity',
|
|
742
|
+
);
|
|
743
|
+
return false;
|
|
744
|
+
}
|
|
745
|
+
return true;
|
|
746
|
+
}
|
|
747
|
+
|
|
708
748
|
/**
|
|
709
749
|
* Env for the spawned channels-bridge MCP subprocess. ORCHESTRA_QUESTION_TIMEOUT_MS
|
|
710
750
|
* tells the bridge our question wait so its last-resort `ask` backstop sits ABOVE
|
|
@@ -831,17 +871,47 @@ class CliProcess extends Process {
|
|
|
831
871
|
// - ghost ids from failed-before-first-turn attempts
|
|
832
872
|
let canResume = false;
|
|
833
873
|
let resumePath = null;
|
|
874
|
+
const strictResume = opts.resumePolicy === 'require-existing-session';
|
|
875
|
+
if (
|
|
876
|
+
strictResume
|
|
877
|
+
&& (
|
|
878
|
+
typeof opts.expectedSessionId !== 'string'
|
|
879
|
+
|| !opts.expectedSessionId
|
|
880
|
+
|| opts.expectedSessionId !== opts.existingSessionId
|
|
881
|
+
)
|
|
882
|
+
) {
|
|
883
|
+
throw Object.assign(
|
|
884
|
+
new Error('strict resume requires expectedSessionId to match existingSessionId'),
|
|
885
|
+
{ code: 'REQUIRED_SESSION_MISMATCH' },
|
|
886
|
+
);
|
|
887
|
+
}
|
|
834
888
|
if (opts.existingSessionId && resolvedCwd) {
|
|
835
|
-
//
|
|
889
|
+
// Claude replaces path separators and dots in project directory names.
|
|
836
890
|
// Verified live at ~/.claude/projects/-Users-ivanshumkov-Music-rekordbox/
|
|
837
|
-
const cwdMangled = resolvedCwd.replace(
|
|
891
|
+
const cwdMangled = resolvedCwd.replace(/[/.]/g, '-');
|
|
838
892
|
resumePath = path.join(os.homedir(), '.claude', 'projects', cwdMangled, `${opts.existingSessionId}.jsonl`);
|
|
839
893
|
try { canResume = fs.statSync(resumePath).isFile(); } catch { canResume = false; }
|
|
840
894
|
}
|
|
895
|
+
if (strictResume && !canResume) {
|
|
896
|
+
throw Object.assign(
|
|
897
|
+
new Error(
|
|
898
|
+
`required session ${opts.expectedSessionId} is unavailable at ${resumePath || '<unknown cwd>'}`,
|
|
899
|
+
),
|
|
900
|
+
{ code: 'REQUIRED_SESSION_NOT_FOUND' },
|
|
901
|
+
);
|
|
902
|
+
}
|
|
841
903
|
if (canResume) {
|
|
842
904
|
claudeArgs.push('--resume', opts.existingSessionId);
|
|
905
|
+
this._pendingResumeAttestation = Object.freeze({
|
|
906
|
+
namespace: 'claude:channels',
|
|
907
|
+
sessionId: opts.existingSessionId,
|
|
908
|
+
resumed: true,
|
|
909
|
+
freshFallback: false,
|
|
910
|
+
});
|
|
843
911
|
} else {
|
|
844
912
|
claudeArgs.push('--session-id', this.claudeSessionId);
|
|
913
|
+
this._resumeAttestation = null;
|
|
914
|
+
this._pendingResumeAttestation = null;
|
|
845
915
|
if (opts.existingSessionId) {
|
|
846
916
|
this.logger.warn?.(
|
|
847
917
|
`[${this.label}] channels: dropping DB session ${opts.existingSessionId} — ` +
|
|
@@ -970,6 +1040,31 @@ class CliProcess extends Process {
|
|
|
970
1040
|
' (the checkbox column stays aligned). Exactly one item carries it at a',
|
|
971
1041
|
' time; when the item completes it becomes `- [x]` and the ⏳ moves to',
|
|
972
1042
|
' the next one. The user sees at a glance what is happening right now.',
|
|
1043
|
+
'6. Delivering the final answer COMPLETES the last step, so CLOSE THE',
|
|
1044
|
+
' CHECKLIST OUT: immediately after that final `reply`, edit that same',
|
|
1045
|
+
' `message_id` one last time, ticking every remaining item and removing',
|
|
1046
|
+
' the ⏳. Its final state is all `- [x]`, zero ⏳. A turn that ends with',
|
|
1047
|
+
' a lingering ⏳ on the checklist is a CONTRACT VIOLATION — the user is',
|
|
1048
|
+
' left looking at work that reads as abandoned one item from the end,',
|
|
1049
|
+
' however good the answer was.',
|
|
1050
|
+
' But NEVER tick an item you did not actually complete — a false `- [x]`',
|
|
1051
|
+
' is worse than an unfinished list. When work stops early — a step fails,',
|
|
1052
|
+
' is skipped, turns out to be blocked — the close-out edit still happens:',
|
|
1053
|
+
' remove the ⏳, leave that item unticked, and name the reason ON its',
|
|
1054
|
+
' line, e.g. `- [ ] Деплой — заблокировано: нет доступа к VPS`. The',
|
|
1055
|
+
' lingering ⏳ is the violation; an honestly labelled unfinished item',
|
|
1056
|
+
' is not.',
|
|
1057
|
+
'',
|
|
1058
|
+
'HARD RULE — a checkbox is a COMMITMENT, not decoration, and this applies to',
|
|
1059
|
+
'EVERY message you send, the final answer included, not just the progress',
|
|
1060
|
+
'checklist. `- [ ]` is EXCLUSIVELY for your own work items: steps YOU will',
|
|
1061
|
+
'tick during this same task. Write one and you are committing to tick it',
|
|
1062
|
+
'yourself before the work ends. Anything addressed to the USER —',
|
|
1063
|
+
'recommendations, follow-ups, decisions for them to make, "you could install',
|
|
1064
|
+
'X" — MUST be a plain bullet (`-`), never a checkbox. A checkbox only the',
|
|
1065
|
+
'user could ever close is one you cannot tick, so it also makes the close-out',
|
|
1066
|
+
'above impossible. Putting a checkbox on something only the user can act on',
|
|
1067
|
+
'is a CONTRACT VIOLATION.',
|
|
973
1068
|
'',
|
|
974
1069
|
'An edit re-renders the bubble exactly as the original `reply` did — a chat',
|
|
975
1070
|
'that renders rich re-renders an edited checklist, table or heading rich, not',
|
|
@@ -1353,6 +1448,7 @@ class CliProcess extends Process {
|
|
|
1353
1448
|
break;
|
|
1354
1449
|
|
|
1355
1450
|
case 'perm_req':
|
|
1451
|
+
this._openApprovals.add(msg.request_id);
|
|
1356
1452
|
// Canonical 'approval-required' shape — matches TmuxProcess emit signature
|
|
1357
1453
|
// (lib/process/tmux-process.js:2877). polygram.js's existing onApprovalRequired
|
|
1358
1454
|
// handler (lib/sdk/callbacks.js wired in polygram.js:2217) consumes this
|
|
@@ -1769,6 +1865,34 @@ class CliProcess extends Process {
|
|
|
1769
1865
|
|
|
1770
1866
|
async _dispatchToolCall(msg) {
|
|
1771
1867
|
const args = msg.args || {};
|
|
1868
|
+
const correlatedPending = args.turn_id
|
|
1869
|
+
? this.pendingTurns.get(args.turn_id)
|
|
1870
|
+
: (this.pendingTurns.size === 1
|
|
1871
|
+
? this.pendingTurns.values().next().value
|
|
1872
|
+
: null);
|
|
1873
|
+
if (msg.name === 'reply' || msg.name === 'stream' || msg.name === 'edit_message') {
|
|
1874
|
+
if (correlatedPending) correlatedPending.outputAttempted = true;
|
|
1875
|
+
else this._cleanRestartEvidenceLost = true;
|
|
1876
|
+
}
|
|
1877
|
+
if (this._cleanRestartOutputFenced) {
|
|
1878
|
+
this._cleanRestartEvidenceLost = true;
|
|
1879
|
+
if (msg.name === 'ask') {
|
|
1880
|
+
this._writeToBridge({
|
|
1881
|
+
kind: 'question_answer',
|
|
1882
|
+
tool_call_id: msg.tool_call_id,
|
|
1883
|
+
result: { cancelled: true, error: 'process retiring' },
|
|
1884
|
+
});
|
|
1885
|
+
} else {
|
|
1886
|
+
this._writeToBridge({
|
|
1887
|
+
kind: 'tool_ack',
|
|
1888
|
+
tool_call_id: msg.tool_call_id,
|
|
1889
|
+
ok: false,
|
|
1890
|
+
error: 'process retiring',
|
|
1891
|
+
attempt_id: msg.tool_call_id,
|
|
1892
|
+
});
|
|
1893
|
+
}
|
|
1894
|
+
return;
|
|
1895
|
+
}
|
|
1772
1896
|
|
|
1773
1897
|
// rc.10 diagnostic: surface every inbound tool call BEFORE any dedup /
|
|
1774
1898
|
// rate-limit / chat-id-mismatch path. Live shumorobot 2026-05-26 23:44
|
|
@@ -3794,6 +3918,162 @@ class CliProcess extends Process {
|
|
|
3794
3918
|
this._logEvent('cli-bg-work-stall-selfcheck', { idle_ms: idleMs, shell_count: count, fired });
|
|
3795
3919
|
}
|
|
3796
3920
|
|
|
3921
|
+
_classifyCleanRestart(deliveryEvidence) {
|
|
3922
|
+
if (this.pendingTurns.size === 0) return ['no-active-turn', null];
|
|
3923
|
+
if (this.pendingTurns.size !== 1) return ['multiple-active-turns', null];
|
|
3924
|
+
const [[turnId, pending]] = this.pendingTurns;
|
|
3925
|
+
const queueEntries = this.pendingQueue.filter(entry => entry.turnId === turnId);
|
|
3926
|
+
const ledger = this.inputLedger.get(turnId);
|
|
3927
|
+
const sourceMsgId = queueEntries[0]?.context?.sourceMsgId ?? ledger?.msgId ?? null;
|
|
3928
|
+
if (
|
|
3929
|
+
queueEntries.length !== 1
|
|
3930
|
+
|| ledger?.source !== 'primary'
|
|
3931
|
+
|| sourceMsgId == null
|
|
3932
|
+
|| ledger.msgId == null
|
|
3933
|
+
|| String(sourceMsgId) !== String(ledger.msgId)
|
|
3934
|
+
) {
|
|
3935
|
+
return ['uncorrelated-source', null];
|
|
3936
|
+
}
|
|
3937
|
+
if (
|
|
3938
|
+
!deliveryEvidence
|
|
3939
|
+
|| typeof deliveryEvidence !== 'object'
|
|
3940
|
+
|| Array.isArray(deliveryEvidence)
|
|
3941
|
+
|| typeof deliveryEvidence.outputAttempted !== 'boolean'
|
|
3942
|
+
|| typeof deliveryEvidence.pending !== 'number'
|
|
3943
|
+
|| !Number.isInteger(deliveryEvidence.pending)
|
|
3944
|
+
|| deliveryEvidence.pending < 0
|
|
3945
|
+
|| deliveryEvidence.fenced !== true
|
|
3946
|
+
) {
|
|
3947
|
+
return ['delivery-ambiguous', sourceMsgId];
|
|
3948
|
+
}
|
|
3949
|
+
if (pending.outputAttempted === true || pending.replies?.length > 0) {
|
|
3950
|
+
return ['prior-output', sourceMsgId];
|
|
3951
|
+
}
|
|
3952
|
+
if (deliveryEvidence.outputAttempted) {
|
|
3953
|
+
return ['prior-output', sourceMsgId];
|
|
3954
|
+
}
|
|
3955
|
+
if (
|
|
3956
|
+
deliveryEvidence.pending > 0
|
|
3957
|
+
|| deliveryEvidence.ambiguous === true
|
|
3958
|
+
|| deliveryEvidence.safe === false
|
|
3959
|
+
) {
|
|
3960
|
+
return ['delivery-ambiguous', sourceMsgId];
|
|
3961
|
+
}
|
|
3962
|
+
if (pending.activeToolIds?.size > 0) return ['unresolved-tool', sourceMsgId];
|
|
3963
|
+
if (this._openQuestions.size > 0) return ['unresolved-question', sourceMsgId];
|
|
3964
|
+
if (this._openApprovals.size > 0) return ['unresolved-approval', sourceMsgId];
|
|
3965
|
+
if (this._pendingSubagentStarts.length > 0) return ['active-subagent', sourceMsgId];
|
|
3966
|
+
if (ledger.state !== 'seen') return ['hook-correlation-missing', sourceMsgId];
|
|
3967
|
+
if (this.hasPendingDeliveryWork()) return ['delivery-ambiguous', sourceMsgId];
|
|
3968
|
+
const nonterminal = [...this.inputLedger.entries()].filter(([, entry]) => (
|
|
3969
|
+
entry.state === 'written'
|
|
3970
|
+
|| entry.state === 'seen'
|
|
3971
|
+
|| entry.state === 'fold-suspected'
|
|
3972
|
+
));
|
|
3973
|
+
if (
|
|
3974
|
+
nonterminal.length !== 1
|
|
3975
|
+
|| nonterminal[0][0] !== turnId
|
|
3976
|
+
|| this.pendingQueue.length !== 1
|
|
3977
|
+
) {
|
|
3978
|
+
return ['other-action-owner', sourceMsgId];
|
|
3979
|
+
}
|
|
3980
|
+
if (this._cleanRestartEvidenceLost) return ['bridge-loss', sourceMsgId];
|
|
3981
|
+
return ['eligible', sourceMsgId];
|
|
3982
|
+
}
|
|
3983
|
+
|
|
3984
|
+
_cleanRestartSourceMsgId() {
|
|
3985
|
+
if (this.pendingTurns.size !== 1) return null;
|
|
3986
|
+
const [[turnId]] = this.pendingTurns;
|
|
3987
|
+
const queueEntries = this.pendingQueue.filter(entry => entry.turnId === turnId);
|
|
3988
|
+
const ledger = this.inputLedger.get(turnId);
|
|
3989
|
+
const sourceMsgId = queueEntries[0]?.context?.sourceMsgId ?? ledger?.msgId ?? null;
|
|
3990
|
+
if (
|
|
3991
|
+
queueEntries.length !== 1
|
|
3992
|
+
|| ledger?.source !== 'primary'
|
|
3993
|
+
|| sourceMsgId == null
|
|
3994
|
+
|| ledger.msgId == null
|
|
3995
|
+
|| String(sourceMsgId) !== String(ledger.msgId)
|
|
3996
|
+
) {
|
|
3997
|
+
return null;
|
|
3998
|
+
}
|
|
3999
|
+
return sourceMsgId;
|
|
4000
|
+
}
|
|
4001
|
+
|
|
4002
|
+
async retireForCleanRestart({ getDeliveryEvidence } = {}) {
|
|
4003
|
+
if (typeof getDeliveryEvidence !== 'function') {
|
|
4004
|
+
throw new TypeError(
|
|
4005
|
+
'CliProcess.retireForCleanRestart: getDeliveryEvidence function required',
|
|
4006
|
+
);
|
|
4007
|
+
}
|
|
4008
|
+
if (this._cleanRestartRetirement) return this._cleanRestartRetirement;
|
|
4009
|
+
this._cleanRestartOutputFenced = true;
|
|
4010
|
+
this._cleanRestartRetiring = true;
|
|
4011
|
+
this._cleanRestartRetirement = (async () => {
|
|
4012
|
+
const failures = [];
|
|
4013
|
+
let deliveryEvidence = null;
|
|
4014
|
+
try {
|
|
4015
|
+
deliveryEvidence = await getDeliveryEvidence(
|
|
4016
|
+
this.sessionKey,
|
|
4017
|
+
this._cleanRestartSourceMsgId(),
|
|
4018
|
+
);
|
|
4019
|
+
} catch (error) {
|
|
4020
|
+
failures.push(error);
|
|
4021
|
+
}
|
|
4022
|
+
if (this.tmuxSession) {
|
|
4023
|
+
try {
|
|
4024
|
+
await this.runner.killSession(this.tmuxSession, { strict: true });
|
|
4025
|
+
this.tmuxSession = null;
|
|
4026
|
+
} catch (error) {
|
|
4027
|
+
failures.push(error);
|
|
4028
|
+
}
|
|
4029
|
+
}
|
|
4030
|
+
if (this.bridgeServer) {
|
|
4031
|
+
try {
|
|
4032
|
+
await this.bridgeServer.close();
|
|
4033
|
+
this.bridgeServer = null;
|
|
4034
|
+
} catch (error) {
|
|
4035
|
+
failures.push(error);
|
|
4036
|
+
}
|
|
4037
|
+
}
|
|
4038
|
+
if (!this._hookTail || typeof this._hookTail.drain !== 'function') {
|
|
4039
|
+
failures.push(new Error('hook tail unavailable'));
|
|
4040
|
+
} else {
|
|
4041
|
+
try {
|
|
4042
|
+
await this._hookTail.drain();
|
|
4043
|
+
} catch (error) {
|
|
4044
|
+
failures.push(error);
|
|
4045
|
+
}
|
|
4046
|
+
try { this._hookTail.close(); } catch (error) { failures.push(error); }
|
|
4047
|
+
this._hookTail = null;
|
|
4048
|
+
}
|
|
4049
|
+
|
|
4050
|
+
const [reason, sourceMsgId] = this._classifyCleanRestart(deliveryEvidence);
|
|
4051
|
+
try {
|
|
4052
|
+
await this._doKill('clean-restart');
|
|
4053
|
+
} catch (error) {
|
|
4054
|
+
failures.push(error);
|
|
4055
|
+
}
|
|
4056
|
+
if (failures.length > 0) {
|
|
4057
|
+
this._cleanRestartEvidenceLost = true;
|
|
4058
|
+
const cause = failures[0];
|
|
4059
|
+
throw Object.assign(
|
|
4060
|
+
new Error(`clean restart retirement failed: ${cause.message}`, { cause }),
|
|
4061
|
+
{
|
|
4062
|
+
code: 'CLEAN_RESTART_RETIREMENT_FAILED',
|
|
4063
|
+
failures: Object.freeze([...failures]),
|
|
4064
|
+
},
|
|
4065
|
+
);
|
|
4066
|
+
}
|
|
4067
|
+
return Object.freeze({
|
|
4068
|
+
sessionKey: this.sessionKey,
|
|
4069
|
+
sourceMsgId,
|
|
4070
|
+
eligible: reason === 'eligible',
|
|
4071
|
+
reason,
|
|
4072
|
+
});
|
|
4073
|
+
})();
|
|
4074
|
+
return this._cleanRestartRetirement;
|
|
4075
|
+
}
|
|
4076
|
+
|
|
3797
4077
|
async kill(reason = 'kill') {
|
|
3798
4078
|
if (this.closed) return;
|
|
3799
4079
|
// Parity P19: re-entry guard for concurrent kill() calls. Mirrors
|
|
@@ -3846,6 +4126,7 @@ class CliProcess extends Process {
|
|
|
3846
4126
|
}
|
|
3847
4127
|
});
|
|
3848
4128
|
this._hookTail.on('error', (err) => {
|
|
4129
|
+
this._cleanRestartEvidenceLost = true;
|
|
3849
4130
|
this.logger.warn?.(`[${this.label}] hook tail error: ${err.message}`);
|
|
3850
4131
|
this.emit('hook-tail-error', { err: err.message });
|
|
3851
4132
|
});
|
|
@@ -3986,6 +4267,14 @@ class CliProcess extends Process {
|
|
|
3986
4267
|
return;
|
|
3987
4268
|
|
|
3988
4269
|
case 'PreToolUse': {
|
|
4270
|
+
const activePending = this.pendingTurns.size === 1
|
|
4271
|
+
? this.pendingTurns.values().next().value
|
|
4272
|
+
: null;
|
|
4273
|
+
if (activePending && ev.toolUseId) {
|
|
4274
|
+
(activePending.activeToolIds ||= new Set()).add(ev.toolUseId);
|
|
4275
|
+
} else if (this.pendingTurns.size > 0) {
|
|
4276
|
+
this._cleanRestartEvidenceLost = true;
|
|
4277
|
+
}
|
|
3989
4278
|
// Phase 1.3: synthesize subagent-start from Agent PreToolUse so the
|
|
3990
4279
|
// reactor can show a distinct subagent-specific reaction during long
|
|
3991
4280
|
// subagent runs. agent_type lives in tool_input.subagent_type per
|
|
@@ -4034,6 +4323,9 @@ class CliProcess extends Process {
|
|
|
4034
4323
|
}
|
|
4035
4324
|
|
|
4036
4325
|
case 'PostToolUse':
|
|
4326
|
+
for (const pending of this.pendingTurns.values()) {
|
|
4327
|
+
pending.activeToolIds?.delete(ev.toolUseId);
|
|
4328
|
+
}
|
|
4037
4329
|
this.emit('tool-result', {
|
|
4038
4330
|
name: ev.toolName,
|
|
4039
4331
|
durationMs: ev.durationMs,
|
|
@@ -4300,6 +4592,12 @@ class CliProcess extends Process {
|
|
|
4300
4592
|
* timer on the dead instance).
|
|
4301
4593
|
*/
|
|
4302
4594
|
async _handleBridgeDisconnected(reason = 'socket-close') {
|
|
4595
|
+
if (this._cleanRestartRetiring) {
|
|
4596
|
+
this.bridgeReady = false;
|
|
4597
|
+
this.mcpReady = false;
|
|
4598
|
+
return;
|
|
4599
|
+
}
|
|
4600
|
+
this._cleanRestartEvidenceLost = true;
|
|
4303
4601
|
this.bridgeReady = false;
|
|
4304
4602
|
this.mcpReady = false;
|
|
4305
4603
|
this._stopStartupPingLoop();
|
|
@@ -4758,6 +5056,7 @@ class CliProcess extends Process {
|
|
|
4758
5056
|
return;
|
|
4759
5057
|
}
|
|
4760
5058
|
this.respondedPermissions.add(requestId);
|
|
5059
|
+
this._openApprovals.delete(requestId);
|
|
4761
5060
|
this._writeToBridge({ kind: 'perm_verdict', request_id: requestId, behavior });
|
|
4762
5061
|
}
|
|
4763
5062
|
|
|
@@ -674,6 +674,12 @@ class ProcessManager {
|
|
|
674
674
|
while (this.totalCost + newCost > this.budget) {
|
|
675
675
|
const evicted = this._evictLRU(); // skips inFlight + background-job-pinned
|
|
676
676
|
if (evicted) continue;
|
|
677
|
+
if (spawnContext?.noWaitForCapacity === true) {
|
|
678
|
+
throw managerError(
|
|
679
|
+
`process capacity is not immediately available for sessionKey ${sessionKey}`,
|
|
680
|
+
'PROCESS_ADMISSION_UNAVAILABLE',
|
|
681
|
+
);
|
|
682
|
+
}
|
|
677
683
|
// _evictLRU freed nothing. Policy C — split by WHY:
|
|
678
684
|
if (this._hasPinnedSession()) {
|
|
679
685
|
// A DURABLE blocker (live background job) holds a slot. Don't park on it (could be
|
|
@@ -1221,6 +1227,21 @@ class ProcessManager {
|
|
|
1221
1227
|
const proc = this.procs.get(sessionKey);
|
|
1222
1228
|
if (!proc) throw new Error(`no process for sessionKey ${sessionKey}`);
|
|
1223
1229
|
proc.lastUsedTs = Date.now();
|
|
1230
|
+
const hasExpectedProcess = (
|
|
1231
|
+
opts != null
|
|
1232
|
+
&& typeof opts === 'object'
|
|
1233
|
+
&& Object.prototype.hasOwnProperty.call(opts, 'expectedProcess')
|
|
1234
|
+
);
|
|
1235
|
+
if (hasExpectedProcess) {
|
|
1236
|
+
if (this.procs.get(sessionKey) !== opts.expectedProcess || proc.closed) {
|
|
1237
|
+
throw managerError(
|
|
1238
|
+
`process precondition failed for sessionKey ${sessionKey}`,
|
|
1239
|
+
'PROCESS_PRECONDITION_FAILED',
|
|
1240
|
+
);
|
|
1241
|
+
}
|
|
1242
|
+
const { expectedProcess: _expectedProcess, ...sendOpts } = opts;
|
|
1243
|
+
return proc.send(prompt, sendOpts);
|
|
1244
|
+
}
|
|
1224
1245
|
return proc.send(prompt, opts);
|
|
1225
1246
|
}
|
|
1226
1247
|
|
|
@@ -1230,6 +1251,40 @@ class ProcessManager {
|
|
|
1230
1251
|
));
|
|
1231
1252
|
}
|
|
1232
1253
|
|
|
1254
|
+
retireExpectedProcess(
|
|
1255
|
+
sessionKey,
|
|
1256
|
+
expectedProcess,
|
|
1257
|
+
reason = 'expected-process-retirement',
|
|
1258
|
+
) {
|
|
1259
|
+
if (this.procs.get(sessionKey) !== expectedProcess) {
|
|
1260
|
+
return Promise.reject(managerError(
|
|
1261
|
+
`process precondition failed for sessionKey ${sessionKey}`,
|
|
1262
|
+
'PROCESS_PRECONDITION_FAILED',
|
|
1263
|
+
));
|
|
1264
|
+
}
|
|
1265
|
+
return this._withRetirementIntent(sessionKey, async () => {
|
|
1266
|
+
if (this.procs.get(sessionKey) !== expectedProcess) {
|
|
1267
|
+
throw managerError(
|
|
1268
|
+
`process precondition failed for sessionKey ${sessionKey}`,
|
|
1269
|
+
'PROCESS_PRECONDITION_FAILED',
|
|
1270
|
+
);
|
|
1271
|
+
}
|
|
1272
|
+
try {
|
|
1273
|
+
await this._strictRetire(expectedProcess, reason);
|
|
1274
|
+
} catch (error) {
|
|
1275
|
+
this._retiring.delete(expectedProcess);
|
|
1276
|
+
throw error;
|
|
1277
|
+
}
|
|
1278
|
+
if (this.procs.get(sessionKey) === expectedProcess) {
|
|
1279
|
+
this.procs.delete(sessionKey);
|
|
1280
|
+
}
|
|
1281
|
+
this._retiring.delete(expectedProcess);
|
|
1282
|
+
if (this._codexLeaseMatches(expectedProcess)) this._codexLease = null;
|
|
1283
|
+
this._maybeSignalLruWaiter();
|
|
1284
|
+
return true;
|
|
1285
|
+
});
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1233
1288
|
async _killLocked(sessionKey, reason = 'kill') {
|
|
1234
1289
|
const proc = this.procs.get(sessionKey);
|
|
1235
1290
|
if (!proc) return false;
|
|
@@ -1310,6 +1365,79 @@ class ProcessManager {
|
|
|
1310
1365
|
}
|
|
1311
1366
|
}
|
|
1312
1367
|
|
|
1368
|
+
async retireForCleanRestart({ getDeliveryEvidence } = {}) {
|
|
1369
|
+
if (typeof getDeliveryEvidence !== 'function') {
|
|
1370
|
+
throw new TypeError(
|
|
1371
|
+
'ProcessManager.retireForCleanRestart: getDeliveryEvidence function required',
|
|
1372
|
+
);
|
|
1373
|
+
}
|
|
1374
|
+
this._shuttingDown = true;
|
|
1375
|
+
for (const w of this._lruWaiters) {
|
|
1376
|
+
clearTimeout(w.timer);
|
|
1377
|
+
w.reject(new Error('shutdown'));
|
|
1378
|
+
}
|
|
1379
|
+
this._lruWaiters.length = 0;
|
|
1380
|
+
|
|
1381
|
+
const admittedResults = await Promise.allSettled(
|
|
1382
|
+
[...this._lifecycleGates.values()],
|
|
1383
|
+
);
|
|
1384
|
+
const targets = [...this.procs.entries()]
|
|
1385
|
+
.filter(([, proc]) => !this._retiring.has(proc));
|
|
1386
|
+
for (const [, proc] of targets) this._retiring.add(proc);
|
|
1387
|
+
|
|
1388
|
+
let settled;
|
|
1389
|
+
try {
|
|
1390
|
+
settled = await Promise.allSettled(targets.map(async ([sessionKey, proc]) => {
|
|
1391
|
+
let snapshot;
|
|
1392
|
+
if (this._isCodex(proc)) {
|
|
1393
|
+
await getDeliveryEvidence(sessionKey, null);
|
|
1394
|
+
await this._strictRetire(proc, 'clean-restart');
|
|
1395
|
+
if (this._codexLeaseMatches(proc)) this._codexLease = null;
|
|
1396
|
+
snapshot = {
|
|
1397
|
+
sourceMsgId: null,
|
|
1398
|
+
eligible: false,
|
|
1399
|
+
reason: 'unsupported-backend',
|
|
1400
|
+
};
|
|
1401
|
+
} else {
|
|
1402
|
+
snapshot = await proc.retireForCleanRestart({
|
|
1403
|
+
getDeliveryEvidence: (_reportedSessionKey, sourceMsgId) => (
|
|
1404
|
+
getDeliveryEvidence(
|
|
1405
|
+
sessionKey,
|
|
1406
|
+
proc.backend === 'cli' ? sourceMsgId : null,
|
|
1407
|
+
)
|
|
1408
|
+
),
|
|
1409
|
+
});
|
|
1410
|
+
}
|
|
1411
|
+
const cliEligible = proc.backend === 'cli' && snapshot?.eligible === true;
|
|
1412
|
+
return Object.freeze({
|
|
1413
|
+
sessionKey,
|
|
1414
|
+
sourceMsgId: proc.backend === 'cli'
|
|
1415
|
+
? (snapshot?.sourceMsgId ?? null)
|
|
1416
|
+
: null,
|
|
1417
|
+
eligible: cliEligible,
|
|
1418
|
+
reason: proc.backend === 'cli'
|
|
1419
|
+
? (snapshot?.reason || 'retirement-uncertain')
|
|
1420
|
+
: 'unsupported-backend',
|
|
1421
|
+
});
|
|
1422
|
+
}));
|
|
1423
|
+
} finally {
|
|
1424
|
+
for (const [sessionKey, proc] of targets) {
|
|
1425
|
+
if (proc.closed && this.procs.get(sessionKey) === proc) {
|
|
1426
|
+
this.procs.delete(sessionKey);
|
|
1427
|
+
}
|
|
1428
|
+
this._retiring.delete(proc);
|
|
1429
|
+
}
|
|
1430
|
+
this._maybeSignalLruWaiter();
|
|
1431
|
+
}
|
|
1432
|
+
const failure = [
|
|
1433
|
+
...admittedResults,
|
|
1434
|
+
...settled,
|
|
1435
|
+
].find(result => result.status === 'rejected');
|
|
1436
|
+
if (failure) throw failure.reason;
|
|
1437
|
+
const results = settled.map(result => result.value);
|
|
1438
|
+
return Object.freeze(results);
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1313
1441
|
// ─── Optional async — feature-detect at call site if needed ──────
|
|
1314
1442
|
|
|
1315
1443
|
/**
|
package/lib/process/process.js
CHANGED
|
@@ -115,6 +115,25 @@ class Process extends EventEmitter {
|
|
|
115
115
|
throw new Error(`${this.constructor.name}.kill() must be overridden`);
|
|
116
116
|
}
|
|
117
117
|
|
|
118
|
+
async retireForCleanRestart({ getDeliveryEvidence } = {}) {
|
|
119
|
+
if (typeof getDeliveryEvidence === 'function') {
|
|
120
|
+
await getDeliveryEvidence(this.sessionKey, null);
|
|
121
|
+
}
|
|
122
|
+
await this.kill('clean-restart');
|
|
123
|
+
if (!this.closed) {
|
|
124
|
+
throw Object.assign(
|
|
125
|
+
new Error('clean restart retirement did not close the process'),
|
|
126
|
+
{ code: 'CLEAN_RESTART_RETIREMENT_FAILED' },
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
return Object.freeze({
|
|
130
|
+
sessionKey: this.sessionKey,
|
|
131
|
+
sourceMsgId: null,
|
|
132
|
+
eligible: false,
|
|
133
|
+
reason: 'unsupported-backend',
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
118
137
|
// ─── OPTIONAL async methods — caller awaits + try/catch ────────────
|
|
119
138
|
|
|
120
139
|
async interrupt() {
|
package/lib/tmux/log-tail.js
CHANGED
|
@@ -107,6 +107,7 @@ class LogTail extends EventEmitter {
|
|
|
107
107
|
this._initialised = false;
|
|
108
108
|
this._readInFlight = false; // debounce concurrent _readNew triggers
|
|
109
109
|
this._readPending = false;
|
|
110
|
+
this._draining = false;
|
|
110
111
|
}
|
|
111
112
|
|
|
112
113
|
start() {
|
|
@@ -194,6 +195,10 @@ class LogTail extends EventEmitter {
|
|
|
194
195
|
*/
|
|
195
196
|
_triggerRead() {
|
|
196
197
|
if (this._closed) return;
|
|
198
|
+
if (this._draining) {
|
|
199
|
+
this._readPending = true;
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
197
202
|
if (this._readInFlight) {
|
|
198
203
|
this._readPending = true;
|
|
199
204
|
return;
|
|
@@ -243,7 +248,7 @@ class LogTail extends EventEmitter {
|
|
|
243
248
|
this._timer = setImmediate(tick);
|
|
244
249
|
}
|
|
245
250
|
|
|
246
|
-
async _readNew() {
|
|
251
|
+
async _readNew(maxOffset = null) {
|
|
247
252
|
let stat;
|
|
248
253
|
try {
|
|
249
254
|
stat = await this.fs.promises.stat(this.path);
|
|
@@ -251,7 +256,8 @@ class LogTail extends EventEmitter {
|
|
|
251
256
|
if (err.code === 'ENOENT') return; // not created yet
|
|
252
257
|
throw err;
|
|
253
258
|
}
|
|
254
|
-
|
|
259
|
+
const observedSize = maxOffset == null ? stat.size : Math.min(stat.size, maxOffset);
|
|
260
|
+
if (observedSize < this._offset) {
|
|
255
261
|
// File truncated (rare for claude debug-file but possible on log
|
|
256
262
|
// rotation). Reset offset and re-read from the beginning.
|
|
257
263
|
this.emit('truncated', { previous: this._offset, current: stat.size });
|
|
@@ -262,10 +268,10 @@ class LogTail extends EventEmitter {
|
|
|
262
268
|
// post-truncation read.
|
|
263
269
|
this._decoder = new StringDecoder('utf8');
|
|
264
270
|
}
|
|
265
|
-
if (
|
|
271
|
+
if (observedSize <= this._offset) return; // unchanged
|
|
266
272
|
const fd = await this.fs.promises.open(this.path, 'r');
|
|
267
273
|
try {
|
|
268
|
-
const bytesToRead =
|
|
274
|
+
const bytesToRead = observedSize - this._offset;
|
|
269
275
|
const buffer = Buffer.alloc(Math.min(bytesToRead, DEFAULT_CHUNK_BYTES));
|
|
270
276
|
let totalRead = 0;
|
|
271
277
|
while (totalRead < bytesToRead && !this._closed) {
|
|
@@ -314,6 +320,33 @@ class LogTail extends EventEmitter {
|
|
|
314
320
|
}
|
|
315
321
|
}
|
|
316
322
|
|
|
323
|
+
async drain() {
|
|
324
|
+
if (this._closed) throw new Error('LogTail: cannot drain a closed tail');
|
|
325
|
+
this._draining = true;
|
|
326
|
+
while (this._readInFlight) {
|
|
327
|
+
await new Promise(resolve => setImmediate(resolve));
|
|
328
|
+
}
|
|
329
|
+
let watermark;
|
|
330
|
+
try {
|
|
331
|
+
watermark = (await this.fs.promises.stat(this.path)).size;
|
|
332
|
+
} catch (err) {
|
|
333
|
+
if (err.code !== 'ENOENT') {
|
|
334
|
+
this._draining = false;
|
|
335
|
+
throw err;
|
|
336
|
+
}
|
|
337
|
+
watermark = 0;
|
|
338
|
+
}
|
|
339
|
+
this._readPending = false;
|
|
340
|
+
this._readInFlight = true;
|
|
341
|
+
try {
|
|
342
|
+
await this._readNew(watermark);
|
|
343
|
+
} finally {
|
|
344
|
+
this._readInFlight = false;
|
|
345
|
+
this._draining = false;
|
|
346
|
+
}
|
|
347
|
+
return Object.freeze({ offset: this._offset, watermark });
|
|
348
|
+
}
|
|
349
|
+
|
|
317
350
|
close() {
|
|
318
351
|
if (this._closed) return;
|
|
319
352
|
this._closed = true;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shumkov/orchestra",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.7",
|
|
4
4
|
"description": "Transport-agnostic session engine for Claude Code and the native Codex app-server: spawn, steer, supervise, observe turns, and recover.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "index.js",
|