@shumkov/orchestra 0.7.3 → 0.8.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.
@@ -195,8 +195,30 @@ direct-binary run; it does not clear the broader hosted-tool enforcement gate.
195
195
  Live pinned-runtime characterization 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
- extends: null}`. The generated stable response schemas do not declare that
199
- field, and no matching `thread/settings/updated` notification was observed.
198
+ extends: null}`. Both attachment responses also return exactly one concrete
199
+ `runtimeWorkspaceRoots` entry equal to the owned cwd. Orchestra exposes that
200
+ entry only as `{count: 1, sha256: [sha256(ownedCwd)]}`.
201
+
202
+ Fresh, resume, and `thread/settings/updated` all return the same legacy
203
+ compatibility envelope:
204
+
205
+ ```json
206
+ {
207
+ "type": "workspaceWrite",
208
+ "networkAccess": false,
209
+ "excludeSlashTmp": true,
210
+ "excludeTmpdirEnvVar": true,
211
+ "writableRootCount": 0,
212
+ "writableRootSha256": []
213
+ }
214
+ ```
215
+
216
+ The zero count means there are no additional legacy writable roots; the
217
+ concrete named-profile workspace grant is attested separately by
218
+ `runtimeWorkspaceRoots`. Settings notifications do not include
219
+ `runtimeWorkspaceRoots`, so Orchestra compares them against a distinct static
220
+ view while retaining the admitted attachment as the concrete-root proof. The
221
+ generated stable response schemas do not declare `activePermissionProfile`.
200
222
 
201
223
  The named-profile subgate accepts this only as a pinned fresh-plus-resume pair
202
224
  and reports:
@@ -205,8 +227,10 @@ and reports:
205
227
  - `provenanceSchemaDeclared: false`;
206
228
  - `provenanceFragile: true`.
207
229
 
208
- A missing, different, or one-sided value remains a stop. Every Codex pin change
209
- must regenerate the schema and rerun this live characterization.
230
+ A missing, different, duplicated, additional, outside-workspace, or one-sided
231
+ runtime root remains a stop. Any legacy network, temp-exclusion, type, or
232
+ additional-root drift also remains a stop. Every Codex pin change must
233
+ regenerate the schema and rerun this live characterization.
210
234
 
211
235
  ## Active-turn steering capability passed; smoke setup remains fragile
212
236
 
@@ -576,6 +576,12 @@ function projectNotification(message, ownedCwd) {
576
576
  source.threadSettings,
577
577
  'thread settings',
578
578
  );
