@shumkov/orchestra 0.7.4 → 0.9.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.
@@ -192,15 +192,22 @@ direct-binary run; it does not clear the broader hosted-tool enforcement gate.
192
192
 
193
193
  ## Profile provenance
194
194
 
195
- Live pinned-runtime characterization found the exact profile at top-level
195
+ Two live pinned-runtime rollout runs found the exact profile at top-level
196
196
  `activePermissionProfile` in both `thread/start` and `thread/resume`
197
197
  responses. The value is fixture-pinned as `{id: "polygram-session",
198
198
  extends: null}`. Both attachment responses also return exactly one concrete
199
199
  `runtimeWorkspaceRoots` entry equal to the owned cwd. Orchestra exposes that
200
200
  entry only as `{count: 1, sha256: [sha256(ownedCwd)]}`.
201
201
 
202
- Fresh, resume, and `thread/settings/updated` all return the same legacy
203
- compatibility envelope:
202
+ Neither rollout run emitted `thread/settings/updated` during fresh or resume
203
+ attachment within the bounded wait. An exact attachment response is therefore
204
+ sufficient profile provenance. If an attachment-time notification does appear,
205
+ the checker still requires its complete static settings view to be exact.
206
+ Notifications caused by explicit experimental `thread/settings/update` calls
207
+ are characterized separately and do not establish attachment-time emission.
208
+
209
+ Fresh and resume responses, and any observed `thread/settings/updated`, use the
210
+ same legacy compatibility envelope:
204
211
 
