thinkpool-pair 0.7.408 → 0.7.410

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.
@@ -1 +1 @@
1
- import{randomUUID as e}from"node:crypto";import{createRequire as t}from"node:module";import{readFileSync as o}from"node:fs";import{dirname as n,join as s}from"node:path";import{query as r}from"@anthropic-ai/claude-agent-sdk";import{sanitizeSession as i}from"./transcript-sanitize.mjs";import{reviewGatePreToolDecision as a}from"./flow-review-gate.mjs";import{crossPostNeedsCard as l}from"./cross-terminal.mjs";import{correctContext as c}from"./context-windows.mjs";import{normalizeClaudeCommandCatalog as d}from"./claude-command-catalog.mjs";import{evidenceForToolResult as u}from"./evidence-citations.mjs";import{THINKPOOL_CASCADE_RULE as p,THINKPOOL_REMOTE_DELIVERY_RULES as m,THINKPOOL_RUNTIME_AUTHORITY_RULE as h,THINKPOOL_RUNTIME_TURN_REMINDER as f,buildThinkPoolTurnGuidance as y,createRoomContextSelector as k,normalizeThinkPoolTurnCause as w,usesFullThinkPoolReminder as g}from"./thinkpool-room-prompt.mjs";import{stallDecision as b,stallEvent as v,isCompactTurn as _}from"./turn-stall.mjs";import{createSameTargetResilienceController as T,formatResilienceTrace as S}from"./provider-resilience.mjs";import{catastrophicPreToolHookDecision as E}from"./catastrophic-command-guard.mjs";const N=t(import.meta.url);export async function claudeOneShot({prompt:e,model:t="claude-haiku-4-5",cwd:o,env:n,timeoutMs:s=8e3}={}){const i=new AbortController,a=setTimeout(()=>{try{i.abort()}catch{}},s);try{const s=r({prompt:e,options:{model:t,...o?{cwd:o}:{},env:n,maxTurns:1,permissionMode:"bypassPermissions",settingSources:[],strictMcpConfig:!0,mcpServers:{},abortController:i}});let a="";for await(const e of s){if("assistant"===e.type)for(const t of e.message?.content||[])"text"===t.type&&(a+=t.text);if("result"===e.type)break}return a.trim()}finally{clearTimeout(a)}}const O=(()=>{try{let e=n(N.resolve("@anthropic-ai/claude-agent-sdk"));for(let t=0;t<8;t++){try{const t=JSON.parse(o(s(e,"package.json"),"utf8"));if("@anthropic-ai/claude-agent-sdk"===t.name)return t.version}catch{}const t=n(e);if(t===e)break;e=t}}catch{}return"unknown"})(),R=/\brm\s+\S|\brmdir\s+\S|\bgit\s+(push\s+(-f|--force)|reset\s+--hard|clean\s+-[a-z]*f)|\bdrop\s+(table|database)\b|\b(mkfs|dd)\b|\bsudo\b|>\s*\/dev\/|\bchmod\s+-R|\bchown\s+-R|\bkillall\b|\btruncate\b/i,A=new Set(["Read","Grep","Glob","NotebookRead","TodoRead","LS"]),D=new Set(["WebFetch","WebSearch"]),x=new Set(["Edit","Write","MultiEdit","NotebookEdit","TodoWrite"]);export function classifyRisk(e,t){if("Bash"===e){const e=t&&(t.command??t.cmd)||"";return R.test(e)?"high":"medium"}return A.has(e)?"low":D.has(e)?"network":(x.has(e),"medium")}const P=/(^|\/)\.claude\/SESSIONS\/|(^|\/)CLAUDE\.md$/;export function isSafeDocWrite(e,t){if(!x.has(e))return!1;const o=t&&(t.file_path||t.notebook_path)||"";return P.test(o)}export function autoAllow({toolName:e,input:t,mode:o="default",alwaysAllow:n=new Set}){const s=classifyRisk(e,t);return"low"===s||"bypassPermissions"===o||"acceptEdits"===o&&x.has(e)&&"high"!==s||isSafeDocWrite(e,t)||n.has(`${e}:${s}`)}export function askUserQuestionHookOutput(e){const t=e&&"object"==typeof e?e.decision:e,o="string"==typeof t&&t.startsWith("answer:")?t.slice(7):"",n=e&&"object"==typeof e?e.responder:null,s="string"==typeof n?.name&&n.name.trim()?n.name.trim():"string"==typeof n?.id&&n.id?`room member ${n.id}`:"The user";return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:o?`${s} answered in the thinkpool room — ${o}. Treat this as their selection and continue; do not call AskUserQuestion again for the same question.`:"The user dismissed the question in the thinkpool room without selecting. Ask in plain prose, or proceed with a sensible default."}}}export function askUserQuestionRegression(e,t){return Array.isArray(e)?e.includes("AskUserQuestion")?null:`[SDK-REGRESSION] agent SDK v${t||"unknown"} init tools[] is missing 'AskUserQuestion' — the multiple-choice question card is disabled. A caret SDK bump likely changed the canUseTool gate; pin a known-good SDK in bridge/package.json + republish.`:null}function I(){const e=[];let t=null,o=!1;return{stream:async function*(){for(;!o;)e.length?yield e.shift():await new Promise(e=>{t=e})}(),push:n=>!o&&(e.push({type:"user",message:{role:"user",content:n}}),t&&(t(),t=null),!0),end(){o=!0,t&&(t(),t=null)}}}const C=(e=[])=>e.map(e=>"text"===e.type?{type:"text",text:e.text}:"thinking"===e.type?{type:"thinking",text:e.thinking||"",reasoningKind:"thought"}:"tool_use"===e.type?{type:"tool_use",id:e.id,name:e.name,input:e.input}:{type:e.type}).filter(Boolean),M=new Set(["default","acceptEdits","plan","bypassPermissions"]),U=["You are Claude in a thinkpool Code room, driven live from a phone or browser — NOT a local terminal. Keep using the room's features.",f,"TERMINAL HIERARCHY: obey your authoritative TERMINAL ROLE. A person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal — NEVER spawn_terminal — even for ordinary work or a handoff. If the wording includes new or separate terminal, main-terminal routing wins. Use spawn_terminal only for agent-decided bounded worker slices or when the person explicitly asks for a worker, sub-terminal, Ensemble lane, or delegated slice. If open_main_terminal is unavailable, say so; never substitute an Ensemble child. Leaf, worker, Side, and managed Flow lanes work directly. Never use built-in invisible Task/Agent subagents or hijack a busy sibling.","WORKTREES: parallel lanes share one repo — before code edits run `git worktree list`; if linked worktrees exist, take your OWN worktree + branch, never the shared checkout or a branch another lane is on.","BUILD WORKFLOW (default, no magic word): right-size within your TERMINAL ROLE — a trivial ask or delegated slice you just do; a conductor-capable role with a genuinely decomposable build FIRST writes a short plan in chat, THEN fans worker slices into visible spawn_terminal lanes and verifies them. Worker/leaf/Side/managed Flow roles do not fan out. A person-requested new or separate terminal uses open_main_terminal. Never plan-mode/ExitPlanMode; plans live in chat and lanes in the existing list."].join(" ");export function startClaudeSession({cwd:t,model:o,effort:n="high",resume:s,env:f,mode:N="default",onEvent:R,requestPermission:A,mcpServers:D,crossPostGate:x,crossRoomPostGate:P,didSpawnTarget:L=null,terminalRolePrompt:W,rolePrompt:F,blockSubagents:j=!1,onSubmitPlan:$=null,onLaneDone:q=null,onReviewVerdict:G=null,reviewGate:B=null,lazy:H=!1,roomContext:K=null,suggest:Q=!0,prepareCwd:Y=null,admitStart:z=null,resilienceObserver:J=null,resilience:V=null}){const X=k(K);let Z=0,ee=!0;const te=(e,{promptIndex:t=0,forceFull:o=!1,turnCause:n=null}={})=>{const s=g({promptIndex:t,forceFull:o,turnCause:n}),r=X({force:s}),i=String(W||"").trim();return`<system-reminder>\n${s&&i?`${i}\n\n`:""}${s?U:y({text:e,promptIndex:t,forceFull:o,turnCause:n})}${r?`\n\n${r}`:""}\n</system-reminder>`},oe=new AbortController;let ne=I(),se=s||null,re=s||null,ie=null,ae=null,le=null,ce=null,de=!1,ue=!1,pe=null,me=!1,he=!1,fe=!1,ye=null,ke=M.has(N)?N:"default";const we=new Set,ge=new Map,be=new Set(["low","medium","high","xhigh","max"]);let ve=be.has(n)?n:"high",_e=0,Te=0,Se=o||null,Ee=null,Ne=null,Oe=Promise.resolve(),Re=!1,Ae=!1;const De=e=>new Promise(t=>setTimeout(t,e)),xe=Math.max(3e4,parseInt(process.env.TP_STALL_MS,10)||9e4);let Pe=!1,Ie=Date.now(),Ce=!1;const Me=/connection closed|connection reset|econnreset|etimedout|socket hang up|fetch failed|network error|socket destroyed/i;let Ue=0;const Le=(e,t={})=>{try{J?.({reason:e,restartCount:Ue,...t})}catch{}},We=!(!V?.policy?.enabled||!V?.providerId||"anthropic"===V.providerId);let Fe=null,je=null,$e=!1,qe=0,Ge=!1,Be=null;const He=Math.max(3*xe,parseInt(process.env.TP_FORCE_STOP_MS,10)||3e5);let Ke=!1,Qe=!1;const Ye=Math.max(He,parseInt(process.env.TP_COMPACT_FORCE_STOP_MS,10)||12e5);let ze=!1,Je=0;const Ve=A;A=async e=>{Je++;try{return await(Ve?.(e))}finally{Je=Math.max(0,Je-1),Ie=Date.now()}};let Xe=!1,Ze=null,et=null,tt=!1,ot="",nt=null;const st=Math.max(1200,parseInt(process.env.TP_SUGGEST_FALLBACK_MS,10)||2500),rt=e=>{try{R?.(e)}catch{}},it=e=>{Ie=Date.now(),e&&"stalled"!==e.kind&&(Ce=!1),!e||"compaction"!==e.kind&&"result"!==e.kind&&"error"!==e.kind||(ze=!1),rt(e)},at=e=>{try{V?.onRecord?.(e)}catch{}"retrying"!==e?.outcome&&"cap_blocked"!==e?.outcome&&"circuit_open"!==e?.outcome||it({kind:"note",text:S(e)})},lt=()=>{if(null!=je){try{(V?.clearTimer||clearTimeout)(je)}catch{}je=null}},ct=()=>{if(lt(),!Fe)return;const e=Number(V?.policy?.timeoutMs);if(!Number.isFinite(e)||e<=0)return;const t=V?.setTimer||setTimeout;je=t(()=>{if(je=null,!de&&Fe&&Pe){Fe.failure({message:"timeout"}),Pe=!1;try{Ee?.abort()}catch{}gt()}},e)},dt=async()=>{if(!Fe)return!0;let e=null;try{e=await Fe.preflight()}catch{return!1}return!0===e?.admitted},ut=setInterval(()=>{const e=Date.now()-Ie,t=b({turnActive:Pe,awaitingUser:Je,quietMs:e,stallMs:xe,forceStopMs:He,stalledSent:Ce,stallRetried:Qe,compacting:ze,compactForceStopMs:Ye});if("none"===t)return;const o=v(t,e);if(o&&rt(o),"status"!==t){if("retry"===t){if(Ke=!0,Fe){Le("resilience_stall",{quietMs:e}),Fe.failure({message:"timeout"}),Pe=!1;try{Ee?.abort()}catch{}return void gt()}return Le("stall_replay",{quietMs:e}),void wt(e)}Ke=!0,Pe=!1}else Ce=!0},5e3);ut.unref?.();const pt=e=>{setTimeout(()=>{Promise.resolve(ye?.setPermissionMode?.(e)).catch(t=>console.error(`[claude-session] setPermissionMode(${e}) failed:`,t?.message||t))},0)},mt={abortController:oe,permissionMode:ke,hooks:{PreToolUse:[{hooks:[async o=>{const n=o.tool_name,s=o.tool_input,r=E({toolName:n,input:s,cwd:t});if(r)return r;const i=o.effort?.level;i&&i!==ve&&(ve=i,it({kind:"effort",level:ve}));const c="Write"===n||"Edit"===n||"MultiEdit"===n||"NotebookEdit"===n;if(j&&c&&/(?:^|[/\\])FLOW_PLAN\.json$/i.test(s?.file_path||s?.notebook_path||"")){const e=s?.content??s?.new_string??"";let t={ok:!1,message:"Plan submission is not wired for this session."};try{t=$&&await $(e)||t}catch(e){t={ok:!1,message:`Plan submission failed: ${e?.message||e}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.message}}}if(j&&("Task"===n||"Agent"===n||"Bash"===n||c))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Bash"===n?"Flow conductors do NOT run Bash — it pops a permission card and stalls the flow. Use the Grep tool (not `grep`/`rg`), the Glob tool (not `find`/`ls`), and Read (not `cat`/`head`) — those run with no prompt. Then DECOMPOSE and submit by Writing your task-graph JSON to the file FLOW_PLAN.json.":c?'Flow conductors do NOT write project or plan-document files. Do NOT use ExitPlanMode and do NOT call submit_flow_plan (both hang here). To SUBMIT your decomposition, use the Write tool with file_path "FLOW_PLAN.json" and content = your task-graph JSON ({"summary":"…","tasks":[…]}). That single Write IS how you submit — the room ingests it directly. Do not write any other file.':"Flow conductors do NOT spawn subagents — it stalls the flow on a permission card. Inspect the codebase yourself with Read/Grep/Glob (no prompt). Then DECOMPOSE and submit by Writing your task-graph JSON to the file FLOW_PLAN.json. Do not call Task/Agent again."}};if(G&&("Write"===n||"Edit"===n)&&/(?:^|[/\\])FLOW_REVIEW(\.[a-zA-Z0-9]+)?$/.test(s?.file_path||"")){let e={ok:!1,message:"verdict signal failed"};try{e=await G(s?.content??s?.new_string??"")||e}catch(t){e={ok:!1,message:`verdict signal failed: ${t?.message||t}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.message}}}if(q&&("Write"===n||"Edit"===n)&&/(?:^|[/\\])FLOW_DONE(\.[a-zA-Z0-9]+)?$/.test(s?.file_path||"")){let e={ok:!1,message:"done signal failed"};try{e=await q(s?.content??s?.new_string??"")||e}catch(t){e={ok:!1,message:`done signal failed: ${t?.message||t}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.message}}}const d=a({reviewGate:B,toolName:n,toolInput:s});if(d)return d;if("mcp__thinkpool__read_terminal"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (read-only thinkpool cross-terminal read)."}};if(/^mcp__thinkpool__preview_(start|capture|inspect|stop)$/.test(n))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (contained bridge-owned viewport preview)."}};if("mcp__thinkpool__submit_flow_plan"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (Flow plan submission — broadcasts the task-graph for human approval)."}};if("mcp__thinkpool__list_sessions"===n||"mcp__thinkpool__read_session"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (read-only thinkpool cross-session read — your own rooms)."}};if("mcp__thinkpool__close_terminal"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (thinkpool cross-terminal close — only self-spawned lanes)."}};if("mcp__thinkpool__spawn_terminal"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (autonomous thinkpool worker; bounded by room caps and isolated in its own worktree)."}};if("mcp__thinkpool__open_main_terminal"===n){const t=s?.mode||ke;if("bypassPermissions"!==t||"bypassPermissions"===ke)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Auto-approved (open a fresh thinkpool terminal in ${t} mode — inherited, no escalation; bounded by room caps).`}};let o="deny";try{o=await(A?.({id:e(),toolName:n,input:{...s,mode:t},risk:"high"}))??"deny"}catch{o="deny"}const r="allow"===o;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:r?"allow":"deny",permissionDecisionReason:r?"Bypass terminal creation approved in the thinkpool room — the new terminal runs autonomously.":"Bypass terminal creation denied in the room — do not retry as bypass; open it without mode:bypassPermissions or ask what to do."}}}if("mcp__thinkpool__post_to_terminal"===n){const t=x?x():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-terminal post not allowed right now."}};const o=!!L&&!!L(s?.terminal);if(!l({mode:ke,spawnedByMe:o}))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"bypassPermissions"===ke?"Auto-approved (cross-terminal post in bypassPermissions mode — bypass means bypass).":"Auto-approved (cross-terminal post into a lane you spawned — parent→child orchestration, no per-post tap)."}};let r="deny";try{r=await(A?.({id:e(),toolName:n,input:s,risk:"high"}))??"deny"}catch{r="deny"}const i="allow"===r;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:i?"allow":"deny",permissionDecisionReason:i?"Cross-terminal post approved in the thinkpool room.":"Cross-terminal post denied in the room — do not retry; ask what to do instead."}}}if("mcp__thinkpool__post_to_session"===n){const t=P?P():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-room post not allowed right now."}};let o="deny";try{o=await(A?.({id:e(),toolName:n,input:s,risk:"high"}))??"deny"}catch{o="deny"}const r="allow"===o;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:r?"allow":"deny",permissionDecisionReason:r?"Cross-room post approved in the sending room — the target room will be asked to accept it.":"Cross-room post denied in the room — do not retry; ask what to do instead."}}}if("ExitPlanMode"===n){if("plan"!==ke)return pt(ke),it({kind:"mode",mode:ke}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`The thinkpool room is in ${ke} mode, not Plan — the user did not ask for a plan. Do NOT call ExitPlanMode; proceed and make the changes directly. Only present a plan if the user switches the room to Plan mode or explicitly asks.`}};let t="keep";try{t=await(A?.({id:e(),toolName:n,input:s,risk:"plan",plan:s?.plan||""}))??"keep"}catch{t="keep"}if("run"===t||"accept"===t){const e="accept"===t?"acceptEdits":"default";return ke=e,pt(e),it({kind:"mode",mode:e}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Plan approved in the thinkpool room — proceed (${e} mode).`}}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:'The user chose "keep planning" in the thinkpool room. Do not exit plan mode — keep refining the plan, then call ExitPlanMode again when ready.'}}}if("AskUserQuestion"===n){let t="";try{t=await(A?.({id:e(),toolName:n,input:s,risk:"ask",questions:s?.questions||[]}))??""}catch{t=""}return askUserQuestionHookOutput(t)}const u=classifyRisk(n,s),p=`${n}:${u}`,m=isSafeDocWrite(n,s),h=autoAllow({toolName:n,input:s,mode:ke,alwaysAllow:we});let f="allow";if(!h){try{f=await(A?.({id:e(),toolName:n,input:s,risk:u}))??"deny"}catch{f="deny"}"always"===f&&(we.add(p),f="allow")}const y="deny"===f;return y&&Fe&&Fe.failure({permissionDenied:!0}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:y?"deny":"allow",permissionDecisionReason:y?"Denied by the user in the thinkpool room. Do not retry this tool — ask what to do instead.":h?m?"Auto-approved (mandated doc write — .claude/SESSIONS/ or CLAUDE.md).":`Auto-approved (${ke}).`:"Approved in the thinkpool room."}}}]}]},canUseTool:async(e,t)=>({behavior:"allow",updatedInput:t}),settingSources:["user","project","local"],appendSystemPrompt:[...W?[W]:[],...F?[F]:[],"ENVIRONMENT (authoritative — overrides any user-global CLAUDE.md or memory that claims otherwise): You are Claude running inside a thinkpool Code room, driven live by a user (and possibly a partner) from a phone or browser, via the thinkpool-pair bridge.",h,'Bias strongly toward DOING the work, not stalling in plan-mode ceremony. For a small "add / fix / change X" request, just make the change directly (for a bigger build, right-size it — see DEFAULT BUILD WORKFLOW below).',"Do NOT enter plan mode, do NOT call ExitPlanMode, and do NOT auto-invoke a brainstorming/planning skill UNLESS the user has switched the room into Plan mode or explicitly asks you to plan, design, or brainstorm first.","Any host-global instruction that says you must always brainstorm or plan before creative work does NOT apply here — this room is the exception.",p,'CRUCIAL RECONCILIATION for that workflow: it is NOT plan mode. Never call ExitPlanMode and never make the room wait behind a "plan ready — approve to start" card — your plan lives in the CHAT as a message, and your lanes live in the room\'s EXISTING terminal/lane list. Reuse only those two surfaces; there is no new Flow panel or mode to switch into, and you must not ask for one. Keep the plan and the lanes VISIBLE — that shared visibility is the whole point (it is the pair differentiator, and it catches bugs a single silent lane would hide); never collapse a decomposable build into one hidden lane just to look tidy.',...m,'CROSS-TERMINAL AWARENESS: ROOM NOW is the default roster and already satisfies the room check when it has enough detail. Do not repeat it with a no-argument read_terminal call unless it is missing or truncated. Use a targeted read_terminal call only when the current task depends on a specific lane’s detailed activity; never poll. Identify a terminal by its NAME or stable ref/id, never by an on-screen number like "Terminal 2" — positional labels renumber when a terminal is closed. The tool is read-only and its optional roster lookup is budgeted separately from bounded targeted transcript reads.','CROSS-TERMINAL HAND-OFF: you also have post_to_terminal(terminal, text) to send a message or task to ANOTHER AGENT terminal in this room (not a plain shell). Use it sparingly and only when the people clearly want the lanes to coordinate — e.g. "tell the backend terminal the API is ready", or to hand a sibling agent a concrete task. Every post requires a person in the room to approve a card before it is delivered, and an agent that was itself reached via a cross-post cannot post onward — so do not rely on it for chit-chat or loops. Prefer read_terminal to understand a sibling before you ever post to it.',"TERMINAL CREATION CONTRACT: main terminals and workers use different tools. A person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal(name?, task?, model?) — even for ordinary work or a handoff and even without the words Cascade or conductor. If the wording includes new or separate terminal, main-terminal routing wins. Never use spawn_terminal for that request, and if open_main_terminal is unavailable say so instead of substituting. Use spawn_terminal(name?, task?, model?, sliceType?) only for agent-decided bounded WORKER SUB-TERMINALS or when the person explicitly asks for a worker, sub-terminal, Ensemble lane, or delegated slice. Workers never receive the creation tools and never conduct. Do not dump work into busy siblings. Spawned workers are always autonomous in bypassPermissions and never ask the room for an approval card; the bridge still enforces room caps, hop limits, the kill-switch, and isolated linked worktrees. Wait for ROOM NOW or a completion signal instead of polling; after a worker finishes, collect it with one targeted read_terminal call and leave it visible until a person dismisses it with the Ensemble X. Never call close_terminal merely because work finished. Main terminals are independent, keep their requested permission mode, and are not owned/closed through Ensemble.","CROSS-SESSION AWARENESS: the Ensemble reaches across your SESSIONS, not just the terminals in this room. list_sessions() lists your OTHER thinkpool Code rooms — both your own rooms running on this machine AND your partner's rooms in the same pair, reachable over the per-pair bus (a room on the partner's machine shows its host). read_session(session, terminal?) reads recent activity inside one (omit `terminal` to list that room's terminals, or pass a ref/name to read that lane). Both are READ-ONLY — they never change another session, and they reach ONLY your own rooms and rooms you share with your partner, never a stranger's. Reach for them when work spans rooms — \"what's the other project up to\", \"pick up where the other session left off\", or to check a long-running task elsewhere before you act here.","CROSS-SESSION HAND-OFF: post_to_session(session, text, terminal?) sends a task or message to an agent in ANOTHER of your rooms — your own, or your partner's over the pair bus. Use it sparingly and only when the people clearly want the rooms to coordinate — e.g. hand the API room's agent a concrete follow-up once the frontend is ready. It is dual-consent: a person in YOUR room approves sending, and a person in the TARGET room approves receiving, before anything is delivered — so never rely on it for chit-chat or loops, and an agent that was itself reached via a cross-room post cannot post onward to a third room. It spends real model tokens in the other room (maybe on the other person's machine), so prefer read_session to understand a room before you ever post into it, and only post one concrete hand-off at a time. Outbound list/read/post tools need the thinkpool account bridge; a standalone owner room can still receive a paired hand-off directly and will always raise its own approval card before delivery.","SUBAGENT POLICY: in this room, a main terminal delegates worker slices through visible spawn_terminal Ensemble lanes. A person-requested new or separate terminal is created with open_main_terminal, never Ensemble. Worker, leaf, Side, and managed Flow lanes do their assigned work directly. Do NOT reach for built-in Task/Agent subagents: an in-process subagent is invisible to the room, cannot be peered at or steered, and its work is lost to the Ensemble.",'RESEARCH LANE: you have a `research` tool that runs a REAL multi-source web search + adversarial verification and returns each claim marked HELD or REJECTED with citations. Reach for it when the people would genuinely benefit from looking something external up or settling a question of current fact — pricing, "is X still maintained / deprecated", "is that benchmark real", a debate over facts you are not sure of. Do NOT run it unprompted or for things you already know: first OFFER in plain language ("want me to spawn a research lane on that and check it?"), and only call `research(question)` once they agree — it spends real budget (plan-gated Free 5 / Plus 100 runs a month) and takes ~a minute. When it returns, present the held/rejected findings clearly and invite both people to weigh the sources, flagging any held claim that rests on a source they might not trust — that shared scrutiny is the point.',"WORKTREES: parallel lanes share one machine and usually one repo. Run `git worktree list` before your first code edit; if linked worktrees exist, the shared main checkout is contended (and may be guard-blocked) — do your work in your OWN worktree on your OWN branch (`git worktree add <dir> -b <branch>`), and never edit a checkout or ride a branch another lane is using.",'WRITE PLANS INTO THE CHAT: whenever you form or revise a plan — because the room is in Plan mode, or because someone asked you to plan, design, or think it through first — write the actual plan out as a normal message in the room as you develop it: the approach, the concrete steps, the files you will touch, the open questions. The room does NOT surface plan files at all, and the plan-approval card does not reliably carry the plan text, so a plan that lives only in a plan file or only inside ExitPlanMode is INVISIBLE to the people you are working with — they just see "plan ready" with no content. The chat is the canonical place your plan lives; put it there so the room can read and react to it before you proceed.'].join(" "),includePartialMessages:!0,promptSuggestions:!0};"1"===process.env.TP_MCP_STRICT&&(mt.strictMcpConfig=!0,mt.mcpServers={}),D&&Object.keys(D).length&&(mt.mcpServers={...mt.mcpServers||{},...D}),t&&(mt.cwd=t),o&&(mt.model=o),mt.effort=ve,mt.env={...f||process.env,CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION:"1"};const ht=async()=>{if(!Q||"worker_completion"===ae)return;const e=(ot||"").trim().slice(-1500);if(e&&!de)try{let o=await claudeOneShot({prompt:`You are predicting the user's NEXT chat message in a live coding session, to prefill their composer. Given the assistant's latest reply below, output the single most likely next user message — short and natural (often just "proceed", "go with option A", "yes do that", or a brief follow-up). One line, <=12 words, imperative, no preamble, no quotes, no markdown.\n\nAssistant's latest reply:\n"""\n${e}\n"""\n\nNext user message:`,model:"claude-haiku-4-5",cwd:t,env:mt.env,timeoutMs:8e3});o=o.trim().split("\n")[0].replace(/^["'`]+|["'`]+$/g,"").trim().slice(0,140),!o||tt||de||/^(sure|of course|certainly|let me know|i can help|happy to)\b/i.test(o)||(it({kind:"suggestion",text:o,source:"haiku"}),process.stderr.write(` ◆ [suggestion] haiku fallback: ${JSON.stringify(o)}\n`))}catch{}},ft=()=>{const e="function"==typeof z?z():{ok:!0};return!1!==e?.ok||(it({kind:"error",message:e.reason||"Host memory is critically low. This agent runtime was not started.",recoverable:!0}),!1)},yt=async({admitted:e=!1}={})=>{if(Ae)return!1;if(!ue&&!e&&!ft())return!1;if(null==pe&&(pe=Date.now()),ue=!0,Ne)try{Ne()}catch{}Oe=new Promise(e=>{Ne=e});const n=new AbortController;Ee=n;const a=()=>{try{n.abort()}catch{}};oe.signal.addEventListener("abort",a,{once:!0});try{if(se){const e=i(t||process.cwd(),se);e.blocks&&process.stderr.write(`\n ◆ healed ${e.blocks} malformed tool block(s) in the transcript before resume.\n`)}ye=r({prompt:ne.stream,options:{...mt,abortController:n,...se?{resume:se}:{}}});for await(const e of ye){if(de)break;switch(e.type){case"system":if("thinking_tokens"===e.subtype){_e+Te===0&&it({kind:"thinking_tokens",tokens:e.estimated_tokens,delta:e.estimated_tokens_delta});break}if("compact_boundary"===e.subtype){ee=!0,it({kind:"compaction",trigger:e.compact_metadata?.trigger||"auto",preTokens:e.compact_metadata?.pre_tokens??null}),(async()=>{try{const e=await(ye?.getContextUsage?.());e&&(it({kind:"usage",ctx:c({used:e.totalTokens,max:e.maxTokens,pct:Math.round(e.percentage),model:e.model})}),e.model&&(Se=e.model))}catch{}})();break}if(e.session_id&&(se=e.session_id),me||(me=!0,process.stderr.write(`\n ◆ session ready in ${Date.now()-pe}ms — MCP ${"1"===process.env.TP_MCP_STRICT?"OFF":"on"}${s?", resume":", fresh"}.\n`)),Se=mt.model||e.model||o||Se,it({kind:"system",sessionId:se,model:mt.model||e.model||o||null,commands:d({slashCommands:e.slash_commands,skills:e.skills})}),!fe&&Array.isArray(e.tools)){fe=!0;const t=askUserQuestionRegression(e.tools,O);t&&(process.stderr.write(`\n ⚠⚠ ${t}\n`),it({kind:"error",message:t}))}he||(he=!0,Promise.resolve(ye?.supportedModels?.()).then(e=>{const t=(e||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);t.length&&it({kind:"models",models:t})}).catch(()=>{}));break;case"assistant":lt(),Fe?.visibleOutput();for(const t of e.message?.content||[])"tool_use"===t?.type&&t.id&&ge.set(t.id,{at:Date.now(),name:t.name,input:t.input});{const t=(e.message?.content||[]).filter(e=>"text"===e?.type).map(e=>e.text).join("\n").trim();t&&(ot=t)}it({kind:"assistant",blocks:C(e.message?.content),parentToolUseId:e.parent_tool_use_id||null});break;case"user":for(const t of e.message?.content||[])if("tool_result"===t?.type){lt(),Fe?.visibleOutput({tool:!0});const o=ge.get(t.tool_use_id);null!=o&&ge.delete(t.tool_use_id);const n=u(o?.name,t.content);it({kind:"tool_result",toolUseId:t.tool_use_id,content:t.content,...n?{evidence:n}:{},isError:!!t.is_error,durationMs:null!=o?.at?Date.now()-o.at:void 0,parentToolUseId:e.parent_tool_use_id||null})}break;case"stream_event":{const t=e.event;"message_start"===t?.type?(_e+=Te,Te=t.message?.usage?.output_tokens||0,it({kind:"thinking_tokens",tokens:_e+Te})):"message_delta"===t?.type&&t.usage&&(Te=t.usage.output_tokens??Te,it({kind:"thinking_tokens",tokens:_e+Te}));break}case"result":if(lt(),e.session_id&&(se=e.session_id),e.is_error&&Array.isArray(e.errors)&&e.errors.some(e=>/no conversation found/i.test(String(e)))&&(se||re)&&Ue<3){Ue++;const e=Pe;Pe=!1,se=null,re=null,it({kind:"note",text:"previous session not found — continuing on a fresh one"});const t=ne;ne=I();try{t.end()}catch{}const o=e?ie:null;Be=setTimeout(()=>{Be=null,de||(yt(),null!=o&&(Pe=!0,Ie=Date.now(),Ce=!1,ne.push([{type:"text",text:o},{type:"text",text:le||te(o,{forceFull:!0})}])))},300);break}if(Xe&&("aborted"===e.subtype||"error_during_execution"===e.subtype)){qe===Ze&&(Pe=!1);break}if(e.is_error&&Fe){if($e)break;Fe.failure({message:Array.isArray(e.errors)?e.errors.join(" "):e.result,status:e.status??e.statusCode,code:e.code}),Pe=!1,gt();break}if(_e=0,Te=0,Pe=!1,Re&&(Re=!1,setTimeout(()=>{de||kt()},0)),"success"===e.subtype&&(Ue=0,se&&(re=se)),"success"===e.subtype&&(Fe?.success(),Fe=null),Ke=!1,Qe=!1,e.modelUsage&&"object"==typeof e.modelUsage){let t=null,o=-1;for(const[n,s]of Object.entries(e.modelUsage)){const e=s?.outputTokens??0;e>o&&(o=e,t=n)}t&&(Se=t)}{const t="string"==typeof e.result?e.result.replace(/\s+/g," ").trim().slice(0,200):"";it({kind:"result",subtype:e.subtype,sessionId:se,model:Se,costUsd:e.total_cost_usd,usage:e.usage,numTurns:e.num_turns,durationMs:e.duration_ms??null,denials:Array.isArray(e.permission_denials)?e.permission_denials.length:0,resultText:t||null})}nt&&clearTimeout(nt),"aborted"!==e.subtype&&"worker_completion"!==ae&&(nt=setTimeout(()=>{nt=null,tt||de||ht()},st)),(async()=>{let t=null;try{const e=await(ye?.getContextUsage?.());e&&(t=c({used:e.totalTokens,max:e.maxTokens,pct:Math.round(e.percentage),model:e.model}),e.model&&(Se=e.model))}catch{}const o=e.usage||{};it({kind:"usage",costUsd:e.total_cost_usd??null,tokens:(o.input_tokens||0)+(o.output_tokens||0),ctx:t})})();break;case"prompt_suggestion":nt&&(clearTimeout(nt),nt=null),e.suggestion&&(tt=!0,it({kind:"suggestion",text:e.suggestion}))}}}catch(e){if(lt(),de)return;if(n.signal.aborted)return;const t=e?.message||String(e);if(Fe&&Pe)return Fe.failure({message:t,status:e?.status??e?.statusCode,code:e?.code}),Pe=!1,void gt();if(Pe=!1,it({kind:"error",message:t}),Me.test(t)&&Ue<3){Ue++,Le("stream_reconnect",{failureClass:"network"}),it({kind:"note",text:`connection dropped — reconnecting (${Ue}/3)`});const e=ne;ne=I();try{e.end()}catch{}return void(Be=setTimeout(()=>{Be=null,de||yt()},Math.min(1e3*Ue,4e3)))}if(/no conversation found/i.test(t)&&se&&Ue<3){Ue++,se=null,re=null;const e=ne;ne=I();try{e.end()}catch{}return void(Be=setTimeout(()=>{Be=null,de||yt()},300))}de=!0}finally{oe.signal.removeEventListener("abort",a),Ee===n&&(Ee=null);try{await(ye?.return?.())}catch{}Ne&&(Ne(),Ne=null)}},kt=async()=>{if(de||Ae||!ue)return;const e=Oe,t=ne;if(ne=I(),Ee)try{Ee.abort()}catch{}try{t.end()}catch{}try{await e}catch{}await De(300),se=re,de||Ae||yt()},wt=async e=>{if(de)return;Qe=!0;const t=Pe&&!_(ie)?ie:null;Pe=!1;const o=Oe,n=ne;if(ne=I(),Ee)try{Ee.abort()}catch{}try{n.end()}catch{}try{await o}catch{}await De(300),se=re,de||(yt(),null!=t&&(Pe=!0,Ie=Date.now(),Ce=!1,ne.push(/^\s*\//.test(t)?[{type:"text",text:t}]:[{type:"text",text:t},{type:"text",text:le||te(t,{forceFull:!0})}]),rt({kind:"note",text:"retrying the stalled turn on a fresh connection"})))},gt=()=>{if(de||Ge||$e)return;const e=Fe,t=qe,o=ce;$e=!0;const n=Oe,s=ne;ne=I();try{s.end()}catch{}Be=setTimeout(async()=>{Be=null;try{await n}catch{}if(!de&&$e&&Fe===e&&qe===t)return await dt()?void(!de&&$e&&Fe===e&&qe===t&&($e=!1,Pe=!0,Ie=Date.now(),Ce=!1,yt(),o&&ne.push(o),ct())):($e=!1,void bt())},0)},bt=()=>{lt(),Pe=!1,Fe=null,ue=!1,it({kind:"error",message:"The configured provider could not complete this turn. Nothing else was sent.",recoverable:!0})};return H||We||yt(),{sendTurn(e,n={}){if(de||Ae||Ge||$e)return!1;if(!ue&&!ft())return!1;if(!ue&&Y)try{const e=Y();e&&(t=e,mt.cwd=e)}catch{}Pe=!0,tt=!1,ie=String(e),ae=w(n?.turnCause),nt&&(clearTimeout(nt),nt=null),Ie=Date.now(),Ce=!1,Qe=!1,Ke=!1;const s=String(e),r=Z++,i=ee;if(ee=/^\s*\/(?:compact|clear|reset)\b/i.test(s),le=/^\s*\//.test(s)?null:te(s,{promptIndex:r,forceFull:i,turnCause:ae}),ze=_(s),ce=/^\s*\//.test(s)?[{type:"text",text:s}]:[{type:"text",text:s},{type:"text",text:le}],qe++,Fe=(()=>{if(!We)return null;try{const e=T({runtime:"claude",providers:V.providers||[],providerId:V.providerId,model:V.model||mt.model||o,requestedModel:V.requestedModel||V.model||mt.model||o,policy:V.policy,bridgeHostId:V.bridgeHostId,circuit:V.circuit,capGate:V.capGate,traceId:V.traceId,turnRev:"function"==typeof V.turnRev?V.turnRev():V.turnRev,onRecord:at});return e.start(),e}catch{return null}})(),Fe){const e=Fe,t=qe,o=ce;dt().then(n=>{!de&&Pe&&Fe===e&&qe===t&&(n?(ue||yt({admitted:!0}),ne.push(o),ct()):bt())}).catch(()=>{!de&&Pe&&Fe===e&&qe===t&&bt()})}else ue||yt({admitted:!0}),ne.push(ce)},warm(){We||ue||de||Ae||yt()},get started(){return ue},async setMode(e){M.has(e)&&!de&&(ke=e,pt(e),it({kind:"mode",mode:ke}))},async setModel(e){mt.model=e,Se=e,it({kind:"note",text:`model → ${e}`}),ue&&!de&&(Pe?Re=!0:await kt())},setEffort:async e=>!(!be.has(e)||de||(ve=e,mt.effort=e,it({kind:"effort",level:e}),ue&&(Pe?(Re=!0,0):(await kt(),0)))),async listModels(){try{const e=(await(ye?.supportedModels?.())||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);e.length&&it({kind:"models",models:e}),it({kind:"note",text:e.length?`models: ${e.map(e=>e.value).join(", ")}`:"no model list available"})}catch{it({kind:"note",text:"usage: /model <name>"})}},async park(){if(de||Ae||Pe||Ge||$e||ze)return!1;if(!ue)return!0;Ae=!0;const e=Oe,t=ne;ne=I(),ue=!1,nt&&(clearTimeout(nt),nt=null);try{if(Ee)try{Ee.abort()}catch{}try{t.end()}catch{}try{await e}catch{}return ye=null,re&&(se=re),!de}finally{Ae=!1}},async abort(){if(!Ge){Ge=!0;try{const e=$e,t=e?Oe:null;(Pe||e)&&(qe++,e||($e=!1),lt(),Fe?.failure({aborted:!0}),e&&(clearTimeout(Be),Be=null,ue=!1),Xe=!0,Ze=qe,clearTimeout(et),et=setTimeout(()=>{Xe=!1,Ze=null},6e3));try{await(ye?.interrupt?.())}catch{}if(t)try{await t}catch{}e&&($e=!1),(Pe||e)&&(Pe=!1,it({kind:"result",subtype:"aborted",sessionId:se}))}finally{Ge=!1}}},end(){de=!0,lt(),clearInterval(ut),clearTimeout(et),clearTimeout(Be),nt&&clearTimeout(nt),ne.end();try{oe.abort()}catch{}},get sessionId(){return se},get mode(){return ke},get turnActive(){return Pe}}}
1
+ import{randomUUID as e}from"node:crypto";import{createRequire as t}from"node:module";import{readFileSync as o}from"node:fs";import{dirname as n,join as s}from"node:path";import{query as r}from"@anthropic-ai/claude-agent-sdk";import{sanitizeSession as i}from"./transcript-sanitize.mjs";import{reviewGatePreToolDecision as a}from"./flow-review-gate.mjs";import{crossPostNeedsCard as l}from"./cross-terminal.mjs";import{correctContext as c}from"./context-windows.mjs";import{normalizeClaudeCommandCatalog as d}from"./claude-command-catalog.mjs";import{evidenceForToolResult as u}from"./evidence-citations.mjs";import{THINKPOOL_CASCADE_RULE as p,THINKPOOL_REMOTE_DELIVERY_RULES as m,THINKPOOL_RUNTIME_AUTHORITY_RULE as h,THINKPOOL_RUNTIME_TURN_REMINDER as f,buildThinkPoolTurnGuidance as y,createRoomContextSelector as k,normalizeThinkPoolTurnCause as w,usesFullThinkPoolReminder as g}from"./thinkpool-room-prompt.mjs";import{stallDecision as b,stallEvent as v,isCompactTurn as _}from"./turn-stall.mjs";import{createSameTargetResilienceController as T,formatResilienceTrace as S}from"./provider-resilience.mjs";import{catastrophicPreToolHookDecision as E}from"./catastrophic-command-guard.mjs";const N=t(import.meta.url);export async function claudeOneShot({prompt:e,model:t="claude-haiku-4-5",cwd:o,env:n,timeoutMs:s=8e3}={}){const i=new AbortController,a=setTimeout(()=>{try{i.abort()}catch{}},s);try{const s=r({prompt:e,options:{model:t,...o?{cwd:o}:{},env:n,maxTurns:1,permissionMode:"bypassPermissions",settingSources:[],strictMcpConfig:!0,mcpServers:{},abortController:i}});let a="";for await(const e of s){if("assistant"===e.type)for(const t of e.message?.content||[])"text"===t.type&&(a+=t.text);if("result"===e.type)break}return a.trim()}finally{clearTimeout(a)}}const O=(()=>{try{let e=n(N.resolve("@anthropic-ai/claude-agent-sdk"));for(let t=0;t<8;t++){try{const t=JSON.parse(o(s(e,"package.json"),"utf8"));if("@anthropic-ai/claude-agent-sdk"===t.name)return t.version}catch{}const t=n(e);if(t===e)break;e=t}}catch{}return"unknown"})(),R=/\brm\s+\S|\brmdir\s+\S|\bgit\s+(push\s+(-f|--force)|reset\s+--hard|clean\s+-[a-z]*f)|\bdrop\s+(table|database)\b|\b(mkfs|dd)\b|\bsudo\b|>\s*\/dev\/|\bchmod\s+-R|\bchown\s+-R|\bkillall\b|\btruncate\b/i,A=new Set(["Read","Grep","Glob","NotebookRead","TodoRead","LS"]),D=new Set(["WebFetch","WebSearch"]),x=new Set(["Edit","Write","MultiEdit","NotebookEdit","TodoWrite"]);export function classifyRisk(e,t){if("Bash"===e){const e=t&&(t.command??t.cmd)||"";return R.test(e)?"high":"medium"}return A.has(e)?"low":D.has(e)?"network":(x.has(e),"medium")}const P=/(^|\/)\.claude\/SESSIONS\/|(^|\/)CLAUDE\.md$/;export function isSafeDocWrite(e,t){if(!x.has(e))return!1;const o=t&&(t.file_path||t.notebook_path)||"";return P.test(o)}export function autoAllow({toolName:e,input:t,mode:o="default",alwaysAllow:n=new Set}){const s=classifyRisk(e,t);return"low"===s||"bypassPermissions"===o||"acceptEdits"===o&&x.has(e)&&"high"!==s||isSafeDocWrite(e,t)||n.has(`${e}:${s}`)}export function askUserQuestionHookOutput(e){const t=e&&"object"==typeof e?e.decision:e,o="string"==typeof t&&t.startsWith("answer:")?t.slice(7):"",n=e&&"object"==typeof e?e.responder:null,s="string"==typeof n?.name&&n.name.trim()?n.name.trim():"string"==typeof n?.id&&n.id?`room member ${n.id}`:"The user";return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:o?`${s} answered in the thinkpool room — ${o}. Treat this as their selection and continue; do not call AskUserQuestion again for the same question.`:"The user dismissed the question in the thinkpool room without selecting. Ask in plain prose, or proceed with a sensible default."}}}export function askUserQuestionRegression(e,t){return Array.isArray(e)?e.includes("AskUserQuestion")?null:`[SDK-REGRESSION] agent SDK v${t||"unknown"} init tools[] is missing 'AskUserQuestion' — the multiple-choice question card is disabled. A caret SDK bump likely changed the canUseTool gate; pin a known-good SDK in bridge/package.json + republish.`:null}function I(){const e=[];let t=null,o=!1;return{stream:async function*(){for(;!o;)e.length?yield e.shift():await new Promise(e=>{t=e})}(),push:n=>!o&&(e.push({type:"user",message:{role:"user",content:n}}),t&&(t(),t=null),!0),end(){o=!0,t&&(t(),t=null)}}}const C=(e=[])=>e.map(e=>"text"===e.type?{type:"text",text:e.text}:"thinking"===e.type?{type:"thinking",text:e.thinking||"",reasoningKind:"thought"}:"tool_use"===e.type?{type:"tool_use",id:e.id,name:e.name,input:e.input}:{type:e.type}).filter(Boolean),M=new Set(["default","acceptEdits","plan","bypassPermissions"]),U=["You are Claude in a thinkpool Code room, driven live from a phone or browser — NOT a local terminal. Keep using the room's features.",f,"TERMINAL HIERARCHY: obey your authoritative TERMINAL ROLE. A person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal — NEVER spawn_terminal — even for ordinary work or a handoff. If the wording includes new or separate terminal, main-terminal routing wins. Use spawn_terminal only for agent-decided bounded worker slices or when the person explicitly asks for a worker, sub-terminal, Ensemble lane, or delegated slice. If open_main_terminal is unavailable, say so; never substitute an Ensemble child. Leaf, worker, Side, and managed Flow lanes work directly. Never use built-in invisible Task/Agent subagents or hijack a busy sibling.","WORKTREES: parallel lanes share one repo — before code edits run `git worktree list`; if linked worktrees exist, take your OWN worktree + branch, never the shared checkout or a branch another lane is on.","BUILD WORKFLOW (default, no magic word): right-size within your TERMINAL ROLE — a trivial ask or delegated slice you just do; a conductor-capable role with a genuinely decomposable build FIRST writes a short plan in chat, THEN fans worker slices into visible spawn_terminal lanes and verifies them. Worker/leaf/Side/managed Flow roles do not fan out. A person-requested new or separate terminal uses open_main_terminal. Never plan-mode/ExitPlanMode; plans live in chat and lanes in the existing list."].join(" ");export function startClaudeSession({cwd:t,model:o,effort:n="high",resume:s,env:f,mode:N="default",onEvent:R,requestPermission:A,mcpServers:D,crossPostGate:x,crossRoomPostGate:P,didSpawnTarget:L=null,terminalRolePrompt:W,rolePrompt:F,blockSubagents:j=!1,onSubmitPlan:$=null,onLaneDone:q=null,onReviewVerdict:G=null,reviewGate:B=null,lazy:H=!1,roomContext:K=null,suggest:Q=!0,prepareCwd:Y=null,admitStart:z=null,resilienceObserver:J=null,resilience:V=null}){const X=k(K);let Z=0,ee=!0;const te=(e,{promptIndex:t=0,forceFull:o=!1,turnCause:n=null}={})=>{const s=g({promptIndex:t,forceFull:o,turnCause:n}),r=X({force:s}),i=String(W||"").trim();return`<system-reminder>\n${s&&i?`${i}\n\n`:""}${s?U:y({text:e,promptIndex:t,forceFull:o,turnCause:n})}${r?`\n\n${r}`:""}\n</system-reminder>`},oe=new AbortController;let ne=I(),se=s||null,re=s||null,ie=null,ae=null,le=null,ce=null,de=!1,ue=!1,pe=null,me=!1,he=!1,fe=!1,ye=null,ke=M.has(N)?N:"default";const we=new Set,ge=new Map,be=new Set(["low","medium","high","xhigh","max"]);let ve=be.has(n)?n:"high",_e=0,Te=0,Se=o||null,Ee=null,Ne=null,Oe=Promise.resolve(),Re=!1,Ae=!1;const De=e=>new Promise(t=>setTimeout(t,e)),xe=Math.max(3e4,parseInt(process.env.TP_STALL_MS,10)||9e4);let Pe=!1,Ie=Date.now(),Ce=!1;const Me=/connection closed|connection reset|econnreset|etimedout|socket hang up|fetch failed|network error|socket destroyed/i;let Ue=0;const Le=(e,t={})=>{try{J?.({reason:e,restartCount:Ue,...t})}catch{}},We=!(!V?.policy?.enabled||!V?.providerId||"anthropic"===V.providerId);let Fe=null,je=null,$e=!1,qe=0,Ge=!1,Be=null;const He=Math.max(3*xe,parseInt(process.env.TP_FORCE_STOP_MS,10)||3e5);let Ke=!1,Qe=!1;const Ye=Math.max(He,parseInt(process.env.TP_COMPACT_FORCE_STOP_MS,10)||12e5);let ze=!1,Je=0;const Ve=A;A=async e=>{Je++;try{return await(Ve?.(e))}finally{Je=Math.max(0,Je-1),Ie=Date.now()}};let Xe=!1,Ze=null,et=null,tt=!1,ot="",nt=null;const st=Math.max(1200,parseInt(process.env.TP_SUGGEST_FALLBACK_MS,10)||2500),rt=e=>{try{R?.(e)}catch{}},it=e=>{Ie=Date.now(),e&&"stalled"!==e.kind&&(Ce=!1),!e||"compaction"!==e.kind&&"result"!==e.kind&&"error"!==e.kind||(ze=!1),rt(e)},at=e=>{try{V?.onRecord?.(e)}catch{}"retrying"!==e?.outcome&&"cap_blocked"!==e?.outcome&&"circuit_open"!==e?.outcome||it({kind:"note",text:S(e)})},lt=()=>{if(null!=je){try{(V?.clearTimer||clearTimeout)(je)}catch{}je=null}},ct=()=>{if(lt(),!Fe)return;const e=Number(V?.policy?.timeoutMs);if(!Number.isFinite(e)||e<=0)return;const t=V?.setTimer||setTimeout;je=t(()=>{if(je=null,!de&&Fe&&Pe){Fe.failure({message:"timeout"}),Pe=!1;try{Ee?.abort()}catch{}gt()}},e)},dt=async()=>{if(!Fe)return!0;let e=null;try{e=await Fe.preflight()}catch{return!1}return!0===e?.admitted},ut=setInterval(()=>{const e=Date.now()-Ie,t=b({turnActive:Pe,awaitingUser:Je,quietMs:e,stallMs:xe,forceStopMs:He,stalledSent:Ce,stallRetried:Qe,compacting:ze,compactForceStopMs:Ye});if("none"===t)return;const o=v(t,e);if(o&&rt(o),"status"!==t){if("retry"===t){if(Ke=!0,Fe){Le("resilience_stall",{quietMs:e}),Fe.failure({message:"timeout"}),Pe=!1;try{Ee?.abort()}catch{}return void gt()}return Le("stall_replay",{quietMs:e}),void wt(e)}Ke=!0,Pe=!1}else Ce=!0},5e3);ut.unref?.();const pt=e=>{setTimeout(()=>{Promise.resolve(ye?.setPermissionMode?.(e)).catch(t=>console.error(`[claude-session] setPermissionMode(${e}) failed:`,t?.message||t))},0)},mt={abortController:oe,permissionMode:ke,hooks:{PreToolUse:[{hooks:[async o=>{const n=o.tool_name,s=o.tool_input,r=E({toolName:n,input:s,cwd:t});if(r)return r;const i=o.effort?.level;i&&i!==ve&&(ve=i,it({kind:"effort",level:ve}));const c="Write"===n||"Edit"===n||"MultiEdit"===n||"NotebookEdit"===n;if(j&&c&&/(?:^|[/\\])FLOW_PLAN\.json$/i.test(s?.file_path||s?.notebook_path||"")){const e=s?.content??s?.new_string??"";let t={ok:!1,message:"Plan submission is not wired for this session."};try{t=$&&await $(e)||t}catch(e){t={ok:!1,message:`Plan submission failed: ${e?.message||e}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.message}}}if(j&&("Task"===n||"Agent"===n||"Bash"===n||c))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Bash"===n?"Flow conductors do NOT run Bash — it pops a permission card and stalls the flow. Use the Grep tool (not `grep`/`rg`), the Glob tool (not `find`/`ls`), and Read (not `cat`/`head`) — those run with no prompt. Then DECOMPOSE and submit by Writing your task-graph JSON to the file FLOW_PLAN.json.":c?'Flow conductors do NOT write project or plan-document files. Do NOT use ExitPlanMode and do NOT call submit_flow_plan (both hang here). To SUBMIT your decomposition, use the Write tool with file_path "FLOW_PLAN.json" and content = your task-graph JSON ({"summary":"…","tasks":[…]}). That single Write IS how you submit — the room ingests it directly. Do not write any other file.':"Flow conductors do NOT spawn subagents — it stalls the flow on a permission card. Inspect the codebase yourself with Read/Grep/Glob (no prompt). Then DECOMPOSE and submit by Writing your task-graph JSON to the file FLOW_PLAN.json. Do not call Task/Agent again."}};if(G&&("Write"===n||"Edit"===n)&&/(?:^|[/\\])FLOW_REVIEW(\.[a-zA-Z0-9]+)?$/.test(s?.file_path||"")){let e={ok:!1,message:"verdict signal failed"};try{e=await G(s?.content??s?.new_string??"")||e}catch(t){e={ok:!1,message:`verdict signal failed: ${t?.message||t}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.message}}}if(q&&("Write"===n||"Edit"===n)&&/(?:^|[/\\])FLOW_DONE(\.[a-zA-Z0-9]+)?$/.test(s?.file_path||"")){let e={ok:!1,message:"done signal failed"};try{e=await q(s?.content??s?.new_string??"")||e}catch(t){e={ok:!1,message:`done signal failed: ${t?.message||t}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.message}}}const d=a({reviewGate:B,toolName:n,toolInput:s});if(d)return d;if("mcp__thinkpool__read_terminal"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (read-only thinkpool cross-terminal read)."}};if(/^mcp__thinkpool__preview_(start|capture|inspect|stop)$/.test(n))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (contained bridge-owned viewport preview)."}};if("mcp__thinkpool__submit_flow_plan"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (Flow plan submission — broadcasts the task-graph for human approval)."}};if("mcp__thinkpool__list_sessions"===n||"mcp__thinkpool__read_session"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (read-only thinkpool cross-session read — your own rooms)."}};if("mcp__thinkpool__close_terminal"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (thinkpool cross-terminal close — only self-spawned lanes)."}};if("mcp__thinkpool__spawn_terminal"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (autonomous thinkpool worker; bounded by room caps and isolated in its own worktree)."}};if("mcp__thinkpool__open_main_terminal"===n){const t=s?.mode||ke;if("bypassPermissions"!==t||"bypassPermissions"===ke)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Auto-approved (open a fresh thinkpool terminal in ${t} mode — inherited, no escalation; bounded by room caps).`}};let o="deny";try{o=await(A?.({id:e(),toolName:n,input:{...s,mode:t},risk:"high"}))??"deny"}catch{o="deny"}const r="allow"===o;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:r?"allow":"deny",permissionDecisionReason:r?"Bypass terminal creation approved in the thinkpool room — the new terminal runs autonomously.":"Bypass terminal creation denied in the room — do not retry as bypass; open it without mode:bypassPermissions or ask what to do."}}}if("mcp__thinkpool__post_to_terminal"===n){const t=x?x():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-terminal post not allowed right now."}};const o=!!L&&!!L(s?.terminal);if(!l({mode:ke,spawnedByMe:o}))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"bypassPermissions"===ke?"Auto-approved (cross-terminal post in bypassPermissions mode — bypass means bypass).":"Auto-approved (cross-terminal post into a lane you spawned — parent→child orchestration, no per-post tap)."}};let r="deny";try{r=await(A?.({id:e(),toolName:n,input:s,risk:"high"}))??"deny"}catch{r="deny"}const i="allow"===r;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:i?"allow":"deny",permissionDecisionReason:i?"Cross-terminal post approved in the thinkpool room.":"Cross-terminal post denied in the room — do not retry; ask what to do instead."}}}if("mcp__thinkpool__post_to_session"===n){const t=P?P():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-room post not allowed right now."}};let o="deny";try{o=await(A?.({id:e(),toolName:n,input:s,risk:"high"}))??"deny"}catch{o="deny"}const r="allow"===o;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:r?"allow":"deny",permissionDecisionReason:r?"Cross-room post approved in the sending room — the target room will be asked to accept it.":"Cross-room post denied in the room — do not retry; ask what to do instead."}}}if("ExitPlanMode"===n){if("plan"!==ke)return pt(ke),it({kind:"mode",mode:ke}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`The thinkpool room is in ${ke} mode, not Plan — the user did not ask for a plan. Do NOT call ExitPlanMode; proceed and make the changes directly. Only present a plan if the user switches the room to Plan mode or explicitly asks.`}};let t="keep";try{t=await(A?.({id:e(),toolName:n,input:s,risk:"plan",plan:s?.plan||""}))??"keep"}catch{t="keep"}if("run"===t||"accept"===t){const e="accept"===t?"acceptEdits":"default";return ke=e,pt(e),it({kind:"mode",mode:e}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Plan approved in the thinkpool room — proceed (${e} mode).`}}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:'The user chose "keep planning" in the thinkpool room. Do not exit plan mode — keep refining the plan, then call ExitPlanMode again when ready.'}}}if("AskUserQuestion"===n){let t="";try{t=await(A?.({id:e(),toolName:n,input:s,risk:"ask",questions:s?.questions||[]}))??""}catch{t=""}return askUserQuestionHookOutput(t)}const u=classifyRisk(n,s),p=`${n}:${u}`,m=isSafeDocWrite(n,s),h=autoAllow({toolName:n,input:s,mode:ke,alwaysAllow:we});let f="allow";if(!h){try{f=await(A?.({id:e(),toolName:n,input:s,risk:u}))??"deny"}catch{f="deny"}"always"===f&&(we.add(p),f="allow")}const y="deny"===f;return y&&Fe&&Fe.failure({permissionDenied:!0}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:y?"deny":"allow",permissionDecisionReason:y?"Denied by the user in the thinkpool room. Do not retry this tool — ask what to do instead.":h?m?"Auto-approved (mandated doc write — .claude/SESSIONS/ or CLAUDE.md).":`Auto-approved (${ke}).`:"Approved in the thinkpool room."}}}]}]},canUseTool:async(e,t)=>({behavior:"allow",updatedInput:t}),settingSources:["user","project","local"],appendSystemPrompt:[...W?[W]:[],...F?[F]:[],"ENVIRONMENT (authoritative — overrides any user-global CLAUDE.md or memory that claims otherwise): You are Claude running inside a thinkpool Code room, driven live by a user (and possibly a partner) from a phone or browser, via the thinkpool-pair bridge.",h,'Bias strongly toward DOING the work, not stalling in plan-mode ceremony. For a small "add / fix / change X" request, just make the change directly (for a bigger build, right-size it — see DEFAULT BUILD WORKFLOW below).',"Do NOT enter plan mode, do NOT call ExitPlanMode, and do NOT auto-invoke a brainstorming/planning skill UNLESS the user has switched the room into Plan mode or explicitly asks you to plan, design, or brainstorm first.","Any host-global instruction that says you must always brainstorm or plan before creative work does NOT apply here — this room is the exception.",p,'CRUCIAL RECONCILIATION for that workflow: it is NOT plan mode. Never call ExitPlanMode and never make the room wait behind a "plan ready — approve to start" card — your plan lives in the CHAT as a message, and your lanes live in the room\'s EXISTING terminal/lane list. Reuse only those two surfaces; there is no new Flow panel or mode to switch into, and you must not ask for one. Keep the plan and the lanes VISIBLE — that shared visibility is the whole point (it is the pair differentiator, and it catches bugs a single silent lane would hide); never collapse a decomposable build into one hidden lane just to look tidy.',...m,'CROSS-TERMINAL AWARENESS: ROOM NOW is the default roster and already satisfies the room check when it has enough detail. Do not repeat it with a no-argument read_terminal call unless it is missing or truncated. Use a targeted read_terminal call only when the current task depends on a specific lane’s detailed activity; never poll. Identify a terminal by its exact room-record NAME or stable ref/id. Stored names are static, even when they look ordinal: if a person says T112, resolve that exact name with read_terminal before any positional interpretation. Never guess a terminal from roster order, task topic, product name, or apparent position. Only an unmatched generic UI placeholder like "Terminal 2" is positional and unsafe because it can renumber when another terminal closes. The tool is read-only and its optional roster lookup is budgeted separately from bounded targeted transcript reads.','CROSS-TERMINAL HAND-OFF: you also have post_to_terminal(terminal, text) to send a message or task to ANOTHER AGENT terminal in this room (not a plain shell). Use it sparingly and only when the people clearly want the lanes to coordinate — e.g. "tell the backend terminal the API is ready", or to hand a sibling agent a concrete task. Every post requires a person in the room to approve a card before it is delivered, and an agent that was itself reached via a cross-post cannot post onward — so do not rely on it for chit-chat or loops. Prefer read_terminal to understand a sibling before you ever post to it.',"TERMINAL CREATION CONTRACT: main terminals and workers use different tools. A person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal(name?, task?, model?) — even for ordinary work or a handoff and even without the words Cascade or conductor. If the wording includes new or separate terminal, main-terminal routing wins. Never use spawn_terminal for that request, and if open_main_terminal is unavailable say so instead of substituting. Use spawn_terminal(name?, task?, model?, sliceType?) only for agent-decided bounded WORKER SUB-TERMINALS or when the person explicitly asks for a worker, sub-terminal, Ensemble lane, or delegated slice. Workers never receive the creation tools and never conduct. Do not dump work into busy siblings. Spawned workers are always autonomous in bypassPermissions and never ask the room for an approval card; the bridge still enforces room caps, hop limits, the kill-switch, and isolated linked worktrees. Wait for ROOM NOW or a completion signal instead of polling; after a worker finishes, collect it with one targeted read_terminal call and leave it visible until a person dismisses it with the Ensemble X. Never call close_terminal merely because work finished. Main terminals are independent, keep their requested permission mode, and are not owned/closed through Ensemble.","CROSS-SESSION AWARENESS: the Ensemble reaches across your SESSIONS, not just the terminals in this room. list_sessions() lists your OTHER thinkpool Code rooms — both your own rooms running on this machine AND your partner's rooms in the same pair, reachable over the per-pair bus (a room on the partner's machine shows its host). read_session(session, terminal?) reads recent activity inside one (omit `terminal` to list that room's terminals, or pass a ref/name to read that lane). Both are READ-ONLY — they never change another session, and they reach ONLY your own rooms and rooms you share with your partner, never a stranger's. Reach for them when work spans rooms — \"what's the other project up to\", \"pick up where the other session left off\", or to check a long-running task elsewhere before you act here.","CROSS-SESSION HAND-OFF: post_to_session(session, text, terminal?) sends a task or message to an agent in ANOTHER of your rooms — your own, or your partner's over the pair bus. Use it sparingly and only when the people clearly want the rooms to coordinate — e.g. hand the API room's agent a concrete follow-up once the frontend is ready. It is dual-consent: a person in YOUR room approves sending, and a person in the TARGET room approves receiving, before anything is delivered — so never rely on it for chit-chat or loops, and an agent that was itself reached via a cross-room post cannot post onward to a third room. It spends real model tokens in the other room (maybe on the other person's machine), so prefer read_session to understand a room before you ever post into it, and only post one concrete hand-off at a time. Outbound list/read/post tools need the thinkpool account bridge; a standalone owner room can still receive a paired hand-off directly and will always raise its own approval card before delivery.","SUBAGENT POLICY: in this room, a main terminal delegates worker slices through visible spawn_terminal Ensemble lanes. A person-requested new or separate terminal is created with open_main_terminal, never Ensemble. Worker, leaf, Side, and managed Flow lanes do their assigned work directly. Do NOT reach for built-in Task/Agent subagents: an in-process subagent is invisible to the room, cannot be peered at or steered, and its work is lost to the Ensemble.",'RESEARCH LANE: you have a `research` tool that runs a REAL multi-source web search + adversarial verification and returns each claim marked HELD or REJECTED with citations. Reach for it when the people would genuinely benefit from looking something external up or settling a question of current fact — pricing, "is X still maintained / deprecated", "is that benchmark real", a debate over facts you are not sure of. Do NOT run it unprompted or for things you already know: first OFFER in plain language ("want me to spawn a research lane on that and check it?"), and only call `research(question)` once they agree — it spends real budget (plan-gated Free 5 / Plus 100 runs a month) and takes ~a minute. When it returns, present the held/rejected findings clearly and invite both people to weigh the sources, flagging any held claim that rests on a source they might not trust — that shared scrutiny is the point.',"WORKTREES: parallel lanes share one machine and usually one repo. Run `git worktree list` before your first code edit; if linked worktrees exist, the shared main checkout is contended (and may be guard-blocked) — do your work in your OWN worktree on your OWN branch (`git worktree add <dir> -b <branch>`), and never edit a checkout or ride a branch another lane is using.",'WRITE PLANS INTO THE CHAT: whenever you form or revise a plan — because the room is in Plan mode, or because someone asked you to plan, design, or think it through first — write the actual plan out as a normal message in the room as you develop it: the approach, the concrete steps, the files you will touch, the open questions. The room does NOT surface plan files at all, and the plan-approval card does not reliably carry the plan text, so a plan that lives only in a plan file or only inside ExitPlanMode is INVISIBLE to the people you are working with — they just see "plan ready" with no content. The chat is the canonical place your plan lives; put it there so the room can read and react to it before you proceed.'].join(" "),includePartialMessages:!0,promptSuggestions:!0};"1"===process.env.TP_MCP_STRICT&&(mt.strictMcpConfig=!0,mt.mcpServers={}),D&&Object.keys(D).length&&(mt.mcpServers={...mt.mcpServers||{},...D}),t&&(mt.cwd=t),o&&(mt.model=o),mt.effort=ve,mt.env={...f||process.env,CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION:"1"};const ht=async()=>{if(!Q||"worker_completion"===ae)return;const e=(ot||"").trim().slice(-1500);if(e&&!de)try{let o=await claudeOneShot({prompt:`You are predicting the user's NEXT chat message in a live coding session, to prefill their composer. Given the assistant's latest reply below, output the single most likely next user message — short and natural (often just "proceed", "go with option A", "yes do that", or a brief follow-up). One line, <=12 words, imperative, no preamble, no quotes, no markdown.\n\nAssistant's latest reply:\n"""\n${e}\n"""\n\nNext user message:`,model:"claude-haiku-4-5",cwd:t,env:mt.env,timeoutMs:8e3});o=o.trim().split("\n")[0].replace(/^["'`]+|["'`]+$/g,"").trim().slice(0,140),!o||tt||de||/^(sure|of course|certainly|let me know|i can help|happy to)\b/i.test(o)||(it({kind:"suggestion",text:o,source:"haiku"}),process.stderr.write(` ◆ [suggestion] haiku fallback: ${JSON.stringify(o)}\n`))}catch{}},ft=()=>{const e="function"==typeof z?z():{ok:!0};return!1!==e?.ok||(it({kind:"error",message:e.reason||"Host memory is critically low. This agent runtime was not started.",recoverable:!0}),!1)},yt=async({admitted:e=!1}={})=>{if(Ae)return!1;if(!ue&&!e&&!ft())return!1;if(null==pe&&(pe=Date.now()),ue=!0,Ne)try{Ne()}catch{}Oe=new Promise(e=>{Ne=e});const n=new AbortController;Ee=n;const a=()=>{try{n.abort()}catch{}};oe.signal.addEventListener("abort",a,{once:!0});try{if(se){const e=i(t||process.cwd(),se);e.blocks&&process.stderr.write(`\n ◆ healed ${e.blocks} malformed tool block(s) in the transcript before resume.\n`)}ye=r({prompt:ne.stream,options:{...mt,abortController:n,...se?{resume:se}:{}}});for await(const e of ye){if(de)break;switch(e.type){case"system":if("thinking_tokens"===e.subtype){_e+Te===0&&it({kind:"thinking_tokens",tokens:e.estimated_tokens,delta:e.estimated_tokens_delta});break}if("compact_boundary"===e.subtype){ee=!0,it({kind:"compaction",trigger:e.compact_metadata?.trigger||"auto",preTokens:e.compact_metadata?.pre_tokens??null}),(async()=>{try{const e=await(ye?.getContextUsage?.());e&&(it({kind:"usage",ctx:c({used:e.totalTokens,max:e.maxTokens,pct:Math.round(e.percentage),model:e.model})}),e.model&&(Se=e.model))}catch{}})();break}if(e.session_id&&(se=e.session_id),me||(me=!0,process.stderr.write(`\n ◆ session ready in ${Date.now()-pe}ms — MCP ${"1"===process.env.TP_MCP_STRICT?"OFF":"on"}${s?", resume":", fresh"}.\n`)),Se=mt.model||e.model||o||Se,it({kind:"system",sessionId:se,model:mt.model||e.model||o||null,commands:d({slashCommands:e.slash_commands,skills:e.skills})}),!fe&&Array.isArray(e.tools)){fe=!0;const t=askUserQuestionRegression(e.tools,O);t&&(process.stderr.write(`\n ⚠⚠ ${t}\n`),it({kind:"error",message:t}))}he||(he=!0,Promise.resolve(ye?.supportedModels?.()).then(e=>{const t=(e||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);t.length&&it({kind:"models",models:t})}).catch(()=>{}));break;case"assistant":lt(),Fe?.visibleOutput();for(const t of e.message?.content||[])"tool_use"===t?.type&&t.id&&ge.set(t.id,{at:Date.now(),name:t.name,input:t.input});{const t=(e.message?.content||[]).filter(e=>"text"===e?.type).map(e=>e.text).join("\n").trim();t&&(ot=t)}it({kind:"assistant",blocks:C(e.message?.content),parentToolUseId:e.parent_tool_use_id||null});break;case"user":for(const t of e.message?.content||[])if("tool_result"===t?.type){lt(),Fe?.visibleOutput({tool:!0});const o=ge.get(t.tool_use_id);null!=o&&ge.delete(t.tool_use_id);const n=u(o?.name,t.content);it({kind:"tool_result",toolUseId:t.tool_use_id,content:t.content,...n?{evidence:n}:{},isError:!!t.is_error,durationMs:null!=o?.at?Date.now()-o.at:void 0,parentToolUseId:e.parent_tool_use_id||null})}break;case"stream_event":{const t=e.event;"message_start"===t?.type?(_e+=Te,Te=t.message?.usage?.output_tokens||0,it({kind:"thinking_tokens",tokens:_e+Te})):"message_delta"===t?.type&&t.usage&&(Te=t.usage.output_tokens??Te,it({kind:"thinking_tokens",tokens:_e+Te}));break}case"result":if(lt(),e.session_id&&(se=e.session_id),e.is_error&&Array.isArray(e.errors)&&e.errors.some(e=>/no conversation found/i.test(String(e)))&&(se||re)&&Ue<3){Ue++;const e=Pe;Pe=!1,se=null,re=null,it({kind:"note",text:"previous session not found — continuing on a fresh one"});const t=ne;ne=I();try{t.end()}catch{}const o=e?ie:null;Be=setTimeout(()=>{Be=null,de||(yt(),null!=o&&(Pe=!0,Ie=Date.now(),Ce=!1,ne.push([{type:"text",text:o},{type:"text",text:le||te(o,{forceFull:!0})}])))},300);break}if(Xe&&("aborted"===e.subtype||"error_during_execution"===e.subtype)){qe===Ze&&(Pe=!1);break}if(e.is_error&&Fe){if($e)break;Fe.failure({message:Array.isArray(e.errors)?e.errors.join(" "):e.result,status:e.status??e.statusCode,code:e.code}),Pe=!1,gt();break}if(_e=0,Te=0,Pe=!1,Re&&(Re=!1,setTimeout(()=>{de||kt()},0)),"success"===e.subtype&&(Ue=0,se&&(re=se)),"success"===e.subtype&&(Fe?.success(),Fe=null),Ke=!1,Qe=!1,e.modelUsage&&"object"==typeof e.modelUsage){let t=null,o=-1;for(const[n,s]of Object.entries(e.modelUsage)){const e=s?.outputTokens??0;e>o&&(o=e,t=n)}t&&(Se=t)}{const t="string"==typeof e.result?e.result.replace(/\s+/g," ").trim().slice(0,200):"";it({kind:"result",subtype:e.subtype,sessionId:se,model:Se,costUsd:e.total_cost_usd,usage:e.usage,numTurns:e.num_turns,durationMs:e.duration_ms??null,denials:Array.isArray(e.permission_denials)?e.permission_denials.length:0,resultText:t||null})}nt&&clearTimeout(nt),"aborted"!==e.subtype&&"worker_completion"!==ae&&(nt=setTimeout(()=>{nt=null,tt||de||ht()},st)),(async()=>{let t=null;try{const e=await(ye?.getContextUsage?.());e&&(t=c({used:e.totalTokens,max:e.maxTokens,pct:Math.round(e.percentage),model:e.model}),e.model&&(Se=e.model))}catch{}const o=e.usage||{};it({kind:"usage",costUsd:e.total_cost_usd??null,tokens:(o.input_tokens||0)+(o.output_tokens||0),ctx:t})})();break;case"prompt_suggestion":nt&&(clearTimeout(nt),nt=null),e.suggestion&&(tt=!0,it({kind:"suggestion",text:e.suggestion}))}}}catch(e){if(lt(),de)return;if(n.signal.aborted)return;const t=e?.message||String(e);if(Fe&&Pe)return Fe.failure({message:t,status:e?.status??e?.statusCode,code:e?.code}),Pe=!1,void gt();if(Pe=!1,it({kind:"error",message:t}),Me.test(t)&&Ue<3){Ue++,Le("stream_reconnect",{failureClass:"network"}),it({kind:"note",text:`connection dropped — reconnecting (${Ue}/3)`});const e=ne;ne=I();try{e.end()}catch{}return void(Be=setTimeout(()=>{Be=null,de||yt()},Math.min(1e3*Ue,4e3)))}if(/no conversation found/i.test(t)&&se&&Ue<3){Ue++,se=null,re=null;const e=ne;ne=I();try{e.end()}catch{}return void(Be=setTimeout(()=>{Be=null,de||yt()},300))}de=!0}finally{oe.signal.removeEventListener("abort",a),Ee===n&&(Ee=null);try{await(ye?.return?.())}catch{}Ne&&(Ne(),Ne=null)}},kt=async()=>{if(de||Ae||!ue)return;const e=Oe,t=ne;if(ne=I(),Ee)try{Ee.abort()}catch{}try{t.end()}catch{}try{await e}catch{}await De(300),se=re,de||Ae||yt()},wt=async e=>{if(de)return;Qe=!0;const t=Pe&&!_(ie)?ie:null;Pe=!1;const o=Oe,n=ne;if(ne=I(),Ee)try{Ee.abort()}catch{}try{n.end()}catch{}try{await o}catch{}await De(300),se=re,de||(yt(),null!=t&&(Pe=!0,Ie=Date.now(),Ce=!1,ne.push(/^\s*\//.test(t)?[{type:"text",text:t}]:[{type:"text",text:t},{type:"text",text:le||te(t,{forceFull:!0})}]),rt({kind:"note",text:"retrying the stalled turn on a fresh connection"})))},gt=()=>{if(de||Ge||$e)return;const e=Fe,t=qe,o=ce;$e=!0;const n=Oe,s=ne;ne=I();try{s.end()}catch{}Be=setTimeout(async()=>{Be=null;try{await n}catch{}if(!de&&$e&&Fe===e&&qe===t)return await dt()?void(!de&&$e&&Fe===e&&qe===t&&($e=!1,Pe=!0,Ie=Date.now(),Ce=!1,yt(),o&&ne.push(o),ct())):($e=!1,void bt())},0)},bt=()=>{lt(),Pe=!1,Fe=null,ue=!1,it({kind:"error",message:"The configured provider could not complete this turn. Nothing else was sent.",recoverable:!0})};return H||We||yt(),{sendTurn(e,n={}){if(de||Ae||Ge||$e)return!1;if(!ue&&!ft())return!1;if(!ue&&Y)try{const e=Y();e&&(t=e,mt.cwd=e)}catch{}Pe=!0,tt=!1,ie=String(e),ae=w(n?.turnCause),nt&&(clearTimeout(nt),nt=null),Ie=Date.now(),Ce=!1,Qe=!1,Ke=!1;const s=String(e),r=Z++,i=ee;if(ee=/^\s*\/(?:compact|clear|reset)\b/i.test(s),le=/^\s*\//.test(s)?null:te(s,{promptIndex:r,forceFull:i,turnCause:ae}),ze=_(s),ce=/^\s*\//.test(s)?[{type:"text",text:s}]:[{type:"text",text:s},{type:"text",text:le}],qe++,Fe=(()=>{if(!We)return null;try{const e=T({runtime:"claude",providers:V.providers||[],providerId:V.providerId,model:V.model||mt.model||o,requestedModel:V.requestedModel||V.model||mt.model||o,policy:V.policy,bridgeHostId:V.bridgeHostId,circuit:V.circuit,capGate:V.capGate,traceId:V.traceId,turnRev:"function"==typeof V.turnRev?V.turnRev():V.turnRev,onRecord:at});return e.start(),e}catch{return null}})(),Fe){const e=Fe,t=qe,o=ce;dt().then(n=>{!de&&Pe&&Fe===e&&qe===t&&(n?(ue||yt({admitted:!0}),ne.push(o),ct()):bt())}).catch(()=>{!de&&Pe&&Fe===e&&qe===t&&bt()})}else ue||yt({admitted:!0}),ne.push(ce)},warm(){We||ue||de||Ae||yt()},get started(){return ue},async setMode(e){M.has(e)&&!de&&(ke=e,pt(e),it({kind:"mode",mode:ke}))},async setModel(e){mt.model=e,Se=e,it({kind:"note",text:`model → ${e}`}),ue&&!de&&(Pe?Re=!0:await kt())},setEffort:async e=>!(!be.has(e)||de||(ve=e,mt.effort=e,it({kind:"effort",level:e}),ue&&(Pe?(Re=!0,0):(await kt(),0)))),async listModels(){try{const e=(await(ye?.supportedModels?.())||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);e.length&&it({kind:"models",models:e}),it({kind:"note",text:e.length?`models: ${e.map(e=>e.value).join(", ")}`:"no model list available"})}catch{it({kind:"note",text:"usage: /model <name>"})}},async park(){if(de||Ae||Pe||Ge||$e||ze)return!1;if(!ue)return!0;Ae=!0;const e=Oe,t=ne;ne=I(),ue=!1,nt&&(clearTimeout(nt),nt=null);try{if(Ee)try{Ee.abort()}catch{}try{t.end()}catch{}try{await e}catch{}return ye=null,re&&(se=re),!de}finally{Ae=!1}},async abort(){if(!Ge){Ge=!0;try{const e=$e,t=e?Oe:null;(Pe||e)&&(qe++,e||($e=!1),lt(),Fe?.failure({aborted:!0}),e&&(clearTimeout(Be),Be=null,ue=!1),Xe=!0,Ze=qe,clearTimeout(et),et=setTimeout(()=>{Xe=!1,Ze=null},6e3));try{await(ye?.interrupt?.())}catch{}if(t)try{await t}catch{}e&&($e=!1),(Pe||e)&&(Pe=!1,it({kind:"result",subtype:"aborted",sessionId:se}))}finally{Ge=!1}}},end(){de=!0,lt(),clearInterval(ut),clearTimeout(et),clearTimeout(Be),nt&&clearTimeout(nt),ne.end();try{oe.abort()}catch{}},get sessionId(){return se},get mode(){return ke},get turnActive(){return Pe}}}
@@ -1 +1 @@
1
- const e=e=>new Promise(t=>setTimeout(t,e));export const acceptedRealtimeDelivery=e=>"ok"===e||!0===e?.success;export function createEventDeliveryQueue({send:t,wait:n=e,retryDelay:l=e=>Math.min(1e4,250*2**Math.min(e,6))}={}){if("function"!=typeof t)throw new TypeError("event delivery queue requires send(frame)");const r=[];let i=!1,a=!1,o=Promise.resolve(),s=null;const c=async()=>{if(!i&&!a){i=!0;try{for(;!a&&r.length;){const e=r[0];let i=null;try{i=await t(e.frame)}catch{i=null}acceptedRealtimeDelivery(i)?r.shift():(e.attempt+=1,await n(l(e.attempt)))}}finally{i=!1,!r.length&&s&&(s(),s=null),!a&&r.length&&c()}}};return{enqueue:e=>!a&&(r.length||i||(o=new Promise(e=>{s=e})),r.push({frame:e,attempt:0}),c(),!0),pending:()=>r.length,whenIdle:()=>o,close(){a=!0,r.length=0,s&&(s(),s=null)}}}
1
+ const e=e=>new Promise(t=>setTimeout(t,e));export const acceptedRealtimeDelivery=e=>"ok"===e||!0===e?.success;export function createEventDeliveryQueue({send:t,wait:n=e,retryDelay:r=e=>Math.min(1e4,250*2**Math.min(e,6))}={}){if("function"!=typeof t)throw new TypeError("event delivery queue requires send(frame)");const l=[];let a=!1,c=!1,o=Promise.resolve(),s=null;const i=async()=>{if(!a&&!c){a=!0;try{for(;!c&&l.length;){const e=l[0];let a=null;try{a=await t(e.frame)}catch{a=null}acceptedRealtimeDelivery(a)||!1===e.retry?l.shift():(e.attempt+=1,await n(r(e.attempt)))}}finally{a=!1,!l.length&&s&&(s(),s=null),!c&&l.length&&i()}}};return{enqueue(e,{coalesceKey:t=null,retry:n=!0}={}){if(c)return!1;l.length||a||(o=new Promise(e=>{s=e}));const r=l.length-1;return t&&r>=(a?1:0)&&l[r]?.coalesceKey===t?l[r]={frame:e,attempt:0,coalesceKey:t,retry:n}:l.push({frame:e,attempt:0,coalesceKey:t,retry:n}),i(),!0},pending:()=>l.length,whenIdle:()=>o,close(){c=!0,l.length=0,s&&(s(),s=null)}}}
@@ -451,6 +451,22 @@ acp_adapter.server.HermesACPAgent._register_session_mcp_servers = constrained_re
451
451
  # does not re-run ACP MCP registration, so the new agent can expose only its
452
452
  # built-ins while the request still returns success. Keep the old state until
453
453
  # the replacement has re-registered and passed the same exact policy check.
454
+ #
455
+ # Upstream also runs provider auto-detection after parsing an explicit provider.
456
+ # For model ids shared with OpenRouter, such as moonshotai/kimi-k3, that changes
457
+ # ``nous:moonshotai/kimi-k3`` back to OpenRouter and then fails on profiles that
458
+ # intentionally have no OPENROUTER_API_KEY. This profile permits model switches
459
+ # only through Nous, so make that invariant structural for both explicit and bare
460
+ # ids before set_session_model reconstructs the agent.
461
+ _resolve_model_selection = getattr(acp_adapter.server.HermesACPAgent, "_resolve_model_selection", None)
462
+ if _resolve_model_selection:
463
+ def constrained_resolve_model_selection(raw_model, _current_provider):
464
+ rendered_model_id = str(raw_model or "").strip()
465
+ if rendered_model_id.lower().startswith("nous:"):
466
+ rendered_model_id = rendered_model_id.split(":", 1)[1]
467
+ return "nous", rendered_model_id
468
+ acp_adapter.server.HermesACPAgent._resolve_model_selection = staticmethod(constrained_resolve_model_selection)
469
+
454
470
  _set_model = acp_adapter.server.HermesACPAgent.set_session_model
455
471
  async def constrained_set_model(self, model_id, session_id, **kwargs):
456
472
  rendered_model_id = str(model_id or "").strip().lower()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "thinkpool-pair",
3
- "version": "0.7.408",
3
+ "version": "0.7.410",
4
4
  "description": "Connect Claude Code, Codex, or Hermes on your computer to a thinkpool Code room.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "format": 1,
3
3
  "package": "thinkpool-pair",
4
- "version": "0.7.408",
4
+ "version": "0.7.410",
5
5
  "kind": "minified",
6
6
  "minifiedModules": 135,
7
- "sourceModuleBytes": 1822618,
8
- "artifactModuleBytes": 832691,
7
+ "sourceModuleBytes": 1823895,
8
+ "artifactModuleBytes": 833323,
9
9
  "files": {
10
- "package.json": "3ad56b7420ecfb37a4b4a68c5bb9719af7ab12b22d85a3b43d7428e709683213",
10
+ "package.json": "bdfa38863564574ebf1f26a418a9a665099edb05f345a63fb7b294ed8995a027",
11
11
  "LICENSE": "8a030197ca1cad9669909ca14c9ad15cf48d9fe551da526ccaf1fca993eddb23",
12
- "bridge.mjs": "4041fed2633ada658ab6b44d24161ec48ff16c4eb31e9a45c4dab45c9f1a9ca3",
12
+ "bridge.mjs": "fc565245d649ac58de1cca1ad1d0deaee17cb55be65b05b3b6c2bf4968c1618e",
13
13
  "bridge-service.sh": "b64f27c473ca8f3a49190fd08c23947ab14ca9958d70b6fa53c7bddc2be91403",
14
14
  "command-guidance.mjs": "b9b967b59ff4e77c9613abb0f28858bf3ac5b106a509e471039777b53bec3e29",
15
15
  "abort-turn-barrier.mjs": "3734a5b7e2e940ec6d7fa8b5b04935e1429a23d1bd9e92b2ac2a2ecd9f77c75e",
@@ -25,14 +25,14 @@
25
25
  "byok-detect.mjs": "f31f2ca426737581a97c391b3cecfc75f0207cfa31f51c6bf4a9148309c9625d",
26
26
  "context-contract.mjs": "ffebb435dc5d75c289329bf16ab909df9d634a2b508154c250c6b25906a02a91",
27
27
  "context-windows.mjs": "80af664f84d7e95ef2b0a2a3131090ac4ccd522709448ac9a0d96c378bbec0f7",
28
- "claude-session.mjs": "8992a67c66cb5745f7a72c373ea2bf06f3dcc77a68a3735f21dcbe8968623edc",
28
+ "claude-session.mjs": "858f37d0fa1e5fd4a92a4a6d32c2ec1a9e111f949549d7e81ba66d3226a48f11",
29
29
  "terminal-name.mjs": "f39bb8d1e148ab9a74cbb96438d31e524d6597b8035f00d7a906c28c306c0cf8",
30
30
  "claude-command-catalog.mjs": "36bd4342b2ae94b43a0072533ef2d1648c7473003964bbad433fdb1a8b2bfec1",
31
31
  "codex-session.mjs": "38c84d43680066b1a5f724575a9bade87bd14a8020bad030ec9990f75fdaa3be",
32
32
  "question-response.mjs": "35a7ba53d3eb117717c18004d2a8441f8f37665b231a3c44f4bd9321ff59dd57",
33
33
  "thinkpool-room-prompt.mjs": "b8cc82ccf4262f6431c2047bbff31ac29c47a0d6c68a64640a2c24d94df4a746",
34
34
  "thinkpool-prompt-contracts.mjs": "051602d7d2fe9b34df92957bd3922c5eeebedbcc60c892adf415243887d8c62f",
35
- "thinkpool-capabilities.json": "5cf22e3a779aa0d6fb76c8162c3ffb334fc4a0d20d61e024740fd2467fd21f92",
35
+ "thinkpool-capabilities.json": "9b1637e5d5285076a051a45e3b28e5bbc9dfa8cdd2edaa0c126ebe3f0f60feb7",
36
36
  "codex-app-server.mjs": "d50e30ba6cb2a383c90d89186bc7a13f4caf900c977dd501572468986009470e",
37
37
  "codex-images.mjs": "31605d6d8b3dd6b73395da63d1b0c513445c95ffa2f4306ee466f201d633ffc0",
38
38
  "codex-mcp-http.mjs": "7472543648a9bb575ce20dc3e3270c2da84174c6ea6e9faf87dfaafb95b6212a",
@@ -56,7 +56,7 @@
56
56
  "runtime-compatibility-profile.mjs": "137730baf95d315723872e8df80e66305bccb909e3c6cb81ae753ea9adadac84",
57
57
  "hermes-model-cache.mjs": "aee23efdebe1aa5e10053f291a9153981fe9b45065c293c9519ca73477251e72",
58
58
  "hermes-policy.mjs": "df6dd384ab130b3626045816b6ac4c1d2aecde37fb7b7a4be0c1bffc375fd8ff",
59
- "hermes-acp-bootstrap.py": "9453b48d1ec0057a1d1754fc828acb949ad3f69c687fd055dc3856823d26c19b",
59
+ "hermes-acp-bootstrap.py": "621ea1e0de6a30645d36dd1f40411444fc81c20e7fec6849d342dcf6cb88eeb1",
60
60
  "hermes-event-mapper.mjs": "7c714e15d06d970c4d602e755461bacf8f4d4136a8afc03406e8b3207ff84cdc",
61
61
  "hermes-probe.mjs": "3fc419707f0df9342bc3a5fbfbba2ec2ba1511309dfb1ad8cc79f6f8da4e6b3d",
62
62
  "hermes-setup.mjs": "50840b3e0101dc94aa2cd6dd2456efd8377e30bd5d797a00d360fae28e13dddb",
@@ -87,7 +87,7 @@
87
87
  "event-id.mjs": "09c75e7fc8da282fc00651add58e5d2f82d3020e0c4dddb9921250cf9a6fa8c0",
88
88
  "event-bounds.mjs": "aa8eb8517c4aa81b3378f71401ed39c550cdc80e28e3a57ab46d0a5ef5c7c9c1",
89
89
  "replay-transport.mjs": "f4ed49dc023e3bb2d9534814bc2684121caafe4d24151b87688407eda47c6c7a",
90
- "event-delivery-queue.mjs": "c596e298384e0e4890bccdc07f622e1807d1784e19b65f0ef5b7b1bfea0c41d4",
90
+ "event-delivery-queue.mjs": "9fd955766e5b6ff3209c59bf916f469784061cfee75b50ae519208d135603fff",
91
91
  "mcp-flight-recorder.mjs": "30bf77f4d567f0449856d6da09f7a0a9c8d7e12c5dcaf200dc9e511a331425be",
92
92
  "plan-meters.mjs": "f7f5aeb3d6a3462b754d3724367bbb331643ba58108e29e91b2aca2f613ab499",
93
93
  "recap.mjs": "17bbc73916381cb70758f2605567a21b1c4290c31f94213ab05b23e28d05a3fd",
@@ -1,16 +1,16 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "bundleVersion": 36,
3
+ "bundleVersion": 37,
4
4
  "contracts": [
5
5
  {
6
6
  "id": "room-coordination",
7
- "version": 11,
7
+ "version": 12,
8
8
  "routes": [
9
9
  {
10
10
  "id": "room-awareness",
11
11
  "tools": ["read_terminal"],
12
12
  "trigger": "\\b(other|another|sibling|peer)\\s+(lane|terminal)|\\bread_terminal\\b",
13
- "prompt": "When the request depends on another lane, a sibling may overlap the work, or a person refers to another terminal, use the current ROOM NOW snapshot as the default roster. Do not repeat it with a no-argument read_terminal call unless the snapshot is missing or truncated; that roster lookup has its own one-call allowance. Read only the relevant terminal by ref or name when its detailed transcript is actually needed. Never poll with read_terminal: wait for the room snapshot or completion signal to show a state change, then collect each finished owned worker once. Leave every finished worker visible for review until a person dismisses it with the Ensemble X. Never call close_terminal merely because work finished. Preserve the bounded targeted-read allowance for worker collection and final review."
13
+ "prompt": "When the request depends on another lane, a sibling may overlap the work, or a person refers to another terminal, use the current ROOM NOW snapshot as the default roster. Do not repeat it with a no-argument read_terminal call unless the snapshot is missing or truncated; that roster lookup has its own one-call allowance. Terminal names are static room-record identities. When a person supplies a terminal name, including an ordinal-looking name such as T112, resolve that exact stored name through ROOM NOW or a targeted read_terminal call before interpreting it as a positional label. Never infer a terminal from roster order, task topic, product name, or an apparent UI position. Only an unmatched generic placeholder such as Terminal 2 is positional and unsafe. Read only the relevant terminal by ref or name when its detailed transcript is actually needed. Never poll with read_terminal: wait for the room snapshot or completion signal to show a state change, then collect each finished owned worker once. Leave every finished worker visible for review until a person dismisses it with the Ensemble X. Never call close_terminal merely because work finished. Preserve the bounded targeted-read allowance for worker collection and final review."
14
14
  },
15
15
  {
16
16
  "id": "cross-room-awareness",