@shumkov/orchestra 0.4.2 → 0.5.0
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/lib/process/channels-bridge-protocol.js +46 -0
- package/lib/process/channels-bridge.mjs +22 -13
- package/lib/process/cli-process.js +410 -45
- package/lib/process/factory.js +5 -0
- package/lib/process/process-manager.js +7 -0
- package/lib/process/process.js +9 -0
- package/lib/process/workflow-completion-correlation.js +417 -0
- package/lib/tmux/tmux-runner.js +31 -10
- package/package.json +1 -1
package/lib/process/factory.js
CHANGED
|
@@ -105,6 +105,9 @@ function _maybeWarnR12Migration({ rawPm, canonical, chatId, threadId, chatCfg, t
|
|
|
105
105
|
* @param {string} [opts.channelsClaudeBin] — absolute path to pinned claude binary;
|
|
106
106
|
* required when ANY chat routes to 'cli'. (Name kept for back-compat with
|
|
107
107
|
* existing wiring; can be renamed to `claudeBin` in a future refactor.)
|
|
108
|
+
* @param {string|null} [opts.sessionLauncher] — optional absolute executable
|
|
109
|
+
* wrapper that receives the pinned Claude binary as its first argument. Defaults to
|
|
110
|
+
* ORCHESTRA_SESSION_LAUNCHER when configured by the consumer.
|
|
108
111
|
* @param {string|Function} [opts.displayHint] — surface-rendering hint prepended to
|
|
109
112
|
* the CliProcess system prompt. Accepts EITHER a static string (applied to every
|
|
110
113
|
* session) OR a resolver `(chatId, threadId, config) => string` invoked once per
|
|
@@ -127,6 +130,7 @@ function createProcessFactory({
|
|
|
127
130
|
botName = null,
|
|
128
131
|
toolDispatcher = null,
|
|
129
132
|
channelsClaudeBin = null,
|
|
133
|
+
sessionLauncher = process.env.ORCHESTRA_SESSION_LAUNCHER || null,
|
|
130
134
|
displayHint = '', // orchestra: consumer surface-rendering hint
|
|
131
135
|
maxOutboundFileBytes = 100 * 1024 * 1024, // orchestra: consumer outbound file cap
|
|
132
136
|
// orchestra identity — forwarded to every CliProcess so the engine is neutral.
|
|
@@ -174,6 +178,7 @@ function createProcessFactory({
|
|
|
174
178
|
tmuxRunner,
|
|
175
179
|
botName,
|
|
176
180
|
claudeBin: channelsClaudeBin,
|
|
181
|
+
sessionLauncher,
|
|
177
182
|
toolDispatcher,
|
|
178
183
|
displayHint: resolvedDisplayHint,
|
|
179
184
|
maxOutboundFileBytes,
|
|
@@ -339,6 +339,10 @@ class ProcessManager {
|
|
|
339
339
|
// NOT evictable — the keyboard is live and claude is blocked on the ask;
|
|
340
340
|
// killing it silently strands both. Skip like inFlight.
|
|
341
341
|
if (typeof p.hasOpenQuestions === 'function' && p.hasOpenQuestions()) { pinnedSkipped++; continue; }
|
|
342
|
+
if (typeof p.hasPendingDeliveryWork === 'function' && p.hasPendingDeliveryWork()) {
|
|
343
|
+
pinnedSkipped++;
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
342
346
|
if (!oldest || (p.lastUsedTs || 0) < (oldest.lastUsedTs || 0)) {
|
|
343
347
|
oldest = p;
|
|
344
348
|
oldestKey = k;
|
|
@@ -372,6 +376,7 @@ class ProcessManager {
|
|
|
372
376
|
_hasPinnedSession() {
|
|
373
377
|
for (const p of this.procs.values()) {
|
|
374
378
|
if (!p.inFlight && p.hasActiveBackgroundWork()) return true;
|
|
379
|
+
if (typeof p.hasPendingDeliveryWork === 'function' && p.hasPendingDeliveryWork()) return true;
|
|
375
380
|
// 0.16 (MF-B): an extended busy-aware-ceiling turn is a DURABLE blocker —
|
|
376
381
|
// it can hold its slot up to the hard backstop (90min), not "seconds" like
|
|
377
382
|
// a normal in-flight turn. Treat it as a pin so getOrSpawn SOFT-overflows
|
|
@@ -386,6 +391,7 @@ class ProcessManager {
|
|
|
386
391
|
const keys = [];
|
|
387
392
|
for (const [k, p] of this.procs.entries()) {
|
|
388
393
|
if (!p.inFlight && p.hasActiveBackgroundWork()) keys.push(k);
|
|
394
|
+
else if (typeof p.hasPendingDeliveryWork === 'function' && p.hasPendingDeliveryWork()) keys.push(k);
|
|
389
395
|
else if (p.inFlight && typeof p.hasExtendedTurn === 'function' && p.hasExtendedTurn()) keys.push(k);
|
|
390
396
|
}
|
|
391
397
|
return keys;
|
|
@@ -599,6 +605,7 @@ class ProcessManager {
|
|
|
599
605
|
// 'idle': a turn completed and pendingQueue is empty. Signal any
|
|
600
606
|
// parked LRU waiter that a non-in-flight slot is available.
|
|
601
607
|
proc.on('idle', () => this._maybeSignalLruWaiter());
|
|
608
|
+
proc.on('delivery-work-settled', () => this._maybeSignalLruWaiter());
|
|
602
609
|
// 'close': process closed itself (iteration loop exited or
|
|
603
610
|
// _closeQuery returned). Remove from the Map + signal LRU.
|
|
604
611
|
proc.on('close', () => {
|
package/lib/process/process.js
CHANGED
|
@@ -174,6 +174,15 @@ class Process extends EventEmitter {
|
|
|
174
174
|
return false;
|
|
175
175
|
}
|
|
176
176
|
|
|
177
|
+
/**
|
|
178
|
+
* Does this process have delivery work whose settlement can still emit or
|
|
179
|
+
* suppress user-visible output? ProcessManager treats it as an eviction pin.
|
|
180
|
+
* Backends without deferred delivery decisions return false.
|
|
181
|
+
*/
|
|
182
|
+
hasPendingDeliveryWork() {
|
|
183
|
+
return false;
|
|
184
|
+
}
|
|
185
|
+
|
|
177
186
|
/**
|
|
178
187
|
* 0.13 D1 (S9): does this process have an open interactive question?
|
|
179
188
|
* Backends without the ask feature return false; CliProcess overrides.
|
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const crypto = require('node:crypto');
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const { canonicalizeToolInput } = require('../canonical-json');
|
|
6
|
+
|
|
7
|
+
const TASK_NOTIFICATION_ID_RE = /<tool-use-id>\s*([^<]+?)\s*<\/tool-use-id>/g;
|
|
8
|
+
|
|
9
|
+
function normalizeVisibleText(value) {
|
|
10
|
+
return typeof value === 'string'
|
|
11
|
+
? value.replace(/\r\n?/g, '\n').trim()
|
|
12
|
+
: '';
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function hashText(value) {
|
|
16
|
+
return crypto.createHash('sha256').update(normalizeVisibleText(value), 'utf8').digest('hex');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function normalizedToolName(name) {
|
|
20
|
+
if (name === 'reply' || /__reply$/.test(name || '')) return 'reply';
|
|
21
|
+
if (name === 'edit_message' || /__edit_message$/.test(name || '')) return 'edit_message';
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function hashDeliveryArguments(name, input = {}) {
|
|
26
|
+
const toolName = normalizedToolName(name);
|
|
27
|
+
if (!toolName) return null;
|
|
28
|
+
const value = {
|
|
29
|
+
tool: toolName,
|
|
30
|
+
chat_id: input.chat_id == null ? null : String(input.chat_id),
|
|
31
|
+
message_id: toolName === 'edit_message' && input.message_id != null
|
|
32
|
+
? String(input.message_id)
|
|
33
|
+
: null,
|
|
34
|
+
interim: toolName === 'reply' && input.interim === true,
|
|
35
|
+
text: normalizeVisibleText(input.text),
|
|
36
|
+
files: Array.isArray(input.files) ? input.files.map(file => String(file)) : [],
|
|
37
|
+
};
|
|
38
|
+
return crypto.createHash('sha256').update(canonicalizeToolInput(value), 'utf8').digest('hex');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function textFromMessage(message) {
|
|
42
|
+
if (!message) return { text: '', toolResultOnly: false, invalid: true };
|
|
43
|
+
if (typeof message.content === 'string') {
|
|
44
|
+
return { text: message.content, toolResultOnly: false, invalid: false };
|
|
45
|
+
}
|
|
46
|
+
if (!Array.isArray(message.content)) {
|
|
47
|
+
return { text: '', toolResultOnly: false, invalid: true };
|
|
48
|
+
}
|
|
49
|
+
const texts = [];
|
|
50
|
+
let hasToolResult = false;
|
|
51
|
+
let hasOther = false;
|
|
52
|
+
for (const block of message.content) {
|
|
53
|
+
if (!block || typeof block !== 'object') {
|
|
54
|
+
hasOther = true;
|
|
55
|
+
} else if (block.type === 'text' && typeof block.text === 'string') {
|
|
56
|
+
texts.push(block.text);
|
|
57
|
+
} else if (block.type === 'tool_result') {
|
|
58
|
+
hasToolResult = true;
|
|
59
|
+
} else {
|
|
60
|
+
hasOther = true;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
text: texts.join('\n\n'),
|
|
65
|
+
toolResultOnly: hasToolResult && texts.length === 0 && !hasOther,
|
|
66
|
+
invalid: hasOther || (hasToolResult && texts.length > 0),
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function parseToolResult(block) {
|
|
71
|
+
let value = block?.content;
|
|
72
|
+
if (Array.isArray(value)) {
|
|
73
|
+
const textBlocks = value.filter(item => item?.type === 'text' && typeof item.text === 'string');
|
|
74
|
+
if (textBlocks.length !== value.length) return null;
|
|
75
|
+
value = textBlocks.map(item => item.text).join('');
|
|
76
|
+
}
|
|
77
|
+
if (typeof value !== 'string') return null;
|
|
78
|
+
try {
|
|
79
|
+
const parsed = JSON.parse(value);
|
|
80
|
+
return parsed && typeof parsed === 'object' ? parsed : null;
|
|
81
|
+
} catch {
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function result(reason, extra = {}) {
|
|
87
|
+
return {
|
|
88
|
+
eligible: false,
|
|
89
|
+
reason,
|
|
90
|
+
deliveredFinal: false,
|
|
91
|
+
visibleHashes: [],
|
|
92
|
+
unresolvedAttempts: [],
|
|
93
|
+
...extra,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function readSnapshot(filePath, byteSize) {
|
|
98
|
+
if (typeof filePath !== 'string' || !filePath || !Number.isSafeInteger(byteSize) || byteSize <= 0) {
|
|
99
|
+
return { ok: false, reason: 'snapshot-missing' };
|
|
100
|
+
}
|
|
101
|
+
let handle;
|
|
102
|
+
try {
|
|
103
|
+
handle = await fs.promises.open(filePath, 'r');
|
|
104
|
+
const buffer = Buffer.allocUnsafe(byteSize);
|
|
105
|
+
let offset = 0;
|
|
106
|
+
while (offset < byteSize) {
|
|
107
|
+
const { bytesRead } = await handle.read(buffer, offset, byteSize - offset, offset);
|
|
108
|
+
if (bytesRead === 0) break;
|
|
109
|
+
offset += bytesRead;
|
|
110
|
+
}
|
|
111
|
+
if (offset !== byteSize) return { ok: false, reason: 'snapshot-truncated' };
|
|
112
|
+
if (buffer[byteSize - 1] !== 0x0a) return { ok: false, reason: 'partial-line' };
|
|
113
|
+
return { ok: true, text: buffer.toString('utf8') };
|
|
114
|
+
} catch {
|
|
115
|
+
return { ok: false, reason: 'snapshot-unreadable' };
|
|
116
|
+
} finally {
|
|
117
|
+
await handle?.close().catch(() => {});
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function collectToolReceipts(branch) {
|
|
122
|
+
const toolUses = new Map();
|
|
123
|
+
const toolResults = new Map();
|
|
124
|
+
let ordinal = 0;
|
|
125
|
+
|
|
126
|
+
for (const row of branch) {
|
|
127
|
+
if (row.type === 'assistant' && Array.isArray(row.message?.content)) {
|
|
128
|
+
for (const block of row.message.content) {
|
|
129
|
+
const blockOrdinal = ordinal++;
|
|
130
|
+
const toolName = normalizedToolName(block?.name);
|
|
131
|
+
if (block?.type !== 'tool_use' || !toolName) continue;
|
|
132
|
+
if (typeof block.id !== 'string' || !block.id || toolUses.has(block.id)) {
|
|
133
|
+
return { ok: false, reason: 'delivery-tool-ambiguous' };
|
|
134
|
+
}
|
|
135
|
+
const argumentHash = hashDeliveryArguments(toolName, block.input);
|
|
136
|
+
if (!argumentHash) return { ok: false, reason: 'delivery-arguments-invalid' };
|
|
137
|
+
toolUses.set(block.id, {
|
|
138
|
+
id: block.id,
|
|
139
|
+
toolName,
|
|
140
|
+
input: block.input || {},
|
|
141
|
+
argumentHash,
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
if (row.type === 'user' && Array.isArray(row.message?.content)) {
|
|
146
|
+
for (const block of row.message.content) {
|
|
147
|
+
const blockOrdinal = ordinal++;
|
|
148
|
+
if (block?.type !== 'tool_result' || !toolUses.has(block.tool_use_id)) continue;
|
|
149
|
+
if (toolResults.has(block.tool_use_id)) {
|
|
150
|
+
return { ok: false, reason: 'delivery-result-ambiguous' };
|
|
151
|
+
}
|
|
152
|
+
toolResults.set(block.tool_use_id, {
|
|
153
|
+
receipt: parseToolResult(block),
|
|
154
|
+
ordinal: blockOrdinal,
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const delivered = [];
|
|
161
|
+
const failuresByAttempt = new Map();
|
|
162
|
+
const attemptIds = new Set();
|
|
163
|
+
for (const toolUse of toolUses.values()) {
|
|
164
|
+
const toolResult = toolResults.get(toolUse.id);
|
|
165
|
+
if (!toolResult?.receipt) return { ok: false, reason: 'delivery-result-missing' };
|
|
166
|
+
const { receipt, ordinal: resultOrdinal } = toolResult;
|
|
167
|
+
if (typeof receipt.attempt_id !== 'string' || !receipt.attempt_id) {
|
|
168
|
+
return { ok: false, reason: 'delivery-attempt-missing' };
|
|
169
|
+
}
|
|
170
|
+
if (attemptIds.has(receipt.attempt_id)) {
|
|
171
|
+
return { ok: false, reason: 'delivery-attempt-ambiguous' };
|
|
172
|
+
}
|
|
173
|
+
attemptIds.add(receipt.attempt_id);
|
|
174
|
+
if (receipt.ok === true) {
|
|
175
|
+
if (receipt.delivery !== 'sent' && receipt.delivery !== 'replayed') {
|
|
176
|
+
return { ok: false, reason: 'delivery-discriminator-missing' };
|
|
177
|
+
}
|
|
178
|
+
delivered.push({ toolUse, receipt, resultOrdinal });
|
|
179
|
+
} else if (receipt.ok === false) {
|
|
180
|
+
failuresByAttempt.set(receipt.attempt_id, { toolUse, receipt, resultOrdinal });
|
|
181
|
+
} else {
|
|
182
|
+
return { ok: false, reason: 'delivery-result-invalid' };
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
let deliveredFinal = false;
|
|
187
|
+
const visibleHashes = new Set();
|
|
188
|
+
const linkedReplaySources = new Set();
|
|
189
|
+
|
|
190
|
+
for (const item of delivered) {
|
|
191
|
+
const { toolUse, receipt, resultOrdinal } = item;
|
|
192
|
+
let provesDelivery = receipt.delivery === 'sent';
|
|
193
|
+
if (receipt.delivery === 'replayed') {
|
|
194
|
+
if (typeof receipt.replay_of !== 'string' || !receipt.replay_of) {
|
|
195
|
+
return { ok: false, reason: 'delivery-replay-source-missing' };
|
|
196
|
+
}
|
|
197
|
+
const source = failuresByAttempt.get(receipt.replay_of);
|
|
198
|
+
if (source && source.resultOrdinal >= resultOrdinal) {
|
|
199
|
+
return { ok: false, reason: 'delivery-replay-order-invalid' };
|
|
200
|
+
}
|
|
201
|
+
provesDelivery = !!source
|
|
202
|
+
&& source.toolUse.toolName === toolUse.toolName
|
|
203
|
+
&& source.toolUse.argumentHash === toolUse.argumentHash;
|
|
204
|
+
if (provesDelivery) linkedReplaySources.add(receipt.replay_of);
|
|
205
|
+
}
|
|
206
|
+
if (!provesDelivery) continue;
|
|
207
|
+
if (toolUse.toolName === 'reply' && toolUse.input.interim !== true) {
|
|
208
|
+
deliveredFinal = true;
|
|
209
|
+
} else {
|
|
210
|
+
visibleHashes.add(hashText(toolUse.input.text));
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const unresolvedAttempts = [];
|
|
215
|
+
for (const [attemptId, item] of failuresByAttempt) {
|
|
216
|
+
if (linkedReplaySources.has(attemptId) || item.receipt.timeout !== true) continue;
|
|
217
|
+
unresolvedAttempts.push({
|
|
218
|
+
attemptId,
|
|
219
|
+
argumentHash: item.toolUse.argumentHash,
|
|
220
|
+
finalReply: item.toolUse.toolName === 'reply' && item.toolUse.input.interim !== true,
|
|
221
|
+
visibleHash: hashText(item.toolUse.input.text),
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
return {
|
|
226
|
+
ok: true,
|
|
227
|
+
deliveredFinal,
|
|
228
|
+
visibleHashes: [...visibleHashes],
|
|
229
|
+
unresolvedAttempts,
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async function correlateWorkflowCompletionSnapshot({
|
|
234
|
+
transcriptPath,
|
|
235
|
+
byteSize,
|
|
236
|
+
sessionId,
|
|
237
|
+
finalText,
|
|
238
|
+
} = {}) {
|
|
239
|
+
const normalizedFinal = normalizeVisibleText(finalText);
|
|
240
|
+
if (!normalizedFinal) return result('final-empty');
|
|
241
|
+
if (typeof sessionId !== 'string' || !sessionId) return result('session-missing');
|
|
242
|
+
|
|
243
|
+
const snapshot = await readSnapshot(transcriptPath, byteSize);
|
|
244
|
+
if (!snapshot.ok) return result(snapshot.reason);
|
|
245
|
+
|
|
246
|
+
const rows = [];
|
|
247
|
+
const lines = snapshot.text.split('\n');
|
|
248
|
+
lines.pop();
|
|
249
|
+
for (let index = 0; index < lines.length; index++) {
|
|
250
|
+
if (!lines[index].trim()) continue;
|
|
251
|
+
let row;
|
|
252
|
+
try {
|
|
253
|
+
row = JSON.parse(lines[index]);
|
|
254
|
+
} catch {
|
|
255
|
+
return result('json-invalid');
|
|
256
|
+
}
|
|
257
|
+
if (!row || typeof row !== 'object') return result('row-invalid');
|
|
258
|
+
rows.push(row);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const mainline = rows.filter(row => (
|
|
262
|
+
row.sessionId === sessionId
|
|
263
|
+
&& row.isSidechain === false
|
|
264
|
+
&& (row.type === 'assistant' || row.type === 'user')
|
|
265
|
+
));
|
|
266
|
+
if (!mainline.length) return result('session-mainline-missing');
|
|
267
|
+
|
|
268
|
+
const byUuid = new Map();
|
|
269
|
+
const children = new Map();
|
|
270
|
+
for (const row of mainline) {
|
|
271
|
+
if (
|
|
272
|
+
typeof row.uuid !== 'string'
|
|
273
|
+
|| !row.uuid
|
|
274
|
+
|| (row.parentUuid !== null && typeof row.parentUuid !== 'string')
|
|
275
|
+
) {
|
|
276
|
+
return result('ancestry-field-missing');
|
|
277
|
+
}
|
|
278
|
+
if (byUuid.has(row.uuid)) return result('duplicate-uuid');
|
|
279
|
+
byUuid.set(row.uuid, row);
|
|
280
|
+
if (row.parentUuid) {
|
|
281
|
+
const list = children.get(row.parentUuid) || [];
|
|
282
|
+
list.push(row.uuid);
|
|
283
|
+
children.set(row.parentUuid, list);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
let terminalIndex = -1;
|
|
288
|
+
for (let index = mainline.length - 1; index >= 0; index--) {
|
|
289
|
+
if (mainline[index].type === 'assistant') {
|
|
290
|
+
terminalIndex = index;
|
|
291
|
+
break;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
if (terminalIndex < 0) return result('terminal-missing');
|
|
295
|
+
if (terminalIndex !== mainline.length - 1) return result('terminal-not-last-mainline');
|
|
296
|
+
|
|
297
|
+
const terminal = mainline[terminalIndex];
|
|
298
|
+
if (
|
|
299
|
+
typeof terminal.requestId !== 'string' || !terminal.requestId
|
|
300
|
+
|| typeof terminal.message?.id !== 'string' || !terminal.message.id
|
|
301
|
+
) {
|
|
302
|
+
return result('terminal-identity-missing');
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
const group = [terminal];
|
|
306
|
+
for (let index = terminalIndex - 1; index >= 0; index--) {
|
|
307
|
+
const prior = mainline[index];
|
|
308
|
+
const first = group[0];
|
|
309
|
+
if (
|
|
310
|
+
prior.type !== 'assistant'
|
|
311
|
+
|| prior.sessionId !== terminal.sessionId
|
|
312
|
+
|| prior.requestId !== terminal.requestId
|
|
313
|
+
|| prior.message?.id !== terminal.message.id
|
|
314
|
+
) break;
|
|
315
|
+
if (first.parentUuid !== prior.uuid) return result('terminal-fragment-chain-broken');
|
|
316
|
+
group.unshift(prior);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
if (terminal.message?.stop_reason !== 'end_turn') return result('terminal-not-end-turn');
|
|
320
|
+
const terminalTexts = [];
|
|
321
|
+
for (const row of group) {
|
|
322
|
+
if (!Array.isArray(row.message?.content)) return result('terminal-content-invalid');
|
|
323
|
+
for (const block of row.message.content) {
|
|
324
|
+
if (block?.type === 'tool_use') return result('terminal-has-tool-use');
|
|
325
|
+
if (block?.type === 'text') {
|
|
326
|
+
if (typeof block.text !== 'string') return result('terminal-text-invalid');
|
|
327
|
+
terminalTexts.push(block.text);
|
|
328
|
+
} else if (block?.type !== 'thinking') {
|
|
329
|
+
return result('terminal-block-invalid');
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
if (normalizeVisibleText(terminalTexts.join('\n\n')) !== normalizedFinal) {
|
|
334
|
+
return result('final-mismatch');
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
const reversePath = [];
|
|
338
|
+
const visited = new Set(group.map(row => row.uuid));
|
|
339
|
+
let cursorUuid = group[0].parentUuid;
|
|
340
|
+
let notification = null;
|
|
341
|
+
while (cursorUuid) {
|
|
342
|
+
if (visited.has(cursorUuid)) return result('ancestry-cycle');
|
|
343
|
+
visited.add(cursorUuid);
|
|
344
|
+
const row = byUuid.get(cursorUuid);
|
|
345
|
+
if (!row) return result('ancestry-broken');
|
|
346
|
+
reversePath.push(row);
|
|
347
|
+
if ((children.get(row.uuid) || []).length > 1) return result('ancestry-fork');
|
|
348
|
+
if (row.type === 'user') {
|
|
349
|
+
const content = textFromMessage(row.message);
|
|
350
|
+
if (content.invalid) return result('user-content-ambiguous');
|
|
351
|
+
if (normalizeVisibleText(content.text)) {
|
|
352
|
+
notification = row;
|
|
353
|
+
break;
|
|
354
|
+
}
|
|
355
|
+
if (!content.toolResultOnly) return result('user-content-empty');
|
|
356
|
+
} else if (row.type !== 'assistant') {
|
|
357
|
+
return result('ancestry-row-ineligible');
|
|
358
|
+
}
|
|
359
|
+
cursorUuid = row.parentUuid;
|
|
360
|
+
}
|
|
361
|
+
if (!notification) return result('notification-missing');
|
|
362
|
+
if (
|
|
363
|
+
notification.origin?.kind !== 'task-notification'
|
|
364
|
+
|| notification.promptSource !== 'system'
|
|
365
|
+
|| notification.isSidechain !== false
|
|
366
|
+
) {
|
|
367
|
+
return result('notification-provenance-invalid');
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
const notificationText = textFromMessage(notification.message).text;
|
|
371
|
+
if (!notificationText.includes('<task-notification>')) {
|
|
372
|
+
return result('notification-shape-invalid');
|
|
373
|
+
}
|
|
374
|
+
const notificationIds = [...notificationText.matchAll(TASK_NOTIFICATION_ID_RE)].map(match => match[1].trim());
|
|
375
|
+
if (notificationIds.length !== 1 || !notificationIds[0]) {
|
|
376
|
+
return result('notification-tool-id-ambiguous');
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const workflowToolId = notificationIds[0];
|
|
380
|
+
const workflowMatches = [];
|
|
381
|
+
cursorUuid = notification.parentUuid;
|
|
382
|
+
const launchVisited = new Set();
|
|
383
|
+
while (cursorUuid) {
|
|
384
|
+
if (launchVisited.has(cursorUuid)) return result('launch-ancestry-cycle');
|
|
385
|
+
launchVisited.add(cursorUuid);
|
|
386
|
+
const row = byUuid.get(cursorUuid);
|
|
387
|
+
if (!row) return result('launch-ancestry-broken');
|
|
388
|
+
if ((children.get(row.uuid) || []).length > 1) return result('launch-ancestry-fork');
|
|
389
|
+
if (row.type === 'assistant' && Array.isArray(row.message?.content)) {
|
|
390
|
+
for (const block of row.message.content) {
|
|
391
|
+
if (block?.type === 'tool_use' && block.id === workflowToolId && block.name === 'Workflow') {
|
|
392
|
+
workflowMatches.push(block);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
cursorUuid = row.parentUuid;
|
|
397
|
+
}
|
|
398
|
+
if (workflowMatches.length !== 1) return result('workflow-tool-match-invalid');
|
|
399
|
+
|
|
400
|
+
const branch = [notification, ...reversePath.slice(0, -1).reverse(), ...group];
|
|
401
|
+
const receipts = collectToolReceipts(branch);
|
|
402
|
+
if (!receipts.ok) return result(receipts.reason);
|
|
403
|
+
|
|
404
|
+
return result('eligible', {
|
|
405
|
+
eligible: true,
|
|
406
|
+
finalHash: hashText(normalizedFinal),
|
|
407
|
+
deliveredFinal: receipts.deliveredFinal,
|
|
408
|
+
visibleHashes: receipts.visibleHashes,
|
|
409
|
+
unresolvedAttempts: receipts.unresolvedAttempts,
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
module.exports = {
|
|
414
|
+
correlateWorkflowCompletionSnapshot,
|
|
415
|
+
hashDeliveryArguments,
|
|
416
|
+
normalizeVisibleText,
|
|
417
|
+
};
|
package/lib/tmux/tmux-runner.js
CHANGED
|
@@ -188,8 +188,10 @@ function createTmuxRunner({
|
|
|
188
188
|
sessionPrefix = 'orchestra',
|
|
189
189
|
logger = console,
|
|
190
190
|
runFn = run,
|
|
191
|
+
requireExistingServer = false,
|
|
191
192
|
} = {}) {
|
|
192
193
|
const runnerPrefix = sessionPrefix;
|
|
194
|
+
const runTmux = (args, opts) => runFn('tmux', requireExistingServer ? ['-N', ...args] : args, opts);
|
|
193
195
|
async function spawn({
|
|
194
196
|
name,
|
|
195
197
|
cwd,
|
|
@@ -213,7 +215,7 @@ function createTmuxRunner({
|
|
|
213
215
|
}
|
|
214
216
|
sessArgs.push(command, ...args);
|
|
215
217
|
try {
|
|
216
|
-
await
|
|
218
|
+
await runTmux(sessArgs);
|
|
217
219
|
} catch (err) {
|
|
218
220
|
throw Object.assign(new Error(`tmux spawn failed: ${err.message}`), {
|
|
219
221
|
code: 'TMUX_SPAWN_FAILED',
|
|
@@ -229,7 +231,7 @@ function createTmuxRunner({
|
|
|
229
231
|
// settable option). capture-pane -J in captureWide() handles
|
|
230
232
|
// any remaining wrap artifacts.
|
|
231
233
|
try {
|
|
232
|
-
await
|
|
234
|
+
await runTmux(['resize-window', '-t', name, '-x', String(paneWidth)]);
|
|
233
235
|
} catch (err) {
|
|
234
236
|
logger.debug?.(`[tmux-runner] resize-window failed for ${name}: ${err.message} (capture-pane -J handles wrap)`);
|
|
235
237
|
}
|
|
@@ -242,7 +244,7 @@ function createTmuxRunner({
|
|
|
242
244
|
* key names like "Enter" and "C-c".
|
|
243
245
|
*/
|
|
244
246
|
async function sendControl(name, key) {
|
|
245
|
-
await
|
|
247
|
+
await runTmux(['send-keys', '-t', name, key]);
|
|
246
248
|
}
|
|
247
249
|
|
|
248
250
|
// rc.13.1: paste+Enter must be ATOMIC per session. Pre-rc.13.1 two
|
|
@@ -318,13 +320,13 @@ function createTmuxRunner({
|
|
|
318
320
|
const sanitized = sanitize(text);
|
|
319
321
|
const oneLine = sanitized.replace(/\r?\n/g, MULTILINE_SEPARATOR);
|
|
320
322
|
const bufName = `${runnerPrefix}-buf-${crypto.randomBytes(3).toString('hex')}`;
|
|
321
|
-
await
|
|
323
|
+
await runTmux(['set-buffer', '-b', bufName, oneLine]);
|
|
322
324
|
try {
|
|
323
325
|
// -d (delete after) so the buffer doesn't accumulate.
|
|
324
|
-
await
|
|
326
|
+
await runTmux(['paste-buffer', '-t', name, '-b', bufName, '-d']);
|
|
325
327
|
} catch (err) {
|
|
326
328
|
// Best-effort buffer cleanup if paste fails.
|
|
327
|
-
await
|
|
329
|
+
await runTmux(['delete-buffer', '-b', bufName]).catch(() => {});
|
|
328
330
|
throw err;
|
|
329
331
|
}
|
|
330
332
|
// Drain delay — see incident note above.
|
|
@@ -346,7 +348,7 @@ function createTmuxRunner({
|
|
|
346
348
|
const args = ['capture-pane', '-t', name, '-p'];
|
|
347
349
|
if (joinWrapped) args.push('-J');
|
|
348
350
|
args.push('-S', `-${lines}`);
|
|
349
|
-
const { stdout } = await
|
|
351
|
+
const { stdout } = await runTmux(args);
|
|
350
352
|
return stdout;
|
|
351
353
|
}
|
|
352
354
|
|
|
@@ -360,15 +362,33 @@ function createTmuxRunner({
|
|
|
360
362
|
|
|
361
363
|
async function sessionExists(name) {
|
|
362
364
|
try {
|
|
363
|
-
await
|
|
365
|
+
await runTmux(['has-session', '-t', name]);
|
|
364
366
|
return true;
|
|
365
367
|
} catch {
|
|
366
368
|
return false;
|
|
367
369
|
}
|
|
368
370
|
}
|
|
369
371
|
|
|
372
|
+
async function sessionProcessAlive(name) {
|
|
373
|
+
try {
|
|
374
|
+
const { stdout } = await runTmux([
|
|
375
|
+
'list-panes',
|
|
376
|
+
'-t',
|
|
377
|
+
name,
|
|
378
|
+
'-F',
|
|
379
|
+
'#{pane_dead} #{pane_pid}',
|
|
380
|
+
]);
|
|
381
|
+
return stdout
|
|
382
|
+
.trim()
|
|
383
|
+
.split('\n')
|
|
384
|
+
.some(line => /^0 [1-9][0-9]*$/.test(line.trim()));
|
|
385
|
+
} catch {
|
|
386
|
+
return false;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
370
390
|
async function killSession(name) {
|
|
371
|
-
await
|
|
391
|
+
await runTmux(['kill-session', '-t', name]).catch(() => {});
|
|
372
392
|
}
|
|
373
393
|
|
|
374
394
|
/**
|
|
@@ -377,7 +397,7 @@ function createTmuxRunner({
|
|
|
377
397
|
*/
|
|
378
398
|
async function listPolygramSessions(botName = null) {
|
|
379
399
|
try {
|
|
380
|
-
const { stdout } = await
|
|
400
|
+
const { stdout } = await runTmux(['list-sessions', '-F', '#{session_name}']);
|
|
381
401
|
const all = stdout.trim().split('\n').filter(Boolean);
|
|
382
402
|
const prefix = botName ? `${runnerPrefix}-${String(botName).replace(/[^\w-]/g, '_')}-` : `${runnerPrefix}-`;
|
|
383
403
|
return all.filter((n) => n.startsWith(prefix));
|
|
@@ -394,6 +414,7 @@ function createTmuxRunner({
|
|
|
394
414
|
capturePane,
|
|
395
415
|
captureWide,
|
|
396
416
|
sessionExists,
|
|
417
|
+
sessionProcessAlive,
|
|
397
418
|
killSession,
|
|
398
419
|
listPolygramSessions,
|
|
399
420
|
sessionName: (b, c, t) => sessionName(b, c, t, sessionPrefix),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shumkov/orchestra",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Drive interactive Claude Code CLI sessions: spawn, inject messages via the MCP channels bridge, observe turns, recover. The transport-agnostic session engine extracted from polygram, shared by polygram (Telegram) and water (WhatsApp).",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "index.js",
|