205
212
  ```json
206
213
  {
@@ -56,7 +56,15 @@ const ToolCallMessageSchema = z.object({
56
56
  // args are {chat_id, turn_id?, questions:[...]}, not reply-shaped. _dispatchToolCall
57
57
  // branches on the name so the reply-only paths (chat_id-mismatch, content-dedup,
58
58
  // reply-turn-binding) don't run for it.
59
- name: z.enum(['reply', 'react', 'edit_message', 'ask']),
59
+ //
60
+ // 'stream': a mid-turn snapshot of the answer the agent is composing, for the
61
+ // consumer's live preview. Args are {chat_id, turn_id, text}; turn_id is
62
+ // REQUIRED (a snapshot that can't be attributed to a turn is dropped, never
63
+ // painted onto whatever turn happens to be in flight). It is NOT a delivery —
64
+ // the daemon forwards it as a `stream-chunk` event and never routes it
65
+ // through the reply/delivery paths. Registered on the bridge only when the
66
+ // consumer opted in (ORCHESTRA_STREAM_TOOL).
67
+ name: z.enum(['reply', 'react', 'edit_message', 'ask', 'stream']),
60
68
  args: z.object({}).passthrough(),
61
69
  }).passthrough();
62
70
 
@@ -46,6 +46,14 @@ const SOCK = process.env.ORCHESTRA_SOCK
46
46
  const SOCK_SECRET = process.env.ORCHESTRA_SOCK_SECRET
47
47
  // P3 naming: align internal variable with the env-var name + wire-format field.
48
48
  const CLAUDE_SESSION_ID = process.env.ORCHESTRA_CLAUDE_SESSION_ID
49
+ // Live-preview streaming is opt-in per consumer, decided at spawn time by the
50
+ // daemon (CliProcess.toolDispatcherCapabilities → _bridgeEnv). A consumer that
51
+ // has no live-preview surface never sets it, so the tool is absent from
52
+ // ListTools and CallTool rejects it — the agent is never told about a
53
+ // capability the other side can't honor. A handshake can't do this job: the
54
+ // bridge is the side claude talks to, and ListTools fires once, racing the
55
+ // daemon socket.
56
+ const STREAM_TOOL_ENABLED = process.env.ORCHESTRA_STREAM_TOOL === '1'
49
57
 
50
58
  if (!SESSION_KEY || !SOCK || !SOCK_SECRET) {
51
59
  process.stderr.write('[water-bridge] missing required env (ORCHESTRA_SESSION_KEY/SOCK/SOCK_SECRET)\n')
@@ -416,12 +424,38 @@ mcp.setRequestHandler(ListToolsRequestSchema, async () => {
416
424
  },
417
425
  required: ['chat_id', 'questions'],
418
426
  },
419
- }],
427
+ },
428
+ // Live preview of the answer being composed. Present only when the consumer
429
+ // opted in at spawn time; the matching prompt section is gated on the same
430
+ // flag, so the agent is never coached to call a tool that isn't registered.
431
+ ...(STREAM_TOOL_ENABLED ? [{
432
+ name: 'stream',
433
+ description: 'Show the user the answer you are composing, live, while you are still writing it. ' +
434
+ 'Pass the FULL answer-so-far (cumulative — not a delta) at natural checkpoints ' +
435
+ 'while composing anything long; each call replaces the preview. ' +
436
+ 'This is a preview, NOT a delivery: it never ends a turn, and you MUST still ' +
437
+ 'finish with a normal `reply` carrying the complete answer. ' +
438
+ 'Returns {ok:true} and has no effect on the turn — never retry a failed stream call.',
439
+ inputSchema: {
440
+ type: 'object',
441
+ properties: {
442
+ chat_id: { type: 'string', description: 'Echo of chat_id from inbound channel meta.' },
443
+ turn_id: { type: 'string', description: 'Echo of turn_id from inbound channel meta (required — a snapshot that cannot be attributed to a turn is dropped).' },
444
+ text: { type: 'string', description: 'The full answer so far (markdown ok).' },
445
+ },
446
+ required: ['chat_id', 'turn_id', 'text'],
447
+ },
448
+ }] : []),
449
+ ],
420
450
  }
421
451
  })
422
452
 
453
+ const CALLABLE_TOOLS = new Set(
454
+ ['reply', 'ask', 'edit_message', ...(STREAM_TOOL_ENABLED ? ['stream'] : [])],
455
+ )
456
+
423
457
  mcp.setRequestHandler(CallToolRequestSchema, async req => {
424
- if (req.params.name !== 'reply' && req.params.name !== 'ask' && req.params.name !== 'edit_message') {
458
+ if (!CALLABLE_TOOLS.has(req.params.name)) {
425
459
  return { content: [{ type: 'text', text: `unknown tool: ${req.params.name}` }], isError: true }
426
460
  }
427
461
  const toolCallId = randomUUID()
@@ -119,6 +119,12 @@ const DEFAULT_TOOL_RATE_LIMIT_PER_SEC = 5; // P2 ADV-6: cap on reply tool call
119
119
  const DEFAULT_TOOL_RATE_BURST = 20; // ADV-6: token bucket capacity
120
120
  const DEFAULT_QUEUE_CAP = 50; // Parity P2: match SDK/tmux pendingQueue cap
121
121
 
122
+ // Live-preview snapshots a single turn may push. Deliberately NOT part of the
123
+ // reply token bucket: the consumer's own edit throttle is the real rate limiter,
124
+ // and sharing a bucket would let a burst of snapshots starve the `reply` that
125
+ // ends the turn. This is only an anti-runaway bound.
126
+ const STREAM_CALLS_PER_TURN_CAP = 200;
127
+
122
128
  function validateSessionLauncher(sessionLauncher) {
123
129
  if (!sessionLauncher) return null;
124
130
  if (typeof sessionLauncher !== 'string' || !path.isAbsolute(sessionLauncher)) {
@@ -277,6 +283,13 @@ class CliProcess extends Process {
277
283
  claudeBin = null,
278
284
  sessionLauncher = process.env.ORCHESTRA_SESSION_LAUNCHER || null,
279
285
  toolDispatcher,
286
+ // Which optional bridge tools this consumer's dispatcher can honor.
287
+ // `{stream: true}` registers the `stream` tool + its prompt section and
288
+ // turns snapshots into `stream-chunk` events. A consumer with no live
289
+ // preview surface leaves it unset and the tool never exists — the boundary
290
+ // that can actually skew is this wiring, not bridge↔daemon (they ship in
291
+ // one package), which is why the gate lives here and not in a handshake.
292
+ toolDispatcherCapabilities = null,
280
293
  // Extraction-time API (orchestra): the consumer injects its surface-rendering
281
294
  // hint (appended to the system prompt) and outbound file-size cap, so the engine
282
295
  // is transport-agnostic. Were hard `require`s in the polygram/water copy.
@@ -333,6 +346,11 @@ class CliProcess extends Process {
333
346
  this.claudeBin = claudeBin || process.env.ORCHESTRA_CLAUDE_BIN;
334
347
  this.sessionLauncher = validateSessionLauncher(sessionLauncher);
335
348
  this.toolDispatcher = toolDispatcher;
349
+ this.streamToolEnabled = toolDispatcherCapabilities?.stream === true;
350
+ // What claude calls the live-preview tool in its hook stream. The
351
+ // PreToolUse/PostToolUse matcher is `.*`, so the agent's own stream calls
352
+ // arrive here as work hooks — see _handleHookEvent for why that matters.
353
+ this._streamToolHookName = `mcp__${bridgeServerName}__stream`;
336
354
  this.displayHint = displayHint;
337
355
  this._injectedMaxOutboundFileBytes = maxOutboundFileBytes;
338
356
  this.sessionPrefix = sessionPrefix;
@@ -701,6 +719,15 @@ class CliProcess extends Process {
701
719
  ORCHESTRA_SOCK_SECRET: this.sockSecret,
702
720
  ORCHESTRA_CLAUDE_SESSION_ID: this.claudeSessionId,
703
721
  ORCHESTRA_QUESTION_TIMEOUT_MS: String(QUESTION_TIMEOUT_MS),
722
+ // Opt-in live-preview tool. Set at spawn time so the registered tool set
723
+ // and the system prompt can never disagree about whether `stream` exists.
724
+ //
725
+ // ALWAYS written, never merely omitted: the bridge reads the ambient
726
+ // environment, and this env travels daemon → tmux → claude → MCP child.
727
+ // An ORCHESTRA_STREAM_TOOL=1 anywhere up that chain (an operator's shell,
728
+ // a co-tenant daemon) would otherwise switch the tool on for a consumer
729
+ // that never opted in. Omission is not a decision; '' is.
730
+ ORCHESTRA_STREAM_TOOL: this.streamToolEnabled ? '1' : '',
704
731
  };
705
732
  }
706
733
 
@@ -944,6 +971,26 @@ class CliProcess extends Process {
944
971
  'Write status in PLAIN language about what you are doing FOR THE USER — never',
945
972
  'tool names. Say "Checking your config now…", not "Running Bash".',
946
973
  '',
974
+ // Present ONLY when the consumer registered the tool (same spawn-time flag
975
+ // that puts `stream` in the bridge's tool list), so the contract below can
976
+ // never coach the agent toward a tool that isn't there.
977
+ ...(this.streamToolEnabled ? [
978
+ '### Showing your answer as you write it',
979
+ '',
980
+ `While you are COMPOSING anything long, call \`mcp__${b}__stream\` with the`,
981
+ 'FULL answer-so-far at natural checkpoints (after a paragraph, a section, a',
982
+ 'finished thought). Each call replaces the preview, so always send the whole',
983
+ 'answer up to that point — never just the new part. The user watches it fill in',
984
+ 'instead of staring at silence.',
985
+ '',
986
+ 'HARD RULE — `stream` is a PREVIEW, not a delivery. It never ends a turn and',
987
+ `it is not the answer. ALWAYS finish with a normal \`mcp__${b}__reply\``,
988
+ 'carrying the complete answer; NEVER end a turn on a stream call.',
989
+ '',
990
+ 'Skip it for short answers (a couple of sentences) — just reply. And never',
991
+ 'retry a stream call: it cannot fail in a way that matters.',
992
+ '',
993
+ ] : []),
947
994
  // TEMPORARY mitigation (2026-06-08 Shumabit@UMI wedge): AskUserQuestion opens
