thinkpool-pair 0.7.407 → 0.7.409
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/claude-session.mjs +1 -1
- package/codex-session.mjs +1 -1
- package/hermes-acp-bootstrap.py +16 -0
- package/package.json +1 -1
- package/publish-manifest.json +8 -8
- package/thinkpool-capabilities.json +3 -3
package/claude-session.mjs
CHANGED
|
@@ -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}}}
|
package/codex-session.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{execFileSync as e,spawn as t}from"node:child_process";import r from"node:fs";import n from"node:os";import o from"node:path";import s from"node:readline";import{buildCodexAppServerArgs as a,codexAppServerGate as i,createCodexAppServer as l}from"./codex-app-server.mjs";import{CodexEventMapper as u}from"./codex-event-mapper.mjs";import{startCodexMcpHttp as d}from"./codex-mcp-http.mjs";import{CODEX_THINKPOOL_FIRST_TURN_PREAMBLE as c,buildThinkPoolTurnGuidance as p,createRoomContextSelector as m,usesFullThinkPoolReminder as f}from"./thinkpool-room-prompt.mjs";import{questionAnswerResponse as h}from"./question-response.mjs";import{codexReviewTarget as x,isCodexCompactCommand as g}from"./codex-commands.mjs";import{createCumulativeEventRelay as y}from"./cumulative-event-relay.mjs";import{stallDecision as v,stallEvent as b}from"./turn-stall.mjs";import{codexCatastrophicHookCliArgs as w}from"./catastrophic-command-guard.mjs";import{codexNativeReasoningEffort as k,codexReasoningEfforts as _,normalizeCodexReasoningEffort as C,normalizeReasoningEffortList as S}from"./reasoning-effort.mjs";const I=new Set(["read-only","workspace-write","danger-full-access"]);export const CODEX_MODE_CONFIG={default:{sandbox:"workspace-write",approvalPolicy:"untrusted"},acceptEdits:{sandbox:"workspace-write",approvalPolicy:"on-request"},plan:{sandbox:"read-only",approvalPolicy:"never"},review:{sandbox:"read-only",approvalPolicy:"never"},bypassPermissions:{sandbox:"danger-full-access",approvalPolicy:"never"}};export const CODEX_STALL_CONTINUATION_PROMPT=["The previous Codex turn was force-stopped after becoming unresponsive.","Continue the same person-authored task from the current conversation and workspace state.","First inspect the current workspace state and any partial work.","Do not repeat commands, edits, external writes, messages, pushes, deployments, or other actions that may already have completed.","Finish only the remaining work, verify the result, and report any uncertainty."].join(" ");export const CODEX_STALL_RETRY_SUGGESTION="Continue from the current workspace state. Inspect partial work first and do not repeat completed actions.";const M=e=>{const t=String(e?.type||"");return["commandExecution","command_execution","fileChange","file_change","mcpToolCall","mcp_tool_call","webSearch","web_search"].includes(t)};export function codexConfigForMode(e){return CODEX_MODE_CONFIG[e]||CODEX_MODE_CONFIG.default}export function codexDefaultCollaborationMode(e,t){if(!e)return null;const r=k(t);return{mode:"default",settings:{model:String(e),reasoning_effort:r,developer_instructions:null}}}export function defaultModeForRuntime(e){return"codex"===e?"bypassPermissions":"default"}export async function codexOneShot({prompt:e,model:s,timeoutMs:a=22e3,outputSchema:i,cwd:l,tmpDir:u=n.tmpdir(),fsImpl:d=r,spawnImpl:c=t}={}){const p=String(e||"").trim();if(!p)throw new Error("codex one-shot requires a prompt");const m=!l,f=l||d.mkdtempSync(o.join(u,"thinkpool-codex-one-shot-"));let h=null;try{i&&(h=o.join(f,"output-schema.json"),d.writeFileSync(h,`${JSON.stringify(i)}\n`,{mode:384}));const e=["exec","--json","--ephemeral","--ignore-rules","--sandbox","read-only","--skip-git-repo-check","--color","never","-c",'approval_policy="never"',"-c",'model_reasoning_effort="low"',...s?["-m",String(s)]:[],...h?["--output-schema",h]:[],p];return await new Promise((t,r)=>{let n,o,s="",i="",l=!1;const u=(e,n)=>{l||(l=!0,o&&clearTimeout(o),e?r(e):t(n))};try{n=c("codex",e,{cwd:f,env:process.env,stdio:["ignore","pipe","pipe"]})}catch(e){return void u(e)}n.stdout.on("data",e=>{s+=e.toString(),s.length>1e6&&(s=s.slice(-1e6))}),n.stderr.on("data",e=>{i+=e.toString(),i.length>2e3&&(i=i.slice(-2e3))}),n.on("error",e=>u(e)),n.on("close",e=>{if(l)return;const t=s.split(/\r?\n/).filter(Boolean).flatMap(e=>{try{const t=JSON.parse(e);return"item.completed"===t?.type&&"agent_message"===t?.item?.type&&"string"==typeof t.item.text?[t.item.text.trim()]:[]}catch{return[]}}).filter(Boolean).at(-1);0===e&&t?u(null,t):u(new Error(`Codex cleanup failed${null==e?"":` (${e})`}${i.trim()?`: ${i.trim().slice(-240)}`:""}`))}),o=setTimeout(()=>{try{n.kill("SIGTERM")}catch{}u(new Error("Codex cleanup timed out"))},Math.max(1e3,Number(a)||22e3))})}finally{if(m)try{d.rmSync(f,{recursive:!0,force:!0})}catch{}}}export function codexWritableDirsForSandbox(e,t=[]){return"read-only"===normalizeCodexSandbox(e)?[]:t}export function codexExtraWritableDirsForMode(e,t,r=[]){return"review"===e?[]:codexWritableDirsForSandbox(t,r)}export function readCodexDefaultModel({home:e=process.env.CODEX_HOME||o.join(n.homedir(),".codex"),fsImpl:t=r}={}){try{const r=t.readFileSync(o.join(e,"config.toml"),"utf8").split(/^\s*\[/m,1)[0].match(/^\s*model\s*=\s*["']([^"']+)["']\s*(?:#.*)?$/m);return r?.[1]?.trim()||null}catch{return null}}export function readCodexModels({home:e=process.env.CODEX_HOME||o.join(n.homedir(),".codex"),fsImpl:t=r}={}){try{const r=JSON.parse(t.readFileSync(o.join(e,"models_cache.json"),"utf8"));return(Array.isArray(r?.models)?r.models:[]).filter(e=>e?.slug&&"hide"!==e.visibility).sort((e,t)=>(Number(e.priority)||999)-(Number(t.priority)||999)).map(e=>({value:e.slug,displayName:e.display_name||e.slug,description:e.description||"",reasoningEfforts:S(e.supported_reasoning_levels)}))}catch{return[]}}const T=new Map;function E(e,{home:t,fsImpl:r}){if(!e)return null;const n=`${t}\0${e}`,s=T.get(n);if(s)return s;const a=o.join(t,"sessions");try{const t=`${e}.jsonl`,s=r.readdirSync(a,{recursive:!0,withFileTypes:!0}).find(e=>e.isFile()&&e.name.endsWith(t));if(!s)return null;const i=o.join(s.parentPath||s.path||a,s.name);return T.set(n,i),i}catch{return null}}export function codexThreadCanResume(e,{home:t=process.env.CODEX_HOME||o.join(n.homedir(),".codex"),fsImpl:s=r}={}){if(!e)return!1;const a=E(e,{home:t,fsImpl:s});if(!a)return!0;try{return Number(s.statSync(a).size)>0}catch{return!0}}export function readCodexThreadUsage(e,{home:t=process.env.CODEX_HOME||o.join(n.homedir(),".codex"),fsImpl:s=r,tailBytes:a=4194304}={}){const i=E(e,{home:t,fsImpl:s});if(!i)return null;let l;try{const e=Number(s.statSync(i).size)||0,t=Math.min(e,Math.max(65536,a)),r=Buffer.alloc(t);l=s.openSync(i,"r"),s.readSync(l,r,0,t,e-t);const n=r.toString("utf8").split("\n");for(let e=n.length-1;e>=0;e--){let t;try{t=JSON.parse(n[e])}catch{continue}if("token_count"!==t?.payload?.type||!t.payload.info)continue;const r=t.payload.info,o=r.last_token_usage||{},s=r.total_token_usage||{},a=Number(o.total_tokens),i=Number(r.model_context_window);return!Number.isFinite(a)||a<0||!Number.isFinite(i)||i<=0?null:{context:{used:Math.floor(a),max:Math.floor(i)},total:{input_tokens:Math.max(0,Number(s.input_tokens)||0),cached_input_tokens:Math.max(0,Number(s.cached_input_tokens)||0),output_tokens:Math.max(0,Number(s.output_tokens)||0)},rateLimits:t.payload.rate_limits||null}}}catch{return null}finally{if(null!=l)try{s.closeSync(l)}catch{}}return null}export function codexUsageSnapshotFromAppServer(e){const t=Number(e?.last?.totalTokens),r=Number(e?.modelContextWindow);if(!Number.isFinite(t)||t<0||!Number.isFinite(r)||r<=0)return null;const n=e?.total||{};return{context:{used:Math.floor(t),max:Math.floor(r)},total:{input_tokens:Math.max(0,Number(n.inputTokens)||0),cached_input_tokens:Math.max(0,Number(n.cachedInputTokens)||0),output_tokens:Math.max(0,Number(n.outputTokens)||0)},rateLimits:e?.rateLimits||null}}export function normalizeCodexSandbox(e){return I.has(e)?e:"workspace-write"}export function codexPublishAccess({cwd:t,env:r=process.env,tmpdir:s=n.tmpdir(),execFile:a=e}={}){const i=[];try{const e=String(a("git",["rev-parse","--git-common-dir"],{cwd:t,encoding:"utf8"})||"").trim();if(e){const r=o.resolve(t,e),n=o.resolve(t);r===n||r.startsWith(n+o.sep)||i.push(r)}}catch{}return{writableDirs:i,env:{...r,NPM_CONFIG_CACHE:o.join(s,"thinkpool-npm-cache")}}}export const CODEX_ROOM_CASCADE_REMINDER=["thinkpool ROOM ROLE ENFORCEMENT: obey the authoritative TERMINAL ROLE above. A person-authored request for 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. Never claim a Cascade or visible lane started without a successful thinkpool opener result containing its room-visible terminal ref. Internal Codex collaboration workers and hidden in-process subagents are not thinkpool terminals and can never substitute for spawn_terminal or open_main_terminal. If the required opener is unavailable or fails, say that nothing started and report the blocker. Leaf, worker, Side, and managed Flow lanes work directly and must not delegate."].join(" ");export function buildCodexPrompt({text:e,terminalRolePrompt:t,rolePrompt:r,roomContext:n,firstTurn:o=!1,promptIndex:s=0,forceFullReminder:a=!1,turnCause:i=null}){const l="function"==typeof n?n():n,u=f({promptIndex:s,forceFull:a,turnCause:i}),d=[o?c:"",u?t:"",p({text:e,promptIndex:s,forceFull:a,turnCause:i}),u?r||CODEX_ROOM_CASCADE_REMINDER:"",l].map(e=>String(e||"").trim()).filter(Boolean);return d.length?`<thinkpool-context>\n${d.join("\n\n")}\n</thinkpool-context>\n\n${String(e??"")}`:String(e??"")}export function buildCodexExecArgs({sessionId:e,model:t,effort:r,sandbox:n,approvalPolicy:s="untrusted",providerConfig:a,mcpUrl:i,writableDirs:l=[],images:u=[],prompt:d}){const c=normalizeCodexSandbox(n),p=[...w(),...e?["exec","resume","--json","--skip-git-repo-check",..."danger-full-access"===c?["--dangerously-bypass-approvals-and-sandbox"]:["-c",`sandbox_mode="${c}"`]]:["exec","--json","--sandbox",c,"--skip-git-repo-check"]];t&&p.push("-m",t),p.push("-c",`approval_policy="${s}"`);const m=k(r);if(m&&p.push("-c",`model_reasoning_effort="${m}"`),a&&p.push("-c",a),!e)for(const e of l)p.push("--add-dir",e);i&&(p.push("-c",`mcp_servers.thinkpool.url=${JSON.stringify(i)}`),p.push("-c","mcp_servers.thinkpool.required=true"));let f=!1;for(const e of u)o.isAbsolute(String(e||""))&&(p.push("--image",String(e)),f=!0);return f&&p.push("--"),e&&p.push(e),p.push(String(d??"")),p}export function codexExecFailedBeforeTurn({stderr:e="",eventTypes:t=[]}={}){if((Array.isArray(t)?t.map(e=>String(e||"")):[]).some(e=>e&&"thread.started"!==e))return!1;const r=String(e||"");return/timed out handshaking with MCP server/i.test(r)||/thread\/resume failed/i.test(r)&&/failed to initialize session/i.test(r)}const F=/\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;export function codexApprovalCard(e,t={},r=null){const n=String(t.approvalId||t.itemId||`${t.turnId||"turn"}:${e}`);if("item/tool/requestUserInput"===e){const e=Array.isArray(t.questions)?t.questions:[];return{id:n,toolName:"AskUserQuestion",input:{questions:e},risk:"ask",questions:e,asker:"Codex",answerFormat:"codex",...Number.isFinite(t.autoResolutionMs)&&t.autoResolutionMs>0?{autoResolutionMs:t.autoResolutionMs}:{}}}if("item/commandExecution/requestApproval"===e){const e=t.command||r?.command||"";return{id:n,toolName:"Bash",input:{command:e,cwd:t.cwd||r?.cwd||"",...t.reason?{reason:t.reason}:{}},risk:F.test(e)?"high":"medium"}}if("item/fileChange/requestApproval"===e){const e=Array.isArray(r?.changes)?r.changes:[],o=e[0]||{};return{id:n,toolName:e.length>1?"MultiEdit":"add"===o.kind?"Write":"Edit",input:e.length>1?{edits:e.map(e=>({file_path:e.path||"",path:e.path||"",kind:e.kind||"update"})),...t.reason?{reason:t.reason}:{}}:{file_path:o.path||t.grantRoot||"",path:o.path||t.grantRoot||"",kind:o.kind||"update",...t.reason?{reason:t.reason}:{}},risk:"medium"}}return null}export function codexApprovalResponse(e){return{decision:"always"===e?"acceptForSession":"allow"===e?"accept":"decline"}}export function codexUserInputResponse(e,t=[]){return h(e,t)}function N(e){if(!e||"object"!=typeof e)return e;const t={...e};switch(e.type){case"agentMessage":return{...t,type:"agent_message"};case"commandExecution":return{...t,type:"command_execution",aggregated_output:e.aggregatedOutput||"",exit_code:e.exitCode};case"fileChange":return{...t,type:"file_change"};case"webSearch":return{...t,type:"web_search"};case"mcpToolCall":return{...t,type:"mcp_tool_call",arguments:e.arguments||{},result:e.result,error:e.error};case"reasoning":return{...t,type:"reasoning",text:[...e.summary||[],...e.content||[]].join("\n")};default:return t}}export function startCodexSession({cwd:e,model:c,models:p=[],effort:h="high",resume:w,env:S,sandbox:I,mode:T="default",onEvent:E,providerConfig:F,terminalRolePrompt:O,rolePrompt:A,roomContext:R,mcpServers:P,prepareCwd:D=null,requestPermission:U,appServerGate:j=i,appServerFactory:$=l,mcpHttpFactory:q=d,spawnImpl:L=t,admitStart:X=null,stallOptions:G={}}){let z=CODEX_MODE_CONFIG[T]?T:"default",B=codexConfigForMode(z);I=normalizeCodexSandbox(I||B.sandbox);const W=codexPublishAccess({cwd:e,env:{...process.env,...S||{}}}),H=W.env,J=w||null,K=!J||codexThreadCanResume(J,{home:H.CODEX_HOME||o.join(n.homedir(),".codex")});let V=K?J:null,Y=V?1:0,Q=0,Z=!0;const ee=m(R);let te=null,re=!1,ne=!1,oe=!1;const se="function"==typeof G.now?G.now:Date.now,ae="function"==typeof G.setInterval?G.setInterval:setInterval,ie="function"==typeof G.clearInterval?G.clearInterval:clearInterval,le=Number.isFinite(G.stallMs)?Math.max(1,Number(G.stallMs)):Math.max(3e4,parseInt(H.TP_STALL_MS,10)||9e4),ue=Number.isFinite(G.forceStopMs)?Math.max(le,Number(G.forceStopMs)):Math.max(3*le,parseInt(H.TP_FORCE_STOP_MS,10)||3e5),de=Number.isFinite(G.intervalMs)?Math.max(1,Number(G.intervalMs)):5e3;let ce=se(),pe=!1,me=!1,fe=!1,he=!1,xe=!0,ge=0,ye=0,ve=null,be=c||null,we=C(h,{models:p,model:be}),ke=V?readCodexThreadUsage(V):null,_e=null;const Ce=j({env:H});let Se=!Ce.enabled,Ie=null,Me=!1;const Te=new WeakSet;let Ee=null,Fe=null,Ne=!1;const Oe=new Set,Ae=new Map,Re=new Set,Pe=new Map;let De=Promise.resolve(),Ue=Promise.resolve();const je=[],$e=y(e=>{try{E?.(e)}catch{}}),qe=()=>{ce=se(),pe=!1},Le=e=>{qe(),$e(e)};Le.cancel=()=>$e.cancel();const Xe=new u({onEvent:Le,model:c||null,usageSnapshotForSession:e=>{const t=readCodexThreadUsage(e);return t&&(ke=t),t||ke}}),Ge=()=>{const e=[...Pe.values()];Pe.clear();for(const t of e)t.text&&Le({kind:"assistant",blocks:[{type:"text",text:t.text}],parentToolUseId:null,replacesCid:t.cid})},ze=e=>{"turn.completed"!==e?.type&&"turn.failed"!==e?.type||(Ge(),oe=!1),Xe.push(e)},Be=e=>{Ge(),oe=!1,Le(e)},We=({retry:e=!1,recoveryAttempt:t=0}={})=>{oe=!0,ce=se(),pe=!1,fe=!1,he=!1,xe=!0,ge=Math.max(0,Number(t)||0),e||(me=!1)},He=e=>Le({kind:"note",text:e}),Je=(e=Ee)=>{const t=String(e||"");if(t)for(Oe.add(t);Oe.size>64;)Oe.delete(Oe.values().next().value)},Ke=(e={})=>{const t=String(e.turnId||"");return!(!t||ne||re||Oe.has(t)||t!==String(Ee||""))};async function Ve(){const e=P?.thinkpool;return e?(_e||(_e=q({sdkServer:e})),_e):null}function Ye(e,t={}){if("thread/tokenUsage/updated"===e){if(t.threadId&&V&&String(t.threadId)!==String(V))return;const e=codexUsageSnapshotFromAppServer(t.tokenUsage);if(!e)return;if(ke=e,Ne){const{used:t,max:r}=e.context;Le({kind:"usage",ctx:{used:t,max:r,pct:Math.min(100,Math.max(0,Math.round(t/r*100))),over:t>r,model:be}})}return}if("turn/started"===e&&t.turn?.id){const e=String(t.turn.id);if(ne||re)return void Je(e);if(Fe){const t=Fe;return Fe=null,void t.resolve(e)}return Ee||(Ee=e),void qe()}if("turn/plan/updated"!==e&&"item/agentMessage/delta"!==e&&"item/started"!==e&&"item/completed"!==e&&"error"!==e||Ke(t)){if(qe(),"turn/plan/updated"===e){const e=(Array.isArray(t.plan)?t.plan:[]).map(({step:e,status:t})=>({content:e||"",activeForm:e||"",status:"inProgress"===t?"in_progress":"completed"===t?"completed":"pending"})).filter(e=>e.content);return void Le({kind:"assistant",blocks:[{type:"tool_use",id:`codex-plan:${t.turnId||"active"}`,name:"TodoWrite",input:{todos:e}}],parentToolUseId:null})}if("item/agentMessage/delta"===e){if(!t.delta)return;const e=t.itemId||`turn:${t.turnId||Ee||"active"}`,r=Pe.get(e)||{cid:`codex-stream:${V||"thread"}:${e}`,text:""};return r.text+=String(t.delta),Pe.set(e,r),void Le({kind:"assistant_stream",cid:r.cid,text:r.text,itemId:e,streaming:!0})}if("item/started"===e||"item/completed"===e){const r=t.item;if(!r)return;if("item/started"===e&&(Ae.set(r.id,r),r.id&&M(r)&&Re.add(r.id)),"item/completed"===e&&(r.id&&Re.delete(r.id),Ae.set(r.id,r),"agentMessage"===r.type&&Pe.has(r.id))){const e=Pe.get(r.id);return Pe.delete(r.id),void Le({kind:"assistant",blocks:[{type:"text",text:r.text||e.text}],parentToolUseId:null,replacesCid:e.cid})}return void ze({type:"item/started"===e?"item.started":"item.completed",item:N(r)})}if("error"===e){const e=t.error?.message||t.message||"codex app-server error";ze({type:"error",message:e})}}}async function Qe(e,t={}){if(!Ke(t))return"item/tool/requestUserInput"===e?{answers:{}}:{decision:"decline"};const r=codexApprovalCard(e,t,Ae.get(t.itemId));if(!r)throw new Error(`Unsupported Codex App Server request: ${e}`);let n="deny";ye++;try{n=await(U?.(r))}catch{}finally{ye=Math.max(0,ye-1),qe()}return"item/tool/requestUserInput"===e?codexUserInputResponse(n,r.questions):codexApprovalResponse(n)}async function Ze(){if(Se)return!1;if(!1===Ie?.alive)return Me=!1,Se=!0,!1;if(Ie&&Me)return!0;let t;try{t=await Ve()}catch(e){He(`thinkpool peer tools unavailable: ${e?.message||e}`)}try{if(!Ie){const r=$({cwd:e,env:H,args:a({providerConfig:F,mcpUrl:t?.url,writableDirs:codexExtraWritableDirsForMode(z,I,W.writableDirs)}),onNotification:Ye,onServerRequest:Qe,onClose:e=>{ne||Se||Te.has(r)||(Me=!1,Se=!0,He(`Codex App Server closed; later turns will use codex exec: ${e?.message||e}`))}});Ie=r,await Ie.start(),qe()}return V=await Ie.startThread({threadId:Y>0?V:null,cwd:e,model:be,sandbox:I,approvalPolicy:B.approvalPolicy,config:{"features.default_mode_request_user_input":!0}}),qe(),t?.url&&(await Ie.waitForMcpServer({threadId:V,name:"thinkpool"}),qe()),Me=!0,ze({type:"thread.started",thread_id:V}),!0}catch{Se=!0;try{Ie?.end()}catch{}return Ie=null,Me=!1,!1}}function et({force:e=!1}={}){const t=Ie,r=Ee;if(t&&e){Je(r),Se=!0,Me=!1;try{t.end()}catch{}Ie===t&&(Ie=null)}else if(t&&r)Je(r),Promise.resolve(t.interrupt({threadId:V,turnId:r})).catch(()=>{Se=!0,Me=!1;try{t.end()}catch{}Ie===t&&(Ie=null)});else if(t){Se=!0,Me=!1;try{t.end()}catch{}Ie===t&&(Ie=null)}if(te){const e=te;try{e.kill("SIGTERM")}catch{}setTimeout(()=>{if(te===e)try{e.kill("SIGKILL")}catch{}},1500)}}async function tt(e,t={}){if(ne||re||he)return!0;if(!await Ze())return!1;if(ne||re||he)return!0;Xe.setUsageBaseline(V?readCodexThreadUsage(V):null),oe=!0;try{if(xe=!1,Ee=await Ie.startTurn({threadId:V,input:e,images:Array.isArray(t.images)?t.images:[],model:be,effort:k(we),approvalPolicy:B.approvalPolicy,collaborationMode:codexDefaultCollaborationMode(be,we)}),qe(),re||ne){Je(Ee);try{await Ie.interrupt({threadId:V,turnId:Ee})}catch{}return!0}const r=await Ie.waitForTurn(Ee);Je(r?.turn?.id||Ee);const n=r?.turn?.status;re?Be({kind:"result",subtype:"aborted",sessionId:V,model:be,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"interrupted"===n&&(fe||he)||("interrupted"===n?Be({kind:"result",subtype:"aborted",sessionId:V,model:be,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"failed"===n?(fe=!1,ze({type:"turn.failed",message:r?.turn?.error?.message||"codex turn failed"})):(fe=!1,ze({type:"turn.completed"})))}catch(e){Se=!0,Me=!1,Je(Ee);try{Ie?.end()}catch{}Ie=null,ne||fe||he||ze({type:"turn.failed",message:`codex app-server turn failed: ${e?.message||e}`})}finally{Ge(),Ee=null,oe=!1,Re.clear(),Ae.clear(),Pe.clear()}return!0}async function rt(e){if(ne||re||he)return!0;if(!await Ze())return!1;if(ne||re||he)return!0;Xe.setUsageBaseline(V?readCodexThreadUsage(V):null),oe=!0;try{xe=!1;const t=await Ie.startReview({threadId:V,target:x(e)});if(Ee=t?.turn?.id||t?.turnId,!Ee)throw new Error("Codex review/start returned no turn id");if(qe(),re||ne){Je(Ee);try{await Ie.interrupt({threadId:V,turnId:Ee})}catch{}return!0}const r=await Ie.waitForTurn(Ee);Je(r?.turn?.id||Ee);const n=r?.turn?.status;re?Be({kind:"result",subtype:"aborted",sessionId:V,model:be,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"interrupted"===n&&(fe||he)||("interrupted"===n?Be({kind:"result",subtype:"aborted",sessionId:V,model:be,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"failed"===n?(fe=!1,ze({type:"turn.failed",message:r?.turn?.error?.message||"codex review failed"})):(fe=!1,ze({type:"turn.completed"})))}catch(e){Se=!0,Me=!1,Je(Ee);try{Ie?.end()}catch{}Ie=null,ne||fe||he||ze({type:"turn.failed",message:`codex review failed: ${e?.message||e}`})}finally{Ge(),Ee=null,oe=!1,Re.clear(),Ae.clear(),Pe.clear()}return!0}async function nt(t,n={}){if(ne||re||he)return;let o;try{o=await Ve()}catch(e){He(`thinkpool peer tools unavailable: ${e?.message||e}`)}try{await(o?.handoff?.())}catch(e){He(`thinkpool peer handoff failed: ${e?.message||e}`)}const a=buildCodexExecArgs({sessionId:0===Y?null:V,model:be,effort:we,sandbox:I,approvalPolicy:B.approvalPolicy,providerConfig:F,mcpUrl:o?.url,writableDirs:codexExtraWritableDirsForMode(z,I,W.writableDirs),images:Array.isArray(n.images)?n.images:[],prompt:t});return Xe.setUsageBaseline(V?readCodexThreadUsage(V):null),new Promise(t=>{let n;try{n=r.openSync("/dev/null","r")}catch{}const o={cwd:e,env:H,stdio:["ignore","pipe","pipe"]};if(null!=n&&(o.stdio=[n,"pipe","pipe"]),oe=!0,xe=!1,te=L("codex",a,o),null!=n)try{r.closeSync(n)}catch{}const i=[];s.createInterface({input:te.stdout,crlfDelay:1/0}).on("line",e=>{if(!e.trim())return;let t;try{t=JSON.parse(e)}catch{return}i.push(t.type),"item.started"===t.type&&t.item?.id&&M(t.item)&&Re.add(t.item.id),"item.completed"===t.type&&t.item?.id&&Re.delete(t.item.id),"thread.started"===t.type&&t.thread_id&&(V=V||t.thread_id),"turn.completed"!==t.type&&"turn.failed"!==t.type||(u=!0,fe=!1),ze(t)});let l="",u=!1,d=!1;te.stderr.on("data",e=>{l+=e.toString(),l.length>800&&(l=l.slice(-800))}),te.on("error",e=>{d||(d=!0,te=null,Re.clear(),fe||he||Be({kind:"error",message:`codex failed to start: ${e.message}`,recoverable:!0}),t({preTurnInitFailure:!1}))}),te.on("close",e=>{if(d)return;d=!0,te=null,oe=!1,Re.clear();const r=`codex exec exited ${e}${l?": "+l.trim().slice(-300):""}`;0===e||null==e||u||!codexExecFailedBeforeTurn({stderr:l,eventTypes:i})||re||he?((!fe&&!he||u||re)&&(re&&!u?Be({kind:"result",subtype:"aborted",sessionId:V,model:be,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null}):re||u||0===e||null==e||Be({kind:"error",message:r,recoverable:!0})),t({preTurnInitFailure:!1})):t({preTurnInitFailure:!0,message:r})})})}function ot(){if(ne)return;const e=je.shift();e&&(Ue=Ue.then(async()=>{const t=Math.max(0,Number(e.options?._stallRecoveryAttempt)||0);We({recoveryAttempt:t}),t>0&&$e({kind:"active-status",sinceMs:0,message:"recovering the stalled turn from current state"});const r=e.options?.turnCause||null,n=f({promptIndex:e.promptIndex,forceFull:e.forceFullReminder,turnCause:r}),o=buildCodexPrompt({text:e.text,terminalRolePrompt:O,rolePrompt:A,roomContext:()=>ee({force:n}),firstTurn:0===Y,promptIndex:e.promptIndex,forceFullReminder:e.forceFullReminder,turnCause:r}),s=/^\s*\/review(?:\s|$)/i.test(String(e.text||""));let a=!1,i=!1;for(;!ne&&!re&&!he;){if(!(s?await rt(e.text):await tt(o,e.options)))if(s)fe=!1,Be({kind:"error",message:"Codex review is unavailable without the tested App Server runtime.",recoverable:!0});else{fe&&(fe=!1,a=!0,We({retry:!0,recoveryAttempt:t}),$e({kind:"note",text:"retrying the stalled turn on a fresh connection"}));const r=await nt(o,e.options);if(r?.preTurnInitFailure){if(!(i||ne||re||he)){i=!0,We({retry:!0,recoveryAttempt:t}),$e({kind:"note",text:"Codex initialization failed before the turn started; retrying once with a fresh thinkpool connection."});continue}Be({kind:"error",message:r.message,recoverable:!0})}}if(!fe||a||he||ne||re)break;fe=!1,a=!0,We({retry:!0,recoveryAttempt:t}),$e({kind:"note",text:"retrying the stalled turn on a fresh connection"})}Y++,ot()}))}return J&&!K&&queueMicrotask(()=>He("The stopped Codex turn had no resumable context; continuing in a fresh thread.")),["0","false","off"].includes(String(H.TP_CODEX_APP_SERVER||"").trim().toLowerCase())||Ce.enabled||queueMicrotask(()=>He(`Codex App Server disabled: ${Ce.reason}`)),ve=ae(()=>{const e=se()-ce,t=v({turnActive:oe,awaitingUser:ye,quietMs:e,stallMs:le,forceStopMs:ue,stalledSent:pe,stallRetried:me});if("none"===t)return;if("retry"===t&&!xe)return he=!0,fe=!1,ge>0?($e({kind:"error",recoverable:!0,message:"The safe recovery continuation also stopped responding. The original prompt was not replayed again. Switch to another model or provider, then continue from the current workspace state."}),$e({kind:"suggestion",text:CODEX_STALL_RETRY_SUGGESTION})):Re.size>0?$e({kind:"error",recoverable:!0,message:"Codex stopped responding while a tool was still running. The transport was stopped, but no automatic continuation was started because that could overlap an uncertain side effect. Inspect the current state before continuing manually."}):(je.unshift({text:CODEX_STALL_CONTINUATION_PROMPT,options:{_stallRecoveryAttempt:1},promptIndex:Q++,forceFullReminder:!0}),$e({kind:"error",recoverable:!0,message:"Codex stopped responding after the turn began. The transport was stopped. A new continuation turn will inspect the current state; the original prompt was not replayed."})),Be({kind:"result",subtype:"aborted",sessionId:V,model:be,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null}),void et({force:!0});const r=b(t,e);if(r&&$e(r),"status"!==t){if("retry"===t)return me=!0,fe=!0,ce=se(),pe=!1,void et();he=!0,fe=!1,je.length=0,Be({kind:"result",subtype:"aborted",sessionId:V,model:be,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null}),et({force:!0})}else pe=!0},de),ve.unref?.(),{get sessionId(){return V},get usageSnapshot(){return ke},get turnActive(){return oe||Ne},get canSteer(){return!(!Ie||!1===Ie.alive||!Me||Se)},get started(){return oe||Ne||!!te||!(!Ie||!1===Ie.alive)},sendTurn(t,r={}){if(ne)return!1;if(!oe&&0===je.length&&!Me&&!te){const e="function"==typeof X?X():{ok:!0};if(!1===e?.ok)return Le({kind:"error",message:e.reason||"Host memory is critically low. This Codex runtime was not started.",recoverable:!0}),!1}const n=Q++,o=Z;if(Z=g(t)||/^\s*\/(?:reset|clear)\b/i.test(String(t||"")),!oe&&0===Y&&D)try{e=D()||e}catch{}if(oe&&Ie&&Ee){qe();const e=r?.turnCause||null,s=f({promptIndex:n,forceFull:o,turnCause:e}),a=buildCodexPrompt({text:t,terminalRolePrompt:O,rolePrompt:A,roomContext:()=>ee({force:s}),promptIndex:n,forceFullReminder:o,turnCause:e}),i=Ee;return De=De.then(()=>Ie.steer({threadId:V,turnId:i,input:a,images:Array.isArray(r.images)?r.images:[]})).catch(e=>{"rejected"===e?.delivery||"not_sent"===e?.delivery?(je.push({text:t,options:r,promptIndex:n,forceFullReminder:o}),oe||1!==je.length||ot()):Le({kind:"error",message:"Codex steering delivery is uncertain; the message was not replayed automatically.",recoverable:!0})}),!0}return je.push({text:t,options:r,promptIndex:n,forceFullReminder:o}),oe||Ne||(re=!1,We({recoveryAttempt:0})),1!==je.length||Ne||ot(),!0},async park(){if(ne||oe||Ne||je.length)return!1;const e=Ue;try{await e}catch{}try{await De}catch{}if(ne||oe||Ne||je.length||te||Ee)return!1;const t=Ie;if(t){Te.add(t),Ie=null,Me=!1,Ae.clear(),Pe.clear();try{t.end()}catch{return!1}}return!0},abort(){const e=Ue,t=oe&&!Ee&&!te;re=!0,fe=!1,he=!1,je.length=0,Je(Ee);let r=Promise.resolve();if(Ie&&Ee&&(r=Ie.interrupt({threadId:V,turnId:Ee}).catch(()=>{})),te){try{te.kill("SIGTERM")}catch{}setTimeout(()=>{try{te?.kill("SIGKILL")}catch{}},1500)}else t&&Be({kind:"result",subtype:"aborted",sessionId:V,model:be,costUsd:null,usage:null,numTurns:0,durationMs:void 0,denials:0,resultText:null});return r.then(()=>e).catch(()=>e).then(()=>{})},end(){if(ne=!0,oe=!1,ve&&ie(ve),Le.cancel(),je.length=0,Je(Ee),te)try{te.kill()}catch{}try{Ie?.end()}catch{}_e?.then(e=>e.close()).catch(()=>{})},setModel(e){if(!e||oe)return!1;be=String(e),Xe.setModel(be);const t=C(we,{models:p,model:be});return t!==we&&(we=t,Le({kind:"effort",level:we})),!0},setMode:e=>!(oe||!CODEX_MODE_CONFIG[e]||(z=e,B=codexConfigForMode(z),I=B.sandbox,V=null,Y=0,ke=null,Me=!1,0)),setEffort:e=>!(oe||!_({models:p,model:be}).includes(e)||(we=e,Le({kind:"effort",level:we}),0)),clearContext:()=>!oe&&(V=null,Y=0,ke=null,Me=!1,!0),async compactContext(){if(oe||Ne)return!1;re=!1,Ne=!0;let e=null,t=!1;try{if(!await Ze()||oe)return!1;const r=new Promise((t,r)=>{e=setTimeout(()=>{Fe=null,r(new Error("Codex did not start the compaction turn"))},5e3),Fe={resolve:t,reject:r}});await Ie.compact({threadId:V}),t=!0;const n=await r;e&&clearTimeout(e);const o=await Ie.waitForTurn(n);Je(o?.turn?.id||n);const s=o?.turn?.status;if("completed"===s)return!0;throw new Error(o?.turn?.error?.message||`compaction ${s||"failed"}`)}catch(e){return t||!["rejected","not_sent"].includes(e?.delivery)?(He(`Native Codex compaction status is uncertain; existing context was preserved: ${e?.message||e}`),null):(He(`Native Codex compaction unavailable; using bounded recap fallback: ${e?.message||e}`),!1)}finally{e&&clearTimeout(e),Fe=null,Ne=!1,je.length&&ot()}},async accountUsage(){if(!await Ze())return null;const[e,t]=await Promise.all([Ie.accountUsage().catch(()=>null),Ie.accountRateLimits().catch(()=>null)]);return{usage:e,limits:t}}}}
|
|
1
|
+
import{execFileSync as e,spawn as t}from"node:child_process";import r from"node:fs";import n from"node:os";import o from"node:path";import a from"node:readline";import{buildCodexAppServerArgs as s,codexAppServerGate as i,createCodexAppServer as l}from"./codex-app-server.mjs";import{CodexEventMapper as u}from"./codex-event-mapper.mjs";import{startCodexMcpHttp as d}from"./codex-mcp-http.mjs";import{CODEX_THINKPOOL_FIRST_TURN_PREAMBLE as c,buildThinkPoolTurnGuidance as p,createRoomContextSelector as m,usesFullThinkPoolReminder as f}from"./thinkpool-room-prompt.mjs";import{questionAnswerResponse as h}from"./question-response.mjs";import{codexReviewTarget as x,isCodexCompactCommand as g}from"./codex-commands.mjs";import{createCumulativeEventRelay as y}from"./cumulative-event-relay.mjs";import{stallDecision as v,stallEvent as b}from"./turn-stall.mjs";import{codexCatastrophicHookCliArgs as w}from"./catastrophic-command-guard.mjs";import{codexNativeReasoningEffort as k,codexReasoningEfforts as _,normalizeCodexReasoningEffort as S,normalizeReasoningEffortList as C}from"./reasoning-effort.mjs";const I=new Set(["read-only","workspace-write","danger-full-access"]);export const CODEX_MODE_CONFIG={default:{sandbox:"workspace-write",approvalPolicy:"untrusted"},acceptEdits:{sandbox:"workspace-write",approvalPolicy:"on-request"},plan:{sandbox:"read-only",approvalPolicy:"never"},review:{sandbox:"read-only",approvalPolicy:"never"},bypassPermissions:{sandbox:"danger-full-access",approvalPolicy:"never"}};export const CODEX_STALL_CONTINUATION_PROMPT=["The previous Codex turn was force-stopped after becoming unresponsive.","Continue the same person-authored task from the current conversation and workspace state.","First inspect the current workspace state and any partial work.","Do not repeat commands, edits, external writes, messages, pushes, deployments, or other actions that may already have completed.","Finish only the remaining work, verify the result, and report any uncertainty."].join(" ");export const CODEX_STALL_RETRY_SUGGESTION="Continue from the current workspace state. Inspect partial work first and do not repeat completed actions.";const M=e=>{const t=String(e?.type||"");return["commandExecution","command_execution","fileChange","file_change","mcpToolCall","mcp_tool_call","webSearch","web_search"].includes(t)};export function codexConfigForMode(e){return CODEX_MODE_CONFIG[e]||CODEX_MODE_CONFIG.default}export function codexDefaultCollaborationMode(e,t){if(!e)return null;const r=k(t);return{mode:"default",settings:{model:String(e),reasoning_effort:r,developer_instructions:null}}}export function defaultModeForRuntime(e){return"codex"===e?"bypassPermissions":"default"}export async function codexOneShot({prompt:e,model:a,timeoutMs:s=22e3,outputSchema:i,cwd:l,tmpDir:u=n.tmpdir(),fsImpl:d=r,spawnImpl:c=t}={}){const p=String(e||"").trim();if(!p)throw new Error("codex one-shot requires a prompt");const m=!l,f=l||d.mkdtempSync(o.join(u,"thinkpool-codex-one-shot-"));let h=null;try{i&&(h=o.join(f,"output-schema.json"),d.writeFileSync(h,`${JSON.stringify(i)}\n`,{mode:384}));const e=["exec","--json","--ephemeral","--ignore-rules","--sandbox","read-only","--skip-git-repo-check","--color","never","-c",'approval_policy="never"',"-c",'model_reasoning_effort="low"',...a?["-m",String(a)]:[],...h?["--output-schema",h]:[],p];return await new Promise((t,r)=>{let n,o,a="",i="",l=!1;const u=(e,n)=>{l||(l=!0,o&&clearTimeout(o),e?r(e):t(n))};try{n=c("codex",e,{cwd:f,env:process.env,stdio:["ignore","pipe","pipe"]})}catch(e){return void u(e)}n.stdout.on("data",e=>{a+=e.toString(),a.length>1e6&&(a=a.slice(-1e6))}),n.stderr.on("data",e=>{i+=e.toString(),i.length>2e3&&(i=i.slice(-2e3))}),n.on("error",e=>u(e)),n.on("close",e=>{if(l)return;const t=a.split(/\r?\n/).filter(Boolean).flatMap(e=>{try{const t=JSON.parse(e);return"item.completed"===t?.type&&"agent_message"===t?.item?.type&&"string"==typeof t.item.text?[t.item.text.trim()]:[]}catch{return[]}}).filter(Boolean).at(-1);0===e&&t?u(null,t):u(new Error(`Codex cleanup failed${null==e?"":` (${e})`}${i.trim()?`: ${i.trim().slice(-240)}`:""}`))}),o=setTimeout(()=>{try{n.kill("SIGTERM")}catch{}u(new Error("Codex cleanup timed out"))},Math.max(1e3,Number(s)||22e3))})}finally{if(m)try{d.rmSync(f,{recursive:!0,force:!0})}catch{}}}export function codexWritableDirsForSandbox(e,t=[]){return"read-only"===normalizeCodexSandbox(e)?[]:t}export function codexExtraWritableDirsForMode(e,t,r=[]){return"review"===e?[]:codexWritableDirsForSandbox(t,r)}export function readCodexDefaultModel({home:e=process.env.CODEX_HOME||o.join(n.homedir(),".codex"),fsImpl:t=r}={}){try{const r=t.readFileSync(o.join(e,"config.toml"),"utf8").split(/^\s*\[/m,1)[0].match(/^\s*model\s*=\s*["']([^"']+)["']\s*(?:#.*)?$/m);return r?.[1]?.trim()||null}catch{return null}}export function readCodexModels({home:e=process.env.CODEX_HOME||o.join(n.homedir(),".codex"),fsImpl:t=r}={}){try{const r=JSON.parse(t.readFileSync(o.join(e,"models_cache.json"),"utf8"));return(Array.isArray(r?.models)?r.models:[]).filter(e=>e?.slug&&"hide"!==e.visibility).sort((e,t)=>(Number(e.priority)||999)-(Number(t.priority)||999)).map(e=>({value:e.slug,displayName:e.display_name||e.slug,description:e.description||"",reasoningEfforts:C(e.supported_reasoning_levels)}))}catch{return[]}}const T=new Map;function E(e,{home:t,fsImpl:r}){if(!e)return null;const n=`${t}\0${e}`,a=T.get(n);if(a)return a;const s=o.join(t,"sessions");try{const t=`${e}.jsonl`,a=r.readdirSync(s,{recursive:!0,withFileTypes:!0}).find(e=>e.isFile()&&e.name.endsWith(t));if(!a)return null;const i=o.join(a.parentPath||a.path||s,a.name);return T.set(n,i),i}catch{return null}}export function codexThreadCanResume(e,{home:t=process.env.CODEX_HOME||o.join(n.homedir(),".codex"),fsImpl:a=r}={}){if(!e)return!1;const s=E(e,{home:t,fsImpl:a});if(!s)return!0;try{return Number(a.statSync(s).size)>0}catch{return!0}}export function readCodexThreadUsage(e,{home:t=process.env.CODEX_HOME||o.join(n.homedir(),".codex"),fsImpl:a=r,tailBytes:s=4194304}={}){const i=E(e,{home:t,fsImpl:a});if(!i)return null;let l;try{const e=Number(a.statSync(i).size)||0,t=Math.min(e,Math.max(65536,s)),r=Buffer.alloc(t);l=a.openSync(i,"r"),a.readSync(l,r,0,t,e-t);const n=r.toString("utf8").split("\n");for(let e=n.length-1;e>=0;e--){let t;try{t=JSON.parse(n[e])}catch{continue}if("token_count"!==t?.payload?.type||!t.payload.info)continue;const r=t.payload.info,o=r.last_token_usage||{},a=r.total_token_usage||{},s=Number(o.total_tokens),i=Number(r.model_context_window);return!Number.isFinite(s)||s<0||!Number.isFinite(i)||i<=0?null:{context:{used:Math.floor(s),max:Math.floor(i)},total:{input_tokens:Math.max(0,Number(a.input_tokens)||0),cached_input_tokens:Math.max(0,Number(a.cached_input_tokens)||0),output_tokens:Math.max(0,Number(a.output_tokens)||0)},rateLimits:t.payload.rate_limits||null}}}catch{return null}finally{if(null!=l)try{a.closeSync(l)}catch{}}return null}export function codexUsageSnapshotFromAppServer(e){const t=Number(e?.last?.totalTokens),r=Number(e?.modelContextWindow);if(!Number.isFinite(t)||t<0||!Number.isFinite(r)||r<=0)return null;const n=e?.total||{};return{context:{used:Math.floor(t),max:Math.floor(r)},total:{input_tokens:Math.max(0,Number(n.inputTokens)||0),cached_input_tokens:Math.max(0,Number(n.cachedInputTokens)||0),output_tokens:Math.max(0,Number(n.outputTokens)||0)},rateLimits:e?.rateLimits||null}}export function normalizeCodexSandbox(e){return I.has(e)?e:"workspace-write"}export function codexPublishAccess({cwd:t,env:r=process.env,tmpdir:a=n.tmpdir(),execFile:s=e}={}){const i=[];try{const e=String(s("git",["rev-parse","--git-common-dir"],{cwd:t,encoding:"utf8"})||"").trim();if(e){const r=o.resolve(t,e),n=o.resolve(t);r===n||r.startsWith(n+o.sep)||i.push(r)}}catch{}return{writableDirs:i,env:{...r,NPM_CONFIG_CACHE:o.join(a,"thinkpool-npm-cache")}}}export const CODEX_ROOM_CASCADE_REMINDER=["thinkpool ROOM ROLE ENFORCEMENT: obey the authoritative TERMINAL ROLE above. A person-authored request for 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. Never claim a Cascade or visible lane started without a successful thinkpool opener result containing its room-visible terminal ref. Internal Codex collaboration workers and hidden in-process subagents are not thinkpool terminals and can never substitute for spawn_terminal or open_main_terminal. If the required opener is unavailable or fails, say that nothing started and report the blocker. Leaf, worker, Side, and managed Flow lanes work directly and must not delegate."].join(" ");export function buildCodexPrompt({text:e,terminalRolePrompt:t,rolePrompt:r,roomContext:n,firstTurn:o=!1,promptIndex:a=0,forceFullReminder:s=!1,turnCause:i=null}){const l="function"==typeof n?n():n,u=f({promptIndex:a,forceFull:s,turnCause:i}),d=[o?c:"",u?t:"",p({text:e,promptIndex:a,forceFull:s,turnCause:i}),u?r||CODEX_ROOM_CASCADE_REMINDER:"",l].map(e=>String(e||"").trim()).filter(Boolean);return d.length?`<thinkpool-context>\n${d.join("\n\n")}\n</thinkpool-context>\n\n${String(e??"")}`:String(e??"")}export function buildCodexExecArgs({sessionId:e,model:t,effort:r,sandbox:n,approvalPolicy:a="untrusted",providerConfig:s,mcpUrl:i,writableDirs:l=[],images:u=[],prompt:d}){const c=normalizeCodexSandbox(n),p=[...w(),...e?["exec","resume","--json","--skip-git-repo-check",..."danger-full-access"===c?["--dangerously-bypass-approvals-and-sandbox"]:["-c",`sandbox_mode="${c}"`]]:["exec","--json","--sandbox",c,"--skip-git-repo-check"]];t&&p.push("-m",t),p.push("-c",`approval_policy="${a}"`);const m=k(r);if(m&&p.push("-c",`model_reasoning_effort="${m}"`),s&&p.push("-c",s),!e)for(const e of l)p.push("--add-dir",e);i&&(p.push("-c",`mcp_servers.thinkpool.url=${JSON.stringify(i)}`),p.push("-c","mcp_servers.thinkpool.required=true"));let f=!1;for(const e of u)o.isAbsolute(String(e||""))&&(p.push("--image",String(e)),f=!0);return f&&p.push("--"),e&&p.push(e),p.push(String(d??"")),p}export function codexExecFailedBeforeTurn({stderr:e="",eventTypes:t=[]}={}){if((Array.isArray(t)?t.map(e=>String(e||"")):[]).some(e=>e&&"thread.started"!==e))return!1;const r=String(e||"");return/timed out handshaking with MCP server/i.test(r)||/thread\/resume failed/i.test(r)&&/failed to initialize session/i.test(r)}const F=/\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;export function codexApprovalCard(e,t={},r=null){const n=String(t.approvalId||t.itemId||`${t.turnId||"turn"}:${e}`);if("item/tool/requestUserInput"===e){const e=Array.isArray(t.questions)?t.questions:[];return{id:n,toolName:"AskUserQuestion",input:{questions:e},risk:"ask",questions:e,asker:"Codex",answerFormat:"codex",...Number.isFinite(t.autoResolutionMs)&&t.autoResolutionMs>0?{autoResolutionMs:t.autoResolutionMs}:{}}}if("item/commandExecution/requestApproval"===e){const e=t.command||r?.command||"";return{id:n,toolName:"Bash",input:{command:e,cwd:t.cwd||r?.cwd||"",...t.reason?{reason:t.reason}:{}},risk:F.test(e)?"high":"medium"}}if("item/fileChange/requestApproval"===e){const e=Array.isArray(r?.changes)?r.changes:[],o=e[0]||{};return{id:n,toolName:e.length>1?"MultiEdit":"add"===o.kind?"Write":"Edit",input:e.length>1?{edits:e.map(e=>({file_path:e.path||"",path:e.path||"",kind:e.kind||"update"})),...t.reason?{reason:t.reason}:{}}:{file_path:o.path||t.grantRoot||"",path:o.path||t.grantRoot||"",kind:o.kind||"update",...t.reason?{reason:t.reason}:{}},risk:"medium"}}return null}export function codexApprovalResponse(e){return{decision:"always"===e?"acceptForSession":"allow"===e?"accept":"decline"}}export function codexUserInputResponse(e,t=[]){return h(e,t)}function N(e){if(!e||"object"!=typeof e)return e;const t={...e};switch(e.type){case"agentMessage":return{...t,type:"agent_message"};case"commandExecution":return{...t,type:"command_execution",aggregated_output:e.aggregatedOutput||"",exit_code:e.exitCode};case"fileChange":return{...t,type:"file_change"};case"webSearch":return{...t,type:"web_search"};case"mcpToolCall":return{...t,type:"mcp_tool_call",arguments:e.arguments||{},result:e.result,error:e.error};case"reasoning":return{...t,type:"reasoning",text:[...e.summary||[],...e.content||[]].join("\n")};default:return t}}export function startCodexSession({cwd:e,model:c,models:p=[],effort:h="high",resume:w,env:C,sandbox:I,mode:T="default",onEvent:E,providerConfig:F,terminalRolePrompt:O,rolePrompt:A,roomContext:R,mcpServers:P,prepareCwd:D=null,requestPermission:U,appServerGate:j=i,appServerFactory:$=l,mcpHttpFactory:L=d,spawnImpl:q=t,admitStart:G=null,stallOptions:X={}}){let z=CODEX_MODE_CONFIG[T]?T:"default",B=codexConfigForMode(z);I=normalizeCodexSandbox(I||B.sandbox);const W=codexPublishAccess({cwd:e,env:{...process.env,...C||{}}}),H=W.env,J=w||null,K=!J||codexThreadCanResume(J,{home:H.CODEX_HOME||o.join(n.homedir(),".codex")});let V=K?J:null,Y=V?1:0,Q=0,Z=!0;const ee=m(R);let te=null,re=!1,ne=!1,oe=!1;const ae="function"==typeof X.now?X.now:Date.now,se="function"==typeof X.setInterval?X.setInterval:setInterval,ie="function"==typeof X.clearInterval?X.clearInterval:clearInterval,le=Number.isFinite(X.stallMs)?Math.max(1,Number(X.stallMs)):Math.max(3e4,parseInt(H.TP_STALL_MS,10)||9e4),ue=Number.isFinite(X.forceStopMs)?Math.max(le,Number(X.forceStopMs)):Math.max(3*le,parseInt(H.TP_FORCE_STOP_MS,10)||3e5),de=Number.isFinite(X.longReasoningForceStopMs)?Math.max(ue,Number(X.longReasoningForceStopMs)):Math.max(ue,parseInt(H.TP_LONG_REASONING_FORCE_STOP_MS,10)||12e5),ce=Number.isFinite(X.intervalMs)?Math.max(1,Number(X.intervalMs)):5e3;let pe=ae(),me=!1,fe=!1,he=!1,xe=!1,ge=!0,ye=0,ve=0,be=null,we=c||null,ke=S(h,{models:p,model:we}),_e=V?readCodexThreadUsage(V):null,Se=null;const Ce=j({env:H});let Ie=!Ce.enabled,Me=null,Te=!1;const Ee=new WeakSet;let Fe=null,Ne=null,Oe=!1;const Ae=new Set,Re=new Map,Pe=new Set,De=new Map;let Ue=Promise.resolve(),je=Promise.resolve();const $e=[],Le=y(e=>{try{E?.(e)}catch{}}),qe=()=>{pe=ae(),me=!1},Ge=e=>{qe(),Le(e)};Ge.cancel=()=>Le.cancel();const Xe=new u({onEvent:Ge,model:c||null,usageSnapshotForSession:e=>{const t=readCodexThreadUsage(e);return t&&(_e=t),t||_e}}),ze=()=>{const e=[...De.values()];De.clear();for(const t of e)t.text&&Ge({kind:"assistant",blocks:[{type:"text",text:t.text}],parentToolUseId:null,replacesCid:t.cid})},Be=e=>{"turn.completed"!==e?.type&&"turn.failed"!==e?.type||(ze(),oe=!1),Xe.push(e)},We=e=>{ze(),oe=!1,Ge(e)},He=({retry:e=!1,recoveryAttempt:t=0}={})=>{oe=!0,pe=ae(),me=!1,he=!1,xe=!1,ge=!0,ye=Math.max(0,Number(t)||0),e||(fe=!1)},Je=e=>Ge({kind:"note",text:e}),Ke=(e=Fe)=>{const t=String(e||"");if(t)for(Ae.add(t);Ae.size>64;)Ae.delete(Ae.values().next().value)},Ve=(e={})=>{const t=String(e.turnId||"");return!(!t||ne||re||Ae.has(t)||t!==String(Fe||""))};async function Ye(){const e=P?.thinkpool;return e?(Se||(Se=L({sdkServer:e})),Se):null}function Qe(e,t={}){if("thread/tokenUsage/updated"===e){if(t.threadId&&V&&String(t.threadId)!==String(V))return;(oe||Oe)&&qe();const e=codexUsageSnapshotFromAppServer(t.tokenUsage);if(!e)return;if(_e=e,Oe){const{used:t,max:r}=e.context;Ge({kind:"usage",ctx:{used:t,max:r,pct:Math.min(100,Math.max(0,Math.round(t/r*100))),over:t>r,model:we}})}return}if("turn/started"===e&&t.turn?.id){const e=String(t.turn.id);if(ne||re)return void Ke(e);if(Ne){const t=Ne;return Ne=null,void t.resolve(e)}return Fe||(Fe=e),void qe()}if("turn/plan/updated"!==e&&"item/agentMessage/delta"!==e&&"item/started"!==e&&"item/completed"!==e&&"error"!==e||Ve(t)){if(qe(),"turn/plan/updated"===e){const e=(Array.isArray(t.plan)?t.plan:[]).map(({step:e,status:t})=>({content:e||"",activeForm:e||"",status:"inProgress"===t?"in_progress":"completed"===t?"completed":"pending"})).filter(e=>e.content);return void Ge({kind:"assistant",blocks:[{type:"tool_use",id:`codex-plan:${t.turnId||"active"}`,name:"TodoWrite",input:{todos:e}}],parentToolUseId:null})}if("item/agentMessage/delta"===e){if(!t.delta)return;const e=t.itemId||`turn:${t.turnId||Fe||"active"}`,r=De.get(e)||{cid:`codex-stream:${V||"thread"}:${e}`,text:""};return r.text+=String(t.delta),De.set(e,r),void Ge({kind:"assistant_stream",cid:r.cid,text:r.text,itemId:e,streaming:!0})}if("item/started"===e||"item/completed"===e){const r=t.item;if(!r)return;if("item/started"===e&&(Re.set(r.id,r),r.id&&M(r)&&Pe.add(r.id)),"item/completed"===e&&(r.id&&Pe.delete(r.id),Re.set(r.id,r),"agentMessage"===r.type&&De.has(r.id))){const e=De.get(r.id);return De.delete(r.id),void Ge({kind:"assistant",blocks:[{type:"text",text:r.text||e.text}],parentToolUseId:null,replacesCid:e.cid})}return void Be({type:"item/started"===e?"item.started":"item.completed",item:N(r)})}if("error"===e){const e=t.error?.message||t.message||"codex app-server error";Be({type:"error",message:e})}}}async function Ze(e,t={}){if(!Ve(t))return"item/tool/requestUserInput"===e?{answers:{}}:{decision:"decline"};const r=codexApprovalCard(e,t,Re.get(t.itemId));if(!r)throw new Error(`Unsupported Codex App Server request: ${e}`);let n="deny";ve++;try{n=await(U?.(r))}catch{}finally{ve=Math.max(0,ve-1),qe()}return"item/tool/requestUserInput"===e?codexUserInputResponse(n,r.questions):codexApprovalResponse(n)}async function et(){if(Ie)return!1;if(!1===Me?.alive)return Te=!1,Ie=!0,!1;if(Me&&Te)return!0;let t;try{t=await Ye()}catch(e){Je(`thinkpool peer tools unavailable: ${e?.message||e}`)}try{if(!Me){const r=$({cwd:e,env:H,args:s({providerConfig:F,mcpUrl:t?.url,writableDirs:codexExtraWritableDirsForMode(z,I,W.writableDirs)}),onNotification:Qe,onServerRequest:Ze,onClose:e=>{ne||Ie||Ee.has(r)||(Te=!1,Ie=!0,Je(`Codex App Server closed; later turns will use codex exec: ${e?.message||e}`))}});Me=r,await Me.start(),qe()}return V=await Me.startThread({threadId:Y>0?V:null,cwd:e,model:we,sandbox:I,approvalPolicy:B.approvalPolicy,config:{"features.default_mode_request_user_input":!0}}),qe(),t?.url&&(await Me.waitForMcpServer({threadId:V,name:"thinkpool"}),qe()),Te=!0,Be({type:"thread.started",thread_id:V}),!0}catch{Ie=!0;try{Me?.end()}catch{}return Me=null,Te=!1,!1}}function tt({force:e=!1}={}){const t=Me,r=Fe;if(t&&e){Ke(r),Ie=!0,Te=!1;try{t.end()}catch{}Me===t&&(Me=null)}else if(t&&r)Ke(r),Promise.resolve(t.interrupt({threadId:V,turnId:r})).catch(()=>{Ie=!0,Te=!1;try{t.end()}catch{}Me===t&&(Me=null)});else if(t){Ie=!0,Te=!1;try{t.end()}catch{}Me===t&&(Me=null)}if(te){const e=te;try{e.kill("SIGTERM")}catch{}setTimeout(()=>{if(te===e)try{e.kill("SIGKILL")}catch{}},1500)}}async function rt(e,t={}){if(ne||re||xe)return!0;if(!await et())return!1;if(ne||re||xe)return!0;Xe.setUsageBaseline(V?readCodexThreadUsage(V):null),oe=!0;try{if(ge=!1,Fe=await Me.startTurn({threadId:V,input:e,images:Array.isArray(t.images)?t.images:[],model:we,effort:k(ke),approvalPolicy:B.approvalPolicy,collaborationMode:codexDefaultCollaborationMode(we,ke)}),qe(),re||ne){Ke(Fe);try{await Me.interrupt({threadId:V,turnId:Fe})}catch{}return!0}const r=await Me.waitForTurn(Fe);Ke(r?.turn?.id||Fe);const n=r?.turn?.status;re?We({kind:"result",subtype:"aborted",sessionId:V,model:we,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"interrupted"===n&&(he||xe)||("interrupted"===n?We({kind:"result",subtype:"aborted",sessionId:V,model:we,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"failed"===n?(he=!1,Be({type:"turn.failed",message:r?.turn?.error?.message||"codex turn failed"})):(he=!1,Be({type:"turn.completed"})))}catch(e){Ie=!0,Te=!1,Ke(Fe);try{Me?.end()}catch{}Me=null,ne||he||xe||Be({type:"turn.failed",message:`codex app-server turn failed: ${e?.message||e}`})}finally{ze(),Fe=null,oe=!1,Pe.clear(),Re.clear(),De.clear()}return!0}async function nt(e){if(ne||re||xe)return!0;if(!await et())return!1;if(ne||re||xe)return!0;Xe.setUsageBaseline(V?readCodexThreadUsage(V):null),oe=!0;try{ge=!1;const t=await Me.startReview({threadId:V,target:x(e)});if(Fe=t?.turn?.id||t?.turnId,!Fe)throw new Error("Codex review/start returned no turn id");if(qe(),re||ne){Ke(Fe);try{await Me.interrupt({threadId:V,turnId:Fe})}catch{}return!0}const r=await Me.waitForTurn(Fe);Ke(r?.turn?.id||Fe);const n=r?.turn?.status;re?We({kind:"result",subtype:"aborted",sessionId:V,model:we,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"interrupted"===n&&(he||xe)||("interrupted"===n?We({kind:"result",subtype:"aborted",sessionId:V,model:we,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"failed"===n?(he=!1,Be({type:"turn.failed",message:r?.turn?.error?.message||"codex review failed"})):(he=!1,Be({type:"turn.completed"})))}catch(e){Ie=!0,Te=!1,Ke(Fe);try{Me?.end()}catch{}Me=null,ne||he||xe||Be({type:"turn.failed",message:`codex review failed: ${e?.message||e}`})}finally{ze(),Fe=null,oe=!1,Pe.clear(),Re.clear(),De.clear()}return!0}async function ot(t,n={}){if(ne||re||xe)return;let o;try{o=await Ye()}catch(e){Je(`thinkpool peer tools unavailable: ${e?.message||e}`)}try{await(o?.handoff?.())}catch(e){Je(`thinkpool peer handoff failed: ${e?.message||e}`)}const s=buildCodexExecArgs({sessionId:0===Y?null:V,model:we,effort:ke,sandbox:I,approvalPolicy:B.approvalPolicy,providerConfig:F,mcpUrl:o?.url,writableDirs:codexExtraWritableDirsForMode(z,I,W.writableDirs),images:Array.isArray(n.images)?n.images:[],prompt:t});return Xe.setUsageBaseline(V?readCodexThreadUsage(V):null),new Promise(t=>{let n;try{n=r.openSync("/dev/null","r")}catch{}const o={cwd:e,env:H,stdio:["ignore","pipe","pipe"]};if(null!=n&&(o.stdio=[n,"pipe","pipe"]),oe=!0,ge=!1,te=q("codex",s,o),null!=n)try{r.closeSync(n)}catch{}const i=[];a.createInterface({input:te.stdout,crlfDelay:1/0}).on("line",e=>{if(!e.trim())return;let t;try{t=JSON.parse(e)}catch{return}qe(),i.push(t.type),"item.started"===t.type&&t.item?.id&&M(t.item)&&Pe.add(t.item.id),"item.completed"===t.type&&t.item?.id&&Pe.delete(t.item.id),"thread.started"===t.type&&t.thread_id&&(V=V||t.thread_id),"turn.completed"!==t.type&&"turn.failed"!==t.type||(u=!0,he=!1),Be(t)});let l="",u=!1,d=!1;te.stderr.on("data",e=>{l+=e.toString(),l.length>800&&(l=l.slice(-800))}),te.on("error",e=>{d||(d=!0,te=null,Pe.clear(),he||xe||We({kind:"error",message:`codex failed to start: ${e.message}`,recoverable:!0}),t({preTurnInitFailure:!1}))}),te.on("close",e=>{if(d)return;d=!0,te=null,oe=!1,Pe.clear();const r=`codex exec exited ${e}${l?": "+l.trim().slice(-300):""}`;0===e||null==e||u||!codexExecFailedBeforeTurn({stderr:l,eventTypes:i})||re||xe?((!he&&!xe||u||re)&&(re&&!u?We({kind:"result",subtype:"aborted",sessionId:V,model:we,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null}):re||u||0===e||null==e||We({kind:"error",message:r,recoverable:!0})),t({preTurnInitFailure:!1})):t({preTurnInitFailure:!0,message:r})})})}function at(){if(ne)return;const e=$e.shift();e&&(je=je.then(async()=>{const t=Math.max(0,Number(e.options?._stallRecoveryAttempt)||0);He({recoveryAttempt:t}),t>0&&Le({kind:"active-status",sinceMs:0,message:"recovering the stalled turn from current state"});const r=e.options?.turnCause||null,n=f({promptIndex:e.promptIndex,forceFull:e.forceFullReminder,turnCause:r}),o=buildCodexPrompt({text:e.text,terminalRolePrompt:O,rolePrompt:A,roomContext:()=>ee({force:n}),firstTurn:0===Y,promptIndex:e.promptIndex,forceFullReminder:e.forceFullReminder,turnCause:r}),a=/^\s*\/review(?:\s|$)/i.test(String(e.text||""));let s=!1,i=!1;for(;!ne&&!re&&!xe;){if(!(a?await nt(e.text):await rt(o,e.options)))if(a)he=!1,We({kind:"error",message:"Codex review is unavailable without the tested App Server runtime.",recoverable:!0});else{he&&(he=!1,s=!0,He({retry:!0,recoveryAttempt:t}),Le({kind:"note",text:"retrying the stalled turn on a fresh connection"}));const r=await ot(o,e.options);if(r?.preTurnInitFailure){if(!(i||ne||re||xe)){i=!0,He({retry:!0,recoveryAttempt:t}),Le({kind:"note",text:"Codex initialization failed before the turn started; retrying once with a fresh thinkpool connection."});continue}We({kind:"error",message:r.message,recoverable:!0})}}if(!he||s||xe||ne||re)break;he=!1,s=!0,He({retry:!0,recoveryAttempt:t}),Le({kind:"note",text:"retrying the stalled turn on a fresh connection"})}Y++,at()}))}return J&&!K&&queueMicrotask(()=>Je("The stopped Codex turn had no resumable context; continuing in a fresh thread.")),["0","false","off"].includes(String(H.TP_CODEX_APP_SERVER||"").trim().toLowerCase())||Ce.enabled||queueMicrotask(()=>Je(`Codex App Server disabled: ${Ce.reason}`)),be=se(()=>{const e=ae()-pe,t=v({turnActive:oe,awaitingUser:ve,quietMs:e,stallMs:le,forceStopMs:["max","ultra"].includes(ke)?de:ue,stalledSent:me,stallRetried:fe});if("none"===t)return;if("retry"===t&&!ge)return xe=!0,he=!1,ye>0?(Le({kind:"error",recoverable:!0,message:"The safe recovery continuation also stopped responding. The original prompt was not replayed again. Switch to another model or provider, then continue from the current workspace state."}),Le({kind:"suggestion",text:CODEX_STALL_RETRY_SUGGESTION})):Pe.size>0?Le({kind:"error",recoverable:!0,message:"Codex stopped responding while a tool was still running. The transport was stopped, but no automatic continuation was started because that could overlap an uncertain side effect. Inspect the current state before continuing manually."}):($e.unshift({text:CODEX_STALL_CONTINUATION_PROMPT,options:{_stallRecoveryAttempt:1},promptIndex:Q++,forceFullReminder:!0}),Le({kind:"error",recoverable:!0,message:"Codex stopped responding after the turn began. The transport was stopped. A new continuation turn will inspect the current state; the original prompt was not replayed."})),We({kind:"result",subtype:"aborted",sessionId:V,model:we,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null}),void tt({force:!0});const r=b(t,e);if(r&&Le(r),"status"!==t){if("retry"===t)return fe=!0,he=!0,pe=ae(),me=!1,void tt();xe=!0,he=!1,$e.length=0,We({kind:"result",subtype:"aborted",sessionId:V,model:we,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null}),tt({force:!0})}else me=!0},ce),be.unref?.(),{get sessionId(){return V},get usageSnapshot(){return _e},get turnActive(){return oe||Oe},get canSteer(){return!(!Me||!1===Me.alive||!Te||Ie)},get started(){return oe||Oe||!!te||!(!Me||!1===Me.alive)},sendTurn(t,r={}){if(ne)return!1;if(!oe&&0===$e.length&&!Te&&!te){const e="function"==typeof G?G():{ok:!0};if(!1===e?.ok)return Ge({kind:"error",message:e.reason||"Host memory is critically low. This Codex runtime was not started.",recoverable:!0}),!1}const n=Q++,o=Z;if(Z=g(t)||/^\s*\/(?:reset|clear)\b/i.test(String(t||"")),!oe&&0===Y&&D)try{e=D()||e}catch{}if(oe&&Me&&Fe){qe();const e=r?.turnCause||null,a=f({promptIndex:n,forceFull:o,turnCause:e}),s=buildCodexPrompt({text:t,terminalRolePrompt:O,rolePrompt:A,roomContext:()=>ee({force:a}),promptIndex:n,forceFullReminder:o,turnCause:e}),i=Fe;return Ue=Ue.then(()=>Me.steer({threadId:V,turnId:i,input:s,images:Array.isArray(r.images)?r.images:[]})).catch(e=>{"rejected"===e?.delivery||"not_sent"===e?.delivery?($e.push({text:t,options:r,promptIndex:n,forceFullReminder:o}),oe||1!==$e.length||at()):Ge({kind:"error",message:"Codex steering delivery is uncertain; the message was not replayed automatically.",recoverable:!0})}),!0}return $e.push({text:t,options:r,promptIndex:n,forceFullReminder:o}),oe||Oe||(re=!1,He({recoveryAttempt:0})),1!==$e.length||Oe||at(),!0},async park(){if(ne||oe||Oe||$e.length)return!1;const e=je;try{await e}catch{}try{await Ue}catch{}if(ne||oe||Oe||$e.length||te||Fe)return!1;const t=Me;if(t){Ee.add(t),Me=null,Te=!1,Re.clear(),De.clear();try{t.end()}catch{return!1}}return!0},abort(){const e=je,t=oe&&!Fe&&!te;re=!0,he=!1,xe=!1,$e.length=0,Ke(Fe);let r=Promise.resolve();if(Me&&Fe&&(r=Me.interrupt({threadId:V,turnId:Fe}).catch(()=>{})),te){try{te.kill("SIGTERM")}catch{}setTimeout(()=>{try{te?.kill("SIGKILL")}catch{}},1500)}else t&&We({kind:"result",subtype:"aborted",sessionId:V,model:we,costUsd:null,usage:null,numTurns:0,durationMs:void 0,denials:0,resultText:null});return r.then(()=>e).catch(()=>e).then(()=>{})},end(){if(ne=!0,oe=!1,be&&ie(be),Ge.cancel(),$e.length=0,Ke(Fe),te)try{te.kill()}catch{}try{Me?.end()}catch{}Se?.then(e=>e.close()).catch(()=>{})},setModel(e){if(!e||oe)return!1;we=String(e),Xe.setModel(we);const t=S(ke,{models:p,model:we});return t!==ke&&(ke=t,Ge({kind:"effort",level:ke})),!0},setMode:e=>!(oe||!CODEX_MODE_CONFIG[e]||(z=e,B=codexConfigForMode(z),I=B.sandbox,V=null,Y=0,_e=null,Te=!1,0)),setEffort:e=>!(oe||!_({models:p,model:we}).includes(e)||(ke=e,Ge({kind:"effort",level:ke}),0)),clearContext:()=>!oe&&(V=null,Y=0,_e=null,Te=!1,!0),async compactContext(){if(oe||Oe)return!1;re=!1,Oe=!0;let e=null,t=!1;try{if(!await et()||oe)return!1;const r=new Promise((t,r)=>{e=setTimeout(()=>{Ne=null,r(new Error("Codex did not start the compaction turn"))},5e3),Ne={resolve:t,reject:r}});await Me.compact({threadId:V}),t=!0;const n=await r;e&&clearTimeout(e);const o=await Me.waitForTurn(n);Ke(o?.turn?.id||n);const a=o?.turn?.status;if("completed"===a)return!0;throw new Error(o?.turn?.error?.message||`compaction ${a||"failed"}`)}catch(e){return t||!["rejected","not_sent"].includes(e?.delivery)?(Je(`Native Codex compaction status is uncertain; existing context was preserved: ${e?.message||e}`),null):(Je(`Native Codex compaction unavailable; using bounded recap fallback: ${e?.message||e}`),!1)}finally{e&&clearTimeout(e),Ne=null,Oe=!1,$e.length&&at()}},async accountUsage(){if(!await et())return null;const[e,t]=await Promise.all([Me.accountUsage().catch(()=>null),Me.accountRateLimits().catch(()=>null)]);return{usage:e,limits:t}}}}
|
package/hermes-acp-bootstrap.py
CHANGED
|
@@ -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
package/publish-manifest.json
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"format": 1,
|
|
3
3
|
"package": "thinkpool-pair",
|
|
4
|
-
"version": "0.7.
|
|
4
|
+
"version": "0.7.409",
|
|
5
5
|
"kind": "minified",
|
|
6
6
|
"minifiedModules": 135,
|
|
7
|
-
"sourceModuleBytes":
|
|
8
|
-
"artifactModuleBytes":
|
|
7
|
+
"sourceModuleBytes": 1822917,
|
|
8
|
+
"artifactModuleBytes": 832990,
|
|
9
9
|
"files": {
|
|
10
|
-
"package.json": "
|
|
10
|
+
"package.json": "7a0b4453cb7e55801a567ebdba4305582b75078698a41096e9527c1805af4db4",
|
|
11
11
|
"LICENSE": "8a030197ca1cad9669909ca14c9ad15cf48d9fe551da526ccaf1fca993eddb23",
|
|
12
12
|
"bridge.mjs": "4041fed2633ada658ab6b44d24161ec48ff16c4eb31e9a45c4dab45c9f1a9ca3",
|
|
13
13
|
"bridge-service.sh": "b64f27c473ca8f3a49190fd08c23947ab14ca9958d70b6fa53c7bddc2be91403",
|
|
@@ -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": "
|
|
28
|
+
"claude-session.mjs": "858f37d0fa1e5fd4a92a4a6d32c2ec1a9e111f949549d7e81ba66d3226a48f11",
|
|
29
29
|
"terminal-name.mjs": "f39bb8d1e148ab9a74cbb96438d31e524d6597b8035f00d7a906c28c306c0cf8",
|
|
30
30
|
"claude-command-catalog.mjs": "36bd4342b2ae94b43a0072533ef2d1648c7473003964bbad433fdb1a8b2bfec1",
|
|
31
|
-
"codex-session.mjs": "
|
|
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": "
|
|
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": "
|
|
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",
|
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schemaVersion": 1,
|
|
3
|
-
"bundleVersion":
|
|
3
|
+
"bundleVersion": 37,
|
|
4
4
|
"contracts": [
|
|
5
5
|
{
|
|
6
6
|
"id": "room-coordination",
|
|
7
|
-
"version":
|
|
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",
|