thinkpool-pair 0.7.443 → 0.7.447

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{randomUUID as e}from"node:crypto";import{createRequire as t}from"node:module";import{readFileSync as o}from"node:fs";import{dirname as n,join as s}from"node:path";import{query as r}from"@anthropic-ai/claude-agent-sdk";import{sanitizeSession as i}from"./transcript-sanitize.mjs";import{reviewGatePreToolDecision as a}from"./flow-review-gate.mjs";import{crossPostNeedsCard as l}from"./cross-terminal.mjs";import{correctContext as c}from"./context-windows.mjs";import{normalizeClaudeCommandCatalog as d}from"./claude-command-catalog.mjs";import{evidenceForToolResult as u}from"./evidence-citations.mjs";import{THINKPOOL_CASCADE_RULE as p,THINKPOOL_REMOTE_DELIVERY_RULES as m,THINKPOOL_RUNTIME_AUTHORITY_RULE as h,THINKPOOL_RUNTIME_TURN_REMINDER as f,buildThinkPoolTurnGuidance as y,createRoomContextSelector as k,normalizeThinkPoolTurnCause as g,usesFullThinkPoolReminder as w}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";import{AUTOMATION_MUTATION_MCP_TOOLS as N,AUTOMATION_READ_MCP_TOOLS as O}from"./code-automations.mjs";const R=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 A=(()=>{try{let e=n(R.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"})(),D=/\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,x=new Set(["Read","Grep","Glob","NotebookRead","TodoRead","LS"]),P=new Set(["WebFetch","WebSearch"]),I=new Set(["Edit","Write","MultiEdit","NotebookEdit","TodoWrite"]);export function classifyRisk(e,t){const o=String(e||"").replace(/^mcp__thinkpool__/,"");if(O.includes(o))return"low";if("delete_automation"===o)return"high";if(N.includes(o))return"medium";if("Bash"===e){const e=t&&(t.command??t.cmd)||"";return D.test(e)?"high":"medium"}return x.has(e)?"low":P.has(e)?"network":(I.has(e),"medium")}const C=/(^|\/)\.claude\/SESSIONS\/|(^|\/)CLAUDE\.md$/;export function isSafeDocWrite(e,t){if(!I.has(e))return!1;const o=t&&(t.file_path||t.notebook_path)||"";return C.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&&I.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 M(){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 U=(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),L=new Set(["default","acceptEdits","plan","bypassPermissions"]),W=["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:O="default",onEvent:R,requestPermission:D,mcpServers:x,crossPostGate:P,crossRoomPostGate:I,didSpawnTarget:C=null,terminalRolePrompt:F,rolePrompt:j,blockSubagents:$=!1,onSubmitPlan:q=null,onLaneDone:G=null,onReviewVerdict:B=null,reviewGate:H=null,lazy:K=!1,roomContext:Q=null,suggest:Y=!0,prepareCwd:z=null,admitStart:J=null,resilienceObserver:V=null,resilience:X=null}){const Z=k(Q);let ee=0,te=!0;const oe=(e,{promptIndex:t=0,forceFull:o=!1,turnCause:n=null}={})=>{const s=w({promptIndex:t,forceFull:o,turnCause:n}),r=Z({force:s}),i=String(F||"").trim();return`<system-reminder>\n${s&&i?`${i}\n\n`:""}${s?W:y({text:e,promptIndex:t,forceFull:o,turnCause:n})}${r?`\n\n${r}`:""}\n</system-reminder>`},ne=new AbortController;let se=M(),re=s||null,ie=s||null,ae=null,le=null,ce=null,de=null,ue=!1,pe=!1,me=null,he=!1,fe=!1,ye=!1,ke=null,ge=L.has(O)?O:"default";const we=new Set,be=new Map,ve=new Set(["low","medium","high","xhigh","max"]);let _e=ve.has(n)?n:"high",Te=0,Se=0,Ee=o||null,Ne=null,Oe=null,Re=Promise.resolve(),Ae=!1,De=!1;const xe=e=>new Promise(t=>setTimeout(t,e)),Pe=Math.max(3e4,parseInt(process.env.TP_STALL_MS,10)||9e4);let Ie=!1,Ce=Date.now(),Me=!1;const Ue=/connection closed|connection reset|econnreset|etimedout|socket hang up|fetch failed|network error|socket destroyed/i;let Le=0;const We=(e,t={})=>{try{V?.({reason:e,restartCount:Le,...t})}catch{}},Fe=!(!X?.policy?.enabled||!X?.providerId||"anthropic"===X.providerId);let je=null,$e=null,qe=!1,Ge=0,Be=!1,He=null;const Ke=Math.max(3*Pe,parseInt(process.env.TP_FORCE_STOP_MS,10)||3e5);let Qe=!1,Ye=!1;const ze=Math.max(Ke,parseInt(process.env.TP_COMPACT_FORCE_STOP_MS,10)||12e5);let Je=!1,Ve=0;const Xe=D;D=async e=>{Ve++;try{return await(Xe?.(e))}finally{Ve=Math.max(0,Ve-1),Ce=Date.now()}};let Ze=!1,et=null,tt=null,ot=!1,nt="",st=null;const rt=Math.max(1200,parseInt(process.env.TP_SUGGEST_FALLBACK_MS,10)||2500),it=e=>{try{R?.(e)}catch{}},at=e=>{Ce=Date.now(),e&&"stalled"!==e.kind&&(Me=!1),!e||"compaction"!==e.kind&&"result"!==e.kind&&"error"!==e.kind||(Je=!1),it(e)},lt=e=>{try{X?.onRecord?.(e)}catch{}"retrying"!==e?.outcome&&"cap_blocked"!==e?.outcome&&"circuit_open"!==e?.outcome||at({kind:"note",text:S(e)})},ct=()=>{if(null!=$e){try{(X?.clearTimer||clearTimeout)($e)}catch{}$e=null}},dt=()=>{if(ct(),!je)return;const e=Number(X?.policy?.timeoutMs);if(!Number.isFinite(e)||e<=0)return;const t=X?.setTimer||setTimeout;$e=t(()=>{if($e=null,!ue&&je&&Ie){je.failure({message:"timeout"}),Ie=!1;try{Ne?.abort()}catch{}bt()}},e)},ut=async()=>{if(!je)return!0;let e=null;try{e=await je.preflight()}catch{return!1}return!0===e?.admitted},pt=setInterval(()=>{const e=Date.now()-Ce,t=b({turnActive:Ie,awaitingUser:Ve,quietMs:e,stallMs:Pe,forceStopMs:Ke,stalledSent:Me,stallRetried:Ye,compacting:Je,compactForceStopMs:ze});if("none"===t)return;const o=v(t,e);if(o&&it(o),"status"!==t){if("retry"===t){if(Qe=!0,je){We("resilience_stall",{quietMs:e}),je.failure({message:"timeout"}),Ie=!1;try{Ne?.abort()}catch{}return void bt()}return We("stall_replay",{quietMs:e}),void wt(e)}Qe=!0,Ie=!1}else Me=!0},5e3);pt.unref?.();const mt=e=>{setTimeout(()=>{Promise.resolve(ke?.setPermissionMode?.(e)).catch(t=>console.error(`[claude-session] setPermissionMode(${e}) failed:`,t?.message||t))},0)},ht={abortController:ne,permissionMode:ge,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!==_e&&(_e=i,at({kind:"effort",level:_e}));const c="Write"===n||"Edit"===n||"MultiEdit"===n||"NotebookEdit"===n;if($&&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=q&&await q(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($&&("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(B&&("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 B(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(G&&("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 G(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:H,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__attach_file"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (workspace-contained file attachment to this thinkpool room)."}};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||ge;if("bypassPermissions"!==t||"bypassPermissions"===ge)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(D?.({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=P?P():{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=!!C&&!!C(s?.terminal);if(!l({mode:ge,spawnedByMe:o}))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"bypassPermissions"===ge?"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(D?.({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=I?I():{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(D?.({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"!==ge)return mt(ge),at({kind:"mode",mode:ge}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`The thinkpool room is in ${ge} 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(D?.({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 ge=e,mt(e),at({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(D?.({id:e(),toolName:n,input:s,risk:"ask",questions:s?.questions||[]}))??""}catch{t=""}return askUserQuestionHookOutput(t)}const u=String(n||"").replace(/^mcp__thinkpool__/,"");if("plan"===ge&&N.includes(u))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Plan mode can inspect Automations but cannot change them. Finish or exit the plan before retrying."}};const p=classifyRisk(n,s),m=`${n}:${p}`,h=isSafeDocWrite(n,s),f=autoAllow({toolName:n,input:s,mode:ge,alwaysAllow:we});let y="allow";if(!f){try{y=await(D?.({id:e(),toolName:n,input:s,risk:p}))??"deny"}catch{y="deny"}"always"===y&&(we.add(m),y="allow")}const k="deny"===y;return k&&je&&je.failure({permissionDenied:!0}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:k?"deny":"allow",permissionDecisionReason:k?"Denied by the user in the thinkpool room. Do not retry this tool — ask what to do instead.":f?h?"Auto-approved (mandated doc write — .claude/SESSIONS/ or CLAUDE.md).":`Auto-approved (${ge}).`:"Approved in the thinkpool room."}}}]}]},canUseTool:async(e,t)=>({behavior:"allow",updatedInput:t}),settingSources:["user","project","local"],appendSystemPrompt:[...F?[F]:[],...j?[j]:[],"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&&(ht.strictMcpConfig=!0,ht.mcpServers={}),x&&Object.keys(x).length&&(ht.mcpServers={...ht.mcpServers||{},...x}),t&&(ht.cwd=t),o&&(ht.model=o),ht.effort=_e,ht.env={...f||process.env,CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION:"1"};const ft=async()=>{if(!Y||"worker_completion"===le)return;const e=(nt||"").trim().slice(-1500);if(e&&!ue)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:ht.env,timeoutMs:8e3});o=o.trim().split("\n")[0].replace(/^["'`]+|["'`]+$/g,"").trim().slice(0,140),!o||ot||ue||/^(sure|of course|certainly|let me know|i can help|happy to)\b/i.test(o)||(at({kind:"suggestion",text:o,source:"haiku"}),process.stderr.write(` ◆ [suggestion] haiku fallback: ${JSON.stringify(o)}\n`))}catch{}},yt=()=>{const e="function"==typeof J?J():{ok:!0};return!1!==e?.ok||(at({kind:"error",message:e.reason||"Host memory is critically low. This agent runtime was not started.",recoverable:!0}),!1)},kt=async({admitted:e=!1}={})=>{if(De)return!1;if(!pe&&!e&&!yt())return!1;if(null==me&&(me=Date.now()),pe=!0,Oe)try{Oe()}catch{}Re=new Promise(e=>{Oe=e});const n=new AbortController;Ne=n;const a=()=>{try{n.abort()}catch{}};ne.signal.addEventListener("abort",a,{once:!0});try{if(re){const e=i(t||process.cwd(),re);e.blocks&&process.stderr.write(`\n ◆ healed ${e.blocks} malformed tool block(s) in the transcript before resume.\n`)}ke=r({prompt:se.stream,options:{...ht,abortController:n,...re?{resume:re}:{}}});for await(const e of ke){if(ue)break;switch(e.type){case"system":if("thinking_tokens"===e.subtype){Te+Se===0&&at({kind:"thinking_tokens",tokens:e.estimated_tokens,delta:e.estimated_tokens_delta});break}if("compact_boundary"===e.subtype){te=!0,at({kind:"compaction",trigger:e.compact_metadata?.trigger||"auto",preTokens:e.compact_metadata?.pre_tokens??null}),(async()=>{try{const e=await(ke?.getContextUsage?.());e&&(at({kind:"usage",ctx:c({used:e.totalTokens,max:e.maxTokens,pct:Math.round(e.percentage),model:e.model})}),e.model&&(Ee=e.model))}catch{}})();break}if(e.session_id&&(re=e.session_id),he||(he=!0,process.stderr.write(`\n ◆ session ready in ${Date.now()-me}ms — MCP ${"1"===process.env.TP_MCP_STRICT?"OFF":"on"}${s?", resume":", fresh"}.\n`)),Ee=ht.model||e.model||o||Ee,at({kind:"system",sessionId:re,model:ht.model||e.model||o||null,commands:d({slashCommands:e.slash_commands,skills:e.skills})}),!ye&&Array.isArray(e.tools)){ye=!0;const t=askUserQuestionRegression(e.tools,A);t&&(process.stderr.write(`\n ⚠⚠ ${t}\n`),at({kind:"error",message:t}))}fe||(fe=!0,Promise.resolve(ke?.supportedModels?.()).then(e=>{const t=(e||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);t.length&&at({kind:"models",models:t})}).catch(()=>{}));break;case"assistant":ct(),je?.visibleOutput();for(const t of e.message?.content||[])"tool_use"===t?.type&&t.id&&be.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&&(nt=t)}at({kind:"assistant",blocks:U(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){ct(),je?.visibleOutput({tool:!0});const o=be.get(t.tool_use_id);null!=o&&be.delete(t.tool_use_id);const n=u(o?.name,t.content);at({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?(Te+=Se,Se=t.message?.usage?.output_tokens||0,at({kind:"thinking_tokens",tokens:Te+Se})):"message_delta"===t?.type&&t.usage&&(Se=t.usage.output_tokens??Se,at({kind:"thinking_tokens",tokens:Te+Se}));break}case"result":if(ct(),e.session_id&&(re=e.session_id),e.is_error&&Array.isArray(e.errors)&&e.errors.some(e=>/no conversation found/i.test(String(e)))&&(re||ie)&&Le<3){Le++;const e=Ie;Ie=!1,re=null,ie=null,at({kind:"note",text:"previous session not found — continuing on a fresh one"});const t=se;se=M();try{t.end()}catch{}const o=e?ae:null;He=setTimeout(()=>{He=null,ue||(kt(),null!=o&&(Ie=!0,Ce=Date.now(),Me=!1,se.push([{type:"text",text:o},{type:"text",text:ce||oe(o,{forceFull:!0})}])))},300);break}if(Ze&&("aborted"===e.subtype||"error_during_execution"===e.subtype)){Ge===et&&(Ie=!1);break}if(e.is_error&&je){if(qe)break;je.failure({message:Array.isArray(e.errors)?e.errors.join(" "):e.result,status:e.status??e.statusCode,code:e.code}),Ie=!1,bt();break}if(Te=0,Se=0,Ie=!1,Ae&&(Ae=!1,setTimeout(()=>{ue||gt()},0)),"success"===e.subtype&&(Le=0,re&&(ie=re)),"success"===e.subtype&&(je?.success(),je=null),Qe=!1,Ye=!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&&(Ee=t)}{const t="string"==typeof e.result?e.result.replace(/\s+/g," ").trim().slice(0,200):"";at({kind:"result",subtype:e.subtype,sessionId:re,model:Ee,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})}st&&clearTimeout(st),"aborted"!==e.subtype&&"worker_completion"!==le&&(st=setTimeout(()=>{st=null,ot||ue||ft()},rt)),(async()=>{let t=null;try{const e=await(ke?.getContextUsage?.());e&&(t=c({used:e.totalTokens,max:e.maxTokens,pct:Math.round(e.percentage),model:e.model}),e.model&&(Ee=e.model))}catch{}const o=e.usage||{};at({kind:"usage",costUsd:e.total_cost_usd??null,tokens:(o.input_tokens||0)+(o.output_tokens||0),ctx:t})})();break;case"prompt_suggestion":st&&(clearTimeout(st),st=null),e.suggestion&&(ot=!0,at({kind:"suggestion",text:e.suggestion}))}}}catch(e){if(ct(),ue)return;if(n.signal.aborted)return;const t=e?.message||String(e);if(je&&Ie)return je.failure({message:t,status:e?.status??e?.statusCode,code:e?.code}),Ie=!1,void bt();if(Ie=!1,at({kind:"error",message:t}),Ue.test(t)&&Le<3){Le++,We("stream_reconnect",{failureClass:"network"}),at({kind:"note",text:`connection dropped — reconnecting (${Le}/3)`});const e=se;se=M();try{e.end()}catch{}return void(He=setTimeout(()=>{He=null,ue||kt()},Math.min(1e3*Le,4e3)))}if(/no conversation found/i.test(t)&&re&&Le<3){Le++,re=null,ie=null;const e=se;se=M();try{e.end()}catch{}return void(He=setTimeout(()=>{He=null,ue||kt()},300))}ue=!0}finally{ne.signal.removeEventListener("abort",a),Ne===n&&(Ne=null);try{await(ke?.return?.())}catch{}Oe&&(Oe(),Oe=null)}},gt=async()=>{if(ue||De||!pe)return;const e=Re,t=se;if(se=M(),Ne)try{Ne.abort()}catch{}try{t.end()}catch{}try{await e}catch{}await xe(300),re=ie,ue||De||kt()},wt=async e=>{if(ue)return;Ye=!0;const t=Ie&&!_(ae)?ae:null;Ie=!1;const o=Re,n=se;if(se=M(),Ne)try{Ne.abort()}catch{}try{n.end()}catch{}try{await o}catch{}await xe(300),re=ie,ue||(kt(),null!=t&&(Ie=!0,Ce=Date.now(),Me=!1,se.push(/^\s*\//.test(t)?[{type:"text",text:t}]:[{type:"text",text:t},{type:"text",text:ce||oe(t,{forceFull:!0})}]),it({kind:"note",text:"retrying the stalled turn on a fresh connection"})))},bt=()=>{if(ue||Be||qe)return;const e=je,t=Ge,o=de;qe=!0;const n=Re,s=se;se=M();try{s.end()}catch{}He=setTimeout(async()=>{He=null;try{await n}catch{}if(!ue&&qe&&je===e&&Ge===t)return await ut()?void(!ue&&qe&&je===e&&Ge===t&&(qe=!1,Ie=!0,Ce=Date.now(),Me=!1,kt(),o&&se.push(o),dt())):(qe=!1,void vt())},0)},vt=()=>{ct(),Ie=!1,je=null,pe=!1,at({kind:"error",message:"The configured provider could not complete this turn. Nothing else was sent.",recoverable:!0})};return K||Fe||kt(),{sendTurn(e,n={}){if(ue||De||Be||qe)return!1;if(!pe&&!yt())return!1;if(!pe&&z)try{const e=z();e&&(t=e,ht.cwd=e)}catch{}Ie=!0,ot=!1,ae=String(e),le=g(n?.turnCause),st&&(clearTimeout(st),st=null),Ce=Date.now(),Me=!1,Ye=!1,Qe=!1;const s=String(e),r=ee++,i=te;if(te=/^\s*\/(?:compact|clear|reset)\b/i.test(s),ce=/^\s*\//.test(s)?null:oe(s,{promptIndex:r,forceFull:i,turnCause:le}),Je=_(s),de=/^\s*\//.test(s)?[{type:"text",text:s}]:[{type:"text",text:s},{type:"text",text:ce}],Ge++,je=(()=>{if(!Fe)return null;try{const e=T({runtime:"claude",providers:X.providers||[],providerId:X.providerId,model:X.model||ht.model||o,requestedModel:X.requestedModel||X.model||ht.model||o,policy:X.policy,bridgeHostId:X.bridgeHostId,circuit:X.circuit,capGate:X.capGate,traceId:X.traceId,turnRev:"function"==typeof X.turnRev?X.turnRev():X.turnRev,onRecord:lt});return e.start(),e}catch{return null}})(),je){const e=je,t=Ge,o=de;ut().then(n=>{!ue&&Ie&&je===e&&Ge===t&&(n?(pe||kt({admitted:!0}),se.push(o),dt()):vt())}).catch(()=>{!ue&&Ie&&je===e&&Ge===t&&vt()})}else pe||kt({admitted:!0}),se.push(de)},warm(){Fe||pe||ue||De||kt()},get started(){return pe},async setMode(e){L.has(e)&&!ue&&(ge=e,mt(e),at({kind:"mode",mode:ge}))},async setModel(e){ht.model=e,Ee=e,at({kind:"note",text:`model → ${e}`}),pe&&!ue&&(Ie?Ae=!0:await gt())},setEffort:async e=>!(!ve.has(e)||ue||(_e=e,ht.effort=e,at({kind:"effort",level:e}),pe&&(Ie?(Ae=!0,0):(await gt(),0)))),async listModels(){try{const e=(await(ke?.supportedModels?.())||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);e.length&&at({kind:"models",models:e}),at({kind:"note",text:e.length?`models: ${e.map(e=>e.value).join(", ")}`:"no model list available"})}catch{at({kind:"note",text:"usage: /model <name>"})}},async park(){if(ue||De||Ie||Be||qe||Je)return!1;if(!pe)return!0;De=!0;const e=Re,t=se;se=M(),pe=!1,st&&(clearTimeout(st),st=null);try{if(Ne)try{Ne.abort()}catch{}try{t.end()}catch{}try{await e}catch{}return ke=null,ie&&(re=ie),!ue}finally{De=!1}},async abort(){if(!Be){Be=!0;try{const e=qe,t=e?Re:null;(Ie||e)&&(Ge++,e||(qe=!1),ct(),je?.failure({aborted:!0}),e&&(clearTimeout(He),He=null,pe=!1),Ze=!0,et=Ge,clearTimeout(tt),tt=setTimeout(()=>{Ze=!1,et=null},6e3));try{await(ke?.interrupt?.())}catch{}if(t)try{await t}catch{}e&&(qe=!1),(Ie||e)&&(Ie=!1,at({kind:"result",subtype:"aborted",sessionId:re}))}finally{Be=!1}}},end(){ue=!0,ct(),clearInterval(pt),clearTimeout(tt),clearTimeout(He),st&&clearTimeout(st),se.end();try{ne.abort()}catch{}},get sessionId(){return re},get mode(){return ge},get turnActive(){return Ie}}}
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 i}from"@anthropic-ai/claude-agent-sdk";import{sanitizeSession as r}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 u}from"./claude-command-catalog.mjs";import{evidenceForToolResult as p}from"./evidence-citations.mjs";import{THINKPOOL_RUNTIME_TURN_REMINDER as d,buildThinkPoolTurnGuidance as m,createRoomContextSelector as h,normalizeThinkPoolTurnCause as f,usesFullThinkPoolReminder as k}from"./thinkpool-room-prompt.mjs";import{stallDecision as y,stallEvent as g,isCompactTurn as w}from"./turn-stall.mjs";import{createSameTargetResilienceController as _,formatResilienceTrace as b}from"./provider-resilience.mjs";import{catastrophicPreToolHookDecision as v}from"./catastrophic-command-guard.mjs";import{AUTOMATION_MUTATION_MCP_TOOLS as T,AUTOMATION_READ_MCP_TOOLS as S}from"./code-automations.mjs";const P=t(import.meta.url);export async function claudeOneShot({prompt:e,model:t="claude-haiku-4-5",cwd:o,env:n,timeoutMs:s=8e3}={}){const r=new AbortController,a=setTimeout(()=>{try{r.abort()}catch{}},s);try{const s=i({prompt:e,options:{model:t,...o?{cwd:o}:{},env:n,maxTurns:1,permissionMode:"bypassPermissions",settingSources:[],strictMcpConfig:!0,mcpServers:{},abortController:r}});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 D=(()=>{try{let e=n(P.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"})(),x=/\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,E=new Set(["Read","Grep","Glob","NotebookRead","TodoRead","LS"]),O=new Set(["WebFetch","WebSearch"]),N=new Set(["Edit","Write","MultiEdit","NotebookEdit","TodoWrite"]);export function classifyRisk(e,t){const o=String(e||"").replace(/^mcp__thinkpool__/,"");if(S.includes(o))return"low";if("delete_automation"===o)return"high";if(T.includes(o))return"medium";if("Bash"===e){const e=t&&(t.command??t.cmd)||"";return x.test(e)?"high":"medium"}return E.has(e)?"low":O.has(e)?"network":(N.has(e),"medium")}const A=/(^|\/)\.claude\/SESSIONS\/|(^|\/)CLAUDE\.md$/;export function isSafeDocWrite(e,t){if(!N.has(e))return!1;const o=t&&(t.file_path||t.notebook_path)||"";return A.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&&N.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 R(){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 U=(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"]),C=["You are Claude in a thinkpool Code room, driven from a phone or browser.",d].join(" ");export function buildClaudeSystemPrompt({terminalRolePrompt:e,rolePrompt:t}={}){return[...e?[e]:[],...t?[t]:[],"ENVIRONMENT: You are Claude in a thinkpool Code room. The current room role, runtime permissions, and task govern execution; host skills and memories do not grant extra authority.","EXECUTION: act on authorized requests. Use existing authorization and make routine in-scope decisions. Plan mode applies only when selected by the user or required by this runtime role. Do not invoke planning or approval workflows merely because a host skill suggests them. When a plan is needed, write it in the room chat so the people can review it.","DELEGATION: follow the shared work-routing contract. Native Task/Agent subagents are invisible to the room and cannot substitute for visible terminal launches. Worker and review permissions come from their actual runtime, never from a blanket bypass claim.","RESEARCH: the metered research tool requires the person’s agreement. Offer it when external evidence would help, then call it only after they agree; ordinary available read-only sources do not require this paid workflow.","WORKTREES: use the linked worktree assigned to this lane and preserve unrelated changes. If the checkout is shared, create an isolated linked worktree and branch before editing code. A separate branch in the shared checkout is not isolation."].join(" ")}export function startClaudeSession({cwd:t,model:o,effort:n="high",resume:s,env:d,mode:S="default",onEvent:P,requestPermission:x,mcpServers:E,crossPostGate:O,crossRoomPostGate:N,didSpawnTarget:A=null,terminalRolePrompt:I,rolePrompt:$,blockSubagents:j=!1,onSubmitPlan:F=null,onLaneDone:W=null,onReviewVerdict:L=null,reviewGate:G=null,lazy:q=!1,roomContext:B=null,suggest:Q=!0,prepareCwd:z=null,admitStart:K=null,resilienceObserver:H=null,resilience:J=null}){const V=h(B);let Y=0,X=!0;const Z=(e,{promptIndex:t=0,forceFull:o=!1,turnCause:n=null}={})=>{const s=k({promptIndex:t,forceFull:o,turnCause:n}),i=V({force:s}),r=String(I||"").trim();return`<system-reminder>\n${s&&r?`${r}\n\n`:""}${s?C:m({text:e,promptIndex:t,forceFull:o,turnCause:n})}${i?`\n\n${i}`:""}\n</system-reminder>`},ee=new AbortController;let te=R(),oe=s||null,ne=s||null,se=null,ie=null,re=null,ae=null,le=!1,ce=!1,ue=null,pe=!1,de=!1,me=!1,he=null,fe=M.has(S)?S:"default";const ke=new Set,ye=new Map,ge=new Set(["low","medium","high","xhigh","max"]);let we=ge.has(n)?n:"high",_e=0,be=0,ve=o||null,Te=null,Se=null,Pe=Promise.resolve(),De=!1,xe=!1;const Ee=e=>new Promise(t=>setTimeout(t,e)),Oe=Math.max(3e4,parseInt(process.env.TP_STALL_MS,10)||9e4);let Ne=!1,Ae=Date.now(),Re=!1;const Ue=/connection closed|connection reset|econnreset|etimedout|socket hang up|fetch failed|network error|socket destroyed/i;let Me=0;const Ce=(e,t={})=>{try{H?.({reason:e,restartCount:Me,...t})}catch{}},Ie=!(!J?.policy?.enabled||!J?.providerId||"anthropic"===J.providerId);let $e=null,je=null,Fe=!1,We=0,Le=!1,Ge=null;const qe=Math.max(3*Oe,parseInt(process.env.TP_FORCE_STOP_MS,10)||3e5);let Be=!1,Qe=!1;const ze=Math.max(qe,parseInt(process.env.TP_COMPACT_FORCE_STOP_MS,10)||12e5);let Ke=!1,He=0;const Je=x;x=async e=>{He++;try{return await(Je?.(e))}finally{He=Math.max(0,He-1),Ae=Date.now()}};let Ve=!1,Ye=null,Xe=null,Ze=!1,et="",tt=null;const ot=Math.max(1200,parseInt(process.env.TP_SUGGEST_FALLBACK_MS,10)||2500),nt=e=>{try{P?.(e)}catch{}},st=e=>{Ae=Date.now(),e&&"stalled"!==e.kind&&(Re=!1),!e||"compaction"!==e.kind&&"result"!==e.kind&&"error"!==e.kind||(Ke=!1),nt(e)},it=e=>{try{J?.onRecord?.(e)}catch{}"retrying"!==e?.outcome&&"cap_blocked"!==e?.outcome&&"circuit_open"!==e?.outcome||st({kind:"note",text:b(e)})},rt=()=>{if(null!=je){try{(J?.clearTimer||clearTimeout)(je)}catch{}je=null}},at=()=>{if(rt(),!$e)return;const e=Number(J?.policy?.timeoutMs);if(!Number.isFinite(e)||e<=0)return;const t=J?.setTimer||setTimeout;je=t(()=>{if(je=null,!le&&$e&&Ne){$e.failure({message:"timeout"}),Ne=!1;try{Te?.abort()}catch{}yt()}},e)},lt=async()=>{if(!$e)return!0;let e=null;try{e=await $e.preflight()}catch{return!1}return!0===e?.admitted},ct=setInterval(()=>{const e=Date.now()-Ae,t=y({turnActive:Ne,awaitingUser:He,quietMs:e,stallMs:Oe,forceStopMs:qe,stalledSent:Re,stallRetried:Qe,compacting:Ke,compactForceStopMs:ze});if("none"===t)return;const o=g(t,e);if(o&&nt(o),"status"!==t){if("retry"===t){if(Be=!0,$e){Ce("resilience_stall",{quietMs:e}),$e.failure({message:"timeout"}),Ne=!1;try{Te?.abort()}catch{}return void yt()}return Ce("stall_replay",{quietMs:e}),void kt(e)}Be=!0,Ne=!1}else Re=!0},5e3);ct.unref?.();const ut=e=>{setTimeout(()=>{Promise.resolve(he?.setPermissionMode?.(e)).catch(t=>console.error(`[claude-session] setPermissionMode(${e}) failed:`,t?.message||t))},0)},pt={abortController:ee,permissionMode:fe,hooks:{PreToolUse:[{hooks:[async o=>{const n=o.tool_name,s=o.tool_input,i=v({toolName:n,input:s,cwd:t});if(i)return i;const r=o.effort?.level;r&&r!==we&&(we=r,st({kind:"effort",level:we}));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=F&&await F(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(L&&("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 L(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(W&&("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 W(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 u=a({reviewGate:G,toolName:n,toolInput:s});if(u)return u;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__attach_file"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (workspace-contained file attachment to this thinkpool room)."}};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||fe;if("bypassPermissions"!==t||"bypassPermissions"===fe)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(x?.({id:e(),toolName:n,input:{...s,mode:t},risk:"high"}))??"deny"}catch{o="deny"}const i="allow"===o;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:i?"allow":"deny",permissionDecisionReason:i?"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=O?O():{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=!!A&&!!A(s?.terminal);if(!l({mode:fe,spawnedByMe:o}))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"bypassPermissions"===fe?"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 i="deny";try{i=await(x?.({id:e(),toolName:n,input:s,risk:"high"}))??"deny"}catch{i="deny"}const r="allow"===i;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:r?"allow":"deny",permissionDecisionReason:r?"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=N?N():{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(x?.({id:e(),toolName:n,input:s,risk:"high"}))??"deny"}catch{o="deny"}const i="allow"===o;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:i?"allow":"deny",permissionDecisionReason:i?"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"!==fe)return ut(fe),st({kind:"mode",mode:fe}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`The thinkpool room is in ${fe} 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(x?.({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 fe=e,ut(e),st({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(x?.({id:e(),toolName:n,input:s,risk:"ask",questions:s?.questions||[]}))??""}catch{t=""}return askUserQuestionHookOutput(t)}const p=String(n||"").replace(/^mcp__thinkpool__/,"");if("plan"===fe&&T.includes(p))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Plan mode can inspect Automations but cannot change them. Finish or exit the plan before retrying."}};const d=classifyRisk(n,s),m=`${n}:${d}`,h=isSafeDocWrite(n,s),f=autoAllow({toolName:n,input:s,mode:fe,alwaysAllow:ke});let k="allow";if(!f){try{k=await(x?.({id:e(),toolName:n,input:s,risk:d}))??"deny"}catch{k="deny"}"always"===k&&(ke.add(m),k="allow")}const y="deny"===k;return y&&$e&&$e.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.":f?h?"Auto-approved (mandated doc write — .claude/SESSIONS/ or CLAUDE.md).":`Auto-approved (${fe}).`:"Approved in the thinkpool room."}}}]}]},canUseTool:async(e,t)=>({behavior:"allow",updatedInput:t}),settingSources:["user","project","local"],appendSystemPrompt:buildClaudeSystemPrompt({terminalRolePrompt:I,rolePrompt:$}),includePartialMessages:!0,promptSuggestions:!0};"1"===process.env.TP_MCP_STRICT&&(pt.strictMcpConfig=!0,pt.mcpServers={}),E&&Object.keys(E).length&&(pt.mcpServers={...pt.mcpServers||{},...E}),t&&(pt.cwd=t),o&&(pt.model=o),pt.effort=we,pt.env={...d||process.env,CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION:"1"};const dt=async()=>{if(!Q||"worker_completion"===ie)return;const e=(et||"").trim().slice(-1500);if(e&&!le)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:pt.env,timeoutMs:8e3});o=o.trim().split("\n")[0].replace(/^["'`]+|["'`]+$/g,"").trim().slice(0,140),!o||Ze||le||/^(sure|of course|certainly|let me know|i can help|happy to)\b/i.test(o)||(st({kind:"suggestion",text:o,source:"haiku"}),process.stderr.write(` ◆ [suggestion] haiku fallback: ${JSON.stringify(o)}\n`))}catch{}},mt=()=>{const e="function"==typeof K?K():{ok:!0};return!1!==e?.ok||(st({kind:"error",message:e.reason||"Host memory is critically low. This agent runtime was not started.",recoverable:!0}),!1)},ht=async({admitted:e=!1}={})=>{if(xe)return!1;if(!ce&&!e&&!mt())return!1;if(null==ue&&(ue=Date.now()),ce=!0,Se)try{Se()}catch{}Pe=new Promise(e=>{Se=e});const n=new AbortController;Te=n;const a=()=>{try{n.abort()}catch{}};ee.signal.addEventListener("abort",a,{once:!0});try{if(oe){const e=r(t||process.cwd(),oe);e.blocks&&process.stderr.write(`\n ◆ healed ${e.blocks} malformed tool block(s) in the transcript before resume.\n`)}he=i({prompt:te.stream,options:{...pt,abortController:n,...oe?{resume:oe}:{}}});for await(const e of he){if(le)break;switch(e.type){case"system":if("thinking_tokens"===e.subtype){_e+be===0&&st({kind:"thinking_tokens",tokens:e.estimated_tokens,delta:e.estimated_tokens_delta});break}if("compact_boundary"===e.subtype){X=!0,st({kind:"compaction",trigger:e.compact_metadata?.trigger||"auto",preTokens:e.compact_metadata?.pre_tokens??null}),(async()=>{try{const e=await(he?.getContextUsage?.());e&&(st({kind:"usage",ctx:c({used:e.totalTokens,max:e.maxTokens,pct:Math.round(e.percentage),model:e.model})}),e.model&&(ve=e.model))}catch{}})();break}if(e.session_id&&(oe=e.session_id),pe||(pe=!0,process.stderr.write(`\n ◆ session ready in ${Date.now()-ue}ms — MCP ${"1"===process.env.TP_MCP_STRICT?"OFF":"on"}${s?", resume":", fresh"}.\n`)),ve=pt.model||e.model||o||ve,st({kind:"system",sessionId:oe,model:pt.model||e.model||o||null,commands:u({slashCommands:e.slash_commands,skills:e.skills})}),!me&&Array.isArray(e.tools)){me=!0;const t=askUserQuestionRegression(e.tools,D);t&&(process.stderr.write(`\n ⚠⚠ ${t}\n`),st({kind:"error",message:t}))}de||(de=!0,Promise.resolve(he?.supportedModels?.()).then(e=>{const t=(e||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);t.length&&st({kind:"models",models:t})}).catch(()=>{}));break;case"assistant":rt(),$e?.visibleOutput();for(const t of e.message?.content||[])"tool_use"===t?.type&&t.id&&ye.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&&(et=t)}st({kind:"assistant",blocks:U(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){rt(),$e?.visibleOutput({tool:!0});const o=ye.get(t.tool_use_id);null!=o&&ye.delete(t.tool_use_id);const n=p(o?.name,t.content);st({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+=be,be=t.message?.usage?.output_tokens||0,st({kind:"thinking_tokens",tokens:_e+be})):"message_delta"===t?.type&&t.usage&&(be=t.usage.output_tokens??be,st({kind:"thinking_tokens",tokens:_e+be}));break}case"result":if(rt(),e.session_id&&(oe=e.session_id),e.is_error&&Array.isArray(e.errors)&&e.errors.some(e=>/no conversation found/i.test(String(e)))&&(oe||ne)&&Me<3){Me++;const e=Ne;Ne=!1,oe=null,ne=null,st({kind:"note",text:"previous session not found — continuing on a fresh one"});const t=te;te=R();try{t.end()}catch{}const o=e?se:null;Ge=setTimeout(()=>{Ge=null,le||(ht(),null!=o&&(Ne=!0,Ae=Date.now(),Re=!1,te.push([{type:"text",text:o},{type:"text",text:re||Z(o,{forceFull:!0})}])))},300);break}if(Ve&&("aborted"===e.subtype||"error_during_execution"===e.subtype)){We===Ye&&(Ne=!1);break}if(e.is_error&&$e){if(Fe)break;$e.failure({message:Array.isArray(e.errors)?e.errors.join(" "):e.result,status:e.status??e.statusCode,code:e.code}),Ne=!1,yt();break}if(_e=0,be=0,Ne=!1,De&&(De=!1,setTimeout(()=>{le||ft()},0)),"success"===e.subtype&&(Me=0,oe&&(ne=oe)),"success"===e.subtype&&($e?.success(),$e=null),Be=!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&&(ve=t)}{const t="string"==typeof e.result?e.result.replace(/\s+/g," ").trim().slice(0,200):"";st({kind:"result",subtype:e.subtype,sessionId:oe,model:ve,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})}tt&&clearTimeout(tt),"aborted"!==e.subtype&&"worker_completion"!==ie&&(tt=setTimeout(()=>{tt=null,Ze||le||dt()},ot)),(async()=>{let t=null;try{const e=await(he?.getContextUsage?.());e&&(t=c({used:e.totalTokens,max:e.maxTokens,pct:Math.round(e.percentage),model:e.model}),e.model&&(ve=e.model))}catch{}const o=e.usage||{};st({kind:"usage",costUsd:e.total_cost_usd??null,tokens:(o.input_tokens||0)+(o.output_tokens||0),ctx:t})})();break;case"prompt_suggestion":tt&&(clearTimeout(tt),tt=null),e.suggestion&&(Ze=!0,st({kind:"suggestion",text:e.suggestion}))}}}catch(e){if(rt(),le)return;if(n.signal.aborted)return;const t=e?.message||String(e);if($e&&Ne)return $e.failure({message:t,status:e?.status??e?.statusCode,code:e?.code}),Ne=!1,void yt();if(Ne=!1,st({kind:"error",message:t}),Ue.test(t)&&Me<3){Me++,Ce("stream_reconnect",{failureClass:"network"}),st({kind:"note",text:`connection dropped — reconnecting (${Me}/3)`});const e=te;te=R();try{e.end()}catch{}return void(Ge=setTimeout(()=>{Ge=null,le||ht()},Math.min(1e3*Me,4e3)))}if(/no conversation found/i.test(t)&&oe&&Me<3){Me++,oe=null,ne=null;const e=te;te=R();try{e.end()}catch{}return void(Ge=setTimeout(()=>{Ge=null,le||ht()},300))}le=!0}finally{ee.signal.removeEventListener("abort",a),Te===n&&(Te=null);try{await(he?.return?.())}catch{}Se&&(Se(),Se=null)}},ft=async()=>{if(le||xe||!ce)return;const e=Pe,t=te;if(te=R(),Te)try{Te.abort()}catch{}try{t.end()}catch{}try{await e}catch{}await Ee(300),oe=ne,le||xe||ht()},kt=async e=>{if(le)return;Qe=!0;const t=Ne&&!w(se)?se:null;Ne=!1;const o=Pe,n=te;if(te=R(),Te)try{Te.abort()}catch{}try{n.end()}catch{}try{await o}catch{}await Ee(300),oe=ne,le||(ht(),null!=t&&(Ne=!0,Ae=Date.now(),Re=!1,te.push(/^\s*\//.test(t)?[{type:"text",text:t}]:[{type:"text",text:t},{type:"text",text:re||Z(t,{forceFull:!0})}]),nt({kind:"note",text:"retrying the stalled turn on a fresh connection"})))},yt=()=>{if(le||Le||Fe)return;const e=$e,t=We,o=ae;Fe=!0;const n=Pe,s=te;te=R();try{s.end()}catch{}Ge=setTimeout(async()=>{Ge=null;try{await n}catch{}if(!le&&Fe&&$e===e&&We===t)return await lt()?void(!le&&Fe&&$e===e&&We===t&&(Fe=!1,Ne=!0,Ae=Date.now(),Re=!1,ht(),o&&te.push(o),at())):(Fe=!1,void gt())},0)},gt=()=>{rt(),Ne=!1,$e=null,ce=!1,st({kind:"error",message:"The configured provider could not complete this turn. Nothing else was sent.",recoverable:!0})};return q||Ie||ht(),{sendTurn(e,n={}){if(le||xe||Le||Fe)return!1;if(!ce&&!mt())return!1;if(!ce&&z)try{const e=z();e&&(t=e,pt.cwd=e)}catch{}Ne=!0,Ze=!1,se=String(e),ie=f(n?.turnCause),tt&&(clearTimeout(tt),tt=null),Ae=Date.now(),Re=!1,Qe=!1,Be=!1;const s=String(e),i=Y++,r=X;if(X=/^\s*\/(?:compact|clear|reset)\b/i.test(s),re=/^\s*\//.test(s)?null:Z(s,{promptIndex:i,forceFull:r,turnCause:ie}),Ke=w(s),ae=/^\s*\//.test(s)?[{type:"text",text:s}]:[{type:"text",text:s},{type:"text",text:re}],We++,$e=(()=>{if(!Ie)return null;try{const e=_({runtime:"claude",providers:J.providers||[],providerId:J.providerId,model:J.model||pt.model||o,requestedModel:J.requestedModel||J.model||pt.model||o,policy:J.policy,bridgeHostId:J.bridgeHostId,circuit:J.circuit,capGate:J.capGate,traceId:J.traceId,turnRev:"function"==typeof J.turnRev?J.turnRev():J.turnRev,onRecord:it});return e.start(),e}catch{return null}})(),$e){const e=$e,t=We,o=ae;lt().then(n=>{!le&&Ne&&$e===e&&We===t&&(n?(ce||ht({admitted:!0}),te.push(o),at()):gt())}).catch(()=>{!le&&Ne&&$e===e&&We===t&&gt()})}else ce||ht({admitted:!0}),te.push(ae)},warm(){Ie||ce||le||xe||ht()},get started(){return ce},async setMode(e){M.has(e)&&!le&&(fe=e,ut(e),st({kind:"mode",mode:fe}))},async setModel(e){pt.model=e,ve=e,st({kind:"note",text:`model → ${e}`}),ce&&!le&&(Ne?De=!0:await ft())},setEffort:async e=>!(!ge.has(e)||le||(we=e,pt.effort=e,st({kind:"effort",level:e}),ce&&(Ne?(De=!0,0):(await ft(),0)))),async listModels(){try{const e=(await(he?.supportedModels?.())||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);e.length&&st({kind:"models",models:e}),st({kind:"note",text:e.length?`models: ${e.map(e=>e.value).join(", ")}`:"no model list available"})}catch{st({kind:"note",text:"usage: /model <name>"})}},async park(){if(le||xe||Ne||Le||Fe||Ke)return!1;if(!ce)return!0;xe=!0;const e=Pe,t=te;te=R(),ce=!1,tt&&(clearTimeout(tt),tt=null);try{if(Te)try{Te.abort()}catch{}try{t.end()}catch{}try{await e}catch{}return he=null,ne&&(oe=ne),!le}finally{xe=!1}},async abort(){if(!Le){Le=!0;try{const e=Fe,t=e?Pe:null;(Ne||e)&&(We++,e||(Fe=!1),rt(),$e?.failure({aborted:!0}),e&&(clearTimeout(Ge),Ge=null,ce=!1),Ve=!0,Ye=We,clearTimeout(Xe),Xe=setTimeout(()=>{Ve=!1,Ye=null},6e3));try{await(he?.interrupt?.())}catch{}if(t)try{await t}catch{}e&&(Fe=!1),(Ne||e)&&(Ne=!1,st({kind:"result",subtype:"aborted",sessionId:oe}))}finally{Le=!1}}},end(){le=!0,rt(),clearInterval(ct),clearTimeout(Xe),clearTimeout(Ge),tt&&clearTimeout(tt),te.end();try{ee.abort()}catch{}},get sessionId(){return oe},get mode(){return fe},get turnActive(){return Ne}}}
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 d}from"./codex-event-mapper.mjs";import{startCodexMcpHttp as c}from"./codex-mcp-http.mjs";import{CODEX_THINKPOOL_FIRST_TURN_PREAMBLE as u,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 w}from"./turn-stall.mjs";import{codexCatastrophicHookCliArgs as b}from"./catastrophic-command-guard.mjs";import{retryCodexSpawnAfterHostHeal as S}from"./codex-host-heal.mjs";import{codexNativeReasoningEffort as M,codexReasoningEfforts as _,normalizeCodexReasoningEffort as C,normalizeReasoningEffortList as k}from"./reasoning-effort.mjs";const T=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 I=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=M(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:d=n.tmpdir(),fsImpl:c=r,spawnImpl:u=t,codexHost:p={}}={}){const m=String(e||"").trim();if(!m)throw new Error("codex one-shot requires a prompt");const f=!l,h=l||c.mkdtempSync(o.join(d,"thinkpool-codex-one-shot-"));let x=null;try{i&&(x=o.join(h,"output-schema.json"),c.writeFileSync(x,`${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)]:[],...x?["--output-schema",x]:[],m];return await S(()=>new Promise((t,r)=>{let n,o,s="",i="",l=!1;const d=(e,n)=>{l||(l=!0,o&&clearTimeout(o),e?r(e):t(n))};try{n=u("codex",e,{cwd:h,env:process.env,stdio:["ignore","pipe","pipe"]})}catch(e){return void d(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=>d(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?d(null,t):d(new Error(`Codex cleanup failed${null==e?"":` (${e})`}${i.trim()?`: ${i.trim().slice(-240)}`:""}`))}),o=setTimeout(()=>{try{n.kill("SIGTERM")}catch{}d(new Error("Codex cleanup timed out"))},Math.max(1e3,Number(a)||22e3))}),p)}finally{if(f)try{c.rmSync(h,{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 normalizeCodexServiceTier(e){const t=String(e||"").trim().toLowerCase();return"priority"===t?"fast":"fast"===t||"default"===t?t:null}export function readCodexDefaultServiceTier({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*service_tier\s*=\s*["']([^"']+)["']\s*(?:#.*)?$/m);return normalizeCodexServiceTier(r?.[1])}catch{return null}}const E=e=>[...new Set((Array.isArray(e)?e:[]).map(e=>normalizeCodexServiceTier("string"==typeof e?e:e?.id)).filter(Boolean))];export function codexModelSupportsFastMode({models:e=[],model:t}={}){const r=(Array.isArray(e)?e:[]).find(e=>e?.value===t);return E(r?.serviceTiers).includes("fast")}const F=e=>"fast"===normalizeCodexServiceTier(e)?"priority":normalizeCodexServiceTier(e);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:k(e.supported_reasoning_levels),serviceTiers:E(e.service_tiers||e.additional_speed_tiers)}))}catch{return[]}}export function codexModelsFromNativeList(e=[]){return(Array.isArray(e)?e:[]).filter(e=>e?.model&&!0!==e.hidden).map(e=>({value:e.model,displayName:e.displayName||e.model,description:e.description||"",reasoningEfforts:k((e.supportedReasoningEfforts||[]).map(e=>e?.reasoningEffort||e)),serviceTiers:E(e.additionalSpeedTiers)}))}export async function loadCodexModelCatalog({cwd:e=process.cwd(),env:t=process.env,home:s=t.CODEX_HOME||o.join(n.homedir(),".codex"),fsImpl:a=r,appServerFactory:i=l,timeoutMs:d=1e4,settleMs:c=1e3,maxAttempts:u=3,sleepImpl:p=e=>new Promise(t=>setTimeout(t,e))}={}){const m=readCodexModels({home:s,fsImpl:a});let f=null;try{f=i({cwd:e,env:t,initializeTimeoutMs:d}),await f.start();let r=null,n=null;const o=Math.max(2,Number(u)||3);for(let e=0;e<o;e++){try{const e=await f.request("model/list",{includeHidden:!1},d),t=codexModelsFromNativeList(e?.data);(!r||t.length>=r.length)&&(r=t)}catch(e){n=e}e+1<o&&await p(Math.max(0,Number(c)||0))}if(!r)throw n||new Error("native catalog returned no response");return{models:r,source:"model/list",attempts:o,...n?{reason:n?.message||String(n)}:{}}}catch(e){return{models:m,source:"disk-cache",reason:e?.message||String(e)}}finally{try{f?.end()}catch{}}}const N=new Map;function O(e,{home:t,fsImpl:r}){if(!e)return null;const n=`${t}\0${e}`,s=N.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 N.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=O(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=O(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 T.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,d=f({promptIndex:s,forceFull:a,turnCause:i}),c=[o?u:"",d?t:"",p({text:e,promptIndex:s,forceFull:a,turnCause:i}),d?r||CODEX_ROOM_CASCADE_REMINDER:"",l].map(e=>String(e||"").trim()).filter(Boolean);return c.length?`<thinkpool-context>\n${c.join("\n\n")}\n</thinkpool-context>\n\n${String(e??"")}`:String(e??"")}export function buildCodexExecArgs({sessionId:e,model:t,serviceTier:r,effort:n,sandbox:s,approvalPolicy:a="untrusted",providerConfig:i,mcpUrl:l,writableDirs:d=[],images:c=[],prompt:u}){const p=normalizeCodexSandbox(s),m=[...b(),...e?["exec","resume","--json","--skip-git-repo-check",..."danger-full-access"===p?["--dangerously-bypass-approvals-and-sandbox"]:["-c",`sandbox_mode="${p}"`]]:["exec","--json","--sandbox",p,"--skip-git-repo-check"]];t&&m.push("-m",t);const f=normalizeCodexServiceTier(r);f&&(m.push("-c",`service_tier=${JSON.stringify(f)}`),"fast"===f&&m.push("-c","features.fast_mode=true")),m.push("-c",`approval_policy="${a}"`);const h=M(n);if(h&&m.push("-c",`model_reasoning_effort="${h}"`),i&&m.push("-c",i),!e)for(const e of d)m.push("--add-dir",e);l&&(m.push("-c",`mcp_servers.thinkpool.url=${JSON.stringify(l)}`),m.push("-c","mcp_servers.thinkpool.required=true"));let x=!1;for(const e of c)o.isAbsolute(String(e||""))&&(m.push("--image",String(e)),x=!0);return x&&m.push("--"),e&&m.push(e),m.push(String(u??"")),m}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 A=/\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:A.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 R(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:u,models:p=[],serviceTier:h=null,effort:b="high",resume:k,env:T,sandbox:E,mode:N="default",onEvent:O,providerConfig:A,terminalRolePrompt:P,rolePrompt:D,roomContext:U,mcpServers:j,prepareCwd:$=null,requestPermission:L,appServerGate:q=i,appServerFactory:z=l,mcpHttpFactory:X=c,spawnImpl:G=t,admitStart:H=null,stallOptions:B={},codexHost:W={}}){let J=CODEX_MODE_CONFIG[N]?N:"default",K=codexConfigForMode(J);E=normalizeCodexSandbox(E||K.sandbox);const V=codexPublishAccess({cwd:e,env:{...process.env,...T||{}}}),Y=V.env,Q=k||null,Z=!Q||codexThreadCanResume(Q,{home:Y.CODEX_HOME||o.join(n.homedir(),".codex")});let ee=Z?Q:null,te=ee?1:0,re=0,ne=!0;const oe=m(U);let se=null,ae=!1,ie=!1,le=!1;const de="function"==typeof B.now?B.now:Date.now,ce="function"==typeof B.setInterval?B.setInterval:setInterval,ue="function"==typeof B.clearInterval?B.clearInterval:clearInterval,pe=Number.isFinite(B.stallMs)?Math.max(1,Number(B.stallMs)):Math.max(3e4,parseInt(Y.TP_STALL_MS,10)||9e4),me=Number.isFinite(B.forceStopMs)?Math.max(pe,Number(B.forceStopMs)):Math.max(3*pe,parseInt(Y.TP_FORCE_STOP_MS,10)||3e5),fe=Number.isFinite(B.longReasoningForceStopMs)?Math.max(me,Number(B.longReasoningForceStopMs)):Math.max(me,parseInt(Y.TP_LONG_REASONING_FORCE_STOP_MS,10)||12e5),he=Number.isFinite(B.intervalMs)?Math.max(1,Number(B.intervalMs)):5e3;let xe=de(),ge=!1,ye=!1,ve=!1,we=!1,be=!0,Se=0,Me=0,_e=null,Ce=u||null;const ke=new Set((Array.isArray(p)?p:[]).map(e=>"string"==typeof e?e:e?.value||e?.slug).filter(Boolean));let Te=normalizeCodexServiceTier(h);"fast"!==Te||codexModelSupportsFastMode({models:p,model:Ce})||(Te="default");let Ie=C(b,{models:p,model:Ce}),Ee=ee?readCodexThreadUsage(ee):null,Fe=null;const Ne=q({env:Y});let Oe=!Ne.enabled,Ae=null,Re=!1;const Pe=new WeakSet;let De=null,Ue=null,je=!1;const $e=new Set,Le=new Map,qe=new Set,ze=new Map;let Xe=Promise.resolve(),Ge=Promise.resolve();const He=[],Be=y(e=>{try{O?.(e)}catch{}}),We=()=>{xe=de(),ge=!1},Je=e=>{We(),Be(e)};Je.cancel=()=>Be.cancel();const Ke=new d({onEvent:Je,model:u||null,usageSnapshotForSession:e=>{const t=readCodexThreadUsage(e);return t&&(Ee=t),t||Ee}}),Ve=()=>{const e=[...ze.values()];ze.clear();for(const t of e)t.text&&Je({kind:"assistant",blocks:[{type:"text",text:t.text}],parentToolUseId:null,replacesCid:t.cid})},Ye=e=>{"turn.completed"!==e?.type&&"turn.failed"!==e?.type||(Ve(),le=!1),Ke.push(e)},Qe=e=>{Ve(),le=!1,Je(e)},Ze=({retry:e=!1,recoveryAttempt:t=0}={})=>{le=!0,xe=de(),ge=!1,ve=!1,we=!1,be=!0,Se=Math.max(0,Number(t)||0),e||(ye=!1)},et=e=>Je({kind:"note",text:e}),tt=(e=De)=>{const t=String(e||"");if(t)for($e.add(t);$e.size>64;)$e.delete($e.values().next().value)},rt=(e={})=>{const t=String(e.turnId||"");return!(!t||ie||ae||$e.has(t)||t!==String(De||""))};async function nt(){const e=j?.thinkpool;return e?(Fe||(Fe=X({sdkServer:e})),Fe):null}function ot(e,t={}){if("thread/tokenUsage/updated"===e){if(t.threadId&&ee&&String(t.threadId)!==String(ee))return;(le||je)&&We();const e=codexUsageSnapshotFromAppServer(t.tokenUsage);if(!e)return;if(Ee=e,je){const{used:t,max:r}=e.context;Je({kind:"usage",ctx:{used:t,max:r,pct:Math.min(100,Math.max(0,Math.round(t/r*100))),over:t>r,model:Ce}})}return}if("turn/started"===e&&t.turn?.id){const e=String(t.turn.id);if(ie||ae)return void tt(e);if(Ue){const t=Ue;return Ue=null,void t.resolve(e)}return De||(De=e),void We()}if("turn/plan/updated"!==e&&"item/agentMessage/delta"!==e&&"item/started"!==e&&"item/completed"!==e&&"error"!==e||rt(t)){if(We(),"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 Je({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||De||"active"}`,r=ze.get(e)||{cid:`codex-stream:${ee||"thread"}:${e}`,text:""};return r.text+=String(t.delta),ze.set(e,r),void Je({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&&(Le.set(r.id,r),r.id&&I(r)&&qe.add(r.id)),"item/completed"===e&&(r.id&&qe.delete(r.id),Le.set(r.id,r),"agentMessage"===r.type&&ze.has(r.id))){const e=ze.get(r.id);return ze.delete(r.id),void Je({kind:"assistant",blocks:[{type:"text",text:r.text||e.text}],parentToolUseId:null,replacesCid:e.cid})}return void Ye({type:"item/started"===e?"item.started":"item.completed",item:R(r)})}if("error"===e){const e=t.error?.message||t.message||"codex app-server error";Ye({type:"error",message:e})}}}async function st(e,t={}){if(!rt(t))return"item/tool/requestUserInput"===e?{answers:{}}:{decision:"decline"};const r=codexApprovalCard(e,t,Le.get(t.itemId));if(!r)throw new Error(`Unsupported Codex App Server request: ${e}`);let n="deny";Me++;try{n=await(L?.(r))}catch{}finally{Me=Math.max(0,Me-1),We()}return"item/tool/requestUserInput"===e?codexUserInputResponse(n,r.questions):codexApprovalResponse(n)}async function at(){if(Oe)return!1;if(!1===Ae?.alive)return Re=!1,Oe=!0,!1;if(Ae&&Re)return!0;let t;try{t=await nt()}catch(e){et(`thinkpool peer tools unavailable: ${e?.message||e}`)}try{if(!Ae){const r=z({cwd:e,env:Y,args:a({providerConfig:A,mcpUrl:t?.url,writableDirs:codexExtraWritableDirsForMode(J,E,V.writableDirs),serviceTier:Te}),onNotification:ot,onServerRequest:st,codexHost:{...W,log:et},onClose:e=>{ie||Oe||Pe.has(r)||(Re=!1,Oe=!0,et(`Codex App Server closed; later turns will use codex exec: ${e?.message||e}`))}});Ae=r,await Ae.start(),We()}return ee=await Ae.startThread({threadId:te>0?ee:null,cwd:e,model:Ce,serviceTier:F(Te),sandbox:E,approvalPolicy:K.approvalPolicy,config:{"features.default_mode_request_user_input":!0}}),We(),t?.url&&(await Ae.waitForMcpServer({threadId:ee,name:"thinkpool"}),We()),Re=!0,Ye({type:"thread.started",thread_id:ee}),!0}catch{Oe=!0;try{Ae?.end()}catch{}return Ae=null,Re=!1,!1}}function it({force:e=!1}={}){const t=Ae,r=De;if(t&&e){tt(r),Oe=!0,Re=!1;try{t.end()}catch{}Ae===t&&(Ae=null)}else if(t&&r)tt(r),Promise.resolve(t.interrupt({threadId:ee,turnId:r})).catch(()=>{Oe=!0,Re=!1;try{t.end()}catch{}Ae===t&&(Ae=null)});else if(t){Oe=!0,Re=!1;try{t.end()}catch{}Ae===t&&(Ae=null)}if(se){const e=se;try{e.kill("SIGTERM")}catch{}setTimeout(()=>{if(se===e)try{e.kill("SIGKILL")}catch{}},1500)}}async function lt(e,t={}){if(ie||ae||we)return!0;if(!await at())return!1;if(ie||ae||we)return!0;Ke.setUsageBaseline(ee?readCodexThreadUsage(ee):null),le=!0;try{if(be=!1,De=await Ae.startTurn({threadId:ee,input:e,images:Array.isArray(t.images)?t.images:[],model:Ce,serviceTier:F(Te),effort:M(Ie),approvalPolicy:K.approvalPolicy,collaborationMode:codexDefaultCollaborationMode(Ce,Ie)}),We(),ae||ie){tt(De);try{await Ae.interrupt({threadId:ee,turnId:De})}catch{}return!0}const r=await Ae.waitForTurn(De);tt(r?.turn?.id||De);const n=r?.turn?.status;ae?Qe({kind:"result",subtype:"aborted",sessionId:ee,model:Ce,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"interrupted"===n&&(ve||we)||("interrupted"===n?Qe({kind:"result",subtype:"aborted",sessionId:ee,model:Ce,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"failed"===n?(ve=!1,Ye({type:"turn.failed",message:r?.turn?.error?.message||"codex turn failed"})):(ve=!1,Ye({type:"turn.completed"})))}catch(e){Oe=!0,Re=!1,tt(De);try{Ae?.end()}catch{}Ae=null,ie||ve||we||Ye({type:"turn.failed",message:`codex app-server turn failed: ${e?.message||e}`})}finally{Ve(),De=null,le=!1,qe.clear(),Le.clear(),ze.clear()}return!0}async function dt(e){if(ie||ae||we)return!0;if(!await at())return!1;if(ie||ae||we)return!0;Ke.setUsageBaseline(ee?readCodexThreadUsage(ee):null),le=!0;try{be=!1;const t=await Ae.startReview({threadId:ee,target:x(e)});if(De=t?.turn?.id||t?.turnId,!De)throw new Error("Codex review/start returned no turn id");if(We(),ae||ie){tt(De);try{await Ae.interrupt({threadId:ee,turnId:De})}catch{}return!0}const r=await Ae.waitForTurn(De);tt(r?.turn?.id||De);const n=r?.turn?.status;ae?Qe({kind:"result",subtype:"aborted",sessionId:ee,model:Ce,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"interrupted"===n&&(ve||we)||("interrupted"===n?Qe({kind:"result",subtype:"aborted",sessionId:ee,model:Ce,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"failed"===n?(ve=!1,Ye({type:"turn.failed",message:r?.turn?.error?.message||"codex review failed"})):(ve=!1,Ye({type:"turn.completed"})))}catch(e){Oe=!0,Re=!1,tt(De);try{Ae?.end()}catch{}Ae=null,ie||ve||we||Ye({type:"turn.failed",message:`codex review failed: ${e?.message||e}`})}finally{Ve(),De=null,le=!1,qe.clear(),Le.clear(),ze.clear()}return!0}async function ct(t,n={}){if(ie||ae||we)return;let o;try{o=await nt()}catch(e){et(`thinkpool peer tools unavailable: ${e?.message||e}`)}try{await(o?.handoff?.())}catch(e){et(`thinkpool peer handoff failed: ${e?.message||e}`)}const a=buildCodexExecArgs({sessionId:0===te?null:ee,model:Ce,serviceTier:Te,effort:Ie,sandbox:E,approvalPolicy:K.approvalPolicy,providerConfig:A,mcpUrl:o?.url,writableDirs:codexExtraWritableDirsForMode(J,E,V.writableDirs),images:Array.isArray(n.images)?n.images:[],prompt:t});Ke.setUsageBaseline(ee?readCodexThreadUsage(ee):null);const i=()=>new Promise((t,n)=>{let o;try{o=r.openSync("/dev/null","r")}catch{}const i={cwd:e,env:Y,stdio:["ignore","pipe","pipe"]};null!=o&&(i.stdio=[o,"pipe","pipe"]),le=!0,be=!1;try{se=G("codex",a,i)}catch(e){if(null!=o)try{r.closeSync(o)}catch{}return le=!1,e.codexExecFailure={spawnFailure:!0,hostRetrySafe:!0,message:`codex failed to start: ${e.message}`,sawTerminalResult:!1},void n(e)}if(null!=o)try{r.closeSync(o)}catch{}const l=se,d=[];s.createInterface({input:l.stdout,crlfDelay:1/0}).on("line",e=>{if(!e.trim())return;let t;try{t=JSON.parse(e)}catch{return}We(),d.push(t.type),"item.started"===t.type&&t.item?.id&&I(t.item)&&qe.add(t.item.id),"item.completed"===t.type&&t.item?.id&&qe.delete(t.item.id),"thread.started"===t.type&&t.thread_id&&(ee=ee||t.thread_id),"turn.completed"!==t.type&&"turn.failed"!==t.type||(u=!0,ve=!1),Ye(t)});let c="",u=!1,p=!1;l.stderr.on("data",e=>{c+=e.toString(),c.length>800&&(c=c.slice(-800))}),l.on("error",e=>{p||(p=!0,se===l&&(se=null),le=!1,qe.clear(),e.codexExecFailure={spawnFailure:!0,hostRetrySafe:0===d.length,message:`codex failed to start: ${e.message}`,sawTerminalResult:!1},n(e))}),l.on("close",e=>{if(p)return;p=!0,se===l&&(se=null),le=!1,qe.clear();const r=`codex exec exited ${e}${c?": "+c.trim().slice(-300):""}`,o=0!==e&&null!=e&&!u&&codexExecFailedBeforeTurn({stderr:c,eventTypes:d});if(!u&&0!==e&&null!=e){const e=new Error(r);return e.codexExecFailure={preTurnInitFailure:o,hostRetrySafe:0===d.length,message:r,sawTerminalResult:!1},void n(e)}ae&&!u&&Qe({kind:"result",subtype:"aborted",sessionId:ee,model:Ce,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null}),t({preTurnInitFailure:!1})})});try{return await S(i,{...W,log:et,shouldHeal:e=>!0===e?.codexExecFailure?.hostRetrySafe&&!0!==e?.codexExecFailure?.preTurnInitFailure})}catch(e){se=null,le=!1,qe.clear();const t=e?.codexExecFailure||e?.cause?.codexExecFailure||{};if("TP_CODEX_HOST_MISSING"===e?.code)Qe({kind:"error",message:e.message,recoverable:!0});else{if(t.preTurnInitFailure&&!ae&&!we)return{preTurnInitFailure:!0,message:t.message};(!ve&&!we||ae)&&Qe(ae?{kind:"result",subtype:"aborted",sessionId:ee,model:Ce,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null}:{kind:"error",message:t.message||e?.message||"codex failed to start",recoverable:!0})}return{preTurnInitFailure:!1}}}function ut(){if(ie)return;const e=He.shift();e&&(Ge=Ge.then(async()=>{const t=Math.max(0,Number(e.options?._stallRecoveryAttempt)||0);Ze({recoveryAttempt:t}),t>0&&Be({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:P,rolePrompt:D,roomContext:()=>oe({force:n}),firstTurn:0===te,promptIndex:e.promptIndex,forceFullReminder:e.forceFullReminder,turnCause:r}),s=/^\s*\/review(?:\s|$)/i.test(String(e.text||""));let a=!1,i=!1;for(;!ie&&!ae&&!we;){if(!(s?await dt(e.text):await lt(o,e.options)))if(s)ve=!1,Qe({kind:"error",message:"Codex review is unavailable without the tested App Server runtime.",recoverable:!0});else{ve&&(ve=!1,a=!0,Ze({retry:!0,recoveryAttempt:t}),Be({kind:"note",text:"retrying the stalled turn on a fresh connection"}));const r=await ct(o,e.options);if(r?.preTurnInitFailure){if(!(i||ie||ae||we)){i=!0,Ze({retry:!0,recoveryAttempt:t}),Be({kind:"note",text:"Codex initialization failed before the turn started; retrying once with a fresh thinkpool connection."});continue}Qe({kind:"error",message:r.message,recoverable:!0})}}if(!ve||a||we||ie||ae)break;ve=!1,a=!0,Ze({retry:!0,recoveryAttempt:t}),Be({kind:"note",text:"retrying the stalled turn on a fresh connection"})}te++,ut()}))}return Q&&!Z&&queueMicrotask(()=>et("The stopped Codex turn had no resumable context; continuing in a fresh thread.")),["0","false","off"].includes(String(Y.TP_CODEX_APP_SERVER||"").trim().toLowerCase())||Ne.enabled||queueMicrotask(()=>et(`Codex App Server disabled: ${Ne.reason}`)),_e=ce(()=>{const e=de()-xe,t=v({turnActive:le,awaitingUser:Me,quietMs:e,stallMs:pe,forceStopMs:["max","ultra"].includes(Ie)?fe:me,stalledSent:ge,stallRetried:ye});if("none"===t)return;if("retry"===t&&!be)return we=!0,ve=!1,Se>0?(Be({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."}),Be({kind:"suggestion",text:CODEX_STALL_RETRY_SUGGESTION})):qe.size>0?Be({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."}):(He.unshift({text:CODEX_STALL_CONTINUATION_PROMPT,options:{_stallRecoveryAttempt:1},promptIndex:re++,forceFullReminder:!0}),Be({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."})),Qe({kind:"result",subtype:"aborted",sessionId:ee,model:Ce,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null}),void it({force:!0});const r=w(t,e);if(r&&Be(r),"status"!==t){if("retry"===t)return ye=!0,ve=!0,xe=de(),ge=!1,void it();we=!0,ve=!1,He.length=0,Qe({kind:"result",subtype:"aborted",sessionId:ee,model:Ce,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null}),it({force:!0})}else ge=!0},he),_e.unref?.(),{get sessionId(){return ee},get usageSnapshot(){return Ee},get turnActive(){return le||je},get canSteer(){return!(!Ae||!1===Ae.alive||!Re||Oe)},get started(){return le||je||!!se||!(!Ae||!1===Ae.alive)},sendTurn(t,r={}){if(ie)return!1;if(!le&&0===He.length&&!Re&&!se){const e="function"==typeof H?H():{ok:!0};if(!1===e?.ok)return Je({kind:"error",message:e.reason||"Host memory is critically low. This Codex runtime was not started.",recoverable:!0}),!1}const n=re++,o=ne;if(ne=g(t)||/^\s*\/(?:reset|clear)\b/i.test(String(t||"")),!le&&0===te&&$)try{e=$()||e}catch{}if(le&&Ae&&De){We();const e=r?.turnCause||null,s=f({promptIndex:n,forceFull:o,turnCause:e}),a=buildCodexPrompt({text:t,terminalRolePrompt:P,rolePrompt:D,roomContext:()=>oe({force:s}),promptIndex:n,forceFullReminder:o,turnCause:e}),i=De;return Xe=Xe.then(()=>Ae.steer({threadId:ee,turnId:i,input:a,images:Array.isArray(r.images)?r.images:[]})).catch(e=>{"rejected"===e?.delivery||"not_sent"===e?.delivery?(He.push({text:t,options:r,promptIndex:n,forceFullReminder:o}),le||1!==He.length||ut()):Je({kind:"error",message:"Codex steering delivery is uncertain; the message was not replayed automatically.",recoverable:!0})}),!0}return He.push({text:t,options:r,promptIndex:n,forceFullReminder:o}),le||je||(ae=!1,Ze({recoveryAttempt:0})),1!==He.length||je||ut(),!0},async park(){if(ie||le||je||He.length)return!1;const e=Ge;try{await e}catch{}try{await Xe}catch{}if(ie||le||je||He.length||se||De)return!1;const t=Ae;if(t){Pe.add(t),Ae=null,Re=!1,Le.clear(),ze.clear();try{t.end()}catch{return!1}}return!0},abort(){const e=Ge,t=le&&!De&&!se;ae=!0,ve=!1,we=!1,He.length=0,tt(De);let r=Promise.resolve();if(Ae&&De&&(r=Ae.interrupt({threadId:ee,turnId:De}).catch(()=>{})),se){try{se.kill("SIGTERM")}catch{}setTimeout(()=>{try{se?.kill("SIGKILL")}catch{}},1500)}else t&&Qe({kind:"result",subtype:"aborted",sessionId:ee,model:Ce,costUsd:null,usage:null,numTurns:0,durationMs:void 0,denials:0,resultText:null});return r.then(()=>e).catch(()=>e).then(()=>{})},end(){if(ie=!0,le=!1,_e&&ue(_e),Je.cancel(),He.length=0,tt(De),se)try{se.kill()}catch{}try{Ae?.end()}catch{}Fe?.then(e=>e.close()).catch(()=>{})},setModel(e){if(!e||le)return!1;const t=String(e);if(!ke.has(t))return!1;Ce=t,Ke.setModel(Ce);const r=C(Ie,{models:p,model:Ce});return r!==Ie&&(Ie=r,Je({kind:"effort",level:Ie})),"fast"!==Te||codexModelSupportsFastMode({models:p,model:Ce})||(Te="default"),!0},setServiceTier(e){if(le||je||He.length)return!1;const t=normalizeCodexServiceTier(e);if(!t)return!1;if("fast"===t&&!codexModelSupportsFastMode({models:p,model:Ce}))return!1;if(t===Te)return!0;Te=t;const r=Ae;if(r){Pe.add(r),Ae=null,Re=!1,Le.clear(),ze.clear();try{r.end()}catch{}}return!0},setMode:e=>!(le||!CODEX_MODE_CONFIG[e]||(J=e,K=codexConfigForMode(J),E=K.sandbox,ee=null,te=0,Ee=null,Re=!1,0)),setEffort:e=>!(le||!_({models:p,model:Ce}).includes(e)||(Ie=e,Je({kind:"effort",level:Ie}),0)),get serviceTier(){return Te},get supportsFastMode(){return codexModelSupportsFastMode({models:p,model:Ce})},clearContext:()=>!le&&(ee=null,te=0,Ee=null,Re=!1,!0),async compactContext(){if(le||je)return!1;ae=!1,je=!0;let e=null,t=!1;try{if(!await at()||le)return!1;const r=new Promise((t,r)=>{e=setTimeout(()=>{Ue=null,r(new Error("Codex did not start the compaction turn"))},5e3),Ue={resolve:t,reject:r}});await Ae.compact({threadId:ee}),t=!0;const n=await r;e&&clearTimeout(e);const o=await Ae.waitForTurn(n);tt(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)?(et(`Native Codex compaction status is uncertain; existing context was preserved: ${e?.message||e}`),null):(et(`Native Codex compaction unavailable; using bounded recap fallback: ${e?.message||e}`),!1)}finally{e&&clearTimeout(e),Ue=null,je=!1,He.length&&ut()}},async accountUsage(){if(!await at())return null;const[e,t]=await Promise.all([Ae.accountUsage().catch(()=>null),Ae.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 s from"node:readline";import{buildCodexAppServerArgs as a,codexAppServerGate as i,createCodexAppServer as l}from"./codex-app-server.mjs";import{CodexEventMapper as d}from"./codex-event-mapper.mjs";import{startCodexMcpHttp as c}from"./codex-mcp-http.mjs";import{CODEX_THINKPOOL_FIRST_TURN_PREAMBLE as u,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 w}from"./turn-stall.mjs";import{codexCatastrophicHookCliArgs as b}from"./catastrophic-command-guard.mjs";import{retryCodexSpawnAfterHostHeal as S}from"./codex-host-heal.mjs";import{codexNativeReasoningEffort as C,codexReasoningEfforts as M,normalizeCodexReasoningEffort as _,normalizeReasoningEffortList as T}from"./reasoning-effort.mjs";const k=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 I=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=C(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:d=n.tmpdir(),fsImpl:c=r,spawnImpl:u=t,codexHost:p={}}={}){const m=String(e||"").trim();if(!m)throw new Error("codex one-shot requires a prompt");const f=!l,h=l||c.mkdtempSync(o.join(d,"thinkpool-codex-one-shot-"));let x=null;try{i&&(x=o.join(h,"output-schema.json"),c.writeFileSync(x,`${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)]:[],...x?["--output-schema",x]:[],m];return await S(()=>new Promise((t,r)=>{let n,o,s="",i="",l=!1;const d=(e,n)=>{l||(l=!0,o&&clearTimeout(o),e?r(e):t(n))};try{n=u("codex",e,{cwd:h,env:process.env,stdio:["ignore","pipe","pipe"]})}catch(e){return void d(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=>d(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?d(null,t):d(new Error(`Codex cleanup failed${null==e?"":` (${e})`}${i.trim()?`: ${i.trim().slice(-240)}`:""}`))}),o=setTimeout(()=>{try{n.kill("SIGTERM")}catch{}d(new Error("Codex cleanup timed out"))},Math.max(1e3,Number(a)||22e3))}),p)}finally{if(f)try{c.rmSync(h,{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 normalizeCodexServiceTier(e){const t=String(e||"").trim().toLowerCase();return"priority"===t?"fast":"fast"===t||"default"===t?t:null}export function readCodexDefaultServiceTier({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*service_tier\s*=\s*["']([^"']+)["']\s*(?:#.*)?$/m);return normalizeCodexServiceTier(r?.[1])}catch{return null}}const E=e=>[...new Set((Array.isArray(e)?e:[]).map(e=>normalizeCodexServiceTier("string"==typeof e?e:e?.id)).filter(Boolean))];export function codexModelSupportsFastMode({models:e=[],model:t}={}){const r=(Array.isArray(e)?e:[]).find(e=>e?.value===t);return E(r?.serviceTiers).includes("fast")}const F=e=>"fast"===normalizeCodexServiceTier(e)?"priority":normalizeCodexServiceTier(e);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:T(e.supported_reasoning_levels),serviceTiers:E(e.service_tiers||e.additional_speed_tiers)}))}catch{return[]}}export function codexModelsFromNativeList(e=[]){return(Array.isArray(e)?e:[]).filter(e=>e?.model&&!0!==e.hidden).map(e=>({value:e.model,displayName:e.displayName||e.model,description:e.description||"",reasoningEfforts:T((e.supportedReasoningEfforts||[]).map(e=>e?.reasoningEffort||e)),serviceTiers:E(e.additionalSpeedTiers)}))}export async function loadCodexModelCatalog({cwd:e=process.cwd(),env:t=process.env,home:s=t.CODEX_HOME||o.join(n.homedir(),".codex"),fsImpl:a=r,appServerFactory:i=l,timeoutMs:d=1e4,settleMs:c=1e3,maxAttempts:u=3,sleepImpl:p=e=>new Promise(t=>setTimeout(t,e))}={}){const m=readCodexModels({home:s,fsImpl:a});let f=null;try{f=i({cwd:e,env:t,initializeTimeoutMs:d}),await f.start();let r=null,n=null;const o=Math.max(2,Number(u)||3);for(let e=0;e<o;e++){try{const e=await f.request("model/list",{includeHidden:!1},d),t=codexModelsFromNativeList(e?.data);(!r||t.length>=r.length)&&(r=t)}catch(e){n=e}e+1<o&&await p(Math.max(0,Number(c)||0))}if(!r)throw n||new Error("native catalog returned no response");return{models:r,source:"model/list",attempts:o,...n?{reason:n?.message||String(n)}:{}}}catch(e){return{models:m,source:"disk-cache",reason:e?.message||String(e)}}finally{try{f?.end()}catch{}}}const N=new Map;function O(e,{home:t,fsImpl:r}){if(!e)return null;const n=`${t}\0${e}`,s=N.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 N.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=O(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=O(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 k.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 and shared work-routing contract. Internal Codex collaboration workers and hidden in-process subagents are not thinkpool terminals. Use open_main_terminal or spawn_terminal only when the role and runtime policy permit it. Leaf, worker, Side, and managed Flow lanes work directly and must not delegate.";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,d=f({promptIndex:s,forceFull:a,turnCause:i}),c=[o?u:"",d?t:"",p({text:e,promptIndex:s,forceFull:a,turnCause:i}),d?r||CODEX_ROOM_CASCADE_REMINDER:"",l].map(e=>String(e||"").trim()).filter(Boolean);return c.length?`<thinkpool-context>\n${c.join("\n\n")}\n</thinkpool-context>\n\n${String(e??"")}`:String(e??"")}export function buildCodexExecArgs({sessionId:e,model:t,serviceTier:r,effort:n,sandbox:s,approvalPolicy:a="untrusted",providerConfig:i,mcpUrl:l,writableDirs:d=[],images:c=[],prompt:u}){const p=normalizeCodexSandbox(s),m=[...b(),...e?["exec","resume","--json","--skip-git-repo-check",..."danger-full-access"===p?["--dangerously-bypass-approvals-and-sandbox"]:["-c",`sandbox_mode="${p}"`]]:["exec","--json","--sandbox",p,"--skip-git-repo-check"]];t&&m.push("-m",t);const f=normalizeCodexServiceTier(r);f&&(m.push("-c",`service_tier=${JSON.stringify(f)}`),"fast"===f&&m.push("-c","features.fast_mode=true")),m.push("-c",`approval_policy="${a}"`);const h=C(n);if(h&&m.push("-c",`model_reasoning_effort="${h}"`),i&&m.push("-c",i),!e)for(const e of d)m.push("--add-dir",e);l&&(m.push("-c",`mcp_servers.thinkpool.url=${JSON.stringify(l)}`),m.push("-c","mcp_servers.thinkpool.required=true"));let x=!1;for(const e of c)o.isAbsolute(String(e||""))&&(m.push("--image",String(e)),x=!0);return x&&m.push("--"),e&&m.push(e),m.push(String(u??"")),m}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 A=/\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:A.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 R(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:u,models:p=[],serviceTier:h=null,effort:b="high",resume:T,env:k,sandbox:E,mode:N="default",onEvent:O,onCommandComplete:A,providerConfig:P,terminalRolePrompt:D,rolePrompt:U,roomContext:j,mcpServers:$,prepareCwd:L=null,requestPermission:q,appServerGate:z=i,appServerFactory:X=l,mcpHttpFactory:G=c,spawnImpl:H=t,admitStart:B=null,stallOptions:W={},codexHost:J={}}){let K=CODEX_MODE_CONFIG[N]?N:"default",Y=codexConfigForMode(K);E=normalizeCodexSandbox(E||Y.sandbox);const Q=codexPublishAccess({cwd:e,env:{...process.env,...k||{}}}),V=Q.env,Z=T||null,ee=!Z||codexThreadCanResume(Z,{home:V.CODEX_HOME||o.join(n.homedir(),".codex")});let te=ee?Z:null,re=te?1:0,ne=0,oe=!0;const se=m(j);let ae=null,ie=!1,le=!1,de=!1;const ce="function"==typeof W.now?W.now:Date.now,ue="function"==typeof W.setInterval?W.setInterval:setInterval,pe="function"==typeof W.clearInterval?W.clearInterval:clearInterval,me=Number.isFinite(W.stallMs)?Math.max(1,Number(W.stallMs)):Math.max(3e4,parseInt(V.TP_STALL_MS,10)||9e4),fe=Number.isFinite(W.forceStopMs)?Math.max(me,Number(W.forceStopMs)):Math.max(3*me,parseInt(V.TP_FORCE_STOP_MS,10)||3e5),he=Number.isFinite(W.longReasoningForceStopMs)?Math.max(fe,Number(W.longReasoningForceStopMs)):Math.max(fe,parseInt(V.TP_LONG_REASONING_FORCE_STOP_MS,10)||12e5),xe=Number.isFinite(W.intervalMs)?Math.max(1,Number(W.intervalMs)):5e3;let ge=ce(),ye=!1,ve=!1,we=!1,be=!1,Se=!0,Ce=0,Me=0,_e=null,Te=u||null;const ke=new Set((Array.isArray(p)?p:[]).map(e=>"string"==typeof e?e:e?.value||e?.slug).filter(Boolean));let Ie=normalizeCodexServiceTier(h);"fast"!==Ie||codexModelSupportsFastMode({models:p,model:Te})||(Ie="default");let Ee=_(b,{models:p,model:Te}),Fe=te?readCodexThreadUsage(te):null,Ne=null;const Oe=z({env:V});let Ae=!Oe.enabled,Re=null,Pe=!1;const De=new WeakSet;let Ue=null,je=null,$e=!1;const Le=new Set,qe=new Map,ze=new Set,Xe=new Map;let Ge=Promise.resolve(),He=Promise.resolve();const Be=[];let We=null;const Je=new Set,Ke=y(e=>{try{O?.(e)}catch{}}),Ye=()=>{ge=ce(),ye=!1},Qe=e=>{if(Ye(),"result"===e.kind){const t=new Set(We?.completed?[]:We?.cids||[]);if(We&&(We.completed=!0),"aborted"===e.subtype&&ie){for(const e of Je)t.add(e);Je.clear()}e={...e,commandCids:[...t]}}Ke(e)};Qe.cancel=()=>Ke.cancel();const Ve=new d({onEvent:Qe,model:u||null,usageSnapshotForSession:e=>{const t=readCodexThreadUsage(e);return t&&(Fe=t),t||Fe}}),Ze=()=>{const e=[...Xe.values()];Xe.clear();for(const t of e)t.text&&Qe({kind:"assistant",blocks:[{type:"text",text:t.text}],parentToolUseId:null,replacesCid:t.cid})},et=e=>{"turn.completed"!==e?.type&&"turn.failed"!==e?.type||(Ze(),de=!1),Ve.push(e)},tt=e=>{Ze(),de=!1,Qe(e)},rt=({retry:e=!1,recoveryAttempt:t=0}={})=>{de=!0,ge=ce(),ye=!1,we=!1,be=!1,Se=!0,Ce=Math.max(0,Number(t)||0),e||(ve=!1)},nt=e=>Qe({kind:"note",text:e}),ot=(e=Ue)=>{const t=String(e||"");if(t)for(Le.add(t);Le.size>64;)Le.delete(Le.values().next().value)},st=(e={})=>{const t=String(e.turnId||"");return!(!t||le||ie||Le.has(t)||t!==String(Ue||""))};async function at(){const e=$?.thinkpool;return e?(Ne||(Ne=G({sdkServer:e})),Ne):null}function it(e,t={}){if("thread/tokenUsage/updated"===e){if(t.threadId&&te&&String(t.threadId)!==String(te))return;(de||$e)&&Ye();const e=codexUsageSnapshotFromAppServer(t.tokenUsage);if(!e)return;if(Fe=e,$e){const{used:t,max:r}=e.context;Qe({kind:"usage",ctx:{used:t,max:r,pct:Math.min(100,Math.max(0,Math.round(t/r*100))),over:t>r,model:Te}})}return}if("turn/started"===e&&t.turn?.id){const e=String(t.turn.id);if(le||ie)return void ot(e);if(je){const t=je;return je=null,void t.resolve(e)}return Ue||(Ue=e),void Ye()}if("turn/plan/updated"!==e&&"item/agentMessage/delta"!==e&&"item/started"!==e&&"item/completed"!==e&&"error"!==e||st(t)){if(Ye(),"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 Qe({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||Ue||"active"}`,r=Xe.get(e)||{cid:`codex-stream:${te||"thread"}:${e}`,text:""};return r.text+=String(t.delta),Xe.set(e,r),void Qe({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&&(qe.set(r.id,r),r.id&&I(r)&&ze.add(r.id)),"item/completed"===e&&(r.id&&ze.delete(r.id),qe.set(r.id,r),"agentMessage"===r.type&&Xe.has(r.id))){const e=Xe.get(r.id);return Xe.delete(r.id),void Qe({kind:"assistant",blocks:[{type:"text",text:r.text||e.text}],parentToolUseId:null,replacesCid:e.cid})}return void et({type:"item/started"===e?"item.started":"item.completed",item:R(r)})}if("error"===e){const e=t.error?.message||t.message||"codex app-server error";et({type:"error",message:e})}}}async function lt(e,t={}){if(!st(t))return"item/tool/requestUserInput"===e?{answers:{}}:{decision:"decline"};const r=codexApprovalCard(e,t,qe.get(t.itemId));if(!r)throw new Error(`Unsupported Codex App Server request: ${e}`);let n="deny";Me++;try{n=await(q?.(r))}catch{}finally{Me=Math.max(0,Me-1),Ye()}return"item/tool/requestUserInput"===e?codexUserInputResponse(n,r.questions):codexApprovalResponse(n)}async function dt(){if(Ae)return!1;if(!1===Re?.alive)return Pe=!1,Ae=!0,!1;if(Re&&Pe)return!0;let t;try{t=await at()}catch(e){nt(`thinkpool peer tools unavailable: ${e?.message||e}`)}try{if(!Re){const r=X({cwd:e,env:V,args:a({providerConfig:P,mcpUrl:t?.url,writableDirs:codexExtraWritableDirsForMode(K,E,Q.writableDirs),serviceTier:Ie}),onNotification:it,onServerRequest:lt,codexHost:{...J,log:nt},onClose:e=>{le||Ae||De.has(r)||(Pe=!1,Ae=!0,nt(`Codex App Server closed; later turns will use codex exec: ${e?.message||e}`))}});Re=r,await Re.start(),Ye()}return te=await Re.startThread({threadId:re>0?te:null,cwd:e,model:Te,serviceTier:F(Ie),sandbox:E,approvalPolicy:Y.approvalPolicy,config:{"features.default_mode_request_user_input":!0}}),Ye(),t?.url&&(await Re.waitForMcpServer({threadId:te,name:"thinkpool"}),Ye()),Pe=!0,et({type:"thread.started",thread_id:te}),!0}catch{Ae=!0;try{Re?.end()}catch{}return Re=null,Pe=!1,!1}}function ct({force:e=!1}={}){const t=Re,r=Ue;if(t&&e){ot(r),Ae=!0,Pe=!1;try{t.end()}catch{}Re===t&&(Re=null)}else if(t&&r)ot(r),Promise.resolve(t.interrupt({threadId:te,turnId:r})).catch(()=>{Ae=!0,Pe=!1;try{t.end()}catch{}Re===t&&(Re=null)});else if(t){Ae=!0,Pe=!1;try{t.end()}catch{}Re===t&&(Re=null)}if(ae){const e=ae;try{e.kill("SIGTERM")}catch{}setTimeout(()=>{if(ae===e)try{e.kill("SIGKILL")}catch{}},1500)}}async function ut(e,t={}){if(le||ie||be)return!0;if(!await dt())return!1;if(le||ie||be)return!0;Ve.setUsageBaseline(te?readCodexThreadUsage(te):null),de=!0;try{if(Se=!1,Ue=await Re.startTurn({threadId:te,input:e,images:Array.isArray(t.images)?t.images:[],model:Te,serviceTier:F(Ie),effort:C(Ee),approvalPolicy:Y.approvalPolicy,collaborationMode:codexDefaultCollaborationMode(Te,Ee)}),Ye(),ie||le){ot(Ue);try{await Re.interrupt({threadId:te,turnId:Ue})}catch{}return!0}const r=await Re.waitForTurn(Ue);ot(r?.turn?.id||Ue);const n=r?.turn?.status;ie?tt({kind:"result",subtype:"aborted",sessionId:te,model:Te,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"interrupted"===n&&(we||be)||("interrupted"===n?tt({kind:"result",subtype:"aborted",sessionId:te,model:Te,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"failed"===n?(we=!1,et({type:"turn.failed",message:r?.turn?.error?.message||"codex turn failed"})):(we=!1,et({type:"turn.completed"})))}catch(e){Ae=!0,Pe=!1,ot(Ue);try{Re?.end()}catch{}Re=null,le||we||be||et({type:"turn.failed",message:`codex app-server turn failed: ${e?.message||e}`})}finally{Ze(),Ue=null,de=!1,ze.clear(),qe.clear(),Xe.clear()}return!0}async function pt(e){if(le||ie||be)return!0;if(!await dt())return!1;if(le||ie||be)return!0;Ve.setUsageBaseline(te?readCodexThreadUsage(te):null),de=!0;try{Se=!1;const t=await Re.startReview({threadId:te,target:x(e)});if(Ue=t?.turn?.id||t?.turnId,!Ue)throw new Error("Codex review/start returned no turn id");if(Ye(),ie||le){ot(Ue);try{await Re.interrupt({threadId:te,turnId:Ue})}catch{}return!0}const r=await Re.waitForTurn(Ue);ot(r?.turn?.id||Ue);const n=r?.turn?.status;ie?tt({kind:"result",subtype:"aborted",sessionId:te,model:Te,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"interrupted"===n&&(we||be)||("interrupted"===n?tt({kind:"result",subtype:"aborted",sessionId:te,model:Te,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"failed"===n?(we=!1,et({type:"turn.failed",message:r?.turn?.error?.message||"codex review failed"})):(we=!1,et({type:"turn.completed"})))}catch(e){Ae=!0,Pe=!1,ot(Ue);try{Re?.end()}catch{}Re=null,le||we||be||et({type:"turn.failed",message:`codex review failed: ${e?.message||e}`})}finally{Ze(),Ue=null,de=!1,ze.clear(),qe.clear(),Xe.clear()}return!0}async function mt(t,n={}){if(le||ie||be)return;let o;try{o=await at()}catch(e){nt(`thinkpool peer tools unavailable: ${e?.message||e}`)}try{await(o?.handoff?.())}catch(e){nt(`thinkpool peer handoff failed: ${e?.message||e}`)}const a=buildCodexExecArgs({sessionId:0===re?null:te,model:Te,serviceTier:Ie,effort:Ee,sandbox:E,approvalPolicy:Y.approvalPolicy,providerConfig:P,mcpUrl:o?.url,writableDirs:codexExtraWritableDirsForMode(K,E,Q.writableDirs),images:Array.isArray(n.images)?n.images:[],prompt:t});Ve.setUsageBaseline(te?readCodexThreadUsage(te):null);const i=()=>new Promise((t,n)=>{let o;try{o=r.openSync("/dev/null","r")}catch{}const i={cwd:e,env:V,stdio:["ignore","pipe","pipe"]};null!=o&&(i.stdio=[o,"pipe","pipe"]),de=!0,Se=!1;try{ae=H("codex",a,i)}catch(e){if(null!=o)try{r.closeSync(o)}catch{}return de=!1,e.codexExecFailure={spawnFailure:!0,hostRetrySafe:!0,message:`codex failed to start: ${e.message}`,sawTerminalResult:!1},void n(e)}if(null!=o)try{r.closeSync(o)}catch{}const l=ae,d=[];s.createInterface({input:l.stdout,crlfDelay:1/0}).on("line",e=>{if(!e.trim())return;let t;try{t=JSON.parse(e)}catch{return}Ye(),d.push(t.type),"item.started"===t.type&&t.item?.id&&I(t.item)&&ze.add(t.item.id),"item.completed"===t.type&&t.item?.id&&ze.delete(t.item.id),"thread.started"===t.type&&t.thread_id&&(te=te||t.thread_id),"turn.completed"!==t.type&&"turn.failed"!==t.type||(u=!0,we=!1),et(t)});let c="",u=!1,p=!1;l.stderr.on("data",e=>{c+=e.toString(),c.length>800&&(c=c.slice(-800))}),l.on("error",e=>{p||(p=!0,ae===l&&(ae=null),de=!1,ze.clear(),e.codexExecFailure={spawnFailure:!0,hostRetrySafe:0===d.length,message:`codex failed to start: ${e.message}`,sawTerminalResult:!1},n(e))}),l.on("close",e=>{if(p)return;p=!0,ae===l&&(ae=null),de=!1,ze.clear();const r=`codex exec exited ${e}${c?": "+c.trim().slice(-300):""}`,o=0!==e&&null!=e&&!u&&codexExecFailedBeforeTurn({stderr:c,eventTypes:d});if(!u&&0!==e&&null!=e){const e=new Error(r);return e.codexExecFailure={preTurnInitFailure:o,hostRetrySafe:0===d.length,message:r,sawTerminalResult:!1},void n(e)}ie&&!u&&tt({kind:"result",subtype:"aborted",sessionId:te,model:Te,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null}),t({preTurnInitFailure:!1})})});try{return await S(i,{...J,log:nt,shouldHeal:e=>!0===e?.codexExecFailure?.hostRetrySafe&&!0!==e?.codexExecFailure?.preTurnInitFailure})}catch(e){ae=null,de=!1,ze.clear();const t=e?.codexExecFailure||e?.cause?.codexExecFailure||{};if("TP_CODEX_HOST_MISSING"===e?.code)tt({kind:"error",message:e.message,recoverable:!0});else{if(t.preTurnInitFailure&&!ie&&!be)return{preTurnInitFailure:!0,message:t.message};(!we&&!be||ie)&&tt(ie?{kind:"result",subtype:"aborted",sessionId:te,model:Te,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null}:{kind:"error",message:t.message||e?.message||"codex failed to start",recoverable:!0})}return{preTurnInitFailure:!1}}}function ft(){if(le)return;const e=Be.shift();e&&(He=He.then(async()=>{We={cids:new Set(e.options?.commandCid?[e.options.commandCid]:[]),completed:!1},Je.delete(e.options?.commandCid);const t=Math.max(0,Number(e.options?._stallRecoveryAttempt)||0);rt({recoveryAttempt:t}),t>0&&Ke({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:D,rolePrompt:U,roomContext:()=>se({force:n}),firstTurn:0===re,promptIndex:e.promptIndex,forceFullReminder:e.forceFullReminder,turnCause:r}),s=/^\s*\/review(?:\s|$)/i.test(String(e.text||""));let a=!1,i=!1;for(;!le&&!ie&&!be;){if(!(s?await pt(e.text):await ut(o,e.options)))if(s)we=!1,tt({kind:"error",message:"Codex review is unavailable without the tested App Server runtime.",recoverable:!0});else{we&&(we=!1,a=!0,rt({retry:!0,recoveryAttempt:t}),Ke({kind:"note",text:"retrying the stalled turn on a fresh connection"}));const r=await mt(o,e.options);if(r?.preTurnInitFailure){if(!(i||le||ie||be)){i=!0,rt({retry:!0,recoveryAttempt:t}),Ke({kind:"note",text:"Codex initialization failed before the turn started; retrying once with a fresh thinkpool connection."});continue}tt({kind:"error",message:r.message,recoverable:!0})}}if(!we||a||be||le||ie)break;we=!1,a=!0,rt({retry:!0,recoveryAttempt:t}),Ke({kind:"note",text:"retrying the stalled turn on a fresh connection"})}re++,ft()}))}return Z&&!ee&&queueMicrotask(()=>nt("The stopped Codex turn had no resumable context; continuing in a fresh thread.")),["0","false","off"].includes(String(V.TP_CODEX_APP_SERVER||"").trim().toLowerCase())||Oe.enabled||queueMicrotask(()=>nt(`Codex App Server disabled: ${Oe.reason}`)),_e=ue(()=>{const e=ce()-ge,t=v({turnActive:de,awaitingUser:Me,quietMs:e,stallMs:me,forceStopMs:["max","ultra"].includes(Ee)?he:fe,stalledSent:ye,stallRetried:ve});if("none"===t)return;if("retry"===t&&!Se)return be=!0,we=!1,Ce>0?(Ke({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."}),Ke({kind:"suggestion",text:CODEX_STALL_RETRY_SUGGESTION})):ze.size>0?Ke({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."}):(Be.unshift({text:CODEX_STALL_CONTINUATION_PROMPT,options:{_stallRecoveryAttempt:1},promptIndex:ne++,forceFullReminder:!0}),Ke({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."})),tt({kind:"result",subtype:"aborted",sessionId:te,model:Te,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null}),void ct({force:!0});const r=w(t,e);if(r&&Ke(r),"status"!==t){if("retry"===t)return ve=!0,we=!0,ge=ce(),ye=!1,void ct();be=!0,we=!1,Be.length=0,tt({kind:"result",subtype:"aborted",sessionId:te,model:Te,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null}),ct({force:!0})}else ye=!0},xe),_e.unref?.(),{get sessionId(){return te},get usageSnapshot(){return Fe},get turnActive(){return de||$e},get canSteer(){return!(!Re||!1===Re.alive||!Pe||Ae)},get started(){return de||$e||!!ae||!(!Re||!1===Re.alive)},sendTurn(t,r={}){if(le)return!1;if(!de&&0===Be.length&&!Pe&&!ae){const e="function"==typeof B?B():{ok:!0};if(!1===e?.ok)return Qe({kind:"error",message:e.reason||"Host memory is critically low. This Codex runtime was not started.",recoverable:!0}),!1}const n=ne++,o=oe;if(oe=g(t)||/^\s*\/(?:reset|clear)\b/i.test(String(t||"")),!de&&0===re&&L)try{e=L()||e}catch{}if(de&&Re&&Ue){Ye();const e=r?.turnCause||null,s=f({promptIndex:n,forceFull:o,turnCause:e}),a=buildCodexPrompt({text:t,terminalRolePrompt:D,rolePrompt:U,roomContext:()=>se({force:s}),promptIndex:n,forceFullReminder:o,turnCause:e}),i=Ue,l=We;return Ge=Ge.then(()=>Re.steer({threadId:te,turnId:i,input:a,images:Array.isArray(r.images)?r.images:[]})).then(e=>{if(e?.turnId!==i)throw new Error("Codex steer did not acknowledge the expected turn");if(r.commandCid&&l&&(l.cids.add(r.commandCid),l.completed))try{A?.(r.commandCid)}catch{}}).catch(e=>{if("rejected"===e?.delivery||"not_sent"===e?.delivery){if(ie||le)return;r.commandCid&&Je.add(r.commandCid),Be.push({text:t,options:r,promptIndex:n,forceFullReminder:o}),de||1!==Be.length||ft()}else Qe({kind:"error",message:"Codex steering delivery is uncertain; the message was not replayed automatically.",recoverable:!0})}),!0}return r.commandCid&&Je.add(r.commandCid),Be.push({text:t,options:r,promptIndex:n,forceFullReminder:o}),de||$e||(ie=!1,rt({recoveryAttempt:0})),1!==Be.length||$e||ft(),!0},async park(){if(le||de||$e||Be.length)return!1;const e=He;try{await e}catch{}try{await Ge}catch{}if(le||de||$e||Be.length||ae||Ue)return!1;const t=Re;if(t){De.add(t),Re=null,Pe=!1,qe.clear(),Xe.clear();try{t.end()}catch{return!1}}return!0},abort(){const e=He,t=de&&!Ue&&!ae;ie=!0,we=!1,be=!1,Be.length=0,ot(Ue);let r=Promise.resolve();if(Re&&Ue&&(r=Re.interrupt({threadId:te,turnId:Ue}).catch(()=>{})),ae){try{ae.kill("SIGTERM")}catch{}setTimeout(()=>{try{ae?.kill("SIGKILL")}catch{}},1500)}else t&&tt({kind:"result",subtype:"aborted",sessionId:te,model:Te,costUsd:null,usage:null,numTurns:0,durationMs:void 0,denials:0,resultText:null});return r.then(()=>e).catch(()=>e).then(()=>{})},end(){if(le=!0,de=!1,_e&&pe(_e),Qe.cancel(),Be.length=0,ot(Ue),ae)try{ae.kill()}catch{}try{Re?.end()}catch{}Ne?.then(e=>e.close()).catch(()=>{})},setModel(e){if(!e||de)return!1;const t=String(e);if(!ke.has(t))return!1;Te=t,Ve.setModel(Te);const r=_(Ee,{models:p,model:Te});return r!==Ee&&(Ee=r,Qe({kind:"effort",level:Ee})),"fast"!==Ie||codexModelSupportsFastMode({models:p,model:Te})||(Ie="default"),!0},setServiceTier(e){if(de||$e||Be.length)return!1;const t=normalizeCodexServiceTier(e);if(!t)return!1;if("fast"===t&&!codexModelSupportsFastMode({models:p,model:Te}))return!1;if(t===Ie)return!0;Ie=t;const r=Re;if(r){De.add(r),Re=null,Pe=!1,qe.clear(),Xe.clear();try{r.end()}catch{}}return!0},setMode:e=>!(de||!CODEX_MODE_CONFIG[e]||(K=e,Y=codexConfigForMode(K),E=Y.sandbox,te=null,re=0,Fe=null,Pe=!1,0)),setEffort:e=>!(de||!M({models:p,model:Te}).includes(e)||(Ee=e,Qe({kind:"effort",level:Ee}),0)),get serviceTier(){return Ie},get supportsFastMode(){return codexModelSupportsFastMode({models:p,model:Te})},clearContext:()=>!de&&(te=null,re=0,Fe=null,Pe=!1,!0),async compactContext(){if(de||$e)return!1;ie=!1,$e=!0;let e=null,t=!1;try{if(!await dt()||de)return!1;const r=new Promise((t,r)=>{e=setTimeout(()=>{je=null,r(new Error("Codex did not start the compaction turn"))},5e3),je={resolve:t,reject:r}});await Re.compact({threadId:te}),t=!0;const n=await r;e&&clearTimeout(e);const o=await Re.waitForTurn(n);ot(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)?(nt(`Native Codex compaction status is uncertain; existing context was preserved: ${e?.message||e}`),null):(nt(`Native Codex compaction unavailable; using bounded recap fallback: ${e?.message||e}`),!1)}finally{e&&clearTimeout(e),je=null,$e=!1,Be.length&&ft()}},async accountUsage(){if(!await dt())return null;const[e,t]=await Promise.all([Re.accountUsage().catch(()=>null),Re.accountRateLimits().catch(()=>null)]);return{usage:e,limits:t}}}}
@@ -1 +1 @@
1
- import{createHash as e}from"node:crypto";import{BLOCKED_REASON as t,projectLaneLifecycle as r}from"./lane-lifecycle.mjs";import{normalizeCascadeMetadata as n}from"./worker-completion.mjs";export const PEEK={defaultLines:20,maxLines:200,perTurnCap:10,rosterPerTurnCap:1,lineCap:200,finalAssistantCap:24e3,rosterPreview:100};export const readTerminalBudgetDecision=({targeted:e=!1,targetedCount:t=0,rosterCount:r=0}={},n=PEEK)=>{const o=Math.max(0,Number(t)||0),i=Math.max(0,Number(r)||0);return e?o>=n.perTurnCap?{ok:!1,targetedCount:o,rosterCount:i,reason:`Cross-terminal transcript read limit reached for this turn (${n.perTurnCap}). Stop polling and continue with the worker results already collected; a fresh accepted room turn resets the allowance.`}:{ok:!0,targetedCount:o+1,rosterCount:i}:i>=n.rosterPerTurnCap?{ok:!1,targetedCount:o,rosterCount:i,reason:`The full terminal roster was already read this turn (${n.rosterPerTurnCap}/${n.rosterPerTurnCap}). Use the current ROOM NOW snapshot or read one relevant terminal by ref or name.`}:{ok:!0,targetedCount:o,rosterCount:i+1}};export const readTerminalTurnBudgetDecision=({targeted:e=!1,targetedCount:t=0,rosterCount:r=0,budgetTurnRev:n=null,currentTurnRev:o=0}={},i=PEEK)=>{const s=Math.max(0,Number(o)||0),a=(null==n?null:Number.isFinite(Number(n))?Number(n):null)===s;return{...readTerminalBudgetDecision({targeted:e,targetedCount:a?t:0,rosterCount:a?r:0},i),budgetTurnRev:s}};export const LANE_STATUS={stuckAfterMs:9e4,repeatedFailureCount:2,failureWindow:12};const o=e=>!!e&&("error"===e.kind||"tool_result"===e.kind&&e.isError||"result"===e.kind&&e.subtype&&"success"!==e.subtype);export const laneBusyOf=(e={})=>"boolean"==typeof e?.busy?e.busy:"boolean"==typeof e?._busyAnn?e._busyAnn:e?.session?.turnActive??!1;export const settleLaneBusy=e=>!(!e||!1===e._busyAnn||(e._busyAnn=!1,0));export const settleLaneControl=(e,t=Date.now())=>!(!e||!0!==e._busyAnn||!settleLaneBusy(e)||(e._settledTurnRev=Number(e._turnRev)||null,e._turnSettledAt=Number(t)||Date.now(),e._turnStart=null,0));export const laneStatusOf=(e={},n=Date.now(),i=LANE_STATUS)=>{const s=Array.isArray(e?.log)?e.log:[],a=s.slice(-i.failureWindow);!e?.lastEvent||e.lastEvent===s[s.length-1]||e.lastEvent.cid&&e.lastEvent.cid===s[s.length-1]?.cid||a.push(e.lastEvent);let l=null;for(let e=a.length-1;e>=0;e--)if(Number.isFinite(a[e]?.ts)){l=a[e].ts;break}const c=Number.isFinite(e?.lastActionAt)?e.lastActionAt:l??null,d=null==c?null:Math.max(0,n-c),p=laneBusyOf(e),u=e?.pending instanceof Map?e.pending.size:Math.max(0,Number(e?.pendingCount)||0),m=e?.pending instanceof Map&&[...e.pending.values()].some(e=>"ask"===e?.payload?.risk)?t.NEEDS_INPUT:t.NEEDS_DECISION,h=((e,t=LANE_STATUS)=>{let r=0,n=0;for(let i=(Array.isArray(e)?e.length:0)-1;i>=0&&n<t.failureWindow;i--){const t=e[i];if(t&&"object"==typeof t){if(n++,"result"===t.kind&&(!t.subtype||"success"===t.subtype)||"you"===t.kind)break;o(t)&&r++}}return r})(a,i);let f=null,g=null;return u>0?(f="BLOCKED",g="waiting for input"):e?.stalled||p&&!e?.compacting&&null!=d&&d>=i.stuckAfterMs?(f="STUCK",g="no events while busy"):h>=i.repeatedFailureCount&&(f="BLOCKED",g="repeated errors"),{busy:!!p,lastActionAt:c,lastActionAgeMs:d,statusFlag:f,statusReason:g,lifecycle:r({events:a,busy:!!p,pendingCount:u,pendingReason:m,stalled:"STUCK"===f,failed:h>=i.repeatedFailureCount&&!p,rawStatus:f||(p?"busy":"idle")})}};export const formatLaneAge=e=>{if(!Number.isFinite(e))return"no activity";const t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s ago`;const r=Math.floor(t/60);if(r<60)return`${r}m ago`;const n=Math.floor(r/60);return n<24?`${n}h ago`:`${Math.floor(n/24)}d ago`};const i=e=>`${e.lifecycle?.state||"Blocked"}${e.lifecycle?.reason?` (${e.lifecycle.reason})`:""} · ${formatLaneAge(e.lastActionAgeMs)}`,s=(e,t)=>{const r=String(null==e?"":e).replace(/\s+/g," ").trim();return r.length>t?r.slice(0,t-1)+"…":r};export const digestLogEvent=(e,t=PEEK.lineCap)=>{if(!e||"object"!=typeof e)return"";switch(e.kind){case"you":return s(`${e.by||"someone"}: ${e.text||""}`,t);case"assistant":{const r=[];for(const t of Array.isArray(e.blocks)?e.blocks:[])"text"===t?.type&&String(t.text||"").trim()?r.push(String(t.text).trim()):"tool_use"===t?.type&&t.name&&r.push(`→ ${t.name}`);return r.length?s(`assistant: ${r.join(" ")}`,t):""}case"tool_result":return e.isError?s("⎿ error",t):"";case"result":return e.subtype&&"success"!==e.subtype?s(`turn ended — ${e.subtype}`,t):"";case"error":return s(`error: ${e.message||""}`,t);default:return""}};const a=e=>"assistant"===e?.kind&&(Array.isArray(e.blocks)?e.blocks:[]).some(e=>"text"===e?.type&&String(e.text||"").trim());export const cleanPtyTail=(e,t)=>String(e||"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b[@-_][0-?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"").split(/\r?\n/).map(e=>e.replace(/\s+$/,"")).filter(e=>e.trim()).slice(-Math.max(1,t));export const siblingRef=e=>String(e).slice(0,8);export const siblingsOf=({selfId:e,sessions:t,terms:r,names:n={},now:o=Date.now()}={})=>{const i=e=>n&&n[e]||"",s=[];for(const[r,n]of t||new Map)r!==e&&s.push({id:r,ref:siblingRef(r),name:i(r),kind:"agent",cmd:n?.cmd||"claude",log:Array.isArray(n?.log)?n.log:[],...laneStatusOf(n,o)});for(const[t,n]of r||new Map)t!==e&&s.push({id:t,ref:siblingRef(t),name:i(t),kind:"shell",cmd:n?.cmd||"shell",buf:n?.buf||"",...laneStatusOf(n,o)});return s};export const isOrdinalRef=e=>/^(terminal\s*)?\d+$/i.test(e)||/^t\d+$/i.test(e);export const resolveSibling=(e,t)=>{const r=String(t||"").toLowerCase().trim();if(!r)return null;const n=Array.isArray(e)?e:[];return n.find(e=>String(e.id).toLowerCase()===r)||n.find(e=>String(e.name||"").toLowerCase()===r)||n.find(e=>String(e.ref).toLowerCase()===r)||(isOrdinalRef(r)?null:n.find(e=>r.length>=4&&String(e.id).toLowerCase().startsWith(r))||n.find(e=>e.name&&String(e.name).toLowerCase().includes(r))||n.find(e=>String(e.cmd).toLowerCase().includes(r))||null)};const l=e=>`${e.ref}${e.name?` · "${e.name}"`:""}`;export const formatPeek=({selfId:e,sessions:t,terms:r,names:n={},terminal:o,lines:c,now:d=Date.now()}={})=>{const p=Math.min(PEEK.maxLines,Math.max(1,Number(c)||PEEK.defaultLines)),u=siblingsOf({selfId:e,sessions:t,terms:r,names:n,now:d});if(!u.length)return"No other terminals are open in this room right now.";if(!o)return`Other terminals in this room (call read_terminal with a ref or name to read one):\n${u.map(e=>{let t;if("agent"===e.kind){const r=e.log.map(e=>digestLogEvent(e,PEEK.rosterPreview)).filter(Boolean);t=r[r.length-1]||"(no activity yet)"}else t=cleanPtyTail(e.buf,1)[0]||"(no output yet)";return`- ${l(e)} · ${e.kind} · ${e.cmd} · ${i(e)} — ${s(t,PEEK.rosterPreview)}`}).join("\n")}`;const m=resolveSibling(u,o);if(!m)return`No terminal matches "${o}". Call read_terminal with no argument to list the open terminals (refer to one by its name or ref).${isOrdinalRef(String(o||"").toLowerCase().trim())?" On-screen numbers like \"Terminal N\" shift when a terminal closes, so they can't identify a lane — use a terminal's name or ref instead.":""}`;let h;if("agent"===m.kind){let e=-1;if("Done"===m.lifecycle?.state)for(let t=m.log.length-1;t>=0;t--)if(a(m.log[t])){e=t;break}h=m.log.map((t,r)=>digestLogEvent(t,r===e?PEEK.finalAssistantCap:PEEK.lineCap)).filter(Boolean).slice(-p).join("\n")||"(no activity yet)"}else h=cleanPtyTail(m.buf,p).join("\n")||"(no output yet)";return`Terminal ${l(m)} (${m.kind} · ${m.cmd}) · ${i(m)} — last ${p} lines:\n${h}`};export const nativeClaudeProviderAccessFailed=e=>{let t="";try{t="string"==typeof e?e:JSON.stringify(e||"")}catch{t=String(e||"")}return/organization has disabled (?:claude(?: subscription access)?|subscription access)|(?:claude )?subscription access (?:has been |is )?disabled|invalid anthropic (?:api )?key|invalid x-api-key|not logged in to claude|(?:run|use) \/login[^\n]{0,80}claude|no valid anthropic (?:api )?key/i.test(t)};const c=Object.freeze(["nous:anthropic/claude-sonnet-4.6","nous:anthropic/claude-sonnet-4.5","nous:anthropic/claude-sonnet-4"]);export const preferredHermesClaudeReviewModel=(e=[])=>{const t=new Set((Array.isArray(e)?e:[]).map(e=>"string"==typeof e?e:e?.value||e?.slug).filter(Boolean));for(const e of c)if(t.has(e))return e;for(const e of t)if(/^nous:anthropic\/claude-sonnet-/i.test(e))return e;for(const e of t)if(/^nous:anthropic\/claude-haiku-/i.test(e))return e;for(const e of t)if(/^nous:anthropic\/claude-opus-/i.test(e))return e;return null};export const nativeClaudeFallbackHint=({parentRuntime:e,parentModels:t,targetRuntime:r,targetLog:n}={})=>{if("claude"!==r||!nativeClaudeProviderAccessFailed(n))return"";const o="thinkpool provider status: native Claude access failed at the account/provider level. Do not retry Sonnet, Opus, Haiku, or another model alias on the same native Claude provider during this task.",i="hermes"===e?preferredHermesClaudeReviewModel(t):null;return i?`\n\n${o} For a visible manual review fallback, spawn exactly one worker with runtime="hermes", model=${JSON.stringify(i)}, mode="default", and sliceType="review". This Hermes lane is permission-gated, not structurally read-only: instruct it not to edit, deny/stop any write request, and do not treat its review as a Flow safety proof. Never use Hermes delegate_task.`:`\n\n${o} Use a different available runtime/provider once, or report the blocker.`};export const ROOMNOW={laneCap:8,previewLen:70,wtCap:10};export const formatRoomNow=({selfId:e,sessions:t,terms:r,names:n={},worktrees:o=[],now:a=Date.now()}={},c=ROOMNOW)=>{const d=siblingsOf({selfId:e,sessions:t,terms:r,names:n,now:a}),p=[];if(d.length){const e=d.slice(0,c.laneCap),t=e.map(e=>{let t;if("agent"===e.kind){const r=e.log.map(e=>digestLogEvent(e,c.previewLen)).filter(Boolean);t=r[r.length-1]||"(no activity yet)"}else t=cleanPtyTail(e.buf,1)[0]||"(no output yet)";return`- ${l(e)} · ${e.kind} · ${i(e)} — ${s(t,c.previewLen)}`});d.length>e.length&&t.push(`- … +${d.length-e.length} more (read_terminal lists all)`),p.push(`Other lanes in this room right now (this is the roster; use targeted read_terminal only for needed detail):\n${t.join("\n")}`)}const u=Array.isArray(o)?o:[],m=u.slice(0,c.wtCap);if(m.length){const e=m.map(e=>`- ${s(e,c.previewLen+30)}`);u.length>m.length&&e.push(`- … +${u.length-m.length} more (\`git worktree list\` shows all)`),p.push(`Active git worktrees on this host (code edits go in your OWN worktree — never one another lane is on):\n${e.join("\n")}`)}return p.length?`ROOM NOW (live snapshot, this turn):\n${p.join("\n")}`:null};export const CROSSPOST={maxHop:1,perTurnCap:3};export const crossPostDecision=({hop:e=0,postCount:t=0,disabled:r=!1}={},n=CROSSPOST)=>{const o={...CROSSPOST,...n||{}};return r?{ok:!1,reason:"Cross-terminal posting is disabled in this room."}:e>=o.maxHop?{ok:!1,reason:"Cross-terminal hop limit reached — an agent reached via cross-post cannot itself post onward; a person must direct the next cross-terminal action."}:t>=o.perTurnCap?{ok:!1,reason:`Cross-terminal post limit reached for this turn (${o.perTurnCap}).`}:{ok:!0}};export const crossPostNeedsCard=({mode:e="default",spawnedByMe:t=!1}={})=>!("bypassPermissions"===e||!0===t);export const SPAWN={maxHop:1,perWindowCap:6,windowMs:6e5,freeMaxSpawned:3,plusMaxSpawned:6,machineMax:12};export const maxSpawnedFor=(e,t=SPAWN)=>{const r={...SPAWN,...t||{}};return"plus"===e?r.plusMaxSpawned:r.freeMaxSpawned};export const isActiveDispatchedWorker=e=>!(!e?.spawnedBy||"conductor"===e.flowRole||e.flowTaskKey&&e.flowDone||!0===e.workerSettled);export const countActiveDispatchedWorkers=(e=[])=>[...e].filter(isActiveDispatchedWorker).length;export const isSettledDispatchedWorker=e=>!!e?.spawnedBy&&!String(e.spawnedBy).startsWith("flow:")&&!0===e.workerSettled;export const countMachineRuntimeLanes=(e=[])=>[...e].filter(e=>!isSettledDispatchedWorker(e)).length;export const machineCapacityDecision=({totalLive:e=0,disabled:t=!1}={},r=SPAWN)=>{const n={...SPAWN,...r||{}};return t?{ok:!1,reason:"Spawning terminals is disabled in this room."}:e>=n.machineMax?{ok:!1,reason:`Room is at the machine cap (${n.machineMax} live lanes) — close one before opening another.`}:{ok:!0}};export const activeWorkerCapacityDecision=({spawnedLive:e=0,totalLive:t=0,plan:r="free",disabled:n=!1}={},o=SPAWN)=>{const i={...SPAWN,...o||{}},s=machineCapacityDecision({totalLive:t,disabled:n},i);if(!s.ok)return s;const a=maxSpawnedFor(r,i);return e>=a?{ok:!1,reason:`Dispatch ceiling reached (${a} lane${1===a?"":"s"} on the ${r} plan)${"plus"!==r?` — Plus raises it to ${i.plusMaxSpawned}.`:"."} Close a dispatched lane to open another.`}:{ok:!0}};export const recentSpawnCount=(e,t,r=SPAWN.windowMs)=>(Array.isArray(e)?e:[]).filter(e=>Number.isFinite(e)&&e>t-r).length;export const spawnDecision=({hop:e=0,spawnTimes:t=[],now:r=0,spawnedLive:n=0,totalLive:o=0,plan:i="free",disabled:s=!1}={},a=SPAWN)=>{const l={...SPAWN,...a||{}};if(s)return{ok:!1,reason:"Spawning terminals is disabled in this room."};if(e>=l.maxHop)return{ok:!1,reason:"Spawn limit reached — a terminal reached via cross-terminal cannot itself open further terminals; a person must open the next lane."};const c=activeWorkerCapacityDecision({spawnedLive:n,totalLive:o,plan:i},l);if(!c.ok)return c;if(recentSpawnCount(t,r,l.windowMs)>=l.perWindowCap){const e=Math.round(l.windowMs/6e4);return{ok:!1,reason:`Spawn burst limit reached (${l.perWindowCap} in ${e} min) — this replenishes as the window slides forward, or instantly when a person types into this lane.`}}return{ok:!0}};const d=Object.freeze(["cascade","mode","model","name","provider","runtime","sliceType","task"]),p=new Set(["default","acceptEdits","bypassPermissions","plan","review"]),u=new Set(["claude","codex","hermes"]),m=new Set(["scaffold","feature","fix","review"]),h=/((?<![a-z0-9])sk-[a-z0-9_-]{8,}|(?<![a-z0-9])gsk_[a-z0-9_-]{8,}|(?<![a-z0-9])AIza[a-z0-9_-]{8,}|bearer\s+[a-z0-9._-]{8,})/gi,f=/(?:\/home\/|\/users\/|\/private\/|\/tmp\/|[a-z]:\\|\\\\)/gi,g=e=>Array.isArray(e)?e.map(g):e&&"object"==typeof e?Object.fromEntries(Object.keys(e).sort().map(t=>[t,g(e[t])])):e,y=(e,t)=>null==e?null:String(e).slice(0,t),w=(e,t)=>y(e,t)?.replace(h,"[credential redacted]").replace(f,"[host path redacted]")||"";export function normalizeDispatchArgs(e={},t={}){if(!e||"object"!=typeof e||Array.isArray(e)||Object.keys(e).some(e=>!d.includes(e)))throw new TypeError("Invalid dispatch arguments");const r=e.runtime||t.runtime||"claude",o=e.mode||("plan"===t.mode?"default":t.mode)||"default";if(!u.has(r)||!p.has(o)||e.sliceType&&!m.has(e.sliceType))throw new TypeError("Invalid dispatch arguments");const i=null==e.cascade?null:n(e.cascade);if(null!=e.cascade&&!i)throw new TypeError("Invalid Cascade metadata");return Object.freeze({cascade:i?Object.freeze(i):null,name:y(e.name,80),task:y(e.task,12e3),model:y(e.model,160),sliceType:y(e.sliceType,24),runtime:r,provider:y(e.provider,160),mode:o})}export function dispatchCapSnapshot({hop:e=0,spawnTimes:t=[],now:r=0,spawnedLive:n=0,totalLive:o=0,plan:i="free",disabled:s=!1}={},a=SPAWN){const l={...SPAWN,...a||{}},c="plus"===i?"plus":"free",d=maxSpawnedFor(c,l);return Object.freeze({killSwitch:!0===s,hop:Object.freeze({used:Math.max(0,Number(e)||0),limit:l.maxHop}),width:Object.freeze({requested:1,live:Math.max(0,Number(n)||0),limit:d}),machine:Object.freeze({live:Math.max(0,Number(o)||0),limit:l.machineMax}),plan:Object.freeze({name:c,price:"plus"===c?"€5/mo":"€0",used:Math.max(0,Number(n)||0),limit:d}),burst:Object.freeze({used:recentSpawnCount(t,r,l.windowMs),limit:l.perWindowCap,windowMinutes:Math.round(l.windowMs/6e4)})})}export function buildDispatchPreview({args:t,initiatorTerminalId:r,roomCode:n,bridgeAuthorityId:o,localAuthorityId:i,context:s={},limits:a=SPAWN}={}){if(!(r&&n&&o&&i))throw new TypeError("Dispatch authority is incomplete");const l=normalizeDispatchArgs(t,{runtime:s.runtime,mode:s.mode}),c=dispatchCapSnapshot(s,a),d=(p={authority:Object.freeze({initiatorTerminalId:String(r),roomCode:String(n).toUpperCase(),bridgeAuthorityId:String(o),localAuthorityId:String(i)}),exactArgs:l,caps:c},e("sha256").update(JSON.stringify(g(p))).digest("hex"));var p;const u=l.provider||("codex"===l.runtime?"OpenAI / Codex login":"hermes"===l.runtime?"Hermes ACP profile":"Anthropic / host default"),m=l.model||s.resolvedModel||"runtime default",h=w(l.name||l.task?.split(/\r?\n/)[0]||"Open one worker lane",120);return Object.freeze({version:1,fingerprint:d,purpose:h,packages:Object.freeze([{title:w(l.name||"Worker package",80),task:w(l.task||"Open idle for a later hand-off.",600)}]),runtime:Object.freeze({name:l.runtime,provider:w(s.providerName||u,120),model:w(m,160),band:"Start: now–1 min · completion: task-dependent",execution:"Runs locally on the bridge machine; no cloud worker is created.",accountAndSpend:`Uses the host’s ${w(s.providerName||u,100)} account/BYOK. Provider usage is the spend source; thinkpool has no credit meter.`}),permissions:Object.freeze({mode:l.mode,consequence:"bypassPermissions"===l.mode?"Unattended local access within this worker’s sandbox and tool policy.":"review"===l.mode?"Read-only inspection of the pinned parent snapshot; writes and approval escapes are unavailable.":"plan"===l.mode?"Planning only; execution remains gated.":"Protected local actions keep their normal permission gates."}),worktree:"Automatically creates one visible lateral worker lane and an isolated git worktree on this machine.",caps:c})}export function authorizeDispatchApproval({preview:e,approvedFingerprint:t,args:r,initiatorTerminalId:n,roomCode:o,bridgeAuthorityId:i,localAuthorityId:s,context:a={},decision:l="allow",consumed:c=!1,permissionId:d=null,consumedPermissionId:p=null,limits:u=SPAWN}={}){return"allow"!==l?{ok:!1,code:"dispatch_canceled"}:c?{ok:!1,code:d&&d===p?"idempotent_replay":"approval_replayed"}:b({preview:e,approvedFingerprint:t,args:r,initiatorTerminalId:n,roomCode:o,bridgeAuthorityId:i,localAuthorityId:s,context:a,limits:u})}export function authorizeDirectDispatch({preview:e,args:t,initiatorTerminalId:r,roomCode:n,bridgeAuthorityId:o,localAuthorityId:i,context:s={},limits:a=SPAWN}={}){return b({preview:e,approvedFingerprint:e?.fingerprint,args:t,initiatorTerminalId:r,roomCode:n,bridgeAuthorityId:o,localAuthorityId:i,context:s,limits:a})}function b({preview:e,approvedFingerprint:t,args:r,initiatorTerminalId:n,roomCode:o,bridgeAuthorityId:i,localAuthorityId:s,context:a={},limits:l=SPAWN}={}){let c;try{c=buildDispatchPreview({args:r,initiatorTerminalId:n,roomCode:o,bridgeAuthorityId:i,localAuthorityId:s,context:a,limits:l})}catch{return{ok:!1,code:"invalid_dispatch"}}if(!e||e.fingerprint!==t)return{ok:!1,code:"approval_mismatch"};if(c.fingerprint!==e.fingerprint)return{ok:!1,code:"stale_dispatch"};const d=spawnDecision(a,l);return d.ok?{ok:!0,code:"approved",preview:c}:{ok:!1,code:"cap_denied",reason:d.reason}}export function verifyDurableDispatchAuthority({item:e,events:t=[],expected:r={}}={}){const n=e=>({ok:!1,code:e}),o=String(r.fingerprint||"");if(!e||e.id!==r.controlItemId)return n("control_item_mismatch");if(e.session_code!==String(r.roomCode||"").toUpperCase())return n("wrong_room");if("dispatch"!==e.action_kind||"approval"!==e.item_kind)return n("wrong_action");if("resolved"!==e.status||"approved"!==e.resolution_code||!e.resolved_by)return n("not_approved");if("either_member"!==e.resolution_policy||null!=e.required_actor_id)return n("wrong_resolution_policy");if(e.bridge_authority_id!==r.bridgeAuthorityId)return n("wrong_bridge_authority");if(e.local_authority_id!==r.localAuthorityId)return n("wrong_local_authority");if(!/^[0-9a-f]{64}$/.test(o))return n("invalid_fingerprint");if(!String(e.request_context?.action||"").includes(`fp:${o}`))return n("request_fingerprint_mismatch");if(e.resolution_payload?.dispatch_fingerprint!==o)return n("resolution_fingerprint_mismatch");const i=(Array.isArray(t)?t:[]).filter(t=>t?.item_id===e.id);if(1!==i.filter(t=>"resolved"===t.event_type&&t.actor_id===e.resolved_by&&t.payload?.resolution_payload?.dispatch_fingerprint===o&&"approved"===t.payload?.resolution_code).length)return n("resolution_event_mismatch");const s=i.filter(t=>"delivery_attempted"===t.event_type&&t.actor_id===e.resolved_by&&t.payload?.data?.dispatch_fingerprint===o);return 1!==s.length?n("delivery_attempt_mismatch"):i.some(e=>"delivered"===e.event_type||"delivery_failed"===e.event_type)?n("delivery_already_final"):{ok:!0,code:"durable_dispatch_authorized",fingerprint:o,humanActorId:e.resolved_by,attemptKey:s[0].correlation_key}}export const CLOSABLE_HINT_MAX=6;export const closeLaneDecision=({callerId:e,spawnedBy:t,busy:r}={})=>e&&t===e?r?{ok:!1,reason:"busy"}:{ok:!0}:{ok:!1,reason:"not-owner"};export const closableLanes=(e,t=[])=>(Array.isArray(t)?t:[]).filter(t=>t&&closeLaneDecision({callerId:e,spawnedBy:t.spawnedBy,busy:t.busy}).ok);export const formatClosableHint=(e,t=[],r=6)=>{const n=closableLanes(e,t);if(!n.length)return"";const o=n.slice(0,r),i=o.map(e=>`${e.ref}${e.name?` ("${e.name}")`:""}`).join(", "),s=n.length>o.length?` (+${n.length-o.length} more)`:"";return`\n\nYou have ${n.length} finished lane${1===n.length?"":"s"} preserved for review. A person can free a slot by closing one with the X in its Ensemble row: ${i}${s}`};export const CROSSROOM={peekPerTurnCap:5};export const PEER_READ_MCP_TOOLS=Object.freeze(["read_terminal","list_sessions","read_session"]);export const PEER_POST_MCP_TOOLS=Object.freeze(["post_to_terminal","post_to_session"]);export const PEER_MCP_TOOLS=Object.freeze([...PEER_READ_MCP_TOOLS,...PEER_POST_MCP_TOOLS]);export const formatPairRoster=(e,{thisRoom:t,error:r}={})=>{if(r)return String(r);const n=new Set,o=(Array.isArray(e)?e:[]).filter(e=>!(!e||!e.code||e.code===t||n.has(e.code)||(n.add(e.code),0)));return o.length?`Your other thinkpool Code sessions (call read_session with a room code to look inside one):\n${o.map(e=>`- ${e.code}${e.name?` · "${e.name}"`:""}${e.host?` · on ${e.host}`:""}${!1===e.online?" · partner bridge offline":""}`).join("\n")}`:"No other sessions of yours are open right now. (Cross-session reach is limited to rooms this account is running here, plus your partner's rooms in the same pair.)"};export const CROSSROOM_BUS={busTimeoutMs:4e3};export const pairKeyFor=(e,t)=>{const r=String(null==e?"":e).toLowerCase().trim(),n=String(null==t?"":t).toLowerCase().trim();return r&&n&&r!==n?r<n?`${r}.${n}`:`${n}.${r}`:null};export const pairTopic=e=>e?`tppair:${e}`:null;export const CROSSROOM_POST={maxRoomHop:1,crossRoomPostCap:1};export const crossRoomPostDecision=({roomHop:e=0,postCount:t=0,disabled:r=!1}={},n=CROSSROOM_POST)=>{const o={...CROSSROOM_POST,...n||{}};return r?{ok:!1,reason:"Cross-room posting is turned off on this bridge."}:e>=o.maxRoomHop?{ok:!1,reason:"Cross-room hop limit reached — a room reached via a cross-room post cannot itself post into another room; a person must direct the next cross-room action."}:t>=o.crossRoomPostCap?{ok:!1,reason:`Cross-room post limit reached for this turn (${o.crossRoomPostCap}).`}:{ok:!0}};
1
+ import{createHash as e}from"node:crypto";import{BLOCKED_REASON as t,projectLaneLifecycle as r}from"./lane-lifecycle.mjs";import{normalizeCascadeMetadata as n}from"./worker-completion.mjs";export const PEEK={defaultLines:20,maxLines:200,perTurnCap:10,rosterPerTurnCap:1,lineCap:200,finalAssistantCap:24e3,rosterPreview:100};export const readTerminalBudgetDecision=({targeted:e=!1,targetedCount:t=0,rosterCount:r=0}={},n=PEEK)=>{const o=Math.max(0,Number(t)||0),i=Math.max(0,Number(r)||0);return e?o>=n.perTurnCap?{ok:!1,targetedCount:o,rosterCount:i,reason:`Cross-terminal transcript read limit reached for this turn (${n.perTurnCap}). Stop polling and continue with the worker results already collected; a fresh accepted room turn resets the allowance.`}:{ok:!0,targetedCount:o+1,rosterCount:i}:i>=n.rosterPerTurnCap?{ok:!1,targetedCount:o,rosterCount:i,reason:`The full terminal roster was already read this turn (${n.rosterPerTurnCap}/${n.rosterPerTurnCap}). Use the current ROOM NOW snapshot or read one relevant terminal by ref or name.`}:{ok:!0,targetedCount:o,rosterCount:i+1}};export const readTerminalTurnBudgetDecision=({targeted:e=!1,targetedCount:t=0,rosterCount:r=0,budgetTurnRev:n=null,currentTurnRev:o=0}={},i=PEEK)=>{const s=Math.max(0,Number(o)||0),a=(null==n?null:Number.isFinite(Number(n))?Number(n):null)===s;return{...readTerminalBudgetDecision({targeted:e,targetedCount:a?t:0,rosterCount:a?r:0},i),budgetTurnRev:s}};export const LANE_STATUS={stuckAfterMs:9e4,repeatedFailureCount:2,failureWindow:12};const o=e=>!!e&&("error"===e.kind&&!0!==e.recoverable||"tool_result"===e.kind&&e.isError||"result"===e.kind&&e.subtype&&"success"!==e.subtype);export const laneBusyOf=(e={})=>"boolean"==typeof e?.busy?e.busy:"boolean"==typeof e?._busyAnn?e._busyAnn:e?.session?.turnActive??!1;export const settleLaneBusy=e=>!(!e||!1===e._busyAnn||(e._busyAnn=!1,0));export const settleLaneControl=(e,t=Date.now())=>!(!e||!0!==e._busyAnn||!settleLaneBusy(e)||(e._settledTurnRev=Number(e._turnRev)||null,e._turnSettledAt=Number(t)||Date.now(),e._turnStart=null,0));export const laneStatusOf=(e={},n=Date.now(),i=LANE_STATUS)=>{const s=Array.isArray(e?.log)?e.log:[],a=s.slice(-i.failureWindow);!e?.lastEvent||e.lastEvent===s[s.length-1]||e.lastEvent.cid&&e.lastEvent.cid===s[s.length-1]?.cid||a.push(e.lastEvent);let l=null;for(let e=a.length-1;e>=0;e--)if(Number.isFinite(a[e]?.ts)){l=a[e].ts;break}const c=Number.isFinite(e?.lastActionAt)?e.lastActionAt:l??null,d=null==c?null:Math.max(0,n-c),p=laneBusyOf(e),u=e?.pending instanceof Map?e.pending.size:Math.max(0,Number(e?.pendingCount)||0),m=e?.pending instanceof Map&&[...e.pending.values()].some(e=>"ask"===e?.payload?.risk)?t.NEEDS_INPUT:t.NEEDS_DECISION,h=((e,t=LANE_STATUS)=>{let r=0,n=0;for(let i=(Array.isArray(e)?e.length:0)-1;i>=0&&n<t.failureWindow;i--){const t=e[i];if(t&&"object"==typeof t){if(n++,"result"===t.kind&&(!t.subtype||"success"===t.subtype)||"you"===t.kind)break;o(t)&&r++}}return r})(a,i);let f=null,g=null;return u>0?(f="BLOCKED",g="waiting for input"):e?.stalled||p&&!e?.compacting&&null!=d&&d>=i.stuckAfterMs?(f="STUCK",g="no events while busy"):h>=i.repeatedFailureCount&&(f="BLOCKED",g="repeated errors"),{busy:!!p,lastActionAt:c,lastActionAgeMs:d,statusFlag:f,statusReason:g,lifecycle:r({events:a,busy:!!p,pendingCount:u,pendingReason:m,stalled:"STUCK"===f,failed:h>=i.repeatedFailureCount&&!p,rawStatus:f||(p?"busy":"idle")})}};export const formatLaneAge=e=>{if(!Number.isFinite(e))return"no activity";const t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s ago`;const r=Math.floor(t/60);if(r<60)return`${r}m ago`;const n=Math.floor(r/60);return n<24?`${n}h ago`:`${Math.floor(n/24)}d ago`};const i=e=>`${e.lifecycle?.state||"Blocked"}${e.lifecycle?.reason?` (${e.lifecycle.reason})`:""} · ${formatLaneAge(e.lastActionAgeMs)}`,s=(e,t)=>{const r=String(null==e?"":e).replace(/\s+/g," ").trim();return r.length>t?r.slice(0,t-1)+"…":r};export const digestLogEvent=(e,t=PEEK.lineCap)=>{if(!e||"object"!=typeof e)return"";switch(e.kind){case"you":return s(`${e.by||"someone"}: ${e.text||""}`,t);case"assistant":{const r=[];for(const t of Array.isArray(e.blocks)?e.blocks:[])"text"===t?.type&&String(t.text||"").trim()?r.push(String(t.text).trim()):"tool_use"===t?.type&&t.name&&r.push(`→ ${t.name}`);return r.length?s(`assistant: ${r.join(" ")}`,t):""}case"tool_result":return e.isError?s("⎿ error",t):"";case"result":return e.subtype&&"success"!==e.subtype?s(`turn ended — ${e.subtype}`,t):"";case"error":return s(`error: ${e.message||""}`,t);default:return""}};const a=e=>"assistant"===e?.kind&&(Array.isArray(e.blocks)?e.blocks:[]).some(e=>"text"===e?.type&&String(e.text||"").trim());export const cleanPtyTail=(e,t)=>String(e||"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b[@-_][0-?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"").split(/\r?\n/).map(e=>e.replace(/\s+$/,"")).filter(e=>e.trim()).slice(-Math.max(1,t));export const siblingRef=e=>String(e).slice(0,8);export const siblingsOf=({selfId:e,sessions:t,terms:r,names:n={},now:o=Date.now()}={})=>{const i=e=>n&&n[e]||"",s=[];for(const[r,n]of t||new Map)r!==e&&s.push({id:r,ref:siblingRef(r),name:i(r),kind:"agent",cmd:n?.cmd||"claude",log:Array.isArray(n?.log)?n.log:[],...laneStatusOf(n,o)});for(const[t,n]of r||new Map)t!==e&&s.push({id:t,ref:siblingRef(t),name:i(t),kind:"shell",cmd:n?.cmd||"shell",buf:n?.buf||"",...laneStatusOf(n,o)});return s};export const isOrdinalRef=e=>/^(terminal\s*)?\d+$/i.test(e)||/^t\d+$/i.test(e);export const resolveSibling=(e,t)=>{const r=String(t||"").toLowerCase().trim();if(!r)return null;const n=Array.isArray(e)?e:[];return n.find(e=>String(e.id).toLowerCase()===r)||n.find(e=>String(e.name||"").toLowerCase()===r)||n.find(e=>String(e.ref).toLowerCase()===r)||(isOrdinalRef(r)?null:n.find(e=>r.length>=4&&String(e.id).toLowerCase().startsWith(r))||n.find(e=>e.name&&String(e.name).toLowerCase().includes(r))||n.find(e=>String(e.cmd).toLowerCase().includes(r))||null)};const l=e=>`${e.ref}${e.name?` · "${e.name}"`:""}`;export const formatPeek=({selfId:e,sessions:t,terms:r,names:n={},terminal:o,lines:c,now:d=Date.now()}={})=>{const p=Math.min(PEEK.maxLines,Math.max(1,Number(c)||PEEK.defaultLines)),u=siblingsOf({selfId:e,sessions:t,terms:r,names:n,now:d});if(!o&&!u.length)return"No other terminals are open in this room right now.";if(!o)return`Other terminals in this room (call read_terminal with a ref or name to read one):\n${u.map(e=>{let t;if("agent"===e.kind){const r=e.log.map(e=>digestLogEvent(e,PEEK.rosterPreview)).filter(Boolean);t=r[r.length-1]||"(no activity yet)"}else t=cleanPtyTail(e.buf,1)[0]||"(no output yet)";return`- ${l(e)} · ${e.kind} · ${e.cmd} · ${i(e)} — ${s(t,PEEK.rosterPreview)}`}).join("\n")}`;const m=resolveSibling(siblingsOf({sessions:t,terms:r,names:n,now:d}),o);if(!m)return`No terminal matches "${o}". Call read_terminal with no argument to list the open terminals (refer to one by its name or ref).${isOrdinalRef(String(o||"").toLowerCase().trim())?" On-screen numbers like \"Terminal N\" shift when a terminal closes, so they can't identify a lane — use a terminal's name or ref instead.":""}`;let h;if("agent"===m.kind){let e=-1;if("Done"===m.lifecycle?.state)for(let t=m.log.length-1;t>=0;t--)if(a(m.log[t])){e=t;break}h=m.log.map((t,r)=>digestLogEvent(t,r===e?PEEK.finalAssistantCap:PEEK.lineCap)).filter(Boolean).slice(-p).join("\n")||"(no activity yet)"}else h=cleanPtyTail(m.buf,p).join("\n")||"(no output yet)";return`Terminal ${l(m)}${m.id===e?" (current terminal)":""} (${m.kind} · ${m.cmd}) · ${i(m)} — last ${p} lines:\n${h}`};export const nativeClaudeProviderAccessFailed=e=>{let t="";try{t="string"==typeof e?e:JSON.stringify(e||"")}catch{t=String(e||"")}return/organization has disabled (?:claude(?: subscription access)?|subscription access)|(?:claude )?subscription access (?:has been |is )?disabled|invalid anthropic (?:api )?key|invalid x-api-key|not logged in to claude|(?:run|use) \/login[^\n]{0,80}claude|no valid anthropic (?:api )?key/i.test(t)};const c=Object.freeze(["nous:anthropic/claude-sonnet-4.6","nous:anthropic/claude-sonnet-4.5","nous:anthropic/claude-sonnet-4"]);export const preferredHermesClaudeReviewModel=(e=[])=>{const t=new Set((Array.isArray(e)?e:[]).map(e=>"string"==typeof e?e:e?.value||e?.slug).filter(Boolean));for(const e of c)if(t.has(e))return e;for(const e of t)if(/^nous:anthropic\/claude-sonnet-/i.test(e))return e;for(const e of t)if(/^nous:anthropic\/claude-haiku-/i.test(e))return e;for(const e of t)if(/^nous:anthropic\/claude-opus-/i.test(e))return e;return null};export const nativeClaudeFallbackHint=({parentRuntime:e,parentModels:t,targetRuntime:r,targetLog:n}={})=>{if("claude"!==r||!nativeClaudeProviderAccessFailed(n))return"";const o="thinkpool provider status: native Claude access failed at the account/provider level. Do not retry Sonnet, Opus, Haiku, or another model alias on the same native Claude provider during this task.",i="hermes"===e?preferredHermesClaudeReviewModel(t):null;return i?`\n\n${o} For a visible manual review fallback, spawn exactly one worker with runtime="hermes", model=${JSON.stringify(i)}, mode="default", and sliceType="review". This Hermes lane is permission-gated, not structurally read-only: instruct it not to edit, deny/stop any write request, and do not treat its review as a Flow safety proof. Never use Hermes delegate_task.`:`\n\n${o} Use a different available runtime/provider once, or report the blocker.`};export const ROOMNOW={laneCap:8,previewLen:70,wtCap:10};export const formatRoomNow=({selfId:e,sessions:t,terms:r,names:n={},worktrees:o=[],now:a=Date.now()}={},c=ROOMNOW)=>{const d=siblingsOf({selfId:e,sessions:t,terms:r,names:n,now:a}),p=[];if(e&&(t?.has(e)||r?.has(e))&&p.push(`Current terminal: ${e}${n[e]?` · ${n[e]}`:""}. This is your own lane.`),d.length){const e=d.slice(0,c.laneCap),t=e.map(e=>{let t;if("agent"===e.kind){const r=e.log.map(e=>digestLogEvent(e,c.previewLen)).filter(Boolean);t=r[r.length-1]||"(no activity yet)"}else t=cleanPtyTail(e.buf,1)[0]||"(no output yet)";return`- ${l(e)} · ${e.kind} · ${i(e)} — ${s(t,c.previewLen)}`});d.length>e.length&&t.push(`- … +${d.length-e.length} more (read_terminal lists all)`),p.push(`Other lanes in this room right now (this is the roster; use targeted read_terminal only for needed detail):\n${t.join("\n")}`)}const u=Array.isArray(o)?o:[],m=u.slice(0,c.wtCap);if(m.length){const e=m.map(e=>`- ${s(e,c.previewLen+30)}`);u.length>m.length&&e.push(`- … +${u.length-m.length} more (\`git worktree list\` shows all)`),p.push(`Active git worktrees on this host (code edits go in your OWN worktree — never one another lane is on):\n${e.join("\n")}`)}return p.length?`ROOM NOW (live snapshot, this turn):\n${p.join("\n")}`:null};export const CROSSPOST={maxHop:1,perTurnCap:3};export const crossPostDecision=({hop:e=0,postCount:t=0,disabled:r=!1}={},n=CROSSPOST)=>{const o={...CROSSPOST,...n||{}};return r?{ok:!1,reason:"Cross-terminal posting is disabled in this room."}:e>=o.maxHop?{ok:!1,reason:"Cross-terminal hop limit reached — an agent reached via cross-post cannot itself post onward; a person must direct the next cross-terminal action."}:t>=o.perTurnCap?{ok:!1,reason:`Cross-terminal post limit reached for this turn (${o.perTurnCap}).`}:{ok:!0}};export const crossPostNeedsCard=({mode:e="default",spawnedByMe:t=!1}={})=>!("bypassPermissions"===e||!0===t);export const SPAWN={maxHop:1,perWindowCap:6,windowMs:6e5,freeMaxSpawned:3,plusMaxSpawned:6,machineMax:12};export const maxSpawnedFor=(e,t=SPAWN)=>{const r={...SPAWN,...t||{}};return"plus"===e?r.plusMaxSpawned:r.freeMaxSpawned};export const isActiveDispatchedWorker=e=>!(!e?.spawnedBy||"conductor"===e.flowRole||e.flowTaskKey&&e.flowDone||!0===e.workerSettled);export const countActiveDispatchedWorkers=(e=[])=>[...e].filter(isActiveDispatchedWorker).length;export const isSettledDispatchedWorker=e=>!!e?.spawnedBy&&!String(e.spawnedBy).startsWith("flow:")&&!0===e.workerSettled;export const countMachineRuntimeLanes=(e=[])=>[...e].filter(e=>!isSettledDispatchedWorker(e)).length;export const machineCapacityDecision=({totalLive:e=0,disabled:t=!1}={},r=SPAWN)=>{const n={...SPAWN,...r||{}};return t?{ok:!1,reason:"Spawning terminals is disabled in this room."}:e>=n.machineMax?{ok:!1,reason:`Room is at the machine cap (${n.machineMax} live lanes) — close one before opening another.`}:{ok:!0}};export const activeWorkerCapacityDecision=({spawnedLive:e=0,totalLive:t=0,plan:r="free",disabled:n=!1}={},o=SPAWN)=>{const i={...SPAWN,...o||{}},s=machineCapacityDecision({totalLive:t,disabled:n},i);if(!s.ok)return s;const a=maxSpawnedFor(r,i);return e>=a?{ok:!1,reason:`Dispatch ceiling reached (${a} lane${1===a?"":"s"} on the ${r} plan)${"plus"!==r?` — Plus raises it to ${i.plusMaxSpawned}.`:"."} Close a dispatched lane to open another.`}:{ok:!0}};export const recentSpawnCount=(e,t,r=SPAWN.windowMs)=>(Array.isArray(e)?e:[]).filter(e=>Number.isFinite(e)&&e>t-r).length;export const spawnDecision=({hop:e=0,spawnTimes:t=[],now:r=0,spawnedLive:n=0,totalLive:o=0,plan:i="free",disabled:s=!1}={},a=SPAWN)=>{const l={...SPAWN,...a||{}};if(s)return{ok:!1,reason:"Spawning terminals is disabled in this room."};if(e>=l.maxHop)return{ok:!1,reason:"Spawn limit reached — a terminal reached via cross-terminal cannot itself open further terminals; a person must open the next lane."};const c=activeWorkerCapacityDecision({spawnedLive:n,totalLive:o,plan:i},l);if(!c.ok)return c;if(recentSpawnCount(t,r,l.windowMs)>=l.perWindowCap){const e=Math.round(l.windowMs/6e4);return{ok:!1,reason:`Spawn burst limit reached (${l.perWindowCap} in ${e} min) — this replenishes as the window slides forward, or instantly when a person types into this lane.`}}return{ok:!0}};const d=Object.freeze(["cascade","mode","model","name","provider","runtime","sliceType","task"]),p=new Set(["default","acceptEdits","bypassPermissions","plan","review"]),u=new Set(["claude","codex","hermes"]),m=new Set(["scaffold","feature","fix","review"]),h=/((?<![a-z0-9])sk-[a-z0-9_-]{8,}|(?<![a-z0-9])gsk_[a-z0-9_-]{8,}|(?<![a-z0-9])AIza[a-z0-9_-]{8,}|bearer\s+[a-z0-9._-]{8,})/gi,f=/(?:\/home\/|\/users\/|\/private\/|\/tmp\/|[a-z]:\\|\\\\)/gi,g=e=>Array.isArray(e)?e.map(g):e&&"object"==typeof e?Object.fromEntries(Object.keys(e).sort().map(t=>[t,g(e[t])])):e,y=(e,t)=>null==e?null:String(e).slice(0,t),w=(e,t)=>y(e,t)?.replace(h,"[credential redacted]").replace(f,"[host path redacted]")||"";export function normalizeDispatchArgs(e={},t={}){if(!e||"object"!=typeof e||Array.isArray(e)||Object.keys(e).some(e=>!d.includes(e)))throw new TypeError("Invalid dispatch arguments");const r=e.runtime||t.runtime||"claude",o=e.mode||("plan"===t.mode?"default":t.mode)||"default";if(!u.has(r)||!p.has(o)||e.sliceType&&!m.has(e.sliceType))throw new TypeError("Invalid dispatch arguments");const i=null==e.cascade?null:n(e.cascade);if(null!=e.cascade&&!i)throw new TypeError("Invalid Cascade metadata");return Object.freeze({cascade:i?Object.freeze(i):null,name:y(e.name,80),task:y(e.task,12e3),model:y(e.model,160),sliceType:y(e.sliceType,24),runtime:r,provider:y(e.provider,160),mode:o})}export function dispatchCapSnapshot({hop:e=0,spawnTimes:t=[],now:r=0,spawnedLive:n=0,totalLive:o=0,plan:i="free",disabled:s=!1}={},a=SPAWN){const l={...SPAWN,...a||{}},c="plus"===i?"plus":"free",d=maxSpawnedFor(c,l);return Object.freeze({killSwitch:!0===s,hop:Object.freeze({used:Math.max(0,Number(e)||0),limit:l.maxHop}),width:Object.freeze({requested:1,live:Math.max(0,Number(n)||0),limit:d}),machine:Object.freeze({live:Math.max(0,Number(o)||0),limit:l.machineMax}),plan:Object.freeze({name:c,price:"plus"===c?"€5/mo":"€0",used:Math.max(0,Number(n)||0),limit:d}),burst:Object.freeze({used:recentSpawnCount(t,r,l.windowMs),limit:l.perWindowCap,windowMinutes:Math.round(l.windowMs/6e4)})})}export function buildDispatchPreview({args:t,initiatorTerminalId:r,roomCode:n,bridgeAuthorityId:o,localAuthorityId:i,context:s={},limits:a=SPAWN}={}){if(!(r&&n&&o&&i))throw new TypeError("Dispatch authority is incomplete");const l=normalizeDispatchArgs(t,{runtime:s.runtime,mode:s.mode}),c=dispatchCapSnapshot(s,a),d=(p={authority:Object.freeze({initiatorTerminalId:String(r),roomCode:String(n).toUpperCase(),bridgeAuthorityId:String(o),localAuthorityId:String(i)}),exactArgs:l,caps:c},e("sha256").update(JSON.stringify(g(p))).digest("hex"));var p;const u=l.provider||("codex"===l.runtime?"OpenAI / Codex login":"hermes"===l.runtime?"Hermes ACP profile":"Anthropic / host default"),m=l.model||s.resolvedModel||"runtime default",h=w(l.name||l.task?.split(/\r?\n/)[0]||"Open one worker lane",120);return Object.freeze({version:1,fingerprint:d,purpose:h,packages:Object.freeze([{title:w(l.name||"Worker package",80),task:w(l.task||"Open idle for a later hand-off.",600)}]),runtime:Object.freeze({name:l.runtime,provider:w(s.providerName||u,120),model:w(m,160),band:"Start: now–1 min · completion: task-dependent",execution:"Runs locally on the bridge machine; no cloud worker is created.",accountAndSpend:`Uses the host’s ${w(s.providerName||u,100)} account/BYOK. Provider usage is the spend source; thinkpool has no credit meter.`}),permissions:Object.freeze({mode:l.mode,consequence:"bypassPermissions"===l.mode?"Unattended local access within this worker’s sandbox and tool policy.":"review"===l.mode?"Read-only inspection of the pinned parent snapshot; writes and approval escapes are unavailable.":"plan"===l.mode?"Planning only; execution remains gated.":"Protected local actions keep their normal permission gates."}),worktree:"Automatically creates one visible lateral worker lane and an isolated git worktree on this machine.",caps:c})}export function authorizeDispatchApproval({preview:e,approvedFingerprint:t,args:r,initiatorTerminalId:n,roomCode:o,bridgeAuthorityId:i,localAuthorityId:s,context:a={},decision:l="allow",consumed:c=!1,permissionId:d=null,consumedPermissionId:p=null,limits:u=SPAWN}={}){return"allow"!==l?{ok:!1,code:"dispatch_canceled"}:c?{ok:!1,code:d&&d===p?"idempotent_replay":"approval_replayed"}:b({preview:e,approvedFingerprint:t,args:r,initiatorTerminalId:n,roomCode:o,bridgeAuthorityId:i,localAuthorityId:s,context:a,limits:u})}export function authorizeDirectDispatch({preview:e,args:t,initiatorTerminalId:r,roomCode:n,bridgeAuthorityId:o,localAuthorityId:i,context:s={},limits:a=SPAWN}={}){return b({preview:e,approvedFingerprint:e?.fingerprint,args:t,initiatorTerminalId:r,roomCode:n,bridgeAuthorityId:o,localAuthorityId:i,context:s,limits:a})}function b({preview:e,approvedFingerprint:t,args:r,initiatorTerminalId:n,roomCode:o,bridgeAuthorityId:i,localAuthorityId:s,context:a={},limits:l=SPAWN}={}){let c;try{c=buildDispatchPreview({args:r,initiatorTerminalId:n,roomCode:o,bridgeAuthorityId:i,localAuthorityId:s,context:a,limits:l})}catch{return{ok:!1,code:"invalid_dispatch"}}if(!e||e.fingerprint!==t)return{ok:!1,code:"approval_mismatch"};if(c.fingerprint!==e.fingerprint)return{ok:!1,code:"stale_dispatch"};const d=spawnDecision(a,l);return d.ok?{ok:!0,code:"approved",preview:c}:{ok:!1,code:"cap_denied",reason:d.reason}}export function verifyDurableDispatchAuthority({item:e,events:t=[],expected:r={}}={}){const n=e=>({ok:!1,code:e}),o=String(r.fingerprint||"");if(!e||e.id!==r.controlItemId)return n("control_item_mismatch");if(e.session_code!==String(r.roomCode||"").toUpperCase())return n("wrong_room");if("dispatch"!==e.action_kind||"approval"!==e.item_kind)return n("wrong_action");if("resolved"!==e.status||"approved"!==e.resolution_code||!e.resolved_by)return n("not_approved");if("either_member"!==e.resolution_policy||null!=e.required_actor_id)return n("wrong_resolution_policy");if(e.bridge_authority_id!==r.bridgeAuthorityId)return n("wrong_bridge_authority");if(e.local_authority_id!==r.localAuthorityId)return n("wrong_local_authority");if(!/^[0-9a-f]{64}$/.test(o))return n("invalid_fingerprint");if(!String(e.request_context?.action||"").includes(`fp:${o}`))return n("request_fingerprint_mismatch");if(e.resolution_payload?.dispatch_fingerprint!==o)return n("resolution_fingerprint_mismatch");const i=(Array.isArray(t)?t:[]).filter(t=>t?.item_id===e.id);if(1!==i.filter(t=>"resolved"===t.event_type&&t.actor_id===e.resolved_by&&t.payload?.resolution_payload?.dispatch_fingerprint===o&&"approved"===t.payload?.resolution_code).length)return n("resolution_event_mismatch");const s=i.filter(t=>"delivery_attempted"===t.event_type&&t.actor_id===e.resolved_by&&t.payload?.data?.dispatch_fingerprint===o);return 1!==s.length?n("delivery_attempt_mismatch"):i.some(e=>"delivered"===e.event_type||"delivery_failed"===e.event_type)?n("delivery_already_final"):{ok:!0,code:"durable_dispatch_authorized",fingerprint:o,humanActorId:e.resolved_by,attemptKey:s[0].correlation_key}}export const CLOSABLE_HINT_MAX=6;export const closeLaneDecision=({callerId:e,spawnedBy:t,busy:r}={})=>e&&t===e?r?{ok:!1,reason:"busy"}:{ok:!0}:{ok:!1,reason:"not-owner"};export const closableLanes=(e,t=[])=>(Array.isArray(t)?t:[]).filter(t=>t&&closeLaneDecision({callerId:e,spawnedBy:t.spawnedBy,busy:t.busy}).ok);export const formatClosableHint=(e,t=[],r=6)=>{const n=closableLanes(e,t);if(!n.length)return"";const o=n.slice(0,r),i=o.map(e=>`${e.ref}${e.name?` ("${e.name}")`:""}`).join(", "),s=n.length>o.length?` (+${n.length-o.length} more)`:"";return`\n\nYou have ${n.length} finished lane${1===n.length?"":"s"} preserved for review. A person can free a slot by closing one with the X in its Ensemble row: ${i}${s}`};export const CROSSROOM={peekPerTurnCap:5};export const PEER_READ_MCP_TOOLS=Object.freeze(["read_terminal","list_sessions","read_session"]);export const PEER_POST_MCP_TOOLS=Object.freeze(["post_to_terminal","post_to_session"]);export const PEER_MCP_TOOLS=Object.freeze([...PEER_READ_MCP_TOOLS,...PEER_POST_MCP_TOOLS]);export const formatPairRoster=(e,{thisRoom:t,error:r}={})=>{if(r)return String(r);const n=new Set,o=(Array.isArray(e)?e:[]).filter(e=>!(!e||!e.code||e.code===t||n.has(e.code)||(n.add(e.code),0)));return o.length?`Your other thinkpool Code sessions (call read_session with a room code to look inside one):\n${o.map(e=>`- ${e.code}${e.name?` · "${e.name}"`:""}${e.host?` · on ${e.host}`:""}${!1===e.online?" · partner bridge offline":""}`).join("\n")}`:"No other sessions of yours are open right now. (Cross-session reach is limited to rooms this account is running here, plus your partner's rooms in the same pair.)"};export const CROSSROOM_BUS={busTimeoutMs:4e3};export const pairKeyFor=(e,t)=>{const r=String(null==e?"":e).toLowerCase().trim(),n=String(null==t?"":t).toLowerCase().trim();return r&&n&&r!==n?r<n?`${r}.${n}`:`${n}.${r}`:null};export const pairTopic=e=>e?`tppair:${e}`:null;export const CROSSROOM_POST={maxRoomHop:1,crossRoomPostCap:1};export const crossRoomPostDecision=({roomHop:e=0,postCount:t=0,disabled:r=!1}={},n=CROSSROOM_POST)=>{const o={...CROSSROOM_POST,...n||{}};return r?{ok:!1,reason:"Cross-room posting is turned off on this bridge."}:e>=o.maxRoomHop?{ok:!1,reason:"Cross-room hop limit reached — a room reached via a cross-room post cannot itself post into another room; a person must direct the next cross-room action."}:t>=o.crossRoomPostCap?{ok:!1,reason:`Cross-room post limit reached for this turn (${o.crossRoomPostCap}).`}:{ok:!0}};
package/design-edit.mjs CHANGED
@@ -1 +1 @@
1
- import e from"node:crypto";import t from"node:fs";import r from"node:os";import n from"node:path";import{DESIGN_SOURCE_MAP_RELATIVE as o,DESIGN_SOURCE_MAP_VERSION as i,MAX_DESIGN_SOURCE_ENTRIES as s,MAX_DESIGN_SOURCE_MAP_BYTES as a}from"./design-source-contract.mjs";const c=2097152,u=4e3,l=new Set(["dist","build",".next",".git","coverage","node_modules"]),d=(e,t)=>String(e??"").replace(/\0/g,"").trim().slice(0,t),p=(e,t)=>{const r=n.relative(e,t);return""===r||!r.startsWith("..")&&!n.isAbsolute(r)};export async function syncRealtimeAuth(e,t,r=null){const n=t||r;if(!n||"function"!=typeof e?.realtime?.setAuth)return!1;try{return await e.realtime.setAuth(n),!0}catch{return!1}}export function sourceRevision(t){return e.createHash("sha256").update(String(t)).digest("hex").slice(0,24)}export function resolveDesignSourceMap(e,r,u){if(!e||!r||!u)return null;let h,m,f,g,v,y;try{h=t.realpathSync(e),f=t.realpathSync(r),m=t.realpathSync(n.join(f,o)),g=t.realpathSync(u);const i=t.statSync(h);if(!i.isFile()||i.size<=0||i.size>a)return null;if(h!==m||!p(g,f)||!p(f,h))return null;v=t.readFileSync(h,"utf8"),y=JSON.parse(v)}catch{return null}if(y?.version!==i||!y.entries||"object"!=typeof y.entries||Array.isArray(y.entries))return null;const b=Object.entries(y.entries);if(b.length>s)return null;const w=new Map,x=new Map;for(const[e,r]of b){if(!/^[A-Za-z0-9_-]{8,80}$/.test(e)||!r||"object"!=typeof r)return null;const o=d(r.file,700);if(!o||n.isAbsolute(o)||o.split(/[\\/]/).some(e=>".."===e||l.has(e)))return null;let i=w.get(o);if(!i){try{i=t.realpathSync(n.resolve(g,o));const e=t.statSync(i);if(!e.isFile()||e.size>c||!p(g,i))return null}catch{return null}w.set(o,i)}const s=Number(r.start),a=Number(r.end),u=Number(r.line),h=Number(r.column),m=d(r.tag,40).toLowerCase(),f=d(r.fileHash,64).toLowerCase();if(![s,a,u,h].every(Number.isSafeInteger)||s<0||a<=s||u<1||h<0)return null;if(!/^[a-z][a-z0-9:-]*$/.test(m)||!/^[a-f0-9]{24}$/.test(f))return null;x.set(e,{sourceId:e,file:o.split(n.sep).join("/"),sourcePath:i,start:s,end:a,line:u,column:h,tag:m,fileHash:f})}return{path:h,revision:sourceRevision(v),buildId:d(y.buildId,80),entries:x}}export function resolveDesignSource(r,o){if(!r||!o)return null;let i,s;try{i=t.realpathSync(r),s=t.realpathSync(o);const e=t.statSync(i);if(!e.isFile()||e.size>c)return null}catch{return null}const a=n.relative(s,i);if(!a||a.startsWith("..")||n.isAbsolute(a)||".html"!==n.extname(i).toLowerCase())return null;if(a.split(n.sep).some(e=>["dist","build",".next",".git","coverage","node_modules"].includes(e)))return null;const u=t.readFileSync(i,"utf8"),l=sourceRevision(u);return{previewId:e.createHash("sha256").update(`${i}\0${l}`).digest("base64url").slice(0,32),revision:l,sourcePath:i,workspaceRoot:s,source:u}}export function resolvePreviewDesignSource(r,o,i){if(!(r&&"preview"===r.sourceKind&&r.snapshot&&o&&i))return null;let s,a,u;try{s=t.realpathSync(r.snapshot),a=t.realpathSync(o),u=t.realpathSync(i);const e=t.statSync(s);if(!e.isFile()||e.size>c)return null}catch{return null}const l=n.relative(u,s);if(!l||l.startsWith("..")||n.isAbsolute(l)||".html"!==n.extname(s).toLowerCase())return null;const h=d(r.route||"/",500),m=d(r.previewRoot||"dist",500),f=d(r.captureKey,1e3);if(!h.startsWith("/")||!f||f!==JSON.stringify([m,h]))return null;const g=t.readFileSync(s,"utf8");let v=null;try{if(v=t.realpathSync(n.resolve(a,m)),!p(a,v))return null}catch{return null}const y=r.sourceMap?resolveDesignSourceMap(r.sourceMap,v,a):null,b=sourceRevision(y?`${g}\0${y.revision}`:g);return{sourceKind:"preview",previewId:e.createHash("sha256").update(`${a}\0${f}\0${b}`).digest("base64url").slice(0,32),revision:b,sourcePath:s,workspaceRoot:a,source:g,outbox:u,route:h,previewRoot:m,captureKey:f,sourceMap:y,sourceMapPath:y?.path||null,sourceMapDeclared:!!r.sourceMap}}export function resolveManifestDesignSource(e,t,{box:r}={}){return e&&"object"==typeof e?"preview"===e.sourceKind?resolvePreviewDesignSource(e,t,r):resolveDesignSource(e.source||e.html,t):null}export function resolveManifestDisplaySource(e,r,{box:o}={}){if(!r)return null;if("preview"===r.sourceKind||!e?.snapshot)return r.source;let i,s;try{i=t.realpathSync(e.snapshot),s=t.realpathSync(o);const r=t.statSync(i);if(!r.isFile()||r.size>c)return null}catch{return null}const a=n.relative(s,i);return!a||a.startsWith("..")||n.isAbsolute(a)||".html"!==n.extname(i).toLowerCase()?null:t.readFileSync(i,"utf8")}export function refreshDesignSource(e){return e?"preview"!==e.sourceKind?resolveDesignSource(e.sourcePath,e.workspaceRoot):resolvePreviewDesignSource({sourceKind:"preview",snapshot:e.sourcePath,route:e.route,previewRoot:e.previewRoot,captureKey:e.captureKey,sourceMap:e.sourceMapPath},e.workspaceRoot,e.outbox):null}export function restoreDesignSources(e,r,o,i=100){if(!e||!r||!o)return[];let s;try{s=t.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(".json")&&!e.name.endsWith(".receipt.json")).map(r=>{const o=n.join(e,r.name);return{file:o,mtimeMs:t.statSync(o).mtimeMs}}).sort((e,t)=>t.mtimeMs-e.mtimeMs).slice(0,Math.max(0,i))}catch{return[]}const a=[];for(const{file:i}of s)try{const s=JSON.parse(t.readFileSync(i,"utf8")),c=resolveManifestDesignSource(s,r,{box:e});if(!c)continue;Object.assign(c,{term:o,slug:String(s.slug||""),title:String(s.title||s.slug||""),desktop:s.desktop||null,mobile:s.mobile||null});const u=n.join(e,".design-revisions",`${c.revision}.html`);t.existsSync(u)&&(c.backupPath=u),a.push(c)}catch{}return a}export function resolveRequestSourceIdentity(e,r){if(!r?.sourceId)return{ok:!0,identity:null};const n=e?.sourceMap?.entries?.get(r.sourceId);if(!n)return{ok:!1,error:e?.sourceMapDeclared?"stale-source-identity":"source-identity-unavailable"};if(r.tag&&n.tag!==r.tag)return{ok:!1,error:"source-identity-mismatch"};let o;try{o=t.readFileSync(n.sourcePath,"utf8")}catch{return{ok:!1,error:"stale-source-identity"}}return sourceRevision(o)!==n.fileHash?{ok:!1,error:"stale-source-identity"}:{ok:!0,identity:{sourceId:n.sourceId,file:n.file,start:n.start,end:n.end,line:n.line,column:n.column,tag:n.tag,fileHash:n.fileHash}}}export function validateDesignRequest(e,t,r=""){if(!e||"object"!=typeof e)return{ok:!1,error:"invalid-request"};const n=d(e.previewId,64),o=t.get(n);if(!o)return{ok:!1,error:"preview-unavailable"};if(d(e.revision,64)!==o.revision)return{ok:!1,error:"stale-preview"};const i=function(e){if(!e||"object"!=typeof e)return null;const t=e.rect&&"object"==typeof e.rect?{x:Number(e.rect.x)||0,y:Number(e.rect.y)||0,width:Math.max(0,Number(e.rect.width)||0),height:Math.max(0,Number(e.rect.height)||0)}:null;return{selector:d(e.selector,600),xpath:d(e.xpath,600),tag:d(e.tag,40).toLowerCase(),role:d(e.role,80),name:d(e.name,240),text:d(e.text,u),canEditText:!0===e.canEditText,canReplaceImage:!0===e.canReplaceImage,nodeKey:d(e.nodeKey,80),parentNodeKey:d(e.parentNodeKey,80),sourceId:d(e.sourceId,80),parentSourceId:d(e.parentSourceId,80),rect:t}}(e.target);if(!i?.selector&&!i?.xpath)return{ok:!1,error:"select-an-element"};const s=["text","prompt","move","image"].includes(e.mode)?e.mode:null;if(!s)return{ok:!1,error:"invalid-mode"};const a=d(e.intent,"text"===s?u:2e3);if(["text","prompt"].includes(s)&&!a)return{ok:!1,error:"text"===s?"enter-text":"describe-change"};if("text"===s&&!i.canEditText)return{ok:!1,error:"text-edit-not-safe"};const c="move"===s?function(e){if(!e||"object"!=typeof e)return null;const t=Number(e.fromIndex),r=Number(e.toIndex);return![t,r].every(Number.isSafeInteger)||t<0||r<0||t>499||r>499?null:{fromIndex:t,toIndex:r}}(e.movement):null;if("move"===s&&(!c||c.fromIndex===c.toIndex))return{ok:!1,error:"invalid-move"};const l="image"===s?function(e,t){if(!e||"object"!=typeof e)return null;const r={path:d(e.path,700),name:d(e.name,240),mediaType:d(e.mediaType,120).toLowerCase(),size:Number(e.size)},n=t?`code/${String(t).toUpperCase()}/design-drafts/`:"code/";return r.path.startsWith(n)&&!r.path.split("/").includes("..")&&r.mediaType.startsWith("image/")?!Number.isSafeInteger(r.size)||r.size<=0||r.size>10485760?null:r:null}(e.asset,r):null;if(!("image"!==s||i.canReplaceImage&&l))return{ok:!1,error:"invalid-image"};const p=resolveRequestSourceIdentity(o,i);return p.ok?{ok:!0,record:o,request:{previewId:n,revision:o.revision,mode:s,intent:a,target:i,movement:c,asset:l,sourceIdentity:p.identity,cid:d(e.cid,80)}}:p}export function validateDesignBatchRequest(e,t,r=""){if(!e||"object"!=typeof e||!Array.isArray(e.edits))return validateDesignRequest(e,t,r);if(e.edits.length<1||e.edits.length>8)return{ok:!1,error:"invalid-batch"};const n=d(e.previewId,64),o=d(e.revision,64),i=d(e.cid,80),s=[],a=new Set;let c=null;for(let u=0;u<e.edits.length;u++){const l=validateDesignRequest({...e.edits[u],previewId:n,revision:o,cid:i},t,r);if(!l.ok)return{...l,editIndex:u};const d=l.request.target.sourceId||l.request.target.nodeKey||l.request.target.selector||l.request.target.xpath;if(a.has(d))return{ok:!1,error:"duplicate-target",editIndex:u};a.add(d),c=l.record,s.push(l.request)}return{ok:!0,record:c,request:{previewId:n,revision:c.revision,mode:"batch",edits:s,cid:i}}}export async function deleteDesignAssetDraft({webBase:e,token:t,room:r,path:n,fetcher:o=fetch}){if(!(e&&t&&r&&n))return!1;const i=await o(`${String(e).replace(/\/$/,"")}/api/code-design-draft`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({code:r,path:n})}).catch(()=>null);return!!i?.ok}export async function materializeDesignAsset({webBase:e,token:o,room:i,asset:s,requestId:a,cleanup:c=!0,fetcher:u=fetch}){if(!(e&&o&&i&&s?.path&&a))return null;const l={"Content-Type":"application/json",Authorization:`Bearer ${o}`},p=await u(`${String(e).replace(/\/$/,"")}/api/code-attachment-url`,{method:"POST",headers:l,body:JSON.stringify({code:i,path:s.path})});if(!p.ok)return null;const{url:h}=await p.json();if(!h)return null;const m=await u(h);if(!m.ok)return null;const f=Buffer.from(await m.arrayBuffer());if(!f.length||f.length>10485760)return null;const g=n.extname(s.name).replace(/[^.a-zA-Z0-9]/g,"").slice(0,9)||".img",v=n.join(r.tmpdir(),"thinkpool-design-assets"),y=n.join(v,`${d(a,80)}${g}`);return t.mkdirSync(v,{recursive:!0}),t.writeFileSync(y,f),c&&await deleteDesignAssetDraft({webBase:e,token:o,room:i,path:s.path,fetcher:u}),y}function h(e){return"text"===e.mode?`Replace only this element's visible text with:\n${e.intent}`:"move"===e.mode?`Move only this selected element within its current direct parent, from sibling position ${e.movement.fromIndex+1} to ${e.movement.toIndex+1}. Preserve the parent, responsive behavior, semantics, and every other sibling.`:"image"===e.mode?`Replace only this selected image's content with the uploaded image at this bridge-local temporary path:\n${e.asset.localPath}\nCopy it into an appropriate durable project asset location. Preserve the existing image frame, dimensions, border radius, object-fit behavior, responsive rules, and surrounding layout.`:`Apply this visual change to only the selected element unless the instruction explicitly requires its immediate context:\n${e.intent}`}function m(e){const t=e.sourceIdentity?`\n\nBridge-verified application source:\n${JSON.stringify(e.sourceIdentity,null,2)}`:"\n\nApplication source identity: unavailable — selector/XPath fallback only.";return`Selected element:\n${JSON.stringify(e.target,null,2)}${t}`}export function designTranscript(e,{restore:t=!1}={}){if(t)return"thinkpool Design · restore the previous verified revision";const r="batch"===e?.mode?e.edits:[e],n=Array.isArray(r)?r.filter(Boolean).slice(0,8):[],o="batch"===e?.mode?`thinkpool Design · ${n.length} pooled edit${1===n.length?"":"s"}`:"thinkpool Design · 1 edit",i=n.map((e,t)=>{const r=d(e.target?.name||e.target?.tag||"element",240);return`${t+1}. ${n=e.mode,{text:"Text",prompt:"Prompt",move:"Move",image:"Image"}[n]||"Edit"} · ${r}\n${function(e){return"text"===e.mode?`Replacement text:\n${d(e.intent,u)}`:"prompt"===e.mode?`Instruction:\n${d(e.intent,2e3)}`:"move"===e.mode?`Move from position ${e.movement.fromIndex+1} to position ${e.movement.toIndex+1}.`:"image"===e.mode?`Replacement image: ${d(e.asset?.name||"uploaded image",240)}`:""}(e)}`;var n});return[o,...i].join("\n\n")}export function designPrompt({record:e,request:t,by:r,restore:n=!1,priorRecord:o=null}){const i="batch"===t.mode?t.edits:null,s=n?`Restore only the immediately previous Design Mode change by comparing the current artifact with this bridge-created verified backup: ${o?.backupPath||"(backup unavailable)"}. Do not overwrite unrelated changes.`:i?i.map((e,t)=>`Edit ${t+1} of ${i.length} · ${e.mode}\n${m(e)}\n\n${h(e)}`).join("\n\n---\n\n"):`${m(t)}\n\n${h(t)}`;return"preview"===e.sourceKind?`A room member used thinkpool Design Mode on a rendered application preview. This is an authorized source edit in your current workspace.\n\nRendered snapshot (read-only evidence): ${e.sourcePath}\nApplication workspace: ${e.workspaceRoot}\nPreview root: ${e.previewRoot}\nPreview route: ${e.route}\nExpected snapshot revision: ${e.revision}\nRequested by: ${d(r||"A room member",120)}\nOperation: ${i?`${i.length} queued edits in one batch`:t.mode}\n\n${s}\n\nRules:\n- Re-read the rendered snapshot and confirm the selected element still matches before editing.\n- Do not edit the snapshot. For an edit with bridge-verified application source, start at that exact relative file and range. For a selector/XPath fallback, locate the represented element in application source and do not call the match exact.\n- Before editing a bridge-verified target, confirm the current source still hashes to the supplied fileHash. If it does not, stop and request a fresh capture/reselection.\n- If fallback selector, text, or surrounding structure does not identify one application source location unambiguously, stop without editing and explain that the person must reselect it.\n${i?"- Apply the queued edits in order in one source pass, then build and capture once after the full batch.":"- Apply only the requested change, then build and capture once."}\n- Preserve the product page faithfully: keep its real copy, structure, fonts, assets, spacing, responsive behavior, and unrelated source unchanged.\n- Run the project build, then use preview_start with root ${e.previewRoot} and preview_capture with path ${e.route}, both viewports, and title ${JSON.stringify(e.title||e.slug||"Design preview")}. The bridge correlates that capture to this request.\n- Do not claim the edit is verified until the room receives the new desktop and mobile capture.\n- If the build or capture fails, report the failure instead of substituting a screenshot-only result.`:`A room member used thinkpool Design Mode on the artifact below. This is an authorized source edit in your current workspace.\n\nArtifact source: ${e.sourcePath}\nWorkspace: ${e.workspaceRoot}\nExpected source revision: ${e.revision}\nRequested by: ${d(r||"A room member",120)}\nOperation: ${n?"restore the immediately previous verified Design Mode revision":i?`${i.length} queued edits in one batch`:t.mode}\n\n${s}\n\nRules:\n- Re-read the exact artifact source and confirm its revision/content still matches every selected element before editing.\n${i?"- Apply the queued edits in order in one source pass, then render once after the full batch.":"- Apply only the requested change, then render the result once."}\n- Edit the canonical source above; do not search for or edit a different plausible file.\n- Preserve the represented product page faithfully: keep its real copy, structure, fonts, assets, spacing, and responsive behavior except for the selected edits. Never replace it with generic mockup content.\n- Preserve unrelated content and styling.\n- Use the existing mockup render workflow to produce both desktop and mobile captures after the edit. Run it with TP_DESIGN_REQUEST_ID=${t.cid} and TP_DESIGN_PARENT_REVISION=${e.revision} in the command environment so the proof correlates to this request.\n- Do not claim this is live until both captures succeed and the room receives the manifest.\n- If any target is stale or ambiguous, stop without editing and explain that the person must reselect it.`}
1
+ import e from"node:crypto";import t from"node:fs";import r from"node:os";import n from"node:path";import{DESIGN_SOURCE_MAP_RELATIVE as i,DESIGN_SOURCE_MAP_VERSION as o,MAX_DESIGN_SOURCE_ENTRIES as s,MAX_DESIGN_SOURCE_MAP_BYTES as a}from"./design-source-contract.mjs";const c=2097152,u=4e3,l=new Set(["dist","build",".next",".git","coverage","node_modules"]),d=(e,t)=>String(e??"").replace(/\0/g,"").trim().slice(0,t),p=(e,t)=>{const r=n.relative(e,t);return""===r||!r.startsWith("..")&&!n.isAbsolute(r)};export function durableDesignOutbox(e,t=process.env.TP_PAIR_ROOT||n.join(r.homedir(),".thinkpool-pair")){if(!/^[a-zA-Z0-9_-]+$/.test(e||""))throw new TypeError("invalid Design room");return n.join(t,"design",e)}export function migrateDesignOutbox(e,r){if(!t.existsSync(e))return;const i=t.realpathSync(e);t.mkdirSync(r,{recursive:!0,mode:448});const o=t.realpathSync(r);if(i===o)return;const s=t=>{if("string"!=typeof t||!n.isAbsolute(t))return t;const r=p(i,t)?i:n.resolve(e);return p(r,t)?n.join(o,n.relative(r,t)):t};let a=2e3;const u=(e,r,i=0)=>{if(!(i>5))for(const o of t.readdirSync(e,{withFileTypes:!0})){if(--a<0)return;const l=n.join(e,o.name),d=n.join(r,o.name);if(o.isSymbolicLink())continue;const p=t.existsSync(d)?t.lstatSync(d):null;if(!p||o.isDirectory()&&p.isDirectory()&&!p.isSymbolicLink())if(o.isDirectory())t.mkdirSync(d,{recursive:!0,mode:448}),u(l,d,i+1);else if(o.isFile()&&t.statSync(l).size<=c){const e=`${d}.migrate-${process.pid}.tmp`;try{if(o.name.endsWith(".json")&&!o.name.endsWith(".receipt.json")){const r=JSON.parse(t.readFileSync(l,"utf8"));for(const e of["snapshot","desktop","mobile"])r[e]=s(r[e]);t.writeFileSync(e,JSON.stringify(r),{mode:384})}else t.copyFileSync(l,e);t.renameSync(e,d)}catch{}finally{t.rmSync(e,{force:!0})}}}};u(i,o)}export async function syncRealtimeAuth(e,t,r=null){const n=t||r;if(!n||"function"!=typeof e?.realtime?.setAuth)return!1;try{return await e.realtime.setAuth(n),!0}catch{return!1}}export function sourceRevision(t){return e.createHash("sha256").update(String(t)).digest("hex").slice(0,24)}export function resolveDesignSourceMap(e,r,u){if(!e||!r||!u)return null;let h,m,f,y,g,v;try{h=t.realpathSync(e),f=t.realpathSync(r),m=t.realpathSync(n.join(f,i)),y=t.realpathSync(u);const o=t.statSync(h);if(!o.isFile()||o.size<=0||o.size>a)return null;if(h!==m||!p(y,f)||!p(f,h))return null;g=t.readFileSync(h,"utf8"),v=JSON.parse(g)}catch{return null}if(v?.version!==o||!v.entries||"object"!=typeof v.entries||Array.isArray(v.entries))return null;const b=Object.entries(v.entries);if(b.length>s)return null;const S=new Map,x=new Map;for(const[e,r]of b){if(!/^[A-Za-z0-9_-]{8,80}$/.test(e)||!r||"object"!=typeof r)return null;const i=d(r.file,700);if(!i||n.isAbsolute(i)||i.split(/[\\/]/).some(e=>".."===e||l.has(e)))return null;let o=S.get(i);if(!o){try{o=t.realpathSync(n.resolve(y,i));const e=t.statSync(o);if(!e.isFile()||e.size>c||!p(y,o))return null}catch{return null}S.set(i,o)}const s=Number(r.start),a=Number(r.end),u=Number(r.line),h=Number(r.column),m=d(r.tag,40).toLowerCase(),f=d(r.fileHash,64).toLowerCase();if(![s,a,u,h].every(Number.isSafeInteger)||s<0||a<=s||u<1||h<0)return null;if(!/^[a-z][a-z0-9:-]*$/.test(m)||!/^[a-f0-9]{24}$/.test(f))return null;x.set(e,{sourceId:e,file:i.split(n.sep).join("/"),sourcePath:o,start:s,end:a,line:u,column:h,tag:m,fileHash:f})}return{path:h,revision:sourceRevision(g),buildId:d(v.buildId,80),entries:x}}export function resolveDesignSource(r,i){if(!r||!i)return null;let o,s;try{o=t.realpathSync(r),s=t.realpathSync(i);const e=t.statSync(o);if(!e.isFile()||e.size>c)return null}catch{return null}const a=n.relative(s,o);if(!a||a.startsWith("..")||n.isAbsolute(a)||".html"!==n.extname(o).toLowerCase())return null;if(a.split(n.sep).some(e=>["dist","build",".next",".git","coverage","node_modules"].includes(e)))return null;const u=t.readFileSync(o,"utf8"),l=sourceRevision(u);return{previewId:e.createHash("sha256").update(`${o}\0${l}`).digest("base64url").slice(0,32),revision:l,sourcePath:o,workspaceRoot:s,source:u}}export function resolvePreviewDesignSource(r,i,o){if(!(r&&"preview"===r.sourceKind&&r.snapshot&&i&&o))return null;let s,a,u;try{s=t.realpathSync(r.snapshot),a=t.realpathSync(i),u=t.realpathSync(o);const e=t.statSync(s);if(!e.isFile()||e.size>c)return null}catch{return null}const l=n.relative(u,s);if(!l||l.startsWith("..")||n.isAbsolute(l)||".html"!==n.extname(s).toLowerCase())return null;const h=d(r.route||"/",500),m=d(r.previewRoot||"dist",500),f=d(r.captureKey,1e3);if(!h.startsWith("/")||!f||f!==JSON.stringify([m,h]))return null;const y=t.readFileSync(s,"utf8");let g=null;try{if(g=t.realpathSync(n.resolve(a,m)),!p(a,g))return null}catch{return null}const v=r.sourceMap?resolveDesignSourceMap(r.sourceMap,g,a):null,b=sourceRevision(v?`${y}\0${v.revision}`:y);return{sourceKind:"preview",previewId:e.createHash("sha256").update(`${a}\0${f}\0${b}`).digest("base64url").slice(0,32),revision:b,sourcePath:s,workspaceRoot:a,source:y,outbox:u,route:h,previewRoot:m,captureKey:f,sourceMap:v,sourceMapPath:v?.path||null,sourceMapDeclared:!!r.sourceMap}}export function resolveManifestDesignSource(e,t,{box:r}={}){return e&&"object"==typeof e?"preview"===e.sourceKind?resolvePreviewDesignSource(e,t,r):resolveDesignSource(e.source||e.html,t):null}export function resolveManifestDisplaySource(e,r,{box:i}={}){if(!r)return null;if("preview"===r.sourceKind||!e?.snapshot)return r.source;let o,s;try{o=t.realpathSync(e.snapshot),s=t.realpathSync(i);const r=t.statSync(o);if(!r.isFile()||r.size>c)return null}catch{return null}const a=n.relative(s,o);return!a||a.startsWith("..")||n.isAbsolute(a)||".html"!==n.extname(o).toLowerCase()?null:t.readFileSync(o,"utf8")}export function refreshDesignSource(e){return e?"preview"!==e.sourceKind?resolveDesignSource(e.sourcePath,e.workspaceRoot):resolvePreviewDesignSource({sourceKind:"preview",snapshot:e.sourcePath,route:e.route,previewRoot:e.previewRoot,captureKey:e.captureKey,sourceMap:e.sourceMapPath},e.workspaceRoot,e.outbox):null}export function restoreDesignSources(e,r,i,o=100){if(!e||!r||!i)return[];let s;try{s=t.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(".json")&&!e.name.endsWith(".receipt.json")).map(r=>{const i=n.join(e,r.name);return{file:i,mtimeMs:t.statSync(i).mtimeMs}}).sort((e,t)=>t.mtimeMs-e.mtimeMs).slice(0,Math.max(0,o))}catch{return[]}const a=[];for(const{file:o}of s)try{const s=JSON.parse(t.readFileSync(o,"utf8")),c=resolveManifestDesignSource(s,r,{box:e});if(!c)continue;Object.assign(c,{term:i,slug:String(s.slug||""),title:String(s.title||s.slug||""),desktop:s.desktop||null,mobile:s.mobile||null});const u=n.join(e,".design-revisions",`${c.revision}.html`);t.existsSync(u)&&(c.backupPath=u),a.push(c)}catch{}return a}export function resolveRequestSourceIdentity(e,r){if(!r?.sourceId)return{ok:!0,identity:null};const n=e?.sourceMap?.entries?.get(r.sourceId);if(!n)return{ok:!1,error:e?.sourceMapDeclared?"stale-source-identity":"source-identity-unavailable"};if(r.tag&&n.tag!==r.tag)return{ok:!1,error:"source-identity-mismatch"};let i;try{i=t.readFileSync(n.sourcePath,"utf8")}catch{return{ok:!1,error:"stale-source-identity"}}return sourceRevision(i)!==n.fileHash?{ok:!1,error:"stale-source-identity"}:{ok:!0,identity:{sourceId:n.sourceId,file:n.file,start:n.start,end:n.end,line:n.line,column:n.column,tag:n.tag,fileHash:n.fileHash}}}export function validateDesignRequest(e,t,r=""){if(!e||"object"!=typeof e)return{ok:!1,error:"invalid-request"};const n=d(e.previewId,64),i=t.get(n);if(!i)return{ok:!1,error:"preview-unavailable"};if(d(e.revision,64)!==i.revision)return{ok:!1,error:"stale-preview"};const o=function(e){if(!e||"object"!=typeof e)return null;const t=e.rect&&"object"==typeof e.rect?{x:Number(e.rect.x)||0,y:Number(e.rect.y)||0,width:Math.max(0,Number(e.rect.width)||0),height:Math.max(0,Number(e.rect.height)||0)}:null;return{selector:d(e.selector,600),xpath:d(e.xpath,600),tag:d(e.tag,40).toLowerCase(),role:d(e.role,80),name:d(e.name,240),text:d(e.text,u),canEditText:!0===e.canEditText,canReplaceImage:!0===e.canReplaceImage,nodeKey:d(e.nodeKey,80),parentNodeKey:d(e.parentNodeKey,80),sourceId:d(e.sourceId,80),parentSourceId:d(e.parentSourceId,80),rect:t}}(e.target);if(!o?.selector&&!o?.xpath)return{ok:!1,error:"select-an-element"};const s=["text","prompt","move","image"].includes(e.mode)?e.mode:null;if(!s)return{ok:!1,error:"invalid-mode"};const a=d(e.intent,"text"===s?u:2e3);if(["text","prompt"].includes(s)&&!a)return{ok:!1,error:"text"===s?"enter-text":"describe-change"};if("text"===s&&!o.canEditText)return{ok:!1,error:"text-edit-not-safe"};const c="move"===s?function(e){if(!e||"object"!=typeof e)return null;const t=Number(e.fromIndex),r=Number(e.toIndex);return![t,r].every(Number.isSafeInteger)||t<0||r<0||t>499||r>499?null:{fromIndex:t,toIndex:r}}(e.movement):null;if("move"===s&&(!c||c.fromIndex===c.toIndex))return{ok:!1,error:"invalid-move"};const l="image"===s?function(e,t){if(!e||"object"!=typeof e)return null;const r={path:d(e.path,700),name:d(e.name,240),mediaType:d(e.mediaType,120).toLowerCase(),size:Number(e.size)},n=t?`code/${String(t).toUpperCase()}/design-drafts/`:"code/";return r.path.startsWith(n)&&!r.path.split("/").includes("..")&&r.mediaType.startsWith("image/")?!Number.isSafeInteger(r.size)||r.size<=0||r.size>10485760?null:r:null}(e.asset,r):null;if(!("image"!==s||o.canReplaceImage&&l))return{ok:!1,error:"invalid-image"};const p=resolveRequestSourceIdentity(i,o);return p.ok?{ok:!0,record:i,request:{previewId:n,revision:i.revision,mode:s,intent:a,target:o,movement:c,asset:l,sourceIdentity:p.identity,cid:d(e.cid,80)}}:p}export function validateDesignBatchRequest(e,t,r=""){if(!e||"object"!=typeof e||!Array.isArray(e.edits))return validateDesignRequest(e,t,r);if(e.edits.length<1||e.edits.length>8)return{ok:!1,error:"invalid-batch"};const n=d(e.previewId,64),i=d(e.revision,64),o=d(e.cid,80),s=[],a=new Set;let c=null;for(let u=0;u<e.edits.length;u++){const l=validateDesignRequest({...e.edits[u],previewId:n,revision:i,cid:o},t,r);if(!l.ok)return{...l,editIndex:u};const d=l.request.target.sourceId||l.request.target.nodeKey||l.request.target.selector||l.request.target.xpath;if(a.has(d))return{ok:!1,error:"duplicate-target",editIndex:u};a.add(d),c=l.record,s.push(l.request)}return{ok:!0,record:c,request:{previewId:n,revision:c.revision,mode:"batch",edits:s,cid:o}}}export async function deleteDesignAssetDraft({webBase:e,token:t,room:r,path:n,fetcher:i=fetch}){if(!(e&&t&&r&&n))return!1;const o=await i(`${String(e).replace(/\/$/,"")}/api/code-design-draft`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({code:r,path:n})}).catch(()=>null);return!!o?.ok}export async function materializeDesignAsset({webBase:e,token:i,room:o,asset:s,requestId:a,cleanup:c=!0,fetcher:u=fetch}){if(!(e&&i&&o&&s?.path&&a))return null;const l={"Content-Type":"application/json",Authorization:`Bearer ${i}`},p=await u(`${String(e).replace(/\/$/,"")}/api/code-attachment-url`,{method:"POST",headers:l,body:JSON.stringify({code:o,path:s.path})});if(!p.ok)return null;const{url:h}=await p.json();if(!h)return null;const m=await u(h);if(!m.ok)return null;const f=Buffer.from(await m.arrayBuffer());if(!f.length||f.length>10485760)return null;const y=n.extname(s.name).replace(/[^.a-zA-Z0-9]/g,"").slice(0,9)||".img",g=n.join(r.tmpdir(),"thinkpool-design-assets"),v=n.join(g,`${d(a,80)}${y}`);return t.mkdirSync(g,{recursive:!0}),t.writeFileSync(v,f),c&&await deleteDesignAssetDraft({webBase:e,token:i,room:o,path:s.path,fetcher:u}),v}function h(e){return"text"===e.mode?`Replace only this element's visible text with:\n${e.intent}`:"move"===e.mode?`Move only this selected element within its current direct parent, from sibling position ${e.movement.fromIndex+1} to ${e.movement.toIndex+1}. Preserve the parent, responsive behavior, semantics, and every other sibling.`:"image"===e.mode?`Replace only this selected image's content with the uploaded image at this bridge-local temporary path:\n${e.asset.localPath}\nCopy it into an appropriate durable project asset location. Preserve the existing image frame, dimensions, border radius, object-fit behavior, responsive rules, and surrounding layout.`:`Apply this visual change to only the selected element unless the instruction explicitly requires its immediate context:\n${e.intent}`}function m(e){const t=e.sourceIdentity?`\n\nBridge-verified application source:\n${JSON.stringify(e.sourceIdentity,null,2)}`:"\n\nApplication source identity: unavailable — selector/XPath fallback only.";return`Selected element:\n${JSON.stringify(e.target,null,2)}${t}`}export function designTranscript(e,{restore:t=!1}={}){if(t)return"thinkpool Design · restore the previous verified revision";const r="batch"===e?.mode?e.edits:[e],n=Array.isArray(r)?r.filter(Boolean).slice(0,8):[],i="batch"===e?.mode?`thinkpool Design · ${n.length} pooled edit${1===n.length?"":"s"}`:"thinkpool Design · 1 edit",o=n.map((e,t)=>{const r=d(e.target?.name||e.target?.tag||"element",240);return`${t+1}. ${n=e.mode,{text:"Text",prompt:"Prompt",move:"Move",image:"Image"}[n]||"Edit"} · ${r}\n${function(e){return"text"===e.mode?`Replacement text:\n${d(e.intent,u)}`:"prompt"===e.mode?`Instruction:\n${d(e.intent,2e3)}`:"move"===e.mode?`Move from position ${e.movement.fromIndex+1} to position ${e.movement.toIndex+1}.`:"image"===e.mode?`Replacement image: ${d(e.asset?.name||"uploaded image",240)}`:""}(e)}`;var n});return[i,...o].join("\n\n")}export function designPrompt({record:e,request:t,by:r,restore:n=!1,priorRecord:i=null}){const o="batch"===t.mode?t.edits:null,s=n?`Restore only the immediately previous Design Mode change by comparing the current artifact with this bridge-created verified backup: ${i?.backupPath||"(backup unavailable)"}. Do not overwrite unrelated changes.`:o?o.map((e,t)=>`Edit ${t+1} of ${o.length} · ${e.mode}\n${m(e)}\n\n${h(e)}`).join("\n\n---\n\n"):`${m(t)}\n\n${h(t)}`;return"preview"===e.sourceKind?`A room member used thinkpool Design Mode on a rendered application preview. This is an authorized source edit in your current workspace.\n\nRendered snapshot (read-only evidence): ${e.sourcePath}\nApplication workspace: ${e.workspaceRoot}\nPreview root: ${e.previewRoot}\nPreview route: ${e.route}\nExpected snapshot revision: ${e.revision}\nRequested by: ${d(r||"A room member",120)}\nOperation: ${o?`${o.length} queued edits in one batch`:t.mode}\n\n${s}\n\nRules:\n- Re-read the rendered snapshot and confirm the selected element still matches before editing.\n- Do not edit the snapshot. For an edit with bridge-verified application source, start at that exact relative file and range. For a selector/XPath fallback, locate the represented element in application source and do not call the match exact.\n- Before editing a bridge-verified target, confirm the current source still hashes to the supplied fileHash. If it does not, stop and request a fresh capture/reselection.\n- If fallback selector, text, or surrounding structure does not identify one application source location unambiguously, stop without editing and explain that the person must reselect it.\n${o?"- Apply the queued edits in order in one source pass, then build and capture once after the full batch.":"- Apply only the requested change, then build and capture once."}\n- Preserve the product page faithfully: keep its real copy, structure, fonts, assets, spacing, responsive behavior, and unrelated source unchanged.\n- Run the project build, then use preview_start with root ${e.previewRoot} and preview_capture with path ${e.route}, both viewports, and title ${JSON.stringify(e.title||e.slug||"Design preview")}. The bridge correlates that capture to this request.\n- Do not claim the edit is verified until the room receives the new desktop and mobile capture.\n- If the build or capture fails, report the failure instead of substituting a screenshot-only result.`:`A room member used thinkpool Design Mode on the artifact below. This is an authorized source edit in your current workspace.\n\nArtifact source: ${e.sourcePath}\nWorkspace: ${e.workspaceRoot}\nExpected source revision: ${e.revision}\nRequested by: ${d(r||"A room member",120)}\nOperation: ${n?"restore the immediately previous verified Design Mode revision":o?`${o.length} queued edits in one batch`:t.mode}\n\n${s}\n\nRules:\n- Re-read the exact artifact source and confirm its revision/content still matches every selected element before editing.\n${o?"- Apply the queued edits in order in one source pass, then render once after the full batch.":"- Apply only the requested change, then render the result once."}\n- Edit the canonical source above; do not search for or edit a different plausible file.\n- Preserve the represented product page faithfully: keep its real copy, structure, fonts, assets, spacing, and responsive behavior except for the selected edits. Never replace it with generic mockup content.\n- Preserve unrelated content and styling.\n- Use the existing mockup render workflow to produce both desktop and mobile captures after the edit. Run it with TP_DESIGN_REQUEST_ID=${t.cid} and TP_DESIGN_PARENT_REVISION=${e.revision} in the command environment so the proof correlates to this request.\n- Do not claim this is live until both captures succeed and the room receives the manifest.\n- If any target is stale or ambiguous, stop without editing and explain that the person must reselect it.`}