948
995
  // a blocking TUI selection widget the channel can't answer → the session
949
996
  // parks until manually Esc'd. REMOVE this whole rule when the rich
@@ -1697,6 +1744,17 @@ class CliProcess extends Process {
1697
1744
  `text_len=${typeof args.text === 'string' ? args.text.length : 'non-string'}`,
1698
1745
  );
1699
1746
 
1747
+ // A live-preview snapshot. Handled BEFORE everything below because it must
1748
+ // not participate in any of it: not the delivery caches (a preview is not a
1749
+ // delivery), not the reply token bucket (a snapshot burst must not starve
1750
+ // the reply that ends the turn), and above all not `_noteActivity` — that
1751
+ // cancels an in-flight stop-grace, so a trailing snapshot would de-finalize
1752
+ // a turn that is already resolving.
1753
+ if (msg.name === 'stream') {
1754
+ this._handleStreamCall(msg, args);
1755
+ return;
1756
+ }
1757
+
1700
1758
  // Review P1 #7: idempotency. If we've already ACK'd this tool_call_id,
1701
1759
  // re-ACK with the cached result rather than re-dispatching to Telegram.
1702
1760
  // Without this, Claude's reply-retry on isError (which can fire after a
@@ -1962,6 +2020,10 @@ class CliProcess extends Process {
1962
2020
  threadId: this.threadId,
1963
2021
  toolName: msg.name,
1964
2022
  text: args.text,
2023
+ // The turn this call names. A consumer holding per-turn state needs it
2024
+ // to refuse a late reply from an earlier turn — without it, a delayed
2025
+ // reply lands on whatever turn the session is holding NOW.
2026
+ turnId: typeof args.turn_id === 'string' ? args.turn_id : null,
1965
2027
  interim: args.interim === true, // status/progress reply — not the turn's answer
1966
2028
  files: args.files,
1967
2029
  messageId: args.message_id, // 0.13: edit_message target bubble
@@ -2071,6 +2133,124 @@ class CliProcess extends Process {
2071
2133
  }
2072
2134
  }
2073
2135
 
