flowviant 0.125.13 → 0.125.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -254,7 +254,8 @@ OpenAI, GitHub, AWS, Slack, OAuth token fields, PEM private keys) with
254
254
  hostname, a lowercase hex string) is left as it is, and a secret in none of
255
255
  those is relayed as printed. What your CLI writes through Flowviant's own tools
256
256
  (such as a tab's progress messages and purpose line, or the cards a New task
257
- chat stages) goes from the CLI to Flowviant, not through the daemon, as written.
257
+ chat stages) is sent to Flowviant as written, either directly or through the
258
+ daemon's root-only capture credential relay.
258
259
  The full list, and the exact test for what looks generated, are in
259
260
  [SECURITY.md](./SECURITY.md#what-is-redacted).
260
261
 
package/bin/cli.mjs CHANGED
@@ -80,6 +80,11 @@
80
80
  // answered here before anything else loads: no config, no update check, no
81
81
  // output but the hook's. An unknown hook exits 2, which Claude Code reads as a
82
82
  // refusal — the read guard's own rule for a hook that cannot judge.
83
+ if (process.argv[2] === '__capture-mcp') {
84
+ await (await import('./lib/captureAuthority.mjs')).captureMcpMain();
85
+ process.exit(process.exitCode ?? 0);
86
+ }
87
+
83
88
  if (process.argv[2] === '__orchestrator-mcp') {
84
89
  await (await import('./lib/orchestratorClient.mjs')).orchestratorMcpMain();
85
90
  process.exit(process.exitCode ?? 0);
@@ -0,0 +1,82 @@
1
+ /** A capture credential never enters a delegated CLI or its children. The
2
+ * daemon relays only calls authorized by the native ROOT's trusted hook.
3
+ * Tickets bind the tool and complete arguments, and replay returns the same
4
+ * promise/result rather than performing a second staging write. */
5
+ import { createHash, randomUUID } from 'node:crypto';
6
+ import { fleetHeaders } from './fleetPost.mjs';
7
+ import { callOrchestrator } from './orchestratorClient.mjs';
8
+ import { mcpRequest, serveMcpStdio } from './mcpStdio.mjs';
9
+ import { captureToolName } from './nativeAgentTools.mjs';
10
+ import { DAEMON_INSTANCE } from './config.mjs';
11
+
12
+ export const CAPTURE_CALL_TICKET = '_flowviantRootCall';
13
+ const CAP = 256;
14
+ const cleanArgs = args => Object.fromEntries(Object.entries(args ?? {}).filter(([key]) => key !== CAPTURE_CALL_TICKET));
15
+ const canonical = value => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object'
16
+ ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value;
17
+ const fingerprint = (name, args) => createHash('sha256').update(JSON.stringify([name, canonical(cleanArgs(args))])).digest('hex');
18
+
19
+ export function createCaptureAuthority({ url, token, turnId, attempt, sessionId, signal, request = fetch, clock = Date.now }) {
20
+ const tickets = new Map(), calls = new Map();
21
+ const lifetime = new AbortController();
22
+ let closed = false, discovery = null;
23
+ const active = () => !closed && !signal?.aborted;
24
+ const remote = async (method, params, callId) => {
25
+ if (!active()) throw new Error('This capture turn stopped.');
26
+ const response = await request(url, { method: 'POST',
27
+ headers: { ...fleetHeaders({ token }), 'X-Flowviant-Capture-Turn': turnId,
28
+ 'X-Flowviant-Capture-Attempt': String(attempt), 'X-Flowviant-Capture-Instance': DAEMON_INSTANCE,
29
+ ...(callId ? { 'X-Flowviant-Capture-Call': callId } : {}) },
30
+ body: JSON.stringify(mcpRequest(method, params, randomUUID())),
31
+ signal: AbortSignal.any([lifetime.signal, ...(signal ? [signal] : []), AbortSignal.timeout(30_000)]),
32
+ });
33
+ const body = await response.json();
34
+ if (!response.ok || body.error || !body.result) throw new Error(body.error?.message ?? 'The capture tool did not answer.');
35
+ if (!active()) throw new Error('This capture turn stopped.');
36
+ return body.result;
37
+ };
38
+ return {
39
+ async describe() {
40
+ discovery ??= (async () => {
41
+ const init = await remote('initialize', { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'flowviant-capture', version: '1' } });
42
+ const list = await remote('list', {});
43
+ if (!Array.isArray(list.tools) || list.tools.length > 64) throw new Error('The capture tool list is unavailable.');
44
+ return { ...init, tools: list.tools.map(tool => ({ ...tool, inputSchema: { ...tool.inputSchema,
45
+ properties: { ...tool.inputSchema?.properties, [CAPTURE_CALL_TICKET]: { type: 'string', description: 'Internal authorization supplied by the native root hook.' } },
46
+ } })) };
47
+ })();
48
+ return discovery;
49
+ },
50
+ authorize(event) {
51
+ if (!active()) return { deny: 'This capture turn stopped.' };
52
+ const name = captureToolName(event.tool_name), id = event.tool_use_id;
53
+ if (!name || typeof id !== 'string' || !id || id.length > 160) return { deny: 'The capture call has no native identity.' };
54
+ const args = cleanArgs(event.tool_input);
55
+ if (args.sessionId !== sessionId) return { deny: 'Capture tools belong to this conversation only.' };
56
+ const hash = fingerprint(name, args), prior = calls.get(id);
57
+ if (prior && prior.hash !== hash) return { deny: 'This native capture call already authorized different arguments.' };
58
+ if (!prior && calls.size >= CAP) return { deny: 'This capture turn has reached its tool-call bound. Finish this reply and continue in the next message.' };
59
+ const ticket = prior?.ticket ?? randomUUID();
60
+ const grant = prior ?? { ticket, hash, name, args, callId: id, at: clock(), response: null };
61
+ calls.set(id, grant); tickets.set(ticket, grant);
62
+ return { updatedInput: { ...args, [CAPTURE_CALL_TICKET]: ticket } };
63
+ },
64
+ async call({ name, args = {} }) {
65
+ if (!active()) throw new Error('This capture turn stopped.');
66
+ const grant = tickets.get(args[CAPTURE_CALL_TICKET]);
67
+ if (!grant || grant.hash !== fingerprint(name, args) || clock() - grant.at > 15 * 60_000)
68
+ throw new Error('Only the capture coordinator may call these tools. No native root authorization was supplied.');
69
+ grant.response ??= remote('call', { name, arguments: grant.args }, grant.callId);
70
+ return grant.response;
71
+ },
72
+ close() { closed = true; lifetime.abort(); tickets.clear(); calls.clear(); },
73
+ };
74
+ }
75
+
76
+ /** The credential-free stdio client. It knows only this attempt's loopback
77
+ * capability. The shared protocol loop preserves raw MCP errors and replies. */
78
+ export async function captureMcpMain() {
79
+ const description = await callOrchestrator('capture_describe', {}, 65_000);
80
+ return serveMcpStdio({ serverInfo: description.serverInfo, tools: description.tools, instructions: description.instructions,
81
+ rawResult: true, call: (name, args) => callOrchestrator('capture_call', { name, args }, 35_000) });
82
+ }
@@ -499,6 +499,15 @@ export function withNativeChildren(perm) {
499
499
  return out;
500
500
  }
501
501
 
502
+ /** A consult keeps exactly its readers and guard. The only additional MCP
503
+ * permission is the daemon's local coordination capability, never flowviant's
504
+ * board/staging tools or a project/personal server. Capture keeps its already
505
+ * allowed flowviant tools behind the daemon's root-only credential relay. */
506
+ export function withReadOnlyCoordination(perm) {
507
+ return withNativeChildren(perm).flatMap(arg => arg === '--allowedTools'
508
+ ? [arg, 'SendMessage', 'TaskStop', 'ToolSearch', 'mcp__card_orchestrator'] : [arg]);
509
+ }
510
+
502
511
  /**
503
512
  * CLAUDE'S PERMISSION LIST FOR A TURN PROFILE, by the profile's name — one
504
513
  * entry per profile Claude declares, plus plan-mode (runtimeClaude.mjs
@@ -31,7 +31,7 @@ export async function main() {
31
31
  // The names are the controller's own list (nativeAgentTools.mjs).
32
32
  // A research card's children only read (FLOWVIANT_ORCHESTRATOR_CHILDREN,
33
33
  // orchestrator.mjs): a child's write is refused here too.
34
- if (gatedSpawnEvent(event, process.env.FLOWVIANT_ORCHESTRATOR_CHILDREN)) { process.exitCode = 2; return; }
34
+ if (gatedSpawnEvent(event, process.env.FLOWVIANT_ORCHESTRATOR_CHILDREN, process.env.FLOWVIANT_ORCHESTRATOR_READ_ONLY === '1')) { process.exitCode = 2; return; }
35
35
  try { await answer({}); } catch { /* the CLI already stopped reading */ }