579
+ if (Object.hasOwn(settings, 'runtimeWorkspaceRoots')) {
580
+ throw new CodexAppServerError(
581
+ 'app-server thread settings unexpectedly included runtime workspace roots',
582
+ 'CODEX_PROTOCOL_ERROR',
583
+ );
584
+ }
579
585
  if (settings.cwd !== ownedCwd) {
580
586
  throw new CodexAppServerError(
581
587
  'app-server thread settings changed the owned workspace',
@@ -1040,6 +1046,15 @@ function projectSandbox(value, ownedCwd) {
1040
1046
  projected.networkAccess = sandbox.networkAccess;
1041
1047
  }
1042
1048
  if (type === 'workspaceWrite') {
1049
+ for (const key of ['excludeSlashTmp', 'excludeTmpdirEnvVar']) {
1050
+ if (sandbox[key] !== undefined && typeof sandbox[key] !== 'boolean') {
1051
+ throw new CodexAppServerError(
1052
+ 'app-server sandbox temp exclusion is malformed',
1053
+ 'CODEX_PROTOCOL_ERROR',
1054
+ );
1055
+ }
1056
+ if (sandbox[key] !== undefined) projected[key] = sandbox[key];
1057
+ }
1043
1058
  if (
1044
1059
  sandbox.writableRoots !== undefined
1045
1060
  && !Array.isArray(sandbox.writableRoots)
@@ -1077,6 +1092,40 @@ function projectSandbox(value, ownedCwd) {
1077
1092
  return projected;
1078
1093
  }
1079
1094
 
1095
+ function projectRuntimeWorkspaceRoots(value, ownedCwd) {
1096
+ if (!Array.isArray(value) || value.length > 64) {
1097
+ throw new CodexAppServerError(
1098
+ 'app-server runtime workspace roots are malformed',
1099
+ 'CODEX_PROTOCOL_ERROR',
1100
+ );
1101
+ }
1102
+ const roots = value.map((root) => (
1103
+ protocolRequiredString(root, 'runtime workspace root', MAX_TEXT_BYTES)
1104
+ ));
1105
+ if (roots.some((root) => (
1106
+ !path.isAbsolute(root)
1107
+ || path.normalize(root) !== root
1108
+ || !isWithin(ownedCwd, root)
1109
+ ))) {
1110
+ throw new CodexAppServerError(
1111
+ 'app-server runtime workspace root escaped the owned workspace',
1112
+ 'CODEX_PROTOCOL_ERROR',
1113
+ );
1114
+ }
1115
+ if (roots.length !== 1 || roots[0] !== ownedCwd) {
1116
+ throw new CodexAppServerError(
1117
+ 'app-server runtime workspace roots did not match the owned workspace',
1118
+ 'CODEX_PROTOCOL_ERROR',
1119
+ );
1120
+ }
1121
+ return {
1122
+ count: roots.length,
1123
+ sha256: roots
1124
+ .map((root) => createHash('sha256').update(root).digest('hex'))
1125
+ .sort(),
1126
+ };
1127
+ }
1128
+
1080
1129
  function projectRpcResult(method, value, ownedCwd) {
1081
1130
  const result = protocolObject(value, `${method} result`);
1082
1131
  if (method === 'initialize') {
@@ -1312,6 +1361,10 @@ function projectRpcResult(method, value, ownedCwd) {
1312
1361
  ),
1313
1362
  approvalPolicy: projectApprovalPolicy(result.approvalPolicy),
1314
1363
  approvalsReviewer: result.approvalsReviewer,
1364
+ runtimeWorkspaceRoots: projectRuntimeWorkspaceRoots(
1365
+ result.runtimeWorkspaceRoots,
1366
+ ownedCwd,
1367
+ ),
1315
1368
  sandbox: projectSandbox(result.sandbox, ownedCwd),
1316
1369
  };
1317
1370
  projected.thread = projectThread(
@@ -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) {
@@ -84,14 +84,18 @@ function dynamicSettings(source) {
84
84
  );
85
85
  }
86
86
 
87
- function staticThreadPolicy(source) {
88
- return {
87
+ function staticThreadPolicy(source, { includeRuntimeWorkspaceRoots = false } = {}) {
88
+ const policy = {
89
89
  modelProvider: source?.modelProvider,
90
90
  approvalPolicy: source?.approvalPolicy,
91
91
  approvalsReviewer: source?.approvalsReviewer,
92
92
  sandbox: source?.sandbox ?? source?.sandboxPolicy,
93
93
  permissionProfile: source?.activePermissionProfile,
94
94
  };
95
+ if (includeRuntimeWorkspaceRoots) {
96
+ policy.runtimeWorkspaceRoots = source?.runtimeWorkspaceRoots;
97
+ }
98
+ return policy;
95
99
  }
96
100
 
97
101
  function isDeepFrozen(value) {
@@ -260,6 +264,11 @@ class CodexProcess extends Process {
260
264
  );
261
265
  }
262
266
  this.expectedStaticPolicy = resolvedStaticPolicy;
267
+ const {
268
+ runtimeWorkspaceRoots: _runtimeWorkspaceRoots,
269
+ ...expectedSettingsPolicy
270
+ } = resolvedStaticPolicy;
271
+ this.expectedSettingsPolicy = Object.freeze(expectedSettingsPolicy);
263
272
  this.expectedPermissionProfileId = nonEmptyString(
264
273
  resolvedStaticPolicy.permissionProfile?.id,
265
274
  'expectedStaticPolicy.permissionProfile.id',
@@ -578,12 +587,26 @@ class CodexProcess extends Process {
578
587
  'CODEX_PROTOCOL_ERROR',
579
588
  );
580
589
  }
581
- this._validateAndObserveThreadPolicy(result, { attaching: true });
590
+ this._validateAndObserveThreadPolicy(result, {
591
+ attaching: true,
592
+ attachmentPolicy: true,
593
+ });
582
594
  }
583
595
 
584
- _validateAndObserveThreadPolicy(source, { attaching = false } = {}) {
585
- const actualStaticPolicy = staticThreadPolicy(source);
586
- if (!isDeepStrictEqual(actualStaticPolicy, this.expectedStaticPolicy)) {
596
+ _validateAndObserveThreadPolicy(
597
+ source,
598
+ { attaching = false, attachmentPolicy = false } = {},
599
+ ) {
600
+ const actualStaticPolicy = staticThreadPolicy(source, {
601
+ includeRuntimeWorkspaceRoots: (
602
+ attachmentPolicy
603
+ && Object.hasOwn(this.expectedStaticPolicy, 'runtimeWorkspaceRoots')
604
+ ),
605
+ });
606
+ const expectedStaticPolicy = attachmentPolicy
607
+ ? this.expectedStaticPolicy
608
+ : this.expectedSettingsPolicy;
609
+ if (!isDeepStrictEqual(actualStaticPolicy, expectedStaticPolicy)) {
587
610
  throw processError(
588
611
  'Codex thread did not attest the exact trusted static policy',
589
612
  'CODEX_THREAD_POLICY_MISMATCH',
@@ -843,6 +866,20 @@ class CodexProcess extends Process {
843
866
  error.deliveryState = 'not-sent';
844
867
  throw error;
845
868
  }
869
+ const assertTurnStartAdmission = () => {
870
+ if (
871
+ pending.startCancellationRequested
872
+ || this.settingsAdmissionClosed
873
+ || this.state === 'Quiescing'
874
+ ) {
875
+ if (pending.turnId) return;
876
+ throw processError(
877
+ 'Codex turn start was cancelled before dispatch',
878
+ 'CODEX_RPC_NOT_SENT',
879
+ );
880
+ }
881
+ this._assertLifecycle(lifecycle);
882
+ };
846
883
  const result = await this._mutation('turn/start', params, {
847
884
  source: pending.context?.sourceMsgId ?? null,
848
885
  clientUserMessageId: pending.clientUserMessageId,
@@ -854,19 +891,8 @@ class CodexProcess extends Process {
854
891
  pending.startResponseOutcome = outcome;
855
892
  }
856
893
  },
857
- assertCanWrite: () => {
858
- if (
859
- pending.startCancellationRequested
860
- || this.settingsAdmissionClosed
861
- || this.state === 'Quiescing'
862
- ) {
863
- if (pending.turnId) return;
864
- throw processError(
865
- 'Codex turn start was cancelled before dispatch',
866
- 'CODEX_RPC_NOT_SENT',
867
- );
868
- }
869
- },
894
+ assertCanWrite: assertTurnStartAdmission,
895
+ assertCanCommit: assertTurnStartAdmission,
870
896
  });
871
897
  this._assertLifecycle(lifecycle);
872
898
  const turnId = result?.turn?.id;
@@ -1674,6 +1700,7 @@ class CodexProcess extends Process {
1674
1700
  this.stateChangingWriteCommitted = true;
1675
1701
  detail.onDeliveryState?.('write-attempted');
1676
1702
  },
1703
+ detail.assertCanCommit,
1677
1704
  );
1678
1705
  },
1679
1706
  onResponseObserved: async (transport) => {
@@ -1687,7 +1714,13 @@ class CodexProcess extends Process {
1687
1714
  });
1688
1715
  }
1689
1716
 
1690
- async _transportCheckpoint(kind, detail, transport, onCommitted = null) {
1717
+ async _transportCheckpoint(
1718
+ kind,
1719
+ detail,
1720
+ transport,
1721
+ onCommitted = null,
1722
+ assertCanCommit = null,
1723
+ ) {
1691
1724
  transport.assertActive?.();
1692
1725
  const payload = this._checkpointPayload(kind, {
1693
1726
  ...detail,
@@ -1704,9 +1737,16 @@ class CodexProcess extends Process {
1704
1737
  },
1705
1738
  };
1706
1739
  let writeCommitted = false;
1740
+ let commitRejection = null;
1707
1741
  const markWriteCommitted = () => {
1708
1742
  transport.assertActive?.();
1709
1743
  if (writeCommitted) return;
1744
+ try {
1745
+ assertCanCommit?.();
1746
+ } catch (error) {
1747
+ commitRejection = error;
1748
+ throw error;
1749
+ }
1710
1750
  transport.markWriteCommitted?.();
1711
1751
  writeCommitted = true;
1712
1752
  onCommitted?.();
@@ -1720,9 +1760,8 @@ class CodexProcess extends Process {
1720
1760
  Object.defineProperties(payload, properties);
1721
1761
  try {
1722
1762
  await this.checkpointSink(payload);
1723
- if (kind === 'request-write-attempted') markWriteCommitted();
1724
- transport.assertActive?.();
1725
1763
  } catch (error) {
1764
+ if (error === commitRejection) throw error;
1726
1765
  const durability = processError(
1727
1766
  `Codex checkpoint ${kind} failed`,
1728
1767
  'CODEX_DURABILITY_FAILED',
@@ -1745,6 +1784,10 @@ class CodexProcess extends Process {
1745
1784
  }
1746
1785
  throw durability;
1747
1786
  }
1787
+ if (kind === 'request-write-attempted') {
1788
+ markWriteCommitted();
1789
+ }
1790
+ transport.assertActive?.();
1748
1791
  }
1749
1792
 
1750
1793
  async _checkpoint(kind, detail = {}, fence = null) {
@@ -2343,6 +2386,7 @@ class CodexProcess extends Process {
2343
2386
  excludedPending = null,
2344
2387
  fence = null,
2345
2388
  ) {
2389
+ this._closeSettingsAdmission();
2346
2390
  if (this.state === 'ContainmentFailed') return;
2347
2391
  this._clearBackgroundWatchdog();
2348
2392
  const ownedTurnId = this.activeTurnId
@@ -146,13 +146,19 @@ function expectedStaticThreadPolicy(profile) {
146
146
  modelProvider: 'openai',
147
147
  approvalPolicy: 'never',
148
148
  approvalsReviewer: 'user',
149
+ runtimeWorkspaceRoots: {
150
+ count: 1,
151
+ sha256: [
152
+ createHash('sha256').update(profile.cwd).digest('hex'),
153
+ ],
154
+ },
149
155
  sandbox: {
150
156
  type: 'workspaceWrite',
151
157
  networkAccess: false,
152
- writableRootCount: 1,
153
- writableRootSha256: [
154
- createHash('sha256').update(profile.cwd).digest('hex'),
155
- ],
158
+ excludeSlashTmp: true,
159
+ excludeTmpdirEnvVar: true,
160
+ writableRootCount: 0,
161
+ writableRootSha256: [],
156
162
  },
157
163
  permissionProfile: {
158
164
  id: profile.permissionProfileId,
@@ -396,6 +402,12 @@ function _maybeWarnR12Migration({ rawPm, canonical, chatId, threadId, chatCfg, t
396
402
  * async ({sessionKey, chatId, threadId, toolName, text, files}) => {ok, error?}.
397
403
  * Called when Claude's reply (or react/edit_message) tool fires inside a
398
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.
399
411
  * @param {string} [opts.channelsClaudeBin] — absolute path to pinned claude binary;
400
412
  * required when ANY chat routes to 'cli'. (Name kept for back-compat with
401
413
  * existing wiring; can be renamed to `claudeBin` in a future refactor.)
@@ -432,6 +444,7 @@ function createProcessFactory({
432
444
  tmuxRunner = null,
433
445
  botName = null,
434
446
  toolDispatcher = null,
447
+ toolDispatcherCapabilities = null,
435
448
  channelsClaudeBin = null,
436
449
  sessionLauncher = process.env.ORCHESTRA_SESSION_LAUNCHER || null,
437
450
  displayHint = '', // orchestra: consumer surface-rendering hint
@@ -509,6 +522,13 @@ function createProcessFactory({
509
522
  const resolvedDisplayHint = typeof displayHint === 'function'
510
523
  ? displayHint(chatId, threadId, config)
511
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;
512
532
  return new CliProcess({
513
533
  sessionKey, chatId, threadId, label,
514
534
  tmuxRunner,
@@ -516,6 +536,7 @@ function createProcessFactory({
516
536
  claudeBin: channelsClaudeBin,
517
537
  sessionLauncher,
518
538
  toolDispatcher,
539
+ toolDispatcherCapabilities: resolvedCapabilities,
519
540
  displayHint: resolvedDisplayHint,
520
541
  maxOutboundFileBytes,
521
542
  sessionPrefix, bridgeServerName, appDataDir, attachmentBase, productName, surfaceName,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumkov/orchestra",
3
- "version": "0.7.3",
3
+ "version": "0.8.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",