2136
+ /**
2137
+ * A `stream` tool call: a snapshot of the answer the agent is still writing.
2138
+ * Forwarded to the consumer as `stream-chunk` — the same event the SDK
2139
+ * backend emits per token batch — so the consumer's existing live-preview
2140
+ * wiring picks it up unchanged.
2141
+ *
2142
+ * Ack policy: EVERY outcome acks {ok:true}, including refusals. A false ack
2143
+ * becomes an MCP isError, and claude retries on isError — so a rejected
2144
+ * snapshot is both free and infinitely repeatable, and the retry loop would
2145
+ * cost the turn its real answer. The reason a snapshot was refused is the
2146
+ * operator's business, not the agent's: it goes to telemetry only, never to
2147
+ * the log (a loop would flood it) and never back over the wire.
2148
+ */
2149
+ _handleStreamCall(msg, args) {
2150
+ const ack = () => this._writeToBridge({
2151
+ kind: 'tool_ack',
2152
+ tool_call_id: msg.tool_call_id,
2153
+ ok: true,
2154
+ attempt_id: msg.tool_call_id,
2155
+ });
2156
+ const refuse = (reason) => {
2157
+ this._logEvent('stream-refused', { reason, turn_id: args?.turn_id ?? null });
2158
+ ack();
2159
+ };
2160
+
2161
+ // Defense in depth against the env gate. The bridge decides what to
2162
+ // REGISTER from its environment, which is not fully ours to control; the
2163
+ // daemon decides what to HONOR, which is. A stream call arriving at a
2164
+ // process whose consumer never opted in means the bridge was enabled by
2165
+ // something other than us — drop it rather than emit stream-chunk at a
2166
+ // consumer with nothing wired to receive it.
2167
+ if (!this.streamToolEnabled) {
2168
+ refuse('tool-not-enabled');
2169
+ return;
2170
+ }
2171
+
2172
+ // Same chat_id gate every tool call gets — no cross-chat preview injection.
2173
+ if (this.chatId != null && String(args.chat_id) !== String(this.chatId)) {
2174
+ refuse('chat-id-mismatch');
2175
+ return;
2176
+ }
2177
+ // A blank snapshot would wipe the preview bubble for no reason.
2178
+ if (typeof args.text !== 'string' || args.text.trim().length === 0) {
2179
+ refuse('empty-text');
2180
+ return;
2181
+ }
2182
+ const turnId = typeof args.turn_id === 'string' ? args.turn_id : '';
2183
+ if (!turnId) {
2184
+ refuse('missing-turn-id');
2185
+ return;
2186
+ }
2187
+
2188
+ // Attribution: only the turn that owns this turn_id may drive its preview.
2189
+ // A foreign cycle (/compact, wakeup, a steered injection) or an already-
2190
+ // closed turn has no queue entry; drop it. Falling back to the head would
2191
+ // paint one user's preview with another cycle's text. The head check is the
2192
+ // same rule from the other side: the consumer routes `stream-chunk` to the
2193
+ // head turn's preview, so a snapshot for a queued (non-head) turn would
2194
+ // land on the wrong bubble.
2195
+ const entry = this.pendingQueue.find(e => e.turnId === turnId);
2196
+ if (!entry || this.pendingQueue[0] !== entry) {
2197
+ // `reason` matters to the operator: 'not-head' means a queued follow-up
2198
+ // turn streamed while an earlier turn held the preview — correct (its
2199
+ // snapshots would paint the wrong bubble) but it silently means NO live
2200
+ // preview for that turn, and only this field makes that visible.
2201
+ this._logEvent('stream-unattributed', {
2202
+ turn_id: turnId,
2203
+ len: args.text.length,
2204
+ reason: entry ? 'not-head' : 'no-pending-turn',
2205
+ });
2206
+ ack();
2207
+ return;
2208
+ }
2209
+
2210
+ // Anti-runaway bound, counted ONLY for the attributed turn and stored on
2211
+ // its queue entry. Counting before attribution — or in any structure keyed
2212
+ // by the caller-supplied turn_id — hands the runaway its own escape: a
2213
+ // burst of invented turn_ids drives the live turn's count out of a bounded
2214
+ // map and the cap resets forever. The entry is created at dispatch and
2215
+ // dropped at settlement, so the count lives exactly as long as the turn it
2216
+ // bounds, and nothing outside that turn can touch it.
2217
+ entry._streamCalls = (entry._streamCalls || 0) + 1;
2218
+ if (entry._streamCalls > STREAM_CALLS_PER_TURN_CAP) {
2219
+ // Two events per turn, not one per dropped call: a runaway would write
2220
+ // thousands of rows describing the same runaway, but a single event can't
2221
+ // tell a chatty turn that brushed the cap from one looping without end.
2222
+ // The second, at twice the cap, is what distinguishes them in the soak.
2223
+ if (entry._streamCalls === STREAM_CALLS_PER_TURN_CAP + 1
2224
+ || entry._streamCalls === STREAM_CALLS_PER_TURN_CAP * 2) {
2225
+ this._logEvent('stream-cap-exceeded', {
2226
+ turn_id: turnId,
2227
+ cap: STREAM_CALLS_PER_TURN_CAP,
2228
+ calls: entry._streamCalls,
2229
+ });
2230
+ }
2231
+ ack();
2232
+ return;
2233
+ }
2234
+
2235
+ // Composing IS work, so push the idle ceiling out — but only that (the full
2236
+ // activity ladder would cancel a stop-grace; see the branch comment above).
2237
+ // Placed AFTER attribution and the cap: the idle ceiling is the backstop for
2238
+ // a wedged turn, so a snapshot that was dropped — foreign, or past the cap —
2239
+ // must not be able to hold that backstop open indefinitely.
2240
+ this._resetIdleCeilings();
2241
+
2242
+ // Segmented fresh-spawn vs resumed: a resumed conversation carries
2243
+ // in-context evidence of the habit, so adoption there says nothing about
2244
+ // whether the prompt alone teaches it. The soak needs the two apart.
2245
+ this._logEvent('stream-seen', {
2246
+ turn_id: turnId,
2247
+ len: args.text.length,
2248
+ resumed: this._resumedSession === true,
2249
+ });
2250
+ this.emit('stream-chunk', args.text);
2251
+ ack();
2252
+ }
2253
+
2074
2254
  /**
2075
2255
  * Route a reply text to the pending turn it belongs to.
2076
2256
  *
@@ -2433,15 +2613,9 @@ class CliProcess extends Process {
2433
2613
  */