36
36
  }
37
37
  }
@@ -15,18 +15,26 @@
15
15
  */
16
16
  import { createInterface } from 'node:readline';
17
17
 
18
+ /** The same vocabulary for daemon-side MCP relays, without another protocol
19
+ * envelope or tools/list spelling in each client. */
20
+ export const mcpRequest = (action, params, id) => ({ jsonrpc: '2.0', id,
21
+ method: { initialize: 'initialize', list: 'tools/list', call: 'tools/call' }[action], params });
22
+
18
23
  /** `call(name, args)` answers a listed tool; what it resolves is the text result, as JSON. */
19
- export async function serveMcpStdio({ serverInfo, tools, call, input = process.stdin, write = s => process.stdout.write(s) }) {
24
+ export async function serveMcpStdio({ serverInfo, tools, call, instructions, rawResult = false, input = process.stdin, write = s => process.stdout.write(s) }) {
20
25
  for await (const line of createInterface({ input })) {
21
26
  let req;
22
27
  try {
23
28
  req = JSON.parse(line); if (req.id === undefined) continue;
24
29
  let result;
25
- if (req.method === 'initialize') result = { protocolVersion: req.params?.protocolVersion ?? '2024-11-05', capabilities: { tools: {} }, serverInfo };
30
+ if (req.method === 'initialize') result = { protocolVersion: req.params?.protocolVersion ?? '2024-11-05', capabilities: { tools: {} }, serverInfo, ...(instructions ? { instructions } : {}) };
26
31
  else if (req.method === 'ping') result = {};
27
32
  else if (req.method === 'tools/list') result = { tools };
28
33
  else if (req.method === 'tools/call' && tools.some(t => t.name === req.params?.name)) {
29
- try { result = { content: [{ type: 'text', text: JSON.stringify(await call(req.params.name, req.params.arguments ?? {})) }] }; }
34
+ try {
35
+ const answer = await call(req.params.name, req.params.arguments ?? {});
36
+ result = rawResult ? answer : { content: [{ type: 'text', text: JSON.stringify(answer) }] };
37
+ }
30
38
  catch (error) { result = { isError: true, content: [{ type: 'text', text: error.message }] }; }
31
39
  } else { write(`${JSON.stringify({ jsonrpc: '2.0', id: req.id, error: { code: -32601, message: 'Unknown method' } })}\n`); continue; }
32
40
  write(`${JSON.stringify({ jsonrpc: '2.0', id: req.id, result })}\n`);
@@ -74,14 +74,17 @@ export const isShellTool = name => nativeName(name) === 'Bash';
74
74
  export const isClaudeFollowupTool = name => NATIVE_AGENT_TOOLS.claude.followup.includes(nativeName(name));
75
75
  // The controller reads only Claude's stop: TaskStop names its child as task_id.
76
76
  export const isClaudeStopTool = name => NATIVE_AGENT_TOOLS.claude.stop.includes(nativeName(name));
77
+ /** Both runtime hook spellings for the capture server. */
78
+ export const captureToolName = name => String(name ?? '').match(/^(?:mcp__flowviant__|mcp[./]flowviant[./]|flowviant[./])([a-z_]+)$/)?.[1] ?? null;
77
79
 
78
80
  /** What the hook refuses while the controller is unreachable: every spawn and
79
81
  * follow-up the controller gates, and on a run whose children only read
80
82
  * (`children` 'read', a research card) a child's write or shell, which only
81
83
  * the controller can fence read-only. */
82
84
  export const GATED_TOOLS = Object.freeze([...SPAWN, ...FOLLOWUP]);
83
- export const gatedSpawnEvent = (event, children = 'edit') => event?.hook_event_name === 'PreToolUse' &&
85
+ export const gatedSpawnEvent = (event, children = 'edit', readOnlyRun = false) => event?.hook_event_name === 'PreToolUse' &&
84
86
  (GATED_TOOLS.includes(nativeName(event.tool_name)) ||
87
+ (readOnlyRun && (isChildWriteTool(event.tool_name) || Boolean(captureToolName(event.tool_name)) || /^(?:mcp__|mcp[./])/.test(String(event.tool_name)))) ||
85
88
  (children === 'read' && Boolean(event.agent_id) && (isChildWriteTool(event.tool_name) || isShellTool(event.tool_name))));
86
89
 
87
90
  /** Claude's PostToolUse and PostToolUseFailure matcher (orchestratorHooks.mjs):
@@ -11,7 +11,7 @@ import { scrub, learnExtraSecrets, forgetExtraSecrets } from './uplinkScrub.mjs'
11
11
  import { OrchestratorInputTooLarge, readOrchestratorInput } from './orchestratorInput.mjs';
12
12
  import { SAFE_POINT_AFTER_EDIT as AFTER_EDIT } from './orchestratorProtocol.mjs';
13
13
  import { MACHINE_MESSAGE_ROUTE_STATES, MESSAGE_ROUTE_FIELD_MAX, OPEN_MESSAGE_ROUTE_STATES, ORCHESTRATOR_SERVER } from './orchestratorProtocol.mjs';
14
- import { isChildWriteTool, isClaudeStopTool, isDiscoveryTool, isFollowupTool, isPersonQuestionTool, isShellTool, isSpawnTool } from './nativeAgentTools.mjs';
14
+ import { captureToolName, isChildWriteTool, isClaudeStopTool, isDiscoveryTool, isFollowupTool, isPersonQuestionTool, isShellTool, isSpawnTool } from './nativeAgentTools.mjs';
15
15
  import { childBrain, childChoice, followupTarget, readOnlyShell, readSpawn, spawnReceipt, withChildContract } from './orchestratorNative.mjs';
16
16
  import { SETTLED_SUBAGENT_STATUSES, SUBAGENT_CAP, SUBAGENT_FIELD_CAPS } from './subagentBounds.mjs';
17
17
 
@@ -35,18 +35,23 @@ const text = (s, n) => scrubNativeText(s, n, scrub);
35
35
  * on Codex, only for a model in `catalog`, the measured spawnable models.
36
36
  */
37
37
  export async function createOrchestrator({ turnId, runtime, trace, admit, request = fleetRequest, notify = () => false, taken = () => {},
38
- interval = 500, hold = 60_000, clock = Date.now, scrubText = text, children = {} } = {}) {
39
- const access = children.access === 'read' ? 'read' : 'edit',
38
+ interval = 500, hold = 60_000, clock = Date.now, scrubText = text, children = {}, readOnlyRun = null, signal, rootTools = null } = {}) {
39
+ // Consults belong to a held attempt, never to a card turn. This capability
40
+ // is entirely local; it cannot report routes or borrow an agent principal.
41
+ if (readOnlyRun && (!['plan', 'capture'].includes(readOnlyRun.scope) || !filled(readOnlyRun.id) ||
42
+ !Number.isSafeInteger(readOnlyRun.attempt) || readOnlyRun.attempt < 0)) throw new Error('A read-only run needs its held attempt identity.');
43
+ if (rootTools && readOnlyRun?.scope !== 'capture') throw new Error('Only a capture coordinator may authorize capture tools.');
44
+ const access = (readOnlyRun || children.access === 'read') ? 'read' : 'edit',
40
45
  card = { model: children.model ?? null, effort: children.effort ?? null, catalog: Array.isArray(children.catalog) ? children.catalog : [] };
41
46
  // A Codex research child's shell runs in a read-only bubblewrap view
42
47
  // (orchestratorNative.mjs `readOnlyShell`); without one it is refused.
43
48
  // Claude's research shell is the posture's guarded readers already.
44
- const bwrap = runtime === 'codex' && access === 'read'
49
+ const bwrap = runtime === 'codex' && access === 'read' && !readOnlyRun
45
50
  ? (children.bwrap !== undefined ? children.bwrap : ['/usr/bin/bwrap', '/bin/bwrap'].find(path => existsSync(path)) ?? null) : null;
46
51
  if (typeof admit !== 'function' || typeof admit.reserve !== 'function') throw new Error('This run has no project admission pool.');
47
52
  // Minted before the server exists, so the scrubber knows it from the start.
48
53
  const capability = mintHeldCapability();
49
- const secretKey = `orchestrator:${turnId}:${capability.slice(0, 8)}`;
54
+ const secretKey = `orchestrator:${readOnlyRun ? `${readOnlyRun.scope}:${readOnlyRun.id}:${readOnlyRun.attempt}` : turnId}:${capability.slice(0, 8)}`;
50
55
  learnExtraSecrets(secretKey, [{ name: 'FLOWVIANT_ORCHESTRATOR_CAPABILITY', value: capability }]);
51
56
  const records = new Map(), aliases = new Map(), calls = new Map(), notes = new Map(), questions = new Map();
52
57
  // A person's notes (Codex) and the daemon's wakes queue apart: a burst of
@@ -54,7 +59,8 @@ export async function createOrchestrator({ turnId, runtime, trace, admit, reques
54
59
  const inbox = new Map(), wakes = new Map();
55
60
  const pending = new Map(), steps = new Map();
56
61
  let closed = false, polling = false, rootSession = null, offerAt = 0;
57
- const identity = { scope: 'agent', turnId, instance: DAEMON_INSTANCE };
62
+ const identity = readOnlyRun ? { ...readOnlyRun, instance: DAEMON_INSTANCE } : { scope: 'agent', turnId, instance: DAEMON_INSTANCE };
63
+ const ended = () => closed || signal?.aborted;
58
64
  const resolve = id => aliases.get(id) ?? id;
59
65
  // A re-held note keeps its native id; resolve it when matched, not when held.
60
66
  const target = note => note.agentId ? resolve(note.agentId) : undefined;
@@ -78,6 +84,7 @@ export async function createOrchestrator({ turnId, runtime, trace, admit, reques
78
84
  };
79
85
  const field = (key, value, cap) => { const v = filled(value) ? scrubText(value, cap) : ''; return v.trim() ? { [key]: v } : {}; };
80
86
  const route = async args => {
87
+ if (readOnlyRun) throw new Error('Read-only coordination has no card routing or board-write capability.');
81
88
  const note = notes.get(args.messageId);
82
89
  if (!note) throw new Error('That note is not held by this run.');
83
90
  if (!MACHINE_MESSAGE_ROUTE_STATES.includes(args.state)) throw new Error('Choose queued, handed or taken.');
@@ -148,9 +155,11 @@ export async function createOrchestrator({ turnId, runtime, trace, admit, reques
148
155
  // stream, and the parent is asked to say why in its own update.
149
156
  const choice = childChoice(event, spawn, card);
150
157
  if (choice) trace.prose('note', `Runs on ${choice}.`, id);
151
- const childContract = `\n\nCard orchestrator agent record id: ${id}. FIRST call card_orchestrator.register_agent with agentId=${id} before doing work (tool discovery is allowed). Share this worktree and preserve others’ edits. Ask questions through card_orchestrator.agent_question with agentId=${id}; read its answer before proceeding. Only your orchestrator escalates person-only decisions. When you are done, end with your work or findings as your final message: that is how they reach your orchestrator, which owns the card’s final commit and JSON. agent_question is only for a question you cannot settle yourself, never for handing back results.`;
158
+ const childContract = readOnlyRun
159
+ ? `\n\nRead-only investigation agent record id: ${id}. FIRST call card_orchestrator.register_agent with agentId=${id} before work (tool discovery is allowed). Share this checkout and its repository/knowledge read boundary. Write no file, edit nothing, commit nothing, start no work and call no board or staging tool. Return findings, source paths and uncertainties in your final message to the coordinator. Ask questions only through card_orchestrator.agent_question with agentId=${id}, and read its answer before proceeding. ${readOnlyRun.scope === 'capture' ? 'Call no flowviant tool, including streaming. Only the coordinator dedupes and authors staged outcomes and asks the person through the existing single-question flowviant-ask fence.' : 'Only the coordinator reconciles the complete workload and returns the proposal.'}`
160
+ : `\n\nCard orchestrator agent record id: ${id}. FIRST call card_orchestrator.register_agent with agentId=${id} before doing work (tool discovery is allowed). Share this worktree and preserve others’ edits. Ask questions through card_orchestrator.agent_question with agentId=${id}; read its answer before proceeding. Only your orchestrator escalates person-only decisions. When you are done, end with your work or findings as your final message: that is how they reach your orchestrator, which owns the card’s final commit and JSON. agent_question is only for a question you cannot settle yourself, never for handing back results.`;
152
161
  return { context: `Agent record id: ${id}. Use it with card_orchestrator for routing and questions.${spawn.relocated ? ' Its isolation and cwd were removed: children share this card’s worktree on this machine.' : ''}${choice ? ` This child runs on ${choice}: name that choice and why in your next update.` : ''}`,
153
- updatedInput: withChildContract(event, spawn, childContract + (access === 'read' ? READ_ONLY_CHILD : ''), chosen.brain) };
162
+ updatedInput: withChildContract(event, spawn, childContract + (access === 'read' && !readOnlyRun ? READ_ONLY_CHILD : ''), chosen.brain) };
154
163
  }
155
164
  // Native readings never revive a settled record or start a waiting spawn
156
165
  // or follow-up (Codex records a refused call's start anyway); only an
@@ -214,6 +223,7 @@ export async function createOrchestrator({ turnId, runtime, trace, admit, reques
214
223
  if (native === null) return claude ? null : { deny: 'Name the native agent to resume.' };
215
224
  const id = named(native);
216
225
  if (!records.has(id)) {
226
+ if (readOnlyRun) return { deny: 'That child does not belong to this read-only attempt. Start a new investigation here.' };
217
227
  // SendMessage also reaches "main" and teammates: only a known child is a follow-up.
218
228
  if (claude) return null;
219
229
  if (records.size >= SUBAGENT_CAP) return { deny: 'Continue the work in this run’s orchestrator.' };
@@ -271,22 +281,30 @@ export async function createOrchestrator({ turnId, runtime, trace, admit, reques
271
281
  }
272
282
  if (child && !records.has(resolve(child)) && !isDiscoveryTool(ev.tool_name))
273
283
  return { deny: 'Before working, call card_orchestrator.register_agent with the agent record id in your prompt. Tool discovery is allowed.' };
274
- if (child && access === 'read' && isChildWriteTool(ev.tool_name)) return { deny: READ_ONLY_REFUSAL };
284
+ if ((child && access === 'read' || readOnlyRun) && isChildWriteTool(ev.tool_name)) return { deny: readOnlyRun ? 'This attempt only reads: no file writes.' : READ_ONLY_REFUSAL };
285
+ if (rootTools && captureToolName(ev.tool_name)) {
286
+ if (child || !rootSession || ev.session_id !== rootSession) return { deny: 'Only the top-level capture coordinator may call capture tools. Return findings to it.' };
287
+ return rootTools.authorize(ev);
288
+ }
289
+ if (readOnlyRun && /^(?:mcp__|mcp[./])/.test(String(ev.tool_name)) && !String(ev.tool_name).includes(ORCHESTRATOR_SERVER))
290
+ return { deny: 'This read-only attempt has only internal coordination tools; no board, staging or external MCP capability.' };
275
291
  if (isSpawnTool(ev.tool_name)) return preSpawn(ev);
276
292
  if (isFollowupTool(ev.tool_name)) { const resumed = preResume(ev); if (resumed) return resumed; }
277
293
  const point = checkpoint(ev); if (point.deny) return point;
278
- if (child && access === 'read' && runtime === 'codex' && isShellTool(ev.tool_name)) {
294
+ if (child && access === 'read' && !readOnlyRun && runtime === 'codex' && isShellTool(ev.tool_name)) {
279
295
  const fenced = readOnlyShell(ev, bwrap);
280
296
  return fenced ? { updatedInput: fenced } : { deny: `${READ_ONLY_REFUSAL} ${bwrap ? 'Its shell could not be fenced read-only: give the command as text.' : 'This machine has no bubblewrap to keep a child’s shell read-only, so a child here searches the web; the orchestrator reads files.'}` };
281
297
  }
282
298
  if (isPersonQuestionTool(ev.tool_name))
283
- return { deny: 'A child asks its orchestrator with agent_question first. The orchestrator escalates only person-only decisions through the existing blocked JSON question card.' };
299
+ return { deny: readOnlyRun?.scope === 'capture' ? 'A child asks the coordinator with agent_question. Only the coordinator asks a person-only question through the existing single-question flowviant-ask fence.' : 'A child asks its orchestrator with agent_question first. The orchestrator escalates only person-only decisions through the existing blocked JSON question card.' };
284
300
  }
285
301
  if (ev.hook_event_name === 'PostToolUse' && (isSpawnTool(ev.tool_name) || isFollowupTool(ev.tool_name))) postSpawn(ev);
286
302
  return {};
287
303
  }
288
304
  async function handle(action, args) {
289
- if (closed) throw new Error('This run stopped.');
305
+ if (ended()) throw new Error('This run stopped.');
306
+ if (action === 'capture_describe' && rootTools) return rootTools.describe();
307
+ if (action === 'capture_call' && rootTools) return rootTools.call(args);
290
308
  if (action === 'hook') {
291
309
  const result = hook(args);
292
310
  // Root PreToolUse/PostToolUse additionalContext is measured on both CLIs.
@@ -300,7 +318,7 @@ export async function createOrchestrator({ turnId, runtime, trace, admit, reques
300
318
  // A person’s answer starts a new CLI turn. The parent carries the earlier
301
319
  // question and native identity in its own conversation; relay that known
302
320
  // context instead of inventing a new child or requiring another question.
303
- if (action === 'answer_agent' && !records.has(id) && typeof id === 'string' && id.length > 0 && id.length <= 160 && records.size < SUBAGENT_CAP &&
321
+ if (!readOnlyRun && action === 'answer_agent' && !records.has(id) && typeof id === 'string' && id.length > 0 && id.length <= 160 && records.size < SUBAGENT_CAP &&
304
322
  typeof args.question === 'string' && args.question.trim() && args.question.length <= 4_000) {
305
323
  // Resumable, never spawnable: no slot is offered until a gated follow-up targets it.
306
324
  emit({ id, kind: scrubText(args.kind ?? '', SUBAGENT_FIELD_CAPS.kind), title: scrubText(args.title ?? '', SUBAGENT_FIELD_CAPS.title), brief: '', status: 'asked', now: args.question, resumable: true });
@@ -319,7 +337,7 @@ export async function createOrchestrator({ turnId, runtime, trace, admit, reques
319
337
  let q = questions.get(id);
320
338
  // The person answers in a later run; the child ends now so this run settles on the question card.
321
339
  if (q?.escalated && !q.answer) return { waiting: true, escalated: true,
322
- instruction: 'Your orchestrator escalated this to the person. Stop now: end your work with a short summary of where you are. You will be continued with the answer.' };
340
+ instruction: readOnlyRun ? 'Stop this investigation and return your findings and the unresolved question to the coordinator. This attempt will not resume after it ends.' : 'Your orchestrator escalated this to the person. Stop now: end your work with a short summary of where you are. You will be continued with the answer.' };
323
341
  // A given answer stands for a reworded poll until the child has it.
324
342
  if (q?.answer && (!q.read || q.question === args.question)) { q.read = true; return { answer: q.answer }; }
325
343
  if (!q || q.question !== args.question) {
@@ -333,7 +351,7 @@ export async function createOrchestrator({ turnId, runtime, trace, admit, reques
333
351
  if (action === 'answer_agent') {
334
352
  const q = questions.get(id); if (!q) throw new Error('That agent has no unanswered question.');
335
353
  if (args.escalate === true) { q.escalated = true; return { askingAgent: { id, nativeAgentId: a.nativeId, kind: a.kind, title: a.title },
336
- question: `${a.kind || a.title || id} asks: ${q.question}`, instruction: 'The child is told to stop. Once every child has finished or been stopped, return the existing blocked JSON question card with this attribution. Leave the agent asked until the person answers.' }; }
354
+ question: `${a.kind || a.title || id} asks: ${q.question}`, instruction: readOnlyRun?.scope === 'capture' ? 'The child is told to stop and return findings. Consolidate person-only uncertainties into the existing one-question flowviant-ask fence in this conversation. Keep staged row IDs, provisional assumptions and the coordinator final reply; do not return a card-delivery JSON or stage a card per child.' : readOnlyRun ? 'The child is told to stop and return findings. Retain the uncertainty in proposal evidence, or use the existing question shape if this is a diagnostic turn. Keep the turn’s existing final JSON protocol.' : 'The child is told to stop. Once every child has finished or been stopped, return the existing blocked JSON question card with this attribution. Leave the agent asked until the person answers.' }; }
337
355
  if (typeof args.answer !== 'string' || !args.answer.trim() || args.answer.length > 4_000) throw new Error('Give the agent a bounded answer.');
338
356
  q.answer = args.answer; trace.handoff(id, runtime, args.answer); emit({ id, status: a.release ? 'running' : 'waiting', now: 'Question answered by the orchestrator' });
339
357
  return { answered: true, instruction: 'Give this answer to the child with its native follow-up/resume tool.' };
@@ -350,12 +368,17 @@ export async function createOrchestrator({ turnId, runtime, trace, admit, reques
350
368
  error: text(error.message, 300), ...(error instanceof OrchestratorInputTooLarge ? { code: error.code } : {}),
351
369
  })); }
352
370
  };
353
- const { server, env: heldEnv, args: argv } = await listenHeldTool({ envPrefix: 'FLOWVIANT_ORCHESTRATOR', verb: '__orchestrator-mcp', requestTimeoutMs: 5_000,
354
- capability, isClosed: () => closed, respond });
371
+ let listener;
372
+ try {
373
+ listener = await listenHeldTool({ envPrefix: 'FLOWVIANT_ORCHESTRATOR', verb: '__orchestrator-mcp', requestTimeoutMs: 5_000,
374
+ capability, isClosed: ended, respond });
375
+ } catch (error) { forgetExtraSecrets(secretKey); throw error; }
376
+ const { server, env: heldEnv, args: argv } = listener;
355
377
  // The hook reads it to refuse a research child's write while this is down.
356
- const env = { ...heldEnv, FLOWVIANT_ORCHESTRATOR_CHILDREN: access };
378
+ const env = { ...heldEnv, FLOWVIANT_ORCHESTRATOR_CHILDREN: access,
379
+ ...(readOnlyRun ? { FLOWVIANT_ORCHESTRATOR_READ_ONLY: '1' } : {}) };
357
380
  const timer = setInterval(() => {
358
- if (closed || polling) return;
381
+ if (ended() || polling) return;
359
382
  polling = true;
360
383
  try {
361
384
  const now = clock();
@@ -397,6 +420,7 @@ export async function createOrchestrator({ turnId, runtime, trace, admit, reques
397
420
  outstanding() { return [...notes.values()].filter(n => OPEN_MESSAGE_ROUTE_STATES.includes(n.state)).map(n => ({ id: n.messageId, state: n.state, body: n.body, agentId: target(n), safePoint: n.safePoint })); },
398
421
  input(id, body) { if (closed || inbox.size >= 64 && !inbox.has(id)) return false; inbox.set(id, body); return true; },
399
422
  observe(update) {
423
+ if (ended()) return;
400
424
  if (update.nativeId) bind(update.nativeId, update.id);
401
425
  if (update.callId && calls.has(update.callId)) bind(update.id, calls.get(update.callId));
402
426
  const id = resolve(update.id);
@@ -408,10 +432,12 @@ export async function createOrchestrator({ turnId, runtime, trace, admit, reques
408
432
  apply(id, update);
409
433
  },
410
434
  async close(stopped = false) {
435
+ if (closed) return;
411
436
  closed = true; clearInterval(timer);
437
+ rootTools?.close();
412
438
  // Only an escalated question waits for the person; any other asked child ended with the run.
413
439
  for (const a of records.values()) { release(a.id); const q = questions.get(a.id);
414
- if (!terminal(a.status) && !(a.status === 'asked' && !stopped && q?.escalated && !q.answer)) emit({ id: a.id, status: 'stopped', now: stopped ? 'Stopped with the run' : 'Run ended' }); }
440
+ if (!terminal(a.status) && !(a.status === 'asked' && !readOnlyRun && !stopped && q?.escalated && !q.answer)) emit({ id: a.id, status: 'stopped', now: stopped ? 'Stopped with the run' : 'Run ended' }); }
415
441
  server.close(); server.closeAllConnections();
416
442
  forgetExtraSecrets(secretKey);
417
443
  },
@@ -9,13 +9,13 @@ export const ORCHESTRATOR_CLIENT_TIMEOUT_MS = 15_000;
9
9
  /** The controller's own refusal (a 409 body's words), relayed as said. */
10
10
  export class OrchestratorRefusal extends Error {}
11
11
 
12
- export async function callOrchestrator(action, args) {
12
+ export async function callOrchestrator(action, args, timeoutMs = ORCHESTRATOR_CLIENT_TIMEOUT_MS) {
13
13
  const url = new URL(process.env.FLOWVIANT_ORCHESTRATOR_URL);
14
14
  if (url.hostname !== '127.0.0.1' || url.protocol !== 'http:') throw new Error('No held run is available.');
15
15
  const body = JSON.stringify({ action, args });
16
16
  if (Buffer.byteLength(body) > ORCHESTRATOR_REQUEST_BYTES) throw new OrchestratorInputTooLarge();
17
17
  const response = await fetch(url, { method: 'POST', headers: { Authorization: `Bearer ${process.env.FLOWVIANT_ORCHESTRATOR_CAPABILITY}`, 'Content-Type': 'application/json' },
18
- body, signal: AbortSignal.timeout(ORCHESTRATOR_CLIENT_TIMEOUT_MS) });
18
+ body, signal: AbortSignal.timeout(timeoutMs) });
19
19
  // A closed or foreign run answers a bare 403: no body to parse.
20
20
  let result = null;
21
21
  try { result = JSON.parse(await response.text()); } catch { result = null; }
@@ -38,6 +38,76 @@ const atCard = (model, effort) =>
38
38
 
39
39
  const childBrain = ({ runtime, model, effort }) => `CHILD MODEL AND EFFORT. ${atCard(model, effort)} By default every child runs at the card's model and effort${model || effort ? '; the gate names them when your spawn names neither, so a child never falls back to the CLI\'s own global default' : ', which it inherits from this run when your spawn names neither'}. For a simple, well-bounded child — a search, a sweep of file reads, a mechanical edit — you may choose a cheaper model or a lower effort. Keep the card's model and effort for hard or judgment-heavy work. Never choose a model or effort above the card's, and only models of this card's own CLI; the gate refuses an effort above the card's. ${CHILD_SPELLING[runtime] ?? ''} When you choose anything other than the card's model or effort for a child, name the choice and why in your update.`.replace(' ', ' ');
40
40
 
41
+ /** Investigators do not propose separate plans. Only this coordinator sees
42
+ * and reconciles the complete selection before the existing JSON validator. */
43
+ export function planningOrchestratorContract({ diagnosis = false, ...brain } = {}) {
44
+ return `READ-ONLY PLANNING COORDINATOR
45
+ ${diagnosis ? 'You alone return the existing diagnostic JSON for the entire selected workload. A fresh planning consult follows a repaired diagnosis; do not return a proposal here.' : 'You alone return the existing proposal JSON for the entire selected workload.'}
46
+ Identify independent repository questions or code areas before investigating.
47
+ Delegate independent investigations to native children while you inspect one
48
+ part yourself. Dependent investigations wait for their inputs; small inseparable
49
+ work stays solo. Use only native children that can call card_orchestrator, sharing
50
+ this checkout, its repository/knowledge read boundary and runtime restrictions.
51
+ Every child only reads: no file writes, commits, worktrees, board/staging tools,
52
+ project/personal MCP or network capability. Ask for findings, source paths and
53
+ uncertainties, not a partial proposal. A claimed citation is not measured proof
54
+ of a successful read. Preserve reader failures and unknown results.
55
+ Reconcile all findings and conflicts across the complete selection, including
56
+ exact card identities, prerequisites first, declared dependencies, cross-source
57
+ file collisions, retained research/source context and live work. Source composers
58
+ are provenance, never grouping boundaries. Never drop an uninvestigated card.
59
+ ${diagnosis ? 'Keep the existing repaired/question diagnostic shape.' : 'Keep the existing proposal shape and per-group human acceptance: no work starts.'}
60
+ Children ask you through agent_question; answer with answer_agent and its native
61
+ follow-up, from this context and the repository. Retain unresolved uncertainties
62
+ in proposal evidence; the existing diagnostic question protocol still applies
63
+ when diagnosing a failed attempt. Only you ask any person-only question.
64
+ The root and children share the project's Turns at once pool. A refused spawn
65
+ has not started: continue investigating yourself. Retry only when offered a
66
+ slot, and finish solo if none becomes available. Do not bypass admission with
67
+ another CLI process. Wait for every started child to finish or stop before your
68
+ final proposal. Stop ends the whole attempt; stale children cannot be resumed.
69
+ ${childBrain(brain).replaceAll('card', 'planning turn')}`;
70
+ }
71
+
72
+ export function captureOrchestratorContract(brain = {}) {
73
+ return `READ-ONLY CAPTURE INVESTIGATIONS
74
+ You own this one ongoing conversation and its staged proposals. For a broad
75
+ request with independent repository questions, give bounded read-only questions
76
+ to native children while you investigate another area. Small focused requests,
77
+ simple corrections and short follow-ups with no independent investigations stay
78
+ solo. Dependent questions wait for their inputs. Use only native children that
79
+ can call card_orchestrator, sharing this checkout and its repository/knowledge
80
+ read boundary. They gain no network or project/personal MCP access.
81
+ Children write no files and call NO flowviant tools, including list/staging or
82
+ stream_session_turn. They return findings, source paths and uncertainties to
83
+ you; you alone ask the person, using the existing single-question fence, and
84
+ you alone read list_cards/list_staged/read_card, dedupe the complete request,
85
+ stage, edit or withdraw rows and stream the conversation. The tool gate and
86
+ credential relay enforce this for descendants and resumed children too.
87
+ Before staging, reconcile all findings with the original request, selected
88
+ repository catalog, exact attached/retained reference versions, prior decisions,
89
+ assumptions and dependencies. A claimed citation does not establish a successful
90
+ read. Preserve actual failed/unknown reader outcomes. Keep grounded references
91
+ and unresolved assumptions on every affected brief. Stage independently shippable
92
+ outcomes, never one card per child or one card per investigation step. Put
93
+ prerequisites first and describe dependencies in both briefs. Refine existing
94
+ staged rows in place; never duplicate or withdraw/restage them to recover.
95
+ Ordinary conversational questions do not create unsolicited cards. Human
96
+ landing, Plan and acceptance controls remain the only ways work starts.
97
+ Each child registers with card_orchestrator and asks you with agent_question;
98
+ answer from this conversation and repository using answer_agent and native
99
+ follow-up. Consolidate person-only uncertainties into the existing one question.
100
+ Wait for every started child to finish or stop before your final reply. Preserve
101
+ the existing final-answer and streamed-reply protocol; child prose is not a
102
+ second conversation reply. A refused spawn has not started: continue yourself,
103
+ retry only when a slot is offered, and finish solo if none is available.
104
+ The root and children share the project's Turns at once pool. Stop ends the
105
+ whole run. Every new native invocation has a fresh capability; do not resume a
106
+ child from a previous turn or retry. Preserve staged row IDs and use list_staged
107
+ to reconcile an interrupted call before repeating it.
108
+ ${childBrain(brain).replaceAll('card', 'capture turn')}`;
109
+ }
110
+
41
111
  /**
42
112
  * The orchestrator's contract for one run: its posture's split and child
43
113
  * rules, the card's own model and effort, then the gate, routing and child