2434
2614
  _noteActivity(source = 'activity') {
2435
2615
  this._lastActivityAt = Date.now();
2616
+ // Idle ceiling: activity IS activity.
2617
+ this._resetIdleCeilings();
2436
2618
  for (const [turnId, pending] of this.pendingTurns) {
2437
- // Idle ceiling: activity IS activity.
2438
- if (pending.hardTimer) {
2439
- clearTimeout(pending.hardTimer);
2440
- pending.hardTimer = setTimeout(
2441
- () => pending._fireTimeout?.('idle'),
2442
- pending._idleCeilingMs || this.turnTimeoutMs,
2443
- );
2444
- }
2445
2619
  if (this._sawHookStream) {
2446
2620
  if (pending._stopGracePending) this._cancelStopGrace(turnId, pending, source);
2447
2621
  if (pending.quietTimer) { clearTimeout(pending.quietTimer); pending.quietTimer = null; }
@@ -2457,6 +2631,23 @@ class CliProcess extends Process {
2457
2631
  }
2458
2632
  }
2459
2633
 
2634
+ /**
2635
+ * Push every pending turn's idle ceiling out. The narrow half of
2636
+ * `_noteActivity` — proof the agent is working, with none of the finalizer
2637
+ * consequences (stop-grace cancellation, quiet-window re-arm). Callers that
2638
+ * only know "still working" and must not touch turn resolution use this.
2639
+ */
2640
+ _resetIdleCeilings() {
2641
+ for (const [, pending] of this.pendingTurns) {
2642
+ if (!pending.hardTimer) continue;
2643
+ clearTimeout(pending.hardTimer);
2644
+ pending.hardTimer = setTimeout(
2645
+ () => pending._fireTimeout?.('idle'),
2646
+ pending._idleCeilingMs || this.turnTimeoutMs,
2647
+ );
2648
+ }
2649
+ }
2650
+
2460
2651
  /**
2461
2652
  * Is this turn eligible for the rung-2 activity-quiet finalize? Eligible when the
2462
2653
  * answer is already captured where a finalize can deliver it:
@@ -2926,6 +3117,19 @@ class CliProcess extends Process {
2926
3117
  // pm-interface PmSpawnContext shape — defensive defaults; the only
2927
3118
  // consumers (sdk/callbacks.js) read .context.* so the rest is fine.
2928
3119
  };
3120
+ // Hand the turn's id to the caller. A consumer holding per-turn state (a
3121
+ // live preview, say) otherwise has no way to tell whether a tool call that
3122
+ // names a turn_id belongs to the turn it is holding — and the alternative,
3123
+ // reading pendingQueue, is reaching into our internals. A callback rather
3124
+ // than a property write on the caller's object: the consumer decides where
3125
+ // the id lands, and we never mutate something we were merely handed.
3126
+ // Fired before the first await, so it is set by the time any tool call can
3127
+ // arrive. A throwing consumer must not take the turn down with it.
3128
+ if (typeof queueEntry.context.onTurnId === 'function') {
3129
+ try { queueEntry.context.onTurnId(turnId); } catch (err) {
3130
+ this.logger.warn?.(`[${this.label}] cli: onTurnId consumer threw: ${err.message}`);
3131
+ }
3132
+ }
2929
3133
  this.pendingQueue.push(queueEntry);
2930
3134
 
2931
3135
  this.emit('thinking');
@@ -3680,7 +3884,19 @@ class CliProcess extends Process {
3680
3884
  // rung-2 no-reply backstop snapshots this at Stop capture; a later increment means
3681
3885
  // claude resumed work, withdrawing the stale Stop's finalize eligibility.
3682
3886
  this._workHookSeq = (this._workHookSeq || 0) + 1;
3683
- this._noteActivity(`hook:${ev.type}`);
3887
+ // The live-preview tool is the ONE tool call that must not run the full
3888
+ // activity ladder. The Pre/PostToolUse matcher is `.*`, so the agent's own
3889
+ // `stream` calls arrive here like any other tool — and _noteActivity
3890
+ // CANCELS an in-flight stop-grace once hooks are live. A trailing snapshot
3891
+ // would then de-finalize a turn that was already resolving, which is
3892
+ // exactly what the socket-side handler refuses to do. Its idle-ceiling
3893
+ // reset happens there instead, after attribution.
3894
+ // (_lastHookEventAt and _workHookSeq above are deliberately left alone:
3895
+ // neither touches stop-grace, and suppressing them would quietly change
3896
+ // the other finalizer rungs.)
3897
+ const isStreamToolHook = (ev.type === 'PreToolUse' || ev.type === 'PostToolUse')
3898
+ && ev.toolName === this._streamToolHookName;
3899
+ if (!isStreamToolHook) this._noteActivity(`hook:${ev.type}`);
3684
3900
  }
3685
3901
 
3686
3902
  switch (ev.type) {
@@ -402,6 +402,12 @@ function _maybeWarnR12Migration({ rawPm, canonical, chatId, threadId, chatCfg, t
402
402
  * async ({sessionKey, chatId, threadId, toolName, text, files}) => {ok, error?}.
403
403
  * Called when Claude's reply (or react/edit_message) tool fires inside a
404
404
  * CliProcess. Polygram supplies the actual Telegram-send wiring.
405
+ * @param {object|Function} [opts.toolDispatcherCapabilities] — optional bridge tools this
406
+ * consumer's dispatcher can honor, e.g. `{stream: true}` for a live-preview surface.
407
+ * Accepts an object (same for every session) OR a resolver
408
+ * `(chatId, threadId, config) => object` invoked once per spawn, so the capability can
409
+ * be rolled out per chat/topic. Unset → the optional tools are never registered and
410
+ * consumers that don't implement them are unaffected.
405
411
  * @param {string} [opts.channelsClaudeBin] — absolute path to pinned claude binary;
406
412
  * required when ANY chat routes to 'cli'. (Name kept for back-compat with
407
413
  * existing wiring; can be renamed to `claudeBin` in a future refactor.)
@@ -438,6 +444,7 @@ function createProcessFactory({
438
444
  tmuxRunner = null,
439
445
  botName = null,
440
446
  toolDispatcher = null,
447
+ toolDispatcherCapabilities = null,
441
448
  channelsClaudeBin = null,
442
449
  sessionLauncher = process.env.ORCHESTRA_SESSION_LAUNCHER || null,
443
450
  displayHint = '', // orchestra: consumer surface-rendering hint
@@ -515,6 +522,13 @@ function createProcessFactory({
515
522
  const resolvedDisplayHint = typeof displayHint === 'function'
516
523
  ? displayHint(chatId, threadId, config)
517
524
  : displayHint;
525
+ // Same string-or-resolver shape as displayHint: the optional tools a
526
+ // consumer can honor may vary per chat/topic (a live preview is a
527
+ // per-chat rollout decision), and the prompt section that teaches them
528
+ // is resolved at the same moment, so the two can never disagree.
529
+ const resolvedCapabilities = typeof toolDispatcherCapabilities === 'function'
530
+ ? toolDispatcherCapabilities(chatId, threadId, config)
531
+ : toolDispatcherCapabilities;
518
532
  return new CliProcess({
519
533
  sessionKey, chatId, threadId, label,
520
534
  tmuxRunner,
@@ -522,6 +536,7 @@ function createProcessFactory({
522
536
  claudeBin: channelsClaudeBin,
523
537
  sessionLauncher,
524
538
  toolDispatcher,
539
+ toolDispatcherCapabilities: resolvedCapabilities,
525
540
  displayHint: resolvedDisplayHint,
526
541
  maxOutboundFileBytes,
527
542
  sessionPrefix, bridgeServerName, appDataDir, attachmentBase, productName, surfaceName,
@@ -31,10 +31,17 @@ const { createTmuxRunner } = require('./tmux-runner');
31
31
  * @param {object} opts
32
32
  * @param {string} opts.botName — only sweep sessions for THIS bot
33
33
  * @param {object} [opts.runner] — injected TmuxRunner (for tests)
34
+ * @param {string} [opts.socketName] — dedicated tmux server to enumerate, when
35
+ * no runner is injected. Must match the caller's own runner.
34
36
  * @param {object} [opts.logger=console]
35
- * @returns {Promise<{ swept: string[], errors: Array<{name:string, error:string}> }>}
37
+ * @returns {Promise<{ swept: string[], errors: Array<{name:string, error:string}>,
38
+ * listFailed: boolean, listError?: string }>} `listFailed` is true when the
39
+ * host could not be enumerated at all — distinct from an empty `swept`, which
40
+ * means the host was reachable and genuinely had no orphans.
36
41
  */
37
- async function sweepTmuxOrphans({ botName, runner, logger = console } = {}) {
42
+ async function sweepTmuxOrphans({
43
+ botName, runner, logger = console, socketName = null,
44
+ } = {}) {
38
45
  if (!botName) throw new TypeError('sweepTmuxOrphans: botName required');
39
46
  // SECURITY (audit M2): dashes in bot names risk prefix-match
40
47
  // collision when two bots share a prefix (e.g. `shumabit` matches
@@ -49,32 +56,43 @@ async function sweepTmuxOrphans({ botName, runner, logger = console } = {}) {
49
56
  + `prefix. Consider renaming (e.g. use _ instead).`,
50
57
  );
51
58
  }
52
- const r = runner || createTmuxRunner({ logger });
59
+ // The fallback runner must target the SAME tmux server the caller uses.
60
+ // Without forwarding socketName it would enumerate the default socket while
61
+ // the app's sessions live on a dedicated one — finding nothing and reporting a
62
+ // clean host, which is the very fail-open this function was hardened against.
63
+ const r = runner || createTmuxRunner({ logger, socketName });
53
64
  let names;
54
65
  try {
55
- names = await r.listPolygramSessions(botName);
66
+ names = await r.listPolygramSessions(botName, { strict: true });
56
67
  } catch (err) {
57
- // Most common: tmux not running. Best-effort = no-op.
58
- logger.log?.(`[orphan-sweep] list-sessions failed (${err.message}); assuming no orphans`);
59
- return { swept: [], errors: [] };
68
+ // "Could not ask" is NOT "nothing to sweep". Enumerating strictly and
69
+ // reporting the failure lets the caller decide: with a dedicated socket and
70
+ // `-N`, an unreachable server means the tmux unit never came up, and booting
71
+ // on would leave the daemon blind to sessions it is supposed to own.
72
+ logger.warn?.(`[orphan-sweep] list-sessions failed (${err.message}); cannot determine whether orphans exist`);
73
+ return { swept: [], errors: [], listFailed: true, listError: err.message };
60
74
  }
61
75
  if (names.length === 0) {
62
76
  logger.log?.(`[orphan-sweep] no orphan tmux sessions for ${botName}`);
63
- return { swept: [], errors: [] };
77
+ return { swept: [], errors: [], listFailed: false };
64
78
  }
65
79
  logger.log?.(`[orphan-sweep] killing ${names.length} orphan tmux session(s): ${names.join(', ')}`);
66
80
  const errors = [];
67
81
  const swept = [];
68
82
  for (const name of names) {
69
83
  try {
70
- await r.killSession(name);
84
+ // strict: this loop REPORTS what it reaped. Non-strict killSession
85
+ // resolves even when tmux refused, so every session would be logged as
86
+ // swept and the `errors` array below could never be populated — a stale
87
+ // session then survives and collides with the next spawn of that name.
88
+ await r.killSession(name, { strict: true });
71
89
  swept.push(name);
72
90
  } catch (err) {
73
91
  errors.push({ name, error: err.message });
74
92
  logger.warn?.(`[orphan-sweep] kill ${name} failed: ${err.message}`);
75
93
  }
76
94
  }
77
- return { swept, errors };
95
+ return { swept, errors, listFailed: false };
78
96
  }
79
97
 
80
98
  module.exports = { sweepTmuxOrphans };
@@ -84,6 +84,12 @@ const CONTROL_CHAR_RE = /[\x00-\x08\x0b-\x1f\x7f]/g;
84
84
  // SIGTERM. 10s is generous headroom over the sub-second norm.
85
85
  const TMUX_RUN_TIMEOUT_MS = 10_000;
86
86
 
87
+ // A tmux socket name becomes a bare CLI argument. execFile means this is not a
88
+ // shell-injection vector, but a value starting with '-' would be parsed by tmux
89
+ // as another server flag, and a path separator would silently select a
90
+ // different socket directory. Same reasoning as the paneWidth guard in spawn().
91
+ const SOCKET_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
92
+
87
93
  /**
88
94
  * Promise-wrapped childProcess.execFile. Returns { stdout, stderr }.
89
95
  * Rejects on non-zero exit (or timeout) with err.stdout + err.stderr
@@ -183,15 +189,37 @@ function ensureLogDir(logPath) {
183
189
  * @param {object} [opts.logger=console]
184
190
  * @param {Function} [opts.runFn] — override the underlying execFile
185
191
  * wrapper (for tests). Same signature: (cmd, args, opts?) → Promise.
192
+ * @param {string} [opts.socketName] — run against a dedicated tmux server
193
+ * (`tmux -L <name>`) instead of the shared default socket.
186
194
  */
187
195
  function createTmuxRunner({
188
196
  sessionPrefix = 'orchestra',
189
197
  logger = console,
190
198
  runFn = run,
191
199
  requireExistingServer = false,
200
+ socketName = null,
192
201
  } = {}) {
202
+ if (socketName != null && !SOCKET_NAME_RE.test(socketName)) {
203
+ throw new TypeError(
204
+ `socketName must match ${SOCKET_NAME_RE} (got ${JSON.stringify(socketName)})`,
205
+ );
206
+ }
193
207
  const runnerPrefix = sessionPrefix;
194
- const runTmux = (args, opts) => runFn('tmux', requireExistingServer ? ['-N', ...args] : args, opts);
208
+ // Server-scope flags, in tmux's required position: before the command word.
209
+ //
210
+ // `-L <name>` gives this app its own tmux server. Without it orchestra shares
211
+ // the DEFAULT socket with the operator's interactive sessions, so one
212
+ // `tmux kill-server` — from a unit's ExecStop or from a human at a prompt —
213
+ // reaches every bot, water and the admin session at once.
214
+ //
215
+ // Blast-radius control, not a privilege boundary: every server here runs under
216
+ // the same uid, so any process that knows the name can still run
217
+ // `tmux -L <name>` against it.
218
+ const serverArgs = [
219
+ ...(socketName ? ['-L', socketName] : []),
220
+ ...(requireExistingServer ? ['-N'] : []),
221
+ ];
222
+ const runTmux = (args, opts) => runFn('tmux', serverArgs.length ? [...serverArgs, ...args] : args, opts);
195
223
  async function spawn({
196
224
  name,
197
225
  cwd,
@@ -387,21 +415,48 @@ function createTmuxRunner({
387
415
  }
388
416
  }
389
417
 
390
- async function killSession(name) {
391
- await runTmux(['kill-session', '-t', name]).catch(() => {});
418
+ /**
419
+ * Kill a tmux session. Best-effort by default (teardown paths race normal
420
+ * exits and must not throw). Pass `{ strict: true }` when the caller reports
421
+ * success or failure to someone: silently swallowing here makes a stale
422
+ * session look reaped, and the next spawn then collides with the name.
423
+ */
424
+ async function killSession(name, { strict = false } = {}) {
425
+ try {
426
+ await runTmux(['kill-session', '-t', name]);
427
+ } catch (err) {
428
+ if (strict) {
429
+ throw Object.assign(new Error(`tmux kill-session failed: ${err.message}`), {
430
+ code: 'TMUX_KILL_FAILED',
431
+ cause: err,
432
+ });
433
+ }
434
+ }
392
435
  }
393
436
 
394
437
  /**
395
438
  * List polygram-managed tmux sessions on the host. Optional `botName`
396
439
  * narrows the prefix; without it returns all `water-*` sessions.
440
+ *
441
+ * Default is best-effort: an unreachable tmux server reads as an empty host.
442
+ * Pass `{ strict: true }` when the caller must distinguish "no sessions" from
443
+ * "could not ask" — with a dedicated socket and `-N` (never auto-start), an
444
+ * unreachable server means the tmux unit failed to come up, and treating that
445
+ * as "nothing here" hides it.
397
446
  */
398
- async function listPolygramSessions(botName = null) {
447
+ async function listPolygramSessions(botName = null, { strict = false } = {}) {
399
448
  try {
400
449
  const { stdout } = await runTmux(['list-sessions', '-F', '#{session_name}']);
401
450
  const all = stdout.trim().split('\n').filter(Boolean);
402
451
  const prefix = botName ? `${runnerPrefix}-${String(botName).replace(/[^\w-]/g, '_')}-` : `${runnerPrefix}-`;
403
452
  return all.filter((n) => n.startsWith(prefix));
404
- } catch {
453
+ } catch (err) {
454
+ if (strict) {
455
+ throw Object.assign(new Error(`tmux list-sessions failed: ${err.message}`), {
456
+ code: 'TMUX_LIST_FAILED',
457
+ cause: err,
458
+ });
459
+ }
405
460
  return [];
406
461
  }
407
462
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumkov/orchestra",
3
- "version": "0.7.4",
3
+ "version": "0.9.0",
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",