thinkpool-pair 0.7.365 → 0.7.367
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +2 -2
- package/README.md +10 -10
- package/abort-turn-barrier.mjs +1 -1
- package/account.mjs +1 -1
- package/bridge.mjs +1 -1
- package/byok-detect.mjs +1 -1
- package/claude-session.mjs +1 -1
- package/code-event-contract.mjs +1 -1
- package/codex-app-server.mjs +1 -1
- package/codex-session.mjs +1 -1
- package/cross-terminal.mjs +1 -1
- package/design-edit.mjs +1 -1
- package/flow-assembly.mjs +1 -1
- package/flow-conductor.mjs +1 -1
- package/flow-models.mjs +1 -1
- package/flow-review.mjs +1 -1
- package/hermes-acp-bootstrap.py +16 -16
- package/hermes-delegation-guard.mjs +1 -1
- package/hermes-isolation.mjs +1 -1
- package/hermes-policy.mjs +1 -1
- package/hermes-probe.mjs +1 -1
- package/hermes-session.mjs +1 -1
- package/hermes-setup.mjs +1 -1
- package/host-memory.mjs +1 -1
- package/keep-awake.mjs +1 -1
- package/launcher.mjs +1 -1
- package/package.json +2 -2
- package/privacy-report.mjs +1 -1
- package/publish-manifest.json +38 -38
- package/service.mjs +1 -1
- package/side-lane.mjs +1 -1
- package/terminal-name.mjs +1 -1
- package/thinkpool-capabilities.json +11 -11
- package/thinkpool-prompt-contracts.mjs +1 -1
- package/thinkpool-room-prompt.mjs +1 -1
- package/worker-completion.mjs +1 -1
package/byok-detect.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const ANTHROPIC_COMPATIBLE={anthropic:{name:"Anthropic",base:"https://api.anthropic.com",models:"https://api.anthropic.com/v1/models",auth:"x-api-key"},openrouter:{name:"OpenRouter (Anthropic models)",base:"https://openrouter.ai/api",models:"https://openrouter.ai/api/v1/models",auth:"bearer"},zai:{name:"Z.ai — GLM",base:"https://api.z.ai/api/anthropic",models:"https://api.z.ai/api/paas/v4/models",auth:"bearer"},deepseek:{name:"DeepSeek",base:"https://api.deepseek.com/anthropic",models:"https://api.deepseek.com/models",auth:"bearer"},moonshot:{name:"Moonshot — Kimi",base:"https://api.moonshot.ai/anthropic",models:"https://api.moonshot.ai/v1/models",auth:"bearer"},minimax:{name:"MiniMax",base:"https://api.minimax.io/anthropic",models:"https://api.minimax.io/v1/models",auth:"bearer"}};const e=[["sk-ant-","anthropic",!0,"Anthropic"],["sk-or-","openrouter",!0,"OpenRouter"],["AIza","google",!1,"Google Gemini"],["gsk_","groq",!1,"Groq"],["pplx-","perplexity",!1,"Perplexity"],["xai-","xai",!1,"xAI (Grok)"],["fw_","fireworks",!1,"Fireworks"],["sk-","openai",!1,"OpenAI"]];export function detectProvider(t){const o=String(t||"").trim();if(!o)return{id:"unknown",name:"unknown",compatible:!1};for(const[t,a,i,r]of e)if(o.startsWith(t))return{id:a,name:r,compatible:i};return{id:"unknown",name:"unknown",compatible:!1}}export async function fetchModels({modelsUrl:e,key:t,auth:o}){const a="x-api-key"===o?{"x-api-key":t,"anthropic-version":"2023-06-01"}:{Authorization:`Bearer ${t}`},i=new AbortController,r=setTimeout(()=>i.abort(),12e3);try{const t=await fetch(e,{headers:a,signal:i.signal,redirect:"error"});if(!t.ok)return[];const o=await t.json();return(Array.isArray(o?.data)?o.data:Array.isArray(o?.models)?o.models:[]).map(e=>String(e.id||e.name||"").replace(/^models\//,"")).filter(Boolean)}catch{return[]}finally{clearTimeout(r)}}export function gatewayHint(e){return`That key looks like ${e}.
|
|
1
|
+
export const ANTHROPIC_COMPATIBLE={anthropic:{name:"Anthropic",base:"https://api.anthropic.com",models:"https://api.anthropic.com/v1/models",auth:"x-api-key"},openrouter:{name:"OpenRouter (Anthropic models)",base:"https://openrouter.ai/api",models:"https://openrouter.ai/api/v1/models",auth:"bearer"},zai:{name:"Z.ai — GLM",base:"https://api.z.ai/api/anthropic",models:"https://api.z.ai/api/paas/v4/models",auth:"bearer"},deepseek:{name:"DeepSeek",base:"https://api.deepseek.com/anthropic",models:"https://api.deepseek.com/models",auth:"bearer"},moonshot:{name:"Moonshot — Kimi",base:"https://api.moonshot.ai/anthropic",models:"https://api.moonshot.ai/v1/models",auth:"bearer"},minimax:{name:"MiniMax",base:"https://api.minimax.io/anthropic",models:"https://api.minimax.io/v1/models",auth:"bearer"}};const e=[["sk-ant-","anthropic",!0,"Anthropic"],["sk-or-","openrouter",!0,"OpenRouter"],["AIza","google",!1,"Google Gemini"],["gsk_","groq",!1,"Groq"],["pplx-","perplexity",!1,"Perplexity"],["xai-","xai",!1,"xAI (Grok)"],["fw_","fireworks",!1,"Fireworks"],["sk-","openai",!1,"OpenAI"]];export function detectProvider(t){const o=String(t||"").trim();if(!o)return{id:"unknown",name:"unknown",compatible:!1};for(const[t,a,i,r]of e)if(o.startsWith(t))return{id:a,name:r,compatible:i};return{id:"unknown",name:"unknown",compatible:!1}}export async function fetchModels({modelsUrl:e,key:t,auth:o}){const a="x-api-key"===o?{"x-api-key":t,"anthropic-version":"2023-06-01"}:{Authorization:`Bearer ${t}`},i=new AbortController,r=setTimeout(()=>i.abort(),12e3);try{const t=await fetch(e,{headers:a,signal:i.signal,redirect:"error"});if(!t.ok)return[];const o=await t.json();return(Array.isArray(o?.data)?o.data:Array.isArray(o?.models)?o.models:[]).map(e=>String(e.id||e.name||"").replace(/^models\//,"")).filter(Boolean)}catch{return[]}finally{clearTimeout(r)}}export function gatewayHint(e){return`That key looks like ${e}. thinkpool Code runs on the Anthropic Messages API — the format Claude, GLM, DeepSeek, Kimi, MiniMax and local models (LM Studio, llama.cpp) all speak natively — but that provider doesn't, so the key can't be used directly. Route it through your own gateway (e.g. LiteLLM) instead.${"OpenAI"===e?" (If that key is actually DeepSeek or Moonshot/Kimi — they also start with sk- — it works directly: pick that provider in the dashboard’s LLM providers panel instead.)":""}`}
|
package/claude-session.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID as e}from"node:crypto";import{createRequire as t}from"node:module";import{readFileSync as o}from"node:fs";import{dirname as n,join as s}from"node:path";import{query as r}from"@anthropic-ai/claude-agent-sdk";import{sanitizeSession as i}from"./transcript-sanitize.mjs";import{reviewGatePreToolDecision as a}from"./flow-review-gate.mjs";import{crossPostNeedsCard as l}from"./cross-terminal.mjs";import{correctContext as c}from"./context-windows.mjs";import{normalizeClaudeCommandCatalog as d}from"./claude-command-catalog.mjs";import{evidenceForToolResult as u}from"./evidence-citations.mjs";import{THINKPOOL_CASCADE_RULE as p,THINKPOOL_REMOTE_DELIVERY_RULES as m,THINKPOOL_RUNTIME_AUTHORITY_RULE as h,THINKPOOL_RUNTIME_TURN_REMINDER as f,buildThinkPoolTurnGuidance as y,createRoomContextSelector as k,usesFullThinkPoolReminder as g}from"./thinkpool-room-prompt.mjs";import{stallDecision as w,stallEvent as b,isCompactTurn as v}from"./turn-stall.mjs";import{createSameTargetResilienceController as _,formatResilienceTrace as T}from"./provider-resilience.mjs";const S=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 E=(()=>{try{let e=n(S.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"})(),N=/\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,O=new Set(["Read","Grep","Glob","NotebookRead","TodoRead","LS"]),P=new Set(["WebFetch","WebSearch"]),R=new Set(["Edit","Write","MultiEdit","NotebookEdit","TodoWrite"]);export function classifyRisk(e,t){if("Bash"===e){const e=t&&(t.command??t.cmd)||"";return N.test(e)?"high":"medium"}return O.has(e)?"low":P.has(e)?"network":(R.has(e),"medium")}const A=/(^|\/)\.claude\/SESSIONS\/|(^|\/)CLAUDE\.md$/;export function isSafeDocWrite(e,t){if(!R.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&&R.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 D(){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 x=(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),I=new Set(["default","acceptEdits","plan","bypassPermissions"]),M=["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:S="default",onEvent:N,requestPermission:O,mcpServers:P,crossPostGate:R,crossRoomPostGate:A,didSpawnTarget:U=null,terminalRolePrompt:C,rolePrompt:L,blockSubagents:W=!1,onSubmitPlan:F=null,onLaneDone:$=null,onReviewVerdict:j=null,reviewGate:q=null,lazy:G=!1,roomContext:B=null,suggest:H=!0,prepareCwd:K=null,admitStart:Q=null,resilienceObserver:Y=null,resilience:z=null}){const J=k(B);let V=0,X=!0;const Z=(e,{promptIndex:t=0,forceFull:o=!1}={})=>{const n=g({promptIndex:t,forceFull:o}),s=J({force:n}),r=String(C||"").trim();return`<system-reminder>\n${n&&r?`${r}\n\n`:""}${n?M:y({text:e,promptIndex:t,forceFull:o})}${s?`\n\n${s}`:""}\n</system-reminder>`},ee=new AbortController;let te=D(),oe=s||null,ne=s||null,se=null,re=null,ie=null,ae=!1,le=!1,ce=null,de=!1,ue=!1,pe=!1,me=null,he=I.has(S)?S:"default";const fe=new Set,ye=new Map,ke=new Set(["low","medium","high","xhigh","max"]);let ge=ke.has(n)?n:"high",we=0,be=0,ve=o||null,_e=null,Te=null,Se=Promise.resolve(),Ee=!1;const Ne=e=>new Promise(t=>setTimeout(t,e)),Oe=Math.max(3e4,parseInt(process.env.TP_STALL_MS,10)||9e4);let Pe=!1,Re=Date.now(),Ae=!1;const De=/connection closed|connection reset|econnreset|etimedout|socket hang up|fetch failed|network error|socket destroyed/i;let xe=0;const Ie=(e,t={})=>{try{Y?.({reason:e,restartCount:xe,...t})}catch{}},Me=!(!z?.policy?.enabled||!z?.providerId||"anthropic"===z.providerId);let Ue=null,Ce=null,Le=!1,We=0,Fe=!1,$e=null;const je=Math.max(3*Oe,parseInt(process.env.TP_FORCE_STOP_MS,10)||3e5);let qe=!1,Ge=!1;const Be=Math.max(je,parseInt(process.env.TP_COMPACT_FORCE_STOP_MS,10)||12e5);let He=!1,Ke=0;const Qe=O;O=async e=>{Ke++;try{return await(Qe?.(e))}finally{Ke=Math.max(0,Ke-1),Re=Date.now()}};let Ye=!1,ze=null,Je=null,Ve=!1,Xe="",Ze=null;const et=Math.max(1200,parseInt(process.env.TP_SUGGEST_FALLBACK_MS,10)||2500),tt=e=>{try{N?.(e)}catch{}},ot=e=>{Re=Date.now(),e&&"stalled"!==e.kind&&(Ae=!1),!e||"compaction"!==e.kind&&"result"!==e.kind&&"error"!==e.kind||(He=!1),tt(e)},nt=e=>{try{z?.onRecord?.(e)}catch{}"retrying"!==e?.outcome&&"cap_blocked"!==e?.outcome&&"circuit_open"!==e?.outcome||ot({kind:"note",text:T(e)})},st=()=>{if(null!=Ce){try{(z?.clearTimer||clearTimeout)(Ce)}catch{}Ce=null}},rt=()=>{if(st(),!Ue)return;const e=Number(z?.policy?.timeoutMs);if(!Number.isFinite(e)||e<=0)return;const t=z?.setTimer||setTimeout;Ce=t(()=>{if(Ce=null,!ae&&Ue&&Pe){Ue.failure({message:"timeout"}),Pe=!1;try{_e?.abort()}catch{}ft()}},e)},it=async()=>{if(!Ue)return!0;let e=null;try{e=await Ue.preflight()}catch{return!1}return!0===e?.admitted},at=setInterval(()=>{const e=Date.now()-Re,t=w({turnActive:Pe,awaitingUser:Ke,quietMs:e,stallMs:Oe,forceStopMs:je,stalledSent:Ae,stallRetried:Ge,compacting:He,compactForceStopMs:Be});if("none"===t)return;const o=b(t,e);if(o&&tt(o),"status"!==t){if("retry"===t){if(qe=!0,Ue){Ie("resilience_stall",{quietMs:e}),Ue.failure({message:"timeout"}),Pe=!1;try{_e?.abort()}catch{}return void ft()}return Ie("stall_replay",{quietMs:e}),void ht(e)}qe=!0,Pe=!1}else Ae=!0},5e3);at.unref?.();const lt=e=>{setTimeout(()=>{Promise.resolve(me?.setPermissionMode?.(e)).catch(t=>console.error(`[claude-session] setPermissionMode(${e}) failed:`,t?.message||t))},0)},ct={abortController:ee,permissionMode:he,hooks:{PreToolUse:[{hooks:[async t=>{const o=t.tool_name,n=t.tool_input,s=t.effort?.level;s&&s!==ge&&(ge=s,ot({kind:"effort",level:ge}));const r="Write"===o||"Edit"===o||"MultiEdit"===o||"NotebookEdit"===o;if(W&&r&&/(?:^|[/\\])FLOW_PLAN\.json$/i.test(n?.file_path||n?.notebook_path||"")){const e=n?.content??n?.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(W&&("Task"===o||"Agent"===o||"Bash"===o||r))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Bash"===o?"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.":r?'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(j&&("Write"===o||"Edit"===o)&&/(?:^|[/\\])FLOW_REVIEW(\.[a-zA-Z0-9]+)?$/.test(n?.file_path||"")){let e={ok:!1,message:"verdict signal failed"};try{e=await j(n?.content??n?.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($&&("Write"===o||"Edit"===o)&&/(?:^|[/\\])FLOW_DONE(\.[a-zA-Z0-9]+)?$/.test(n?.file_path||"")){let e={ok:!1,message:"done signal failed"};try{e=await $(n?.content??n?.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 i=a({reviewGate:q,toolName:o,toolInput:n});if(i)return i;if("mcp__thinkpool__read_terminal"===o)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(o))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (contained bridge-owned viewport preview)."}};if("mcp__thinkpool__submit_flow_plan"===o)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"===o||"mcp__thinkpool__read_session"===o)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"===o)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (ThinkPool cross-terminal close — only self-spawned lanes)."}};if("mcp__thinkpool__spawn_terminal"===o)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"===o){const t=n?.mode||he;if("bypassPermissions"!==t||"bypassPermissions"===he)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 s="deny";try{s=await(O?.({id:e(),toolName:o,input:{...n,mode:t},risk:"high"}))??"deny"}catch{s="deny"}const r="allow"===s;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"===o){const t=R?R():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-terminal post not allowed right now."}};const s=!!U&&!!U(n?.terminal);if(!l({mode:he,spawnedByMe:s}))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"bypassPermissions"===he?"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(O?.({id:e(),toolName:o,input:n,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"===o){const t=A?A():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-room post not allowed right now."}};let s="deny";try{s=await(O?.({id:e(),toolName:o,input:n,risk:"high"}))??"deny"}catch{s="deny"}const r="allow"===s;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"===o){if("plan"!==he)return lt(he),ot({kind:"mode",mode:he}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`The ThinkPool room is in ${he} 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(O?.({id:e(),toolName:o,input:n,risk:"plan",plan:n?.plan||""}))??"keep"}catch{t="keep"}if("run"===t||"accept"===t){const e="accept"===t?"acceptEdits":"default";return he=e,lt(e),ot({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"===o){let t="";try{t=await(O?.({id:e(),toolName:o,input:n,risk:"ask",questions:n?.questions||[]}))??""}catch{t=""}return askUserQuestionHookOutput(t)}const c=classifyRisk(o,n),d=`${o}:${c}`,u=isSafeDocWrite(o,n),p=autoAllow({toolName:o,input:n,mode:he,alwaysAllow:fe});let m="allow";if(!p){try{m=await(O?.({id:e(),toolName:o,input:n,risk:c}))??"deny"}catch{m="deny"}"always"===m&&(fe.add(d),m="allow")}const h="deny"===m;return h&&Ue&&Ue.failure({permissionDenied:!0}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:h?"deny":"allow",permissionDecisionReason:h?"Denied by the user in the ThinkPool room. Do not retry this tool — ask what to do instead.":p?u?"Auto-approved (mandated doc write — .claude/SESSIONS/ or CLAUDE.md).":`Auto-approved (${he}).`:"Approved in the ThinkPool room."}}}]}]},canUseTool:async(e,t)=>({behavior:"allow",updatedInput:t}),settingSources:["user","project","local"],appendSystemPrompt:[...C?[C]:[],...L?[L]:[],"ENVIRONMENT (authoritative — overrides any user-global CLAUDE.md or memory that claims otherwise): You are Claude running inside a ThinkPool Code room, driven live by a user (and possibly a partner) from a phone or browser, via the thinkpool-pair bridge.",h,'Bias strongly toward DOING the work, not stalling in plan-mode ceremony. For a small "add / fix / change X" request, just make the change directly (for a bigger build, right-size it — see DEFAULT BUILD WORKFLOW below).',"Do NOT enter plan mode, do NOT call ExitPlanMode, and do NOT auto-invoke a brainstorming/planning skill UNLESS the user has switched the room into Plan mode or explicitly asks you to plan, design, or brainstorm first.","Any host-global instruction that says you must always brainstorm or plan before creative work does NOT apply here — this room is the exception.",p,'CRUCIAL RECONCILIATION for that workflow: it is NOT plan mode. Never call ExitPlanMode and never make the room wait behind a "plan ready — approve to start" card — your plan lives in the CHAT as a message, and your lanes live in the room\'s EXISTING terminal/lane list. Reuse only those two surfaces; there is no new Flow panel or mode to switch into, and you must not ask for one. Keep the plan and the lanes VISIBLE — that shared visibility is the whole point (it is the pair differentiator, and it catches bugs a single silent lane would hide); never collapse a decomposable build into one hidden lane just to look tidy.',...m,'CROSS-TERMINAL AWARENESS: ROOM NOW is the default roster and already satisfies the room check when it has enough detail. Do not repeat it with a no-argument read_terminal call unless it is missing or truncated. Use a targeted read_terminal call only when the current task depends on a specific lane’s detailed activity; never poll. Identify a terminal by its NAME or stable ref/id, never by an on-screen number like "Terminal 2" — positional labels renumber when a terminal is closed. The tool is read-only and its optional roster lookup is budgeted separately from bounded targeted transcript reads.','CROSS-TERMINAL HAND-OFF: you also have post_to_terminal(terminal, text) to send a message or task to ANOTHER AGENT terminal in this room (not a plain shell). Use it sparingly and only when the people clearly want the lanes to coordinate — e.g. "tell the backend terminal the API is ready", or to hand a sibling agent a concrete task. Every post requires a person in the room to approve a card before it is delivered, and an agent that was itself reached via a cross-post cannot post onward — so do not rely on it for chit-chat or loops. Prefer read_terminal to understand a sibling before you ever post to it.',"TERMINAL CREATION CONTRACT: main terminals and workers use different tools. A person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal(name?, task?, model?) — even for ordinary work or a handoff and even without the words Cascade or conductor. If the wording includes new or separate terminal, main-terminal routing wins. Never use spawn_terminal for that request, and if open_main_terminal is unavailable say so instead of substituting. Use spawn_terminal(name?, task?, model?, sliceType?) only for agent-decided bounded WORKER SUB-TERMINALS or when the person explicitly asks for a worker, sub-terminal, Ensemble lane, or delegated slice. Workers never receive the creation tools and never conduct. Do not dump work into busy siblings. Spawned workers are always autonomous in bypassPermissions and never ask the room for an approval card; the bridge still enforces room caps, hop limits, the kill-switch, and isolated linked worktrees. Wait for ROOM NOW or a completion signal instead of polling; after a worker finishes, collect it with one targeted read_terminal call and close_terminal immediately. 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&&(ct.strictMcpConfig=!0,ct.mcpServers={}),P&&Object.keys(P).length&&(ct.mcpServers={...ct.mcpServers||{},...P}),t&&(ct.cwd=t),o&&(ct.model=o),ct.effort=ge,ct.env={...f||process.env,CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION:"1"};const dt=async()=>{if(!H)return;const e=(Xe||"").trim().slice(-1500);if(e&&!ae)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:ct.env,timeoutMs:8e3});o=o.trim().split("\n")[0].replace(/^["'`]+|["'`]+$/g,"").trim().slice(0,140),!o||Ve||ae||/^(sure|of course|certainly|let me know|i can help|happy to)\b/i.test(o)||(ot({kind:"suggestion",text:o,source:"haiku"}),process.stderr.write(` ◆ [suggestion] haiku fallback: ${JSON.stringify(o)}\n`))}catch{}},ut=()=>{const e="function"==typeof Q?Q():{ok:!0};return!1!==e?.ok||(ot({kind:"error",message:e.reason||"Host memory is critically low. This agent runtime was not started.",recoverable:!0}),!1)},pt=async({admitted:e=!1}={})=>{if(!le&&!e&&!ut())return!1;if(null==ce&&(ce=Date.now()),le=!0,Te)try{Te()}catch{}Se=new Promise(e=>{Te=e});const n=new AbortController;_e=n;const a=()=>{try{n.abort()}catch{}};ee.signal.addEventListener("abort",a,{once:!0});try{if(oe){const e=i(t||process.cwd(),oe);e.blocks&&process.stderr.write(`\n ◆ healed ${e.blocks} malformed tool block(s) in the transcript before resume.\n`)}me=r({prompt:te.stream,options:{...ct,abortController:n,...oe?{resume:oe}:{}}});for await(const e of me){if(ae)break;switch(e.type){case"system":if("thinking_tokens"===e.subtype){we+be===0&&ot({kind:"thinking_tokens",tokens:e.estimated_tokens,delta:e.estimated_tokens_delta});break}if("compact_boundary"===e.subtype){X=!0,ot({kind:"compaction",trigger:e.compact_metadata?.trigger||"auto",preTokens:e.compact_metadata?.pre_tokens??null}),(async()=>{try{const e=await(me?.getContextUsage?.());e&&(ot({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),de||(de=!0,process.stderr.write(`\n ◆ session ready in ${Date.now()-ce}ms — MCP ${"1"===process.env.TP_MCP_STRICT?"OFF":"on"}${s?", resume":", fresh"}.\n`)),ve=ct.model||e.model||o||ve,ot({kind:"system",sessionId:oe,model:ct.model||e.model||o||null,commands:d({slashCommands:e.slash_commands,skills:e.skills})}),!pe&&Array.isArray(e.tools)){pe=!0;const t=askUserQuestionRegression(e.tools,E);t&&(process.stderr.write(`\n ⚠⚠ ${t}\n`),ot({kind:"error",message:t}))}ue||(ue=!0,Promise.resolve(me?.supportedModels?.()).then(e=>{const t=(e||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);t.length&&ot({kind:"models",models:t})}).catch(()=>{}));break;case"assistant":st(),Ue?.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&&(Xe=t)}ot({kind:"assistant",blocks:x(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){st(),Ue?.visibleOutput({tool:!0});const o=ye.get(t.tool_use_id);null!=o&&ye.delete(t.tool_use_id);const n=u(o?.name,t.content);ot({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?(we+=be,be=t.message?.usage?.output_tokens||0,ot({kind:"thinking_tokens",tokens:we+be})):"message_delta"===t?.type&&t.usage&&(be=t.usage.output_tokens??be,ot({kind:"thinking_tokens",tokens:we+be}));break}case"result":if(st(),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)&&xe<3){xe++;const e=Pe;Pe=!1,oe=null,ne=null,ot({kind:"note",text:"previous session not found — continuing on a fresh one"});const t=te;te=D();try{t.end()}catch{}const o=e?se:null;$e=setTimeout(()=>{$e=null,ae||(pt(),null!=o&&(Pe=!0,Re=Date.now(),Ae=!1,te.push([{type:"text",text:o},{type:"text",text:re||Z(o,{forceFull:!0})}])))},300);break}if(Ye&&("aborted"===e.subtype||"error_during_execution"===e.subtype)){We===ze&&(Pe=!1);break}if(e.is_error&&Ue){if(Le)break;Ue.failure({message:Array.isArray(e.errors)?e.errors.join(" "):e.result,status:e.status??e.statusCode,code:e.code}),Pe=!1,ft();break}if(we=0,be=0,Pe=!1,Ee&&(Ee=!1,setTimeout(()=>{ae||mt()},0)),"success"===e.subtype&&(xe=0,oe&&(ne=oe)),"success"===e.subtype&&(Ue?.success(),Ue=null),qe=!1,Ge=!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):"";ot({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})}Ze&&clearTimeout(Ze),"aborted"!==e.subtype&&(Ze=setTimeout(()=>{Ze=null,Ve||ae||dt()},et)),(async()=>{let t=null;try{const e=await(me?.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||{};ot({kind:"usage",costUsd:e.total_cost_usd??null,tokens:(o.input_tokens||0)+(o.output_tokens||0),ctx:t})})();break;case"prompt_suggestion":Ze&&(clearTimeout(Ze),Ze=null),e.suggestion&&(Ve=!0,ot({kind:"suggestion",text:e.suggestion}))}}}catch(e){if(st(),ae)return;if(n.signal.aborted)return;const t=e?.message||String(e);if(Ue&&Pe)return Ue.failure({message:t,status:e?.status??e?.statusCode,code:e?.code}),Pe=!1,void ft();if(Pe=!1,ot({kind:"error",message:t}),De.test(t)&&xe<3){xe++,Ie("stream_reconnect",{failureClass:"network"}),ot({kind:"note",text:`connection dropped — reconnecting (${xe}/3)`});const e=te;te=D();try{e.end()}catch{}return void($e=setTimeout(()=>{$e=null,ae||pt()},Math.min(1e3*xe,4e3)))}if(/no conversation found/i.test(t)&&oe&&xe<3){xe++,oe=null,ne=null;const e=te;te=D();try{e.end()}catch{}return void($e=setTimeout(()=>{$e=null,ae||pt()},300))}ae=!0}finally{ee.signal.removeEventListener("abort",a),_e===n&&(_e=null);try{await(me?.return?.())}catch{}Te&&(Te(),Te=null)}},mt=async()=>{if(ae||!le)return;const e=Se,t=te;if(te=D(),_e)try{_e.abort()}catch{}try{t.end()}catch{}try{await e}catch{}await Ne(300),oe=ne,ae||pt()},ht=async e=>{if(ae)return;Ge=!0;const t=Pe&&!v(se)?se:null;Pe=!1;const o=Se,n=te;if(te=D(),_e)try{_e.abort()}catch{}try{n.end()}catch{}try{await o}catch{}await Ne(300),oe=ne,ae||(pt(),null!=t&&(Pe=!0,Re=Date.now(),Ae=!1,te.push(/^\s*\//.test(t)?[{type:"text",text:t}]:[{type:"text",text:t},{type:"text",text:re||Z(t,{forceFull:!0})}]),tt({kind:"note",text:"retrying the stalled turn on a fresh connection"})))},ft=()=>{if(ae||Fe||Le)return;const e=Ue,t=We,o=ie;Le=!0;const n=Se,s=te;te=D();try{s.end()}catch{}$e=setTimeout(async()=>{$e=null;try{await n}catch{}if(!ae&&Le&&Ue===e&&We===t)return await it()?void(!ae&&Le&&Ue===e&&We===t&&(Le=!1,Pe=!0,Re=Date.now(),Ae=!1,pt(),o&&te.push(o),rt())):(Le=!1,void yt())},0)},yt=()=>{st(),Pe=!1,Ue=null,le=!1,ot({kind:"error",message:"The configured provider could not complete this turn. Nothing else was sent.",recoverable:!0})};return G||Me||pt(),{sendTurn(e){if(ae||Fe||Le)return!1;if(!le&&!ut())return!1;if(!le&&K)try{const e=K();e&&(t=e,ct.cwd=e)}catch{}Pe=!0,Ve=!1,se=String(e),Ze&&(clearTimeout(Ze),Ze=null),Re=Date.now(),Ae=!1,Ge=!1,qe=!1;const n=String(e),s=V++,r=X;if(X=/^\s*\/(?:compact|clear|reset)\b/i.test(n),re=/^\s*\//.test(n)?null:Z(n,{promptIndex:s,forceFull:r}),He=v(n),ie=/^\s*\//.test(n)?[{type:"text",text:n}]:[{type:"text",text:n},{type:"text",text:re}],We++,Ue=(()=>{if(!Me)return null;try{const e=_({runtime:"claude",providers:z.providers||[],providerId:z.providerId,model:z.model||ct.model||o,requestedModel:z.requestedModel||z.model||ct.model||o,policy:z.policy,bridgeHostId:z.bridgeHostId,circuit:z.circuit,capGate:z.capGate,traceId:z.traceId,turnRev:"function"==typeof z.turnRev?z.turnRev():z.turnRev,onRecord:nt});return e.start(),e}catch{return null}})(),Ue){const e=Ue,t=We,o=ie;it().then(n=>{!ae&&Pe&&Ue===e&&We===t&&(n?(le||pt({admitted:!0}),te.push(o),rt()):yt())}).catch(()=>{!ae&&Pe&&Ue===e&&We===t&&yt()})}else le||pt({admitted:!0}),te.push(ie)},warm(){Me||le||ae||pt()},get started(){return le},async setMode(e){I.has(e)&&!ae&&(he=e,lt(e),ot({kind:"mode",mode:he}))},async setModel(e){ct.model=e,ve=e,ot({kind:"note",text:`model → ${e}`}),le&&!ae&&(Pe?Ee=!0:await mt())},setEffort:async e=>!(!ke.has(e)||ae||(ge=e,ct.effort=e,ot({kind:"effort",level:e}),le&&(Pe?(Ee=!0,0):(await mt(),0)))),async listModels(){try{const e=(await(me?.supportedModels?.())||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);e.length&&ot({kind:"models",models:e}),ot({kind:"note",text:e.length?`models: ${e.map(e=>e.value).join(", ")}`:"no model list available"})}catch{ot({kind:"note",text:"usage: /model <name>"})}},async abort(){if(!Fe){Fe=!0;try{const e=Le,t=e?Se:null;(Pe||e)&&(We++,e||(Le=!1),st(),Ue?.failure({aborted:!0}),e&&(clearTimeout($e),$e=null,le=!1),Ye=!0,ze=We,clearTimeout(Je),Je=setTimeout(()=>{Ye=!1,ze=null},6e3));try{await(me?.interrupt?.())}catch{}if(t)try{await t}catch{}e&&(Le=!1),(Pe||e)&&(Pe=!1,ot({kind:"result",subtype:"aborted",sessionId:oe}))}finally{Fe=!1}}},end(){ae=!0,st(),clearInterval(at),clearTimeout(Je),clearTimeout($e),Ze&&clearTimeout(Ze),te.end();try{ee.abort()}catch{}},get sessionId(){return oe},get mode(){return he},get turnActive(){return Pe}}}
|
|
1
|
+
import{randomUUID as e}from"node:crypto";import{createRequire as t}from"node:module";import{readFileSync as o}from"node:fs";import{dirname as n,join as s}from"node:path";import{query as r}from"@anthropic-ai/claude-agent-sdk";import{sanitizeSession as i}from"./transcript-sanitize.mjs";import{reviewGatePreToolDecision as a}from"./flow-review-gate.mjs";import{crossPostNeedsCard as l}from"./cross-terminal.mjs";import{correctContext as c}from"./context-windows.mjs";import{normalizeClaudeCommandCatalog as d}from"./claude-command-catalog.mjs";import{evidenceForToolResult as u}from"./evidence-citations.mjs";import{THINKPOOL_CASCADE_RULE as p,THINKPOOL_REMOTE_DELIVERY_RULES as m,THINKPOOL_RUNTIME_AUTHORITY_RULE as h,THINKPOOL_RUNTIME_TURN_REMINDER as f,buildThinkPoolTurnGuidance as y,createRoomContextSelector as k,usesFullThinkPoolReminder as g}from"./thinkpool-room-prompt.mjs";import{stallDecision as w,stallEvent as b,isCompactTurn as v}from"./turn-stall.mjs";import{createSameTargetResilienceController as _,formatResilienceTrace as T}from"./provider-resilience.mjs";const S=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 E=(()=>{try{let e=n(S.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"})(),N=/\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,O=new Set(["Read","Grep","Glob","NotebookRead","TodoRead","LS"]),R=new Set(["WebFetch","WebSearch"]),A=new Set(["Edit","Write","MultiEdit","NotebookEdit","TodoWrite"]);export function classifyRisk(e,t){if("Bash"===e){const e=t&&(t.command??t.cmd)||"";return N.test(e)?"high":"medium"}return O.has(e)?"low":R.has(e)?"network":(A.has(e),"medium")}const D=/(^|\/)\.claude\/SESSIONS\/|(^|\/)CLAUDE\.md$/;export function isSafeDocWrite(e,t){if(!A.has(e))return!1;const o=t&&(t.file_path||t.notebook_path)||"";return D.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&&A.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 x(){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 P=(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),I=new Set(["default","acceptEdits","plan","bypassPermissions"]),M=["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:S="default",onEvent:N,requestPermission:O,mcpServers:R,crossPostGate:A,crossRoomPostGate:D,didSpawnTarget:U=null,terminalRolePrompt:C,rolePrompt:L,blockSubagents:W=!1,onSubmitPlan:F=null,onLaneDone:$=null,onReviewVerdict:j=null,reviewGate:q=null,lazy:G=!1,roomContext:B=null,suggest:H=!0,prepareCwd:K=null,admitStart:Q=null,resilienceObserver:Y=null,resilience:z=null}){const J=k(B);let V=0,X=!0;const Z=(e,{promptIndex:t=0,forceFull:o=!1}={})=>{const n=g({promptIndex:t,forceFull:o}),s=J({force:n}),r=String(C||"").trim();return`<system-reminder>\n${n&&r?`${r}\n\n`:""}${n?M:y({text:e,promptIndex:t,forceFull:o})}${s?`\n\n${s}`:""}\n</system-reminder>`},ee=new AbortController;let te=x(),oe=s||null,ne=s||null,se=null,re=null,ie=null,ae=!1,le=!1,ce=null,de=!1,ue=!1,pe=!1,me=null,he=I.has(S)?S:"default";const fe=new Set,ye=new Map,ke=new Set(["low","medium","high","xhigh","max"]);let ge=ke.has(n)?n:"high",we=0,be=0,ve=o||null,_e=null,Te=null,Se=Promise.resolve(),Ee=!1;const Ne=e=>new Promise(t=>setTimeout(t,e)),Oe=Math.max(3e4,parseInt(process.env.TP_STALL_MS,10)||9e4);let Re=!1,Ae=Date.now(),De=!1;const xe=/connection closed|connection reset|econnreset|etimedout|socket hang up|fetch failed|network error|socket destroyed/i;let Pe=0;const Ie=(e,t={})=>{try{Y?.({reason:e,restartCount:Pe,...t})}catch{}},Me=!(!z?.policy?.enabled||!z?.providerId||"anthropic"===z.providerId);let Ue=null,Ce=null,Le=!1,We=0,Fe=!1,$e=null;const je=Math.max(3*Oe,parseInt(process.env.TP_FORCE_STOP_MS,10)||3e5);let qe=!1,Ge=!1;const Be=Math.max(je,parseInt(process.env.TP_COMPACT_FORCE_STOP_MS,10)||12e5);let He=!1,Ke=0;const Qe=O;O=async e=>{Ke++;try{return await(Qe?.(e))}finally{Ke=Math.max(0,Ke-1),Ae=Date.now()}};let Ye=!1,ze=null,Je=null,Ve=!1,Xe="",Ze=null;const et=Math.max(1200,parseInt(process.env.TP_SUGGEST_FALLBACK_MS,10)||2500),tt=e=>{try{N?.(e)}catch{}},ot=e=>{Ae=Date.now(),e&&"stalled"!==e.kind&&(De=!1),!e||"compaction"!==e.kind&&"result"!==e.kind&&"error"!==e.kind||(He=!1),tt(e)},nt=e=>{try{z?.onRecord?.(e)}catch{}"retrying"!==e?.outcome&&"cap_blocked"!==e?.outcome&&"circuit_open"!==e?.outcome||ot({kind:"note",text:T(e)})},st=()=>{if(null!=Ce){try{(z?.clearTimer||clearTimeout)(Ce)}catch{}Ce=null}},rt=()=>{if(st(),!Ue)return;const e=Number(z?.policy?.timeoutMs);if(!Number.isFinite(e)||e<=0)return;const t=z?.setTimer||setTimeout;Ce=t(()=>{if(Ce=null,!ae&&Ue&&Re){Ue.failure({message:"timeout"}),Re=!1;try{_e?.abort()}catch{}ft()}},e)},it=async()=>{if(!Ue)return!0;let e=null;try{e=await Ue.preflight()}catch{return!1}return!0===e?.admitted},at=setInterval(()=>{const e=Date.now()-Ae,t=w({turnActive:Re,awaitingUser:Ke,quietMs:e,stallMs:Oe,forceStopMs:je,stalledSent:De,stallRetried:Ge,compacting:He,compactForceStopMs:Be});if("none"===t)return;const o=b(t,e);if(o&&tt(o),"status"!==t){if("retry"===t){if(qe=!0,Ue){Ie("resilience_stall",{quietMs:e}),Ue.failure({message:"timeout"}),Re=!1;try{_e?.abort()}catch{}return void ft()}return Ie("stall_replay",{quietMs:e}),void ht(e)}qe=!0,Re=!1}else De=!0},5e3);at.unref?.();const lt=e=>{setTimeout(()=>{Promise.resolve(me?.setPermissionMode?.(e)).catch(t=>console.error(`[claude-session] setPermissionMode(${e}) failed:`,t?.message||t))},0)},ct={abortController:ee,permissionMode:he,hooks:{PreToolUse:[{hooks:[async t=>{const o=t.tool_name,n=t.tool_input,s=t.effort?.level;s&&s!==ge&&(ge=s,ot({kind:"effort",level:ge}));const r="Write"===o||"Edit"===o||"MultiEdit"===o||"NotebookEdit"===o;if(W&&r&&/(?:^|[/\\])FLOW_PLAN\.json$/i.test(n?.file_path||n?.notebook_path||"")){const e=n?.content??n?.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(W&&("Task"===o||"Agent"===o||"Bash"===o||r))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Bash"===o?"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.":r?'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(j&&("Write"===o||"Edit"===o)&&/(?:^|[/\\])FLOW_REVIEW(\.[a-zA-Z0-9]+)?$/.test(n?.file_path||"")){let e={ok:!1,message:"verdict signal failed"};try{e=await j(n?.content??n?.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($&&("Write"===o||"Edit"===o)&&/(?:^|[/\\])FLOW_DONE(\.[a-zA-Z0-9]+)?$/.test(n?.file_path||"")){let e={ok:!1,message:"done signal failed"};try{e=await $(n?.content??n?.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 i=a({reviewGate:q,toolName:o,toolInput:n});if(i)return i;if("mcp__thinkpool__read_terminal"===o)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(o))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (contained bridge-owned viewport preview)."}};if("mcp__thinkpool__submit_flow_plan"===o)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"===o||"mcp__thinkpool__read_session"===o)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"===o)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (thinkpool cross-terminal close — only self-spawned lanes)."}};if("mcp__thinkpool__spawn_terminal"===o)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"===o){const t=n?.mode||he;if("bypassPermissions"!==t||"bypassPermissions"===he)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 s="deny";try{s=await(O?.({id:e(),toolName:o,input:{...n,mode:t},risk:"high"}))??"deny"}catch{s="deny"}const r="allow"===s;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"===o){const t=A?A():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-terminal post not allowed right now."}};const s=!!U&&!!U(n?.terminal);if(!l({mode:he,spawnedByMe:s}))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"bypassPermissions"===he?"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(O?.({id:e(),toolName:o,input:n,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"===o){const t=D?D():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-room post not allowed right now."}};let s="deny";try{s=await(O?.({id:e(),toolName:o,input:n,risk:"high"}))??"deny"}catch{s="deny"}const r="allow"===s;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"===o){if("plan"!==he)return lt(he),ot({kind:"mode",mode:he}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`The thinkpool room is in ${he} 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(O?.({id:e(),toolName:o,input:n,risk:"plan",plan:n?.plan||""}))??"keep"}catch{t="keep"}if("run"===t||"accept"===t){const e="accept"===t?"acceptEdits":"default";return he=e,lt(e),ot({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"===o){let t="";try{t=await(O?.({id:e(),toolName:o,input:n,risk:"ask",questions:n?.questions||[]}))??""}catch{t=""}return askUserQuestionHookOutput(t)}const c=classifyRisk(o,n),d=`${o}:${c}`,u=isSafeDocWrite(o,n),p=autoAllow({toolName:o,input:n,mode:he,alwaysAllow:fe});let m="allow";if(!p){try{m=await(O?.({id:e(),toolName:o,input:n,risk:c}))??"deny"}catch{m="deny"}"always"===m&&(fe.add(d),m="allow")}const h="deny"===m;return h&&Ue&&Ue.failure({permissionDenied:!0}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:h?"deny":"allow",permissionDecisionReason:h?"Denied by the user in the thinkpool room. Do not retry this tool — ask what to do instead.":p?u?"Auto-approved (mandated doc write — .claude/SESSIONS/ or CLAUDE.md).":`Auto-approved (${he}).`:"Approved in the thinkpool room."}}}]}]},canUseTool:async(e,t)=>({behavior:"allow",updatedInput:t}),settingSources:["user","project","local"],appendSystemPrompt:[...C?[C]:[],...L?[L]:[],"ENVIRONMENT (authoritative — overrides any user-global CLAUDE.md or memory that claims otherwise): You are Claude running inside a thinkpool Code room, driven live by a user (and possibly a partner) from a phone or browser, via the thinkpool-pair bridge.",h,'Bias strongly toward DOING the work, not stalling in plan-mode ceremony. For a small "add / fix / change X" request, just make the change directly (for a bigger build, right-size it — see DEFAULT BUILD WORKFLOW below).',"Do NOT enter plan mode, do NOT call ExitPlanMode, and do NOT auto-invoke a brainstorming/planning skill UNLESS the user has switched the room into Plan mode or explicitly asks you to plan, design, or brainstorm first.","Any host-global instruction that says you must always brainstorm or plan before creative work does NOT apply here — this room is the exception.",p,'CRUCIAL RECONCILIATION for that workflow: it is NOT plan mode. Never call ExitPlanMode and never make the room wait behind a "plan ready — approve to start" card — your plan lives in the CHAT as a message, and your lanes live in the room\'s EXISTING terminal/lane list. Reuse only those two surfaces; there is no new Flow panel or mode to switch into, and you must not ask for one. Keep the plan and the lanes VISIBLE — that shared visibility is the whole point (it is the pair differentiator, and it catches bugs a single silent lane would hide); never collapse a decomposable build into one hidden lane just to look tidy.',...m,'CROSS-TERMINAL AWARENESS: ROOM NOW is the default roster and already satisfies the room check when it has enough detail. Do not repeat it with a no-argument read_terminal call unless it is missing or truncated. Use a targeted read_terminal call only when the current task depends on a specific lane’s detailed activity; never poll. Identify a terminal by its NAME or stable ref/id, never by an on-screen number like "Terminal 2" — positional labels renumber when a terminal is closed. The tool is read-only and its optional roster lookup is budgeted separately from bounded targeted transcript reads.','CROSS-TERMINAL HAND-OFF: you also have post_to_terminal(terminal, text) to send a message or task to ANOTHER AGENT terminal in this room (not a plain shell). Use it sparingly and only when the people clearly want the lanes to coordinate — e.g. "tell the backend terminal the API is ready", or to hand a sibling agent a concrete task. Every post requires a person in the room to approve a card before it is delivered, and an agent that was itself reached via a cross-post cannot post onward — so do not rely on it for chit-chat or loops. Prefer read_terminal to understand a sibling before you ever post to it.',"TERMINAL CREATION CONTRACT: main terminals and workers use different tools. A person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal(name?, task?, model?) — even for ordinary work or a handoff and even without the words Cascade or conductor. If the wording includes new or separate terminal, main-terminal routing wins. Never use spawn_terminal for that request, and if open_main_terminal is unavailable say so instead of substituting. Use spawn_terminal(name?, task?, model?, sliceType?) only for agent-decided bounded WORKER SUB-TERMINALS or when the person explicitly asks for a worker, sub-terminal, Ensemble lane, or delegated slice. Workers never receive the creation tools and never conduct. Do not dump work into busy siblings. Spawned workers are always autonomous in bypassPermissions and never ask the room for an approval card; the bridge still enforces room caps, hop limits, the kill-switch, and isolated linked worktrees. Wait for ROOM NOW or a completion signal instead of polling; after a worker finishes, collect it with one targeted read_terminal call and close_terminal immediately. 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&&(ct.strictMcpConfig=!0,ct.mcpServers={}),R&&Object.keys(R).length&&(ct.mcpServers={...ct.mcpServers||{},...R}),t&&(ct.cwd=t),o&&(ct.model=o),ct.effort=ge,ct.env={...f||process.env,CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION:"1"};const dt=async()=>{if(!H)return;const e=(Xe||"").trim().slice(-1500);if(e&&!ae)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:ct.env,timeoutMs:8e3});o=o.trim().split("\n")[0].replace(/^["'`]+|["'`]+$/g,"").trim().slice(0,140),!o||Ve||ae||/^(sure|of course|certainly|let me know|i can help|happy to)\b/i.test(o)||(ot({kind:"suggestion",text:o,source:"haiku"}),process.stderr.write(` ◆ [suggestion] haiku fallback: ${JSON.stringify(o)}\n`))}catch{}},ut=()=>{const e="function"==typeof Q?Q():{ok:!0};return!1!==e?.ok||(ot({kind:"error",message:e.reason||"Host memory is critically low. This agent runtime was not started.",recoverable:!0}),!1)},pt=async({admitted:e=!1}={})=>{if(!le&&!e&&!ut())return!1;if(null==ce&&(ce=Date.now()),le=!0,Te)try{Te()}catch{}Se=new Promise(e=>{Te=e});const n=new AbortController;_e=n;const a=()=>{try{n.abort()}catch{}};ee.signal.addEventListener("abort",a,{once:!0});try{if(oe){const e=i(t||process.cwd(),oe);e.blocks&&process.stderr.write(`\n ◆ healed ${e.blocks} malformed tool block(s) in the transcript before resume.\n`)}me=r({prompt:te.stream,options:{...ct,abortController:n,...oe?{resume:oe}:{}}});for await(const e of me){if(ae)break;switch(e.type){case"system":if("thinking_tokens"===e.subtype){we+be===0&&ot({kind:"thinking_tokens",tokens:e.estimated_tokens,delta:e.estimated_tokens_delta});break}if("compact_boundary"===e.subtype){X=!0,ot({kind:"compaction",trigger:e.compact_metadata?.trigger||"auto",preTokens:e.compact_metadata?.pre_tokens??null}),(async()=>{try{const e=await(me?.getContextUsage?.());e&&(ot({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),de||(de=!0,process.stderr.write(`\n ◆ session ready in ${Date.now()-ce}ms — MCP ${"1"===process.env.TP_MCP_STRICT?"OFF":"on"}${s?", resume":", fresh"}.\n`)),ve=ct.model||e.model||o||ve,ot({kind:"system",sessionId:oe,model:ct.model||e.model||o||null,commands:d({slashCommands:e.slash_commands,skills:e.skills})}),!pe&&Array.isArray(e.tools)){pe=!0;const t=askUserQuestionRegression(e.tools,E);t&&(process.stderr.write(`\n ⚠⚠ ${t}\n`),ot({kind:"error",message:t}))}ue||(ue=!0,Promise.resolve(me?.supportedModels?.()).then(e=>{const t=(e||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);t.length&&ot({kind:"models",models:t})}).catch(()=>{}));break;case"assistant":st(),Ue?.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&&(Xe=t)}ot({kind:"assistant",blocks:P(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){st(),Ue?.visibleOutput({tool:!0});const o=ye.get(t.tool_use_id);null!=o&&ye.delete(t.tool_use_id);const n=u(o?.name,t.content);ot({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?(we+=be,be=t.message?.usage?.output_tokens||0,ot({kind:"thinking_tokens",tokens:we+be})):"message_delta"===t?.type&&t.usage&&(be=t.usage.output_tokens??be,ot({kind:"thinking_tokens",tokens:we+be}));break}case"result":if(st(),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)&&Pe<3){Pe++;const e=Re;Re=!1,oe=null,ne=null,ot({kind:"note",text:"previous session not found — continuing on a fresh one"});const t=te;te=x();try{t.end()}catch{}const o=e?se:null;$e=setTimeout(()=>{$e=null,ae||(pt(),null!=o&&(Re=!0,Ae=Date.now(),De=!1,te.push([{type:"text",text:o},{type:"text",text:re||Z(o,{forceFull:!0})}])))},300);break}if(Ye&&("aborted"===e.subtype||"error_during_execution"===e.subtype)){We===ze&&(Re=!1);break}if(e.is_error&&Ue){if(Le)break;Ue.failure({message:Array.isArray(e.errors)?e.errors.join(" "):e.result,status:e.status??e.statusCode,code:e.code}),Re=!1,ft();break}if(we=0,be=0,Re=!1,Ee&&(Ee=!1,setTimeout(()=>{ae||mt()},0)),"success"===e.subtype&&(Pe=0,oe&&(ne=oe)),"success"===e.subtype&&(Ue?.success(),Ue=null),qe=!1,Ge=!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):"";ot({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})}Ze&&clearTimeout(Ze),"aborted"!==e.subtype&&(Ze=setTimeout(()=>{Ze=null,Ve||ae||dt()},et)),(async()=>{let t=null;try{const e=await(me?.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||{};ot({kind:"usage",costUsd:e.total_cost_usd??null,tokens:(o.input_tokens||0)+(o.output_tokens||0),ctx:t})})();break;case"prompt_suggestion":Ze&&(clearTimeout(Ze),Ze=null),e.suggestion&&(Ve=!0,ot({kind:"suggestion",text:e.suggestion}))}}}catch(e){if(st(),ae)return;if(n.signal.aborted)return;const t=e?.message||String(e);if(Ue&&Re)return Ue.failure({message:t,status:e?.status??e?.statusCode,code:e?.code}),Re=!1,void ft();if(Re=!1,ot({kind:"error",message:t}),xe.test(t)&&Pe<3){Pe++,Ie("stream_reconnect",{failureClass:"network"}),ot({kind:"note",text:`connection dropped — reconnecting (${Pe}/3)`});const e=te;te=x();try{e.end()}catch{}return void($e=setTimeout(()=>{$e=null,ae||pt()},Math.min(1e3*Pe,4e3)))}if(/no conversation found/i.test(t)&&oe&&Pe<3){Pe++,oe=null,ne=null;const e=te;te=x();try{e.end()}catch{}return void($e=setTimeout(()=>{$e=null,ae||pt()},300))}ae=!0}finally{ee.signal.removeEventListener("abort",a),_e===n&&(_e=null);try{await(me?.return?.())}catch{}Te&&(Te(),Te=null)}},mt=async()=>{if(ae||!le)return;const e=Se,t=te;if(te=x(),_e)try{_e.abort()}catch{}try{t.end()}catch{}try{await e}catch{}await Ne(300),oe=ne,ae||pt()},ht=async e=>{if(ae)return;Ge=!0;const t=Re&&!v(se)?se:null;Re=!1;const o=Se,n=te;if(te=x(),_e)try{_e.abort()}catch{}try{n.end()}catch{}try{await o}catch{}await Ne(300),oe=ne,ae||(pt(),null!=t&&(Re=!0,Ae=Date.now(),De=!1,te.push(/^\s*\//.test(t)?[{type:"text",text:t}]:[{type:"text",text:t},{type:"text",text:re||Z(t,{forceFull:!0})}]),tt({kind:"note",text:"retrying the stalled turn on a fresh connection"})))},ft=()=>{if(ae||Fe||Le)return;const e=Ue,t=We,o=ie;Le=!0;const n=Se,s=te;te=x();try{s.end()}catch{}$e=setTimeout(async()=>{$e=null;try{await n}catch{}if(!ae&&Le&&Ue===e&&We===t)return await it()?void(!ae&&Le&&Ue===e&&We===t&&(Le=!1,Re=!0,Ae=Date.now(),De=!1,pt(),o&&te.push(o),rt())):(Le=!1,void yt())},0)},yt=()=>{st(),Re=!1,Ue=null,le=!1,ot({kind:"error",message:"The configured provider could not complete this turn. Nothing else was sent.",recoverable:!0})};return G||Me||pt(),{sendTurn(e){if(ae||Fe||Le)return!1;if(!le&&!ut())return!1;if(!le&&K)try{const e=K();e&&(t=e,ct.cwd=e)}catch{}Re=!0,Ve=!1,se=String(e),Ze&&(clearTimeout(Ze),Ze=null),Ae=Date.now(),De=!1,Ge=!1,qe=!1;const n=String(e),s=V++,r=X;if(X=/^\s*\/(?:compact|clear|reset)\b/i.test(n),re=/^\s*\//.test(n)?null:Z(n,{promptIndex:s,forceFull:r}),He=v(n),ie=/^\s*\//.test(n)?[{type:"text",text:n}]:[{type:"text",text:n},{type:"text",text:re}],We++,Ue=(()=>{if(!Me)return null;try{const e=_({runtime:"claude",providers:z.providers||[],providerId:z.providerId,model:z.model||ct.model||o,requestedModel:z.requestedModel||z.model||ct.model||o,policy:z.policy,bridgeHostId:z.bridgeHostId,circuit:z.circuit,capGate:z.capGate,traceId:z.traceId,turnRev:"function"==typeof z.turnRev?z.turnRev():z.turnRev,onRecord:nt});return e.start(),e}catch{return null}})(),Ue){const e=Ue,t=We,o=ie;it().then(n=>{!ae&&Re&&Ue===e&&We===t&&(n?(le||pt({admitted:!0}),te.push(o),rt()):yt())}).catch(()=>{!ae&&Re&&Ue===e&&We===t&&yt()})}else le||pt({admitted:!0}),te.push(ie)},warm(){Me||le||ae||pt()},get started(){return le},async setMode(e){I.has(e)&&!ae&&(he=e,lt(e),ot({kind:"mode",mode:he}))},async setModel(e){ct.model=e,ve=e,ot({kind:"note",text:`model → ${e}`}),le&&!ae&&(Re?Ee=!0:await mt())},setEffort:async e=>!(!ke.has(e)||ae||(ge=e,ct.effort=e,ot({kind:"effort",level:e}),le&&(Re?(Ee=!0,0):(await mt(),0)))),async listModels(){try{const e=(await(me?.supportedModels?.())||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);e.length&&ot({kind:"models",models:e}),ot({kind:"note",text:e.length?`models: ${e.map(e=>e.value).join(", ")}`:"no model list available"})}catch{ot({kind:"note",text:"usage: /model <name>"})}},async abort(){if(!Fe){Fe=!0;try{const e=Le,t=e?Se:null;(Re||e)&&(We++,e||(Le=!1),st(),Ue?.failure({aborted:!0}),e&&(clearTimeout($e),$e=null,le=!1),Ye=!0,ze=We,clearTimeout(Je),Je=setTimeout(()=>{Ye=!1,ze=null},6e3));try{await(me?.interrupt?.())}catch{}if(t)try{await t}catch{}e&&(Le=!1),(Re||e)&&(Re=!1,ot({kind:"result",subtype:"aborted",sessionId:oe}))}finally{Fe=!1}}},end(){ae=!0,st(),clearInterval(at),clearTimeout(Je),clearTimeout($e),Ze&&clearTimeout(Ze),te.end();try{ee.abort()}catch{}},get sessionId(){return oe},get mode(){return he},get turnActive(){return Re}}}
|
package/code-event-contract.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{recoveryCodeEvent as e}from"./error-recovery.mjs";export const EVENT_CLASS=Object.freeze({VOLATILE_PRESENCE:"volatile-presence",REPLAYABLE_PROGRESS:"replayable-progress",REPLAYABLE_COMMAND:"replayable-command",DURABLE_DELIVERY_EVIDENCE:"durable-delivery-evidence",UNKNOWN:"unknown"});const n=EVENT_CLASS.VOLATILE_PRESENCE,t=EVENT_CLASS.REPLAYABLE_PROGRESS,o=EVENT_CLASS.REPLAYABLE_COMMAND,r=EVENT_CLASS.DURABLE_DELIVERY_EVIDENCE;export const CODE_EVENT_REGISTRY=Object.freeze({system:n,thinking_tokens:n,effort:n,mode:n,usage:n,suggestion:n,stalled:n,compact:n,assistant_stream:n,models:n,"model-switch":n,capabilities:n,"update-available":n,you:t,assistant:t,tool_result:t,note:t,pool:t,chat:t,whisper:t,compaction:t,"side-started":t,"side-handback":t,answer:o,control:o,"repo-search":o,clear:o,"queue-add":o,"queue-cancel":o,propose:o,"propose-done":o,result:r,error:r,mockup:r,image:r,"needs-input":r,"needs-resolved":r,continuation:r,"turn-done":r,"flow-review-receipt":r});export const CODE_EVENT_KINDS=Object.freeze(Object.keys(CODE_EVENT_REGISTRY));const s=()=>"undefined"!=typeof process&&("test"===process.env?.NODE_ENV||"development"===process.env?.NODE_ENV);export function classifyCodeEvent(e,{strict:t=s()}={}){const o="string"==typeof e?e:e?.kind,E="string"==typeof o?CODE_EVENT_REGISTRY[o]:null;if(!E){if(t)throw new TypeError(`Unknown
|
|
1
|
+
import{recoveryCodeEvent as e}from"./error-recovery.mjs";export const EVENT_CLASS=Object.freeze({VOLATILE_PRESENCE:"volatile-presence",REPLAYABLE_PROGRESS:"replayable-progress",REPLAYABLE_COMMAND:"replayable-command",DURABLE_DELIVERY_EVIDENCE:"durable-delivery-evidence",UNKNOWN:"unknown"});const n=EVENT_CLASS.VOLATILE_PRESENCE,t=EVENT_CLASS.REPLAYABLE_PROGRESS,o=EVENT_CLASS.REPLAYABLE_COMMAND,r=EVENT_CLASS.DURABLE_DELIVERY_EVIDENCE;export const CODE_EVENT_REGISTRY=Object.freeze({system:n,thinking_tokens:n,effort:n,mode:n,usage:n,suggestion:n,stalled:n,compact:n,assistant_stream:n,models:n,"model-switch":n,capabilities:n,"update-available":n,you:t,assistant:t,tool_result:t,note:t,pool:t,chat:t,whisper:t,compaction:t,"side-started":t,"side-handback":t,answer:o,control:o,"repo-search":o,clear:o,"queue-add":o,"queue-cancel":o,propose:o,"propose-done":o,result:r,error:r,mockup:r,image:r,"needs-input":r,"needs-resolved":r,continuation:r,"turn-done":r,"flow-review-receipt":r});export const CODE_EVENT_KINDS=Object.freeze(Object.keys(CODE_EVENT_REGISTRY));const s=()=>"undefined"!=typeof process&&("test"===process.env?.NODE_ENV||"development"===process.env?.NODE_ENV);export function classifyCodeEvent(e,{strict:t=s()}={}){const o="string"==typeof e?e:e?.kind,E="string"==typeof o?CODE_EVENT_REGISTRY[o]:null;if(!E){if(t)throw new TypeError(`Unknown thinkpool Code event kind: ${String(o)}`);return Object.freeze({kind:o??null,known:!1,eventClass:EVENT_CLASS.UNKNOWN,durable:!1,replayable:!1,authorizes:!1,completes:!1})}return Object.freeze({kind:o,known:!0,eventClass:E,durable:E===r,replayable:E!==n,authorizes:!1,completes:!1})}export function unknownCodeEventNotice(e){const n="string"==typeof e?e:e?.kind,t="string"==typeof n?n.slice(0,120):null;return{kind:"error",subtype:"unknown_event",message:`Unrecognized Code event${t?` "${t}"`:""} was rejected; this lane needs recovery.`,unknownKind:t}}export const isKnownCodeEventKind=e=>Object.hasOwn(CODE_EVENT_REGISTRY,e);export function boundedRecoveryCodeEvent(n){return e(n)}
|
package/codex-app-server.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{execFileSync as e,spawn as t}from"node:child_process";import r from"node:readline";export const CODEX_APP_SERVER_ENV="TP_CODEX_APP_SERVER";export const MIN_CODEX_APP_SERVER_VERSION=Object.freeze([0,144,1]);export const MAX_CODEX_APP_SERVER_VERSION=Object.freeze([0,145,0]);const i=(e,t)=>{for(let r=0;r<3;r++){if(e[r]>t[r])return!0;if(e[r]<t[r])return!1}return!0},s=(e,t="unknown")=>{const r=e instanceof Error?e:new Error(String(e||"Codex App Server transport failed"));return r.delivery=t,r};export function codexAppServerGate({env:t=process.env,execFile:r=e}={}){const s=String(t?.[CODEX_APP_SERVER_ENV]||"").trim().toLowerCase();if(["0","false","off"].includes(s))return{enabled:!1,reason:`${CODEX_APP_SERVER_ENV} disables App Server`,version:null};if(s&&!["1","true","on"].includes(s))return{enabled:!1,reason:`${CODEX_APP_SERVER_ENV} has an invalid value`,version:null};try{const e=r("codex",["--version"],{encoding:"utf8",env:t}),s=(e=>{const t=String(e||"").match(/(?:codex-cli\s+)?(\d+)\.(\d+)\.(\d+)/i);return t?t.slice(1,4).map(Number):null})(e);if(!s)return{enabled:!1,reason:`unrecognized Codex version: ${String(e).trim()}`,version:null};const o=s.join(".");return i(s,MIN_CODEX_APP_SERVER_VERSION)?i(s,MAX_CODEX_APP_SERVER_VERSION)?{enabled:!1,reason:`Codex ${o} is newer than the tested App Server protocol (<${MAX_CODEX_APP_SERVER_VERSION.join(".")})`,version:o}:{enabled:!0,reason:null,version:o}:{enabled:!1,reason:`Codex ${o} is older than ${MIN_CODEX_APP_SERVER_VERSION.join(".")}`,version:o}}catch(e){return{enabled:!1,reason:`could not read Codex version: ${e?.message||e}`,version:null}}}export function buildCodexAppServerArgs({providerConfig:e,mcpUrl:t,writableDirs:r=[]}={}){const i=["app-server","--stdio"];return e&&i.push("-c",e),t&&(i.push("-c",`mcp_servers.thinkpool.url=${JSON.stringify(t)}`),i.push("-c","mcp_servers.thinkpool.required=true")),r.length&&i.push("-c",`sandbox_workspace_write.writable_roots=${JSON.stringify(r)}`),i}const o=(e,t=-32e3)=>({code:t,message:String(e||"App Server request failed")}),n=(e,t=[])=>[{type:"text",text:String(e??"")},...t.filter(Boolean).map(e=>({type:"localImage",path:String(e)}))];export class CodexAppServerClient{constructor({cwd:e,env:r,args:i=["app-server","--stdio"],spawnImpl:s=t,onNotification:o,onServerRequest:n,onClose:a,initializeTimeoutMs:d=3e3,threadTimeoutMs:c=5e3,turnStartTimeoutMs:l=5e3,controlTimeoutMs:h=5e3}={}){this.cwd=e,this.env=r,this.args=i,this.spawnImpl=s,this.onNotification=o,this.onServerRequest=n,this.onClose=a,this.initializeTimeoutMs=d,this.threadTimeoutMs=c,this.turnStartTimeoutMs=l,this.controlTimeoutMs=h,this.child=null,this.nextId=1,this.pending=new Map,this.turnWaiters=new Map,this.completedTurns=new Map,this.mcpStartup=new Map,this.mcpWaiters=new Map,this.closedError=null,this.stderrTail=""}get alive(){return!!this.child&&!this.closedError}async start(){if(this.child)return;const e=this.spawnImpl("codex",this.args,{cwd:this.cwd,env:this.env,stdio:["pipe","pipe","pipe"]});this.child=e,r.createInterface({input:e.stdout,crlfDelay:1/0}).on("line",e=>this._onLine(e)),e.stderr?.on?.("data",e=>{this.stderrTail+=String(e),this.stderrTail.length>1200&&(this.stderrTail=this.stderrTail.slice(-1200))}),e.stdin?.on?.("error",e=>this._close(e)),e.on("error",e=>this._close(e)),e.on("close",e=>this._close(new Error(`codex app-server exited ${e??"unknown"}${this.stderrTail?`: ${this.stderrTail.trim().slice(-300)}`:""}`))),await this.request("initialize",{clientInfo:{name:"thinkpool-pair",title:"
|
|
1
|
+
import{execFileSync as e,spawn as t}from"node:child_process";import r from"node:readline";export const CODEX_APP_SERVER_ENV="TP_CODEX_APP_SERVER";export const MIN_CODEX_APP_SERVER_VERSION=Object.freeze([0,144,1]);export const MAX_CODEX_APP_SERVER_VERSION=Object.freeze([0,145,0]);const i=(e,t)=>{for(let r=0;r<3;r++){if(e[r]>t[r])return!0;if(e[r]<t[r])return!1}return!0},s=(e,t="unknown")=>{const r=e instanceof Error?e:new Error(String(e||"Codex App Server transport failed"));return r.delivery=t,r};export function codexAppServerGate({env:t=process.env,execFile:r=e}={}){const s=String(t?.[CODEX_APP_SERVER_ENV]||"").trim().toLowerCase();if(["0","false","off"].includes(s))return{enabled:!1,reason:`${CODEX_APP_SERVER_ENV} disables App Server`,version:null};if(s&&!["1","true","on"].includes(s))return{enabled:!1,reason:`${CODEX_APP_SERVER_ENV} has an invalid value`,version:null};try{const e=r("codex",["--version"],{encoding:"utf8",env:t}),s=(e=>{const t=String(e||"").match(/(?:codex-cli\s+)?(\d+)\.(\d+)\.(\d+)/i);return t?t.slice(1,4).map(Number):null})(e);if(!s)return{enabled:!1,reason:`unrecognized Codex version: ${String(e).trim()}`,version:null};const o=s.join(".");return i(s,MIN_CODEX_APP_SERVER_VERSION)?i(s,MAX_CODEX_APP_SERVER_VERSION)?{enabled:!1,reason:`Codex ${o} is newer than the tested App Server protocol (<${MAX_CODEX_APP_SERVER_VERSION.join(".")})`,version:o}:{enabled:!0,reason:null,version:o}:{enabled:!1,reason:`Codex ${o} is older than ${MIN_CODEX_APP_SERVER_VERSION.join(".")}`,version:o}}catch(e){return{enabled:!1,reason:`could not read Codex version: ${e?.message||e}`,version:null}}}export function buildCodexAppServerArgs({providerConfig:e,mcpUrl:t,writableDirs:r=[]}={}){const i=["app-server","--stdio"];return e&&i.push("-c",e),t&&(i.push("-c",`mcp_servers.thinkpool.url=${JSON.stringify(t)}`),i.push("-c","mcp_servers.thinkpool.required=true")),r.length&&i.push("-c",`sandbox_workspace_write.writable_roots=${JSON.stringify(r)}`),i}const o=(e,t=-32e3)=>({code:t,message:String(e||"App Server request failed")}),n=(e,t=[])=>[{type:"text",text:String(e??"")},...t.filter(Boolean).map(e=>({type:"localImage",path:String(e)}))];export class CodexAppServerClient{constructor({cwd:e,env:r,args:i=["app-server","--stdio"],spawnImpl:s=t,onNotification:o,onServerRequest:n,onClose:a,initializeTimeoutMs:d=3e3,threadTimeoutMs:c=5e3,turnStartTimeoutMs:l=5e3,controlTimeoutMs:h=5e3}={}){this.cwd=e,this.env=r,this.args=i,this.spawnImpl=s,this.onNotification=o,this.onServerRequest=n,this.onClose=a,this.initializeTimeoutMs=d,this.threadTimeoutMs=c,this.turnStartTimeoutMs=l,this.controlTimeoutMs=h,this.child=null,this.nextId=1,this.pending=new Map,this.turnWaiters=new Map,this.completedTurns=new Map,this.mcpStartup=new Map,this.mcpWaiters=new Map,this.closedError=null,this.stderrTail=""}get alive(){return!!this.child&&!this.closedError}async start(){if(this.child)return;const e=this.spawnImpl("codex",this.args,{cwd:this.cwd,env:this.env,stdio:["pipe","pipe","pipe"]});this.child=e,r.createInterface({input:e.stdout,crlfDelay:1/0}).on("line",e=>this._onLine(e)),e.stderr?.on?.("data",e=>{this.stderrTail+=String(e),this.stderrTail.length>1200&&(this.stderrTail=this.stderrTail.slice(-1200))}),e.stdin?.on?.("error",e=>this._close(e)),e.on("error",e=>this._close(e)),e.on("close",e=>this._close(new Error(`codex app-server exited ${e??"unknown"}${this.stderrTail?`: ${this.stderrTail.trim().slice(-300)}`:""}`))),await this.request("initialize",{clientInfo:{name:"thinkpool-pair",title:"thinkpool Code",version:"1"},capabilities:{experimentalApi:!0}},this.initializeTimeoutMs),this.notify("initialized")}_write(e){if(!this.child?.stdin||this.closedError)throw this.closedError||new Error("codex app-server is not running");this.child.stdin.write(`${JSON.stringify(e)}\n`)}request(e,t={},r=0){const i=this.nextId++;return new Promise((o,n)=>{let a=null;r>0&&(a=setTimeout(()=>{this.pending.delete(i),n(s(`${e} timed out after ${r}ms`,"unknown"))},r)),this.pending.set(i,{resolve:o,reject:n,timer:a,method:e});try{this._write({id:i,method:e,params:t})}catch(e){this.pending.delete(i),a&&clearTimeout(a),n(s(e,"not_sent"))}})}notify(e,t){this._write(void 0===t?{method:e}:{method:e,params:t})}respond(e,t){this._write({id:e,result:t})}respondError(e,t){this._write({id:e,error:o(t?.message||t)})}_onLine(e){if(!String(e).trim())return;let t;try{t=JSON.parse(e)}catch{return}if(null!=t.id&&("result"in t||"error"in t)&&!t.method){const e=this.pending.get(t.id);if(!e)return;if(this.pending.delete(t.id),e.timer&&clearTimeout(e.timer),t.error){const r=s(t.error.message||`${e.method} failed`,"rejected");r.code=t.error.code,r.data=t.error.data,e.reject(r)}else e.resolve(t.result);return}if(null!=t.id&&t.method)Promise.resolve().then(()=>{if(!this.onServerRequest)throw new Error(`Unsupported Codex App Server request: ${t.method}`);return this.onServerRequest(t.method,t.params||{},t.id)}).then(e=>{try{this.respond(t.id,e??{})}catch{}}).catch(e=>{try{this.respondError(t.id,e)}catch{}});else if(t.method){if("turn/completed"===t.method){const e=t.params?.turn,r=e?.id;if(r){const e=this.turnWaiters.get(r);if(e)this.turnWaiters.delete(r),e.resolve(t.params);else for(this.completedTurns.set(r,t.params);this.completedTurns.size>32;)this.completedTurns.delete(this.completedTurns.keys().next().value)}}if("mcpServer/startupStatus/updated"===t.method){const e=t.params||{},r=String(e.threadId||""),i=String(e.name||"");if(r&&i){const t=`${r}\0${i}`;this.mcpStartup.set(t,e);const s=this.mcpWaiters.get(t);s&&"ready"===e.status?(this.mcpWaiters.delete(t),s.timer&&clearTimeout(s.timer),s.resolve(e)):s&&("failed"===e.status||e.error||e.failureReason)&&(this.mcpWaiters.delete(t),s.timer&&clearTimeout(s.timer),s.reject(new Error(`Codex MCP server ${i} failed to start: ${e.error||e.failureReason||e.status}`)))}}try{this.onNotification?.(t.method,t.params||{})}catch{}}}_close(e){if(!this.closedError){this.closedError=s(e instanceof Error?e:String(e||"codex app-server closed"),"unknown"),this.child=null;for(const{reject:e,timer:t}of this.pending.values())t&&clearTimeout(t),e(this.closedError);this.pending.clear();for(const{reject:e}of this.turnWaiters.values())e(this.closedError);this.turnWaiters.clear(),this.completedTurns.clear();for(const{reject:e,timer:t}of this.mcpWaiters.values())t&&clearTimeout(t),e(this.closedError);this.mcpWaiters.clear(),this.mcpStartup.clear();try{this.onClose?.(this.closedError)}catch{}}}async startThread({threadId:e,cwd:t,model:r,sandbox:i,approvalPolicy:s,config:o}={}){const n={cwd:t,model:r,sandbox:i,approvalPolicy:s,...o?{config:o}:{}},a=e?await this.request("thread/resume",{...n,threadId:e},this.threadTimeoutMs):await this.request("thread/start",n,this.threadTimeoutMs),d=a?.thread?.id||a?.threadId||e;if(!d)throw new Error("Codex App Server did not return a thread id");return d}waitForMcpServer({threadId:e,name:t,timeoutMs:r=this.threadTimeoutMs}={}){const i=String(e||""),s=String(t||"");if(!i||!s)return Promise.reject(new Error("Codex MCP readiness needs a thread id and server name"));const o=`${i}\0${s}`,n=this.mcpStartup.get(o);if("ready"===n?.status)return Promise.resolve(n);if(n&&("failed"===n.status||n.error||n.failureReason))return Promise.reject(new Error(`Codex MCP server ${s} failed to start: ${n.error||n.failureReason||n.status}`));if(this.mcpWaiters.has(o))return this.mcpWaiters.get(o).promise;let a,d,c=null;const l=new Promise((e,t)=>{a=e,d=t,r>0&&(c=setTimeout(()=>{this.mcpWaiters.delete(o),t(new Error(`Codex MCP server ${s} did not become ready within ${r}ms`))},r))});return this.mcpWaiters.set(o,{promise:l,resolve:a,reject:d,timer:c}),l}async startTurn({threadId:e,input:t,images:r,model:i,effort:s,approvalPolicy:o,collaborationMode:a}={}){const d=await this.request("turn/start",{threadId:e,input:n(t,r),...i?{model:i}:{},...s?{effort:s}:{},...o?{approvalPolicy:o}:{},...a?{collaborationMode:a}:{}},this.turnStartTimeoutMs),c=d?.turn?.id||d?.turnId;if(!c)throw new Error("Codex App Server did not return a turn id");return c}waitForTurn(e){if(this.completedTurns.has(e)){const t=this.completedTurns.get(e);return this.completedTurns.delete(e),Promise.resolve(t)}return this.turnWaiters.has(e)?Promise.reject(new Error(`Already waiting for Codex turn ${e}`)):new Promise((t,r)=>this.turnWaiters.set(e,{resolve:t,reject:r}))}async steer({threadId:e,turnId:t,input:r,images:i}={}){return this.request("turn/steer",{threadId:e,expectedTurnId:t,input:n(r,i)},this.controlTimeoutMs)}interrupt({threadId:e,turnId:t}={}){return this.request("turn/interrupt",{threadId:e,turnId:t},this.controlTimeoutMs)}compact({threadId:e}={}){return this.request("thread/compact/start",{threadId:e},this.controlTimeoutMs)}accountUsage(){return this.request("account/usage/read",null,this.controlTimeoutMs)}accountRateLimits(){return this.request("account/rateLimits/read",null,this.controlTimeoutMs)}startReview({threadId:e,target:t}={}){return this.request("review/start",{threadId:e,target:t||{type:"uncommittedChanges"},delivery:"inline"},this.turnStartTimeoutMs)}end(){const e=this.child;if(this._close(new Error("codex app-server ended")),e)try{e.kill("SIGTERM")}catch{}}}export function createCodexAppServer(e){return new CodexAppServerClient(e)}
|
package/codex-session.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{execFileSync as e,spawn as t}from"node:child_process";import r from"node:fs";import n from"node:os";import o from"node:path";import s from"node:readline";import{buildCodexAppServerArgs as a,codexAppServerGate as i,createCodexAppServer as l}from"./codex-app-server.mjs";import{CodexEventMapper as u}from"./codex-event-mapper.mjs";import{startCodexMcpHttp as d}from"./codex-mcp-http.mjs";import{CODEX_THINKPOOL_FIRST_TURN_PREAMBLE as c,buildThinkPoolTurnGuidance as p,createRoomContextSelector as m,usesFullThinkPoolReminder as f}from"./thinkpool-room-prompt.mjs";import{questionAnswerResponse as h}from"./question-response.mjs";import{codexReviewTarget as x,isCodexCompactCommand as g}from"./codex-commands.mjs";import{createCumulativeEventRelay as y}from"./cumulative-event-relay.mjs";import{stallDecision as v,stallEvent as b}from"./turn-stall.mjs";const w=new Set(["read-only","workspace-write","danger-full-access"]);export const EFFORT_LEVELS=new Set(["low","medium","high","xhigh","max"]);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 function codexConfigForMode(e){return CODEX_MODE_CONFIG[e]||CODEX_MODE_CONFIG.default}export function codexDefaultCollaborationMode(e,t){return e?{mode:"default",settings:{model:String(e),reasoning_effort:EFFORT_LEVELS.has(t)?t:null,developer_instructions:null}}:null}export function defaultModeForRuntime(e){return"codex"===e?"bypassPermissions":"default"}export function codexWritableDirsForSandbox(e,t=[]){return"read-only"===normalizeCodexSandbox(e)?[]:t}export function codexExtraWritableDirsForMode(e,t,r=[]){return"review"===e?[]:codexWritableDirsForSandbox(t,r)}export function readCodexDefaultModel({home:e=process.env.CODEX_HOME||o.join(n.homedir(),".codex"),fsImpl:t=r}={}){try{const r=t.readFileSync(o.join(e,"config.toml"),"utf8").split(/^\s*\[/m,1)[0].match(/^\s*model\s*=\s*["']([^"']+)["']\s*(?:#.*)?$/m);return r?.[1]?.trim()||null}catch{return null}}export function readCodexModels({home:e=process.env.CODEX_HOME||o.join(n.homedir(),".codex"),fsImpl:t=r}={}){try{const r=JSON.parse(t.readFileSync(o.join(e,"models_cache.json"),"utf8"));return(Array.isArray(r?.models)?r.models:[]).filter(e=>e?.slug&&"hide"!==e.visibility).sort((e,t)=>(Number(e.priority)||999)-(Number(t.priority)||999)).map(e=>({value:e.slug,displayName:e.display_name||e.slug,description:e.description||""}))}catch{return[]}}const k=new Map;function I(e,{home:t,fsImpl:r}){if(!e)return null;const n=`${t}\0${e}`,s=k.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 k.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=I(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=I(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)}}}export function normalizeCodexSandbox(e){return w.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. If open_main_terminal is unavailable, say so; never substitute an Ensemble child. Leaf, worker, Side, and managed Flow lanes work directly and must not delegate. Never use hidden in-process subagents."].join(" ");export function buildCodexPrompt({text:e,terminalRolePrompt:t,rolePrompt:r,roomContext:n,firstTurn:o=!1,promptIndex:s=0,forceFullReminder:a=!1}){const i="function"==typeof n?n():n,l=f({promptIndex:s,forceFull:a}),u=[o?c:"",l?t:"",p({text:e,promptIndex:s,forceFull:a}),l?r||CODEX_ROOM_CASCADE_REMINDER:"",i].map(e=>String(e||"").trim()).filter(Boolean);return u.length?`<thinkpool-context>\n${u.join("\n\n")}\n</thinkpool-context>\n\n${String(e??"")}`:String(e??"")}export function buildCodexExecArgs({sessionId:e,model:t,effort:r,sandbox:n,approvalPolicy:s="untrusted",providerConfig:a,mcpUrl:i,writableDirs:l=[],images:u=[],prompt:d}){const c=normalizeCodexSandbox(n),p=e?["exec","resume","--json","--skip-git-repo-check",..."danger-full-access"===c?["--dangerously-bypass-approvals-and-sandbox"]:["-c",`sandbox_mode="${c}"`]]:["exec","--json","--sandbox",c,"--skip-git-repo-check"];if(t&&p.push("-m",t),p.push("-c",`approval_policy="${s}"`),EFFORT_LEVELS.has(r)&&p.push("-c",`model_reasoning_effort="${r}"`),a&&p.push("-c",a),!e)for(const e of l)p.push("--add-dir",e);i&&(p.push("-c",`mcp_servers.thinkpool.url=${JSON.stringify(i)}`),p.push("-c","mcp_servers.thinkpool.required=true"));let m=!1;for(const e of u)o.isAbsolute(String(e||""))&&(p.push("--image",String(e)),m=!0);return m&&p.push("--"),e&&p.push(e),p.push(String(d??"")),p}export function codexExecFailedBeforeTurn({stderr:e="",eventTypes:t=[]}={}){if((Array.isArray(t)?t.map(e=>String(e||"")):[]).some(e=>e&&"thread.started"!==e))return!1;const r=String(e||"");return/timed out handshaking with MCP server/i.test(r)||/thread\/resume failed/i.test(r)&&/failed to initialize session/i.test(r)}const _=/\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:_.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 M(e){if(!e||"object"!=typeof e)return e;const t={...e};switch(e.type){case"agentMessage":return{...t,type:"agent_message"};case"commandExecution":return{...t,type:"command_execution",aggregated_output:e.aggregatedOutput||"",exit_code:e.exitCode};case"fileChange":return{...t,type:"file_change"};case"webSearch":return{...t,type:"web_search"};case"mcpToolCall":return{...t,type:"mcp_tool_call",arguments:e.arguments||{},result:e.result,error:e.error};case"reasoning":return{...t,type:"reasoning",text:[...e.summary||[],...e.content||[]].join("\n")};default:return t}}export function startCodexSession({cwd:e,model:c,effort:p="high",resume:h,env:w,sandbox:k,mode:I="default",onEvent:_,providerConfig:S,terminalRolePrompt:C,rolePrompt:E,roomContext:T,mcpServers:F,prepareCwd:O=null,requestPermission:R,appServerGate:N=i,appServerFactory:P=l,mcpHttpFactory:A=d,spawnImpl:U=t,admitStart:D=null,stallOptions:$={}}){let j=CODEX_MODE_CONFIG[I]?I:"default",L=codexConfigForMode(j);k=normalizeCodexSandbox(k||L.sandbox);const q=codexPublishAccess({cwd:e,env:{...process.env,...w||{}}}),X=q.env,G=h||null,z=!G||codexThreadCanResume(G,{home:X.CODEX_HOME||o.join(n.homedir(),".codex")});let W=z?G:null,B=W?1:0,H=0,V=!0;const J=m(T);let K=null,Q=!1,Y=!1,Z=!1;const ee="function"==typeof $.now?$.now:Date.now,te="function"==typeof $.setInterval?$.setInterval:setInterval,re="function"==typeof $.clearInterval?$.clearInterval:clearInterval,ne=Number.isFinite($.stallMs)?Math.max(1,Number($.stallMs)):Math.max(3e4,parseInt(X.TP_STALL_MS,10)||9e4),oe=Number.isFinite($.forceStopMs)?Math.max(ne,Number($.forceStopMs)):Math.max(3*ne,parseInt(X.TP_FORCE_STOP_MS,10)||3e5),se=Number.isFinite($.intervalMs)?Math.max(1,Number($.intervalMs)):5e3;let ae=ee(),ie=!1,le=!1,ue=!1,de=!1,ce=!0,pe=0,me=null,fe=c||null,he=EFFORT_LEVELS.has(p)?p:"high",xe=W?readCodexThreadUsage(W):null,ge=null;const ye=N({env:X});let ve=!ye.enabled,be=null,we=!1,ke=null,Ie=null,_e=!1;const Me=new Set,Se=new Map,Ce=new Map;let Ee=Promise.resolve(),Te=Promise.resolve();const Fe=[],Oe=y(e=>{try{_?.(e)}catch{}}),Re=()=>{ae=ee(),ie=!1},Ne=e=>{Re(),Oe(e)};Ne.cancel=()=>Oe.cancel();const Pe=new u({onEvent:Ne,model:c||null,usageSnapshotForSession:e=>{const t=readCodexThreadUsage(e);return t&&(xe=t),t||xe}}),Ae=e=>{"turn.completed"!==e?.type&&"turn.failed"!==e?.type||(Z=!1),Pe.push(e)},Ue=e=>{Z=!1,Ne(e)},De=({retry:e=!1}={})=>{Z=!0,ae=ee(),ie=!1,ue=!1,de=!1,ce=!0,e||(le=!1)},$e=e=>Ne({kind:"note",text:e}),je=(e=ke)=>{const t=String(e||"");if(t)for(Me.add(t);Me.size>64;)Me.delete(Me.values().next().value)},Le=(e={})=>{const t=String(e.turnId||"");return!(!t||Y||Q||Me.has(t)||t!==String(ke||""))};async function qe(){const e=F?.thinkpool;return e?(ge||(ge=A({sdkServer:e})),ge):null}function Xe(e,t={}){if("thread/tokenUsage/updated"===e){if(t.threadId&&W&&String(t.threadId)!==String(W))return;const e=codexUsageSnapshotFromAppServer(t.tokenUsage);if(!e)return;if(xe=e,_e){const{used:t,max:r}=e.context;Ne({kind:"usage",ctx:{used:t,max:r,pct:Math.min(100,Math.max(0,Math.round(t/r*100))),over:t>r,model:fe}})}return}if("turn/started"===e&&t.turn?.id){const e=String(t.turn.id);if(Y||Q)return void je(e);if(Ie){const t=Ie;return Ie=null,void t.resolve(e)}return ke||(ke=e),void Re()}if("turn/plan/updated"!==e&&"item/agentMessage/delta"!==e&&"item/started"!==e&&"item/completed"!==e&&"error"!==e||Le(t)){if(Re(),"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 Ne({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||ke||"active"}`,r=Ce.get(e)||{cid:`codex-stream:${W||"thread"}:${e}`,text:""};return r.text+=String(t.delta),Ce.set(e,r),void Ne({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&&Se.set(r.id,r),"item/completed"===e&&(Se.set(r.id,r),"agentMessage"===r.type&&Ce.has(r.id))){const e=Ce.get(r.id);return Ce.delete(r.id),void Ne({kind:"assistant",blocks:[{type:"text",text:r.text||e.text}],parentToolUseId:null,replacesCid:e.cid})}return void Ae({type:"item/started"===e?"item.started":"item.completed",item:M(r)})}if("error"===e){const e=t.error?.message||t.message||"codex app-server error";Ae({type:"error",message:e})}}}async function Ge(e,t={}){if(!Le(t))return"item/tool/requestUserInput"===e?{answers:{}}:{decision:"decline"};const r=codexApprovalCard(e,t,Se.get(t.itemId));if(!r)throw new Error(`Unsupported Codex App Server request: ${e}`);let n="deny";pe++;try{n=await(R?.(r))}catch{}finally{pe=Math.max(0,pe-1),Re()}return"item/tool/requestUserInput"===e?codexUserInputResponse(n,r.questions):codexApprovalResponse(n)}async function ze(){if(ve)return!1;if(!1===be?.alive)return we=!1,ve=!0,!1;if(be&&we)return!0;let t;try{t=await qe()}catch(e){$e(`Thinkpool peer tools unavailable: ${e?.message||e}`)}try{return be||(be=P({cwd:e,env:X,args:a({providerConfig:S,mcpUrl:t?.url,writableDirs:codexExtraWritableDirsForMode(j,k,q.writableDirs)}),onNotification:Xe,onServerRequest:Ge,onClose:e=>{Y||ve||(we=!1,ve=!0,$e(`Codex App Server closed; later turns will use codex exec: ${e?.message||e}`))}}),await be.start(),Re()),W=await be.startThread({threadId:B>0?W:null,cwd:e,model:fe,sandbox:k,approvalPolicy:L.approvalPolicy,config:{"features.default_mode_request_user_input":!0}}),Re(),t?.url&&(await be.waitForMcpServer({threadId:W,name:"thinkpool"}),Re()),we=!0,Ae({type:"thread.started",thread_id:W}),!0}catch{ve=!0;try{be?.end()}catch{}return be=null,we=!1,!1}}function We({force:e=!1}={}){const t=be,r=ke;if(t&&e){je(r),ve=!0,we=!1;try{t.end()}catch{}be===t&&(be=null)}else if(t&&r)je(r),Promise.resolve(t.interrupt({threadId:W,turnId:r})).catch(()=>{ve=!0,we=!1;try{t.end()}catch{}be===t&&(be=null)});else if(t){ve=!0,we=!1;try{t.end()}catch{}be===t&&(be=null)}if(K){const e=K;try{e.kill("SIGTERM")}catch{}setTimeout(()=>{if(K===e)try{e.kill("SIGKILL")}catch{}},1500)}}async function Be(e,t={}){if(Y||Q||de)return!0;if(!await ze())return!1;if(Y||Q||de)return!0;Pe.setUsageBaseline(W?readCodexThreadUsage(W):null),Z=!0;try{if(ce=!1,ke=await be.startTurn({threadId:W,input:e,images:Array.isArray(t.images)?t.images:[],model:fe,effort:he,approvalPolicy:L.approvalPolicy,collaborationMode:codexDefaultCollaborationMode(fe,he)}),Re(),Q||Y){je(ke);try{await be.interrupt({threadId:W,turnId:ke})}catch{}return!0}const r=await be.waitForTurn(ke);je(r?.turn?.id||ke);const n=r?.turn?.status;Q?Ue({kind:"result",subtype:"aborted",sessionId:W,model:fe,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"interrupted"===n&&(ue||de)||("interrupted"===n?Ue({kind:"result",subtype:"aborted",sessionId:W,model:fe,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"failed"===n?(ue=!1,Ae({type:"turn.failed",message:r?.turn?.error?.message||"codex turn failed"})):(ue=!1,Ae({type:"turn.completed"})))}catch(e){ve=!0,we=!1,je(ke);try{be?.end()}catch{}be=null,Y||ue||de||Ae({type:"turn.failed",message:`codex app-server turn failed: ${e?.message||e}`})}finally{for(const e of Ce.values())e.text&&Ne({kind:"assistant",blocks:[{type:"text",text:e.text}],parentToolUseId:null,replacesCid:e.cid});ke=null,Z=!1,Se.clear(),Ce.clear()}return!0}async function He(e){if(Y||Q||de)return!0;if(!await ze())return!1;if(Y||Q||de)return!0;Pe.setUsageBaseline(W?readCodexThreadUsage(W):null),Z=!0;try{ce=!1;const t=await be.startReview({threadId:W,target:x(e)});if(ke=t?.turn?.id||t?.turnId,!ke)throw new Error("Codex review/start returned no turn id");if(Re(),Q||Y){je(ke);try{await be.interrupt({threadId:W,turnId:ke})}catch{}return!0}const r=await be.waitForTurn(ke);je(r?.turn?.id||ke);const n=r?.turn?.status;Q?Ue({kind:"result",subtype:"aborted",sessionId:W,model:fe,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"interrupted"===n&&(ue||de)||("interrupted"===n?Ue({kind:"result",subtype:"aborted",sessionId:W,model:fe,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"failed"===n?(ue=!1,Ae({type:"turn.failed",message:r?.turn?.error?.message||"codex review failed"})):(ue=!1,Ae({type:"turn.completed"})))}catch(e){ve=!0,we=!1,je(ke);try{be?.end()}catch{}be=null,Y||ue||de||Ae({type:"turn.failed",message:`codex review failed: ${e?.message||e}`})}finally{for(const e of Ce.values())e.text&&Ne({kind:"assistant",blocks:[{type:"text",text:e.text}],parentToolUseId:null,replacesCid:e.cid});ke=null,Z=!1,Se.clear(),Ce.clear()}return!0}async function Ve(t,n={}){if(Y||Q||de)return;let o;try{o=await qe()}catch(e){$e(`Thinkpool peer tools unavailable: ${e?.message||e}`)}try{await(o?.handoff?.())}catch(e){$e(`Thinkpool peer handoff failed: ${e?.message||e}`)}const a=buildCodexExecArgs({sessionId:0===B?null:W,model:fe,effort:he,sandbox:k,approvalPolicy:L.approvalPolicy,providerConfig:S,mcpUrl:o?.url,writableDirs:codexExtraWritableDirsForMode(j,k,q.writableDirs),images:Array.isArray(n.images)?n.images:[],prompt:t});return Pe.setUsageBaseline(W?readCodexThreadUsage(W):null),new Promise(t=>{let n;try{n=r.openSync("/dev/null","r")}catch{}const o={cwd:e,env:X,stdio:["ignore","pipe","pipe"]};if(null!=n&&(o.stdio=[n,"pipe","pipe"]),Z=!0,ce=!1,K=U("codex",a,o),null!=n)try{r.closeSync(n)}catch{}const i=[];s.createInterface({input:K.stdout,crlfDelay:1/0}).on("line",e=>{if(!e.trim())return;let t;try{t=JSON.parse(e)}catch{return}i.push(t.type),"thread.started"===t.type&&t.thread_id&&(W=W||t.thread_id),"turn.completed"!==t.type&&"turn.failed"!==t.type||(u=!0,ue=!1),Ae(t)});let l="",u=!1,d=!1;K.stderr.on("data",e=>{l+=e.toString(),l.length>800&&(l=l.slice(-800))}),K.on("error",e=>{d||(d=!0,K=null,ue||de||Ue({kind:"error",message:`codex failed to start: ${e.message}`,recoverable:!0}),t({preTurnInitFailure:!1}))}),K.on("close",e=>{if(d)return;d=!0,K=null,Z=!1;const r=`codex exec exited ${e}${l?": "+l.trim().slice(-300):""}`;0===e||null==e||u||!codexExecFailedBeforeTurn({stderr:l,eventTypes:i})||Q||de?((!ue&&!de||u||Q)&&(Q&&!u?Ue({kind:"result",subtype:"aborted",sessionId:W,model:fe,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null}):Q||u||0===e||null==e||Ue({kind:"error",message:r,recoverable:!0})),t({preTurnInitFailure:!1})):t({preTurnInitFailure:!0,message:r})})})}function Je(){if(Y)return;const e=Fe.shift();e&&(Te=Te.then(async()=>{De();const t=f({promptIndex:e.promptIndex,forceFull:e.forceFullReminder}),r=buildCodexPrompt({text:e.text,terminalRolePrompt:C,rolePrompt:E,roomContext:()=>J({force:t}),firstTurn:0===B,promptIndex:e.promptIndex,forceFullReminder:e.forceFullReminder}),n=/^\s*\/review(?:\s|$)/i.test(String(e.text||""));let o=!1,s=!1;for(;!Y&&!Q&&!de;){if(!(n?await He(e.text):await Be(r,e.options)))if(n)ue=!1,Ue({kind:"error",message:"Codex review is unavailable without the tested App Server runtime.",recoverable:!0});else{ue&&(ue=!1,o=!0,De({retry:!0}),Oe({kind:"note",text:"retrying the stalled turn on a fresh connection"}));const t=await Ve(r,e.options);if(t?.preTurnInitFailure){if(!(s||Y||Q||de)){s=!0,De({retry:!0}),Oe({kind:"note",text:"Codex initialization failed before the turn started; retrying once with a fresh ThinkPool connection."});continue}Ue({kind:"error",message:t.message,recoverable:!0})}}if(!ue||o||de||Y||Q)break;ue=!1,o=!0,De({retry:!0}),Oe({kind:"note",text:"retrying the stalled turn on a fresh connection"})}B++,Je()}))}return G&&!z&&queueMicrotask(()=>$e("The stopped Codex turn had no resumable context; continuing in a fresh thread.")),["0","false","off"].includes(String(X.TP_CODEX_APP_SERVER||"").trim().toLowerCase())||ye.enabled||queueMicrotask(()=>$e(`Codex App Server disabled: ${ye.reason}`)),me=te(()=>{const e=ee()-ae,t=v({turnActive:Z,awaitingUser:pe,quietMs:e,stallMs:ne,forceStopMs:oe,stalledSent:ie,stallRetried:le});if("none"===t)return;if("retry"===t&&!ce)return de=!0,ue=!1,Oe({kind:"error",recoverable:!0,message:"Codex stopped responding after the turn began. The transport was stopped, but the prompt was not replayed automatically."}),Ue({kind:"result",subtype:"aborted",sessionId:W,model:fe,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null}),void We({force:!0});const r=b(t,e);if(r&&Oe(r),"status"!==t){if("retry"===t)return le=!0,ue=!0,ae=ee(),ie=!1,void We();de=!0,ue=!1,Fe.length=0,Ue({kind:"result",subtype:"aborted",sessionId:W,model:fe,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null}),We({force:!0})}else ie=!0},se),me.unref?.(),{get sessionId(){return W},get usageSnapshot(){return xe},get turnActive(){return Z||_e},get canSteer(){return!(!be||!1===be.alive||!we||ve)},get started(){return B>0||Z},sendTurn(t,r={}){if(Y)return!1;if(!Z&&0===Fe.length&&!we&&!K){const e="function"==typeof D?D():{ok:!0};if(!1===e?.ok)return Ne({kind:"error",message:e.reason||"Host memory is critically low. This Codex runtime was not started.",recoverable:!0}),!1}const n=H++,o=V;if(V=g(t)||/^\s*\/(?:reset|clear)\b/i.test(String(t||"")),!Z&&0===B&&O)try{e=O()||e}catch{}if(Z&&be&&ke){Re();const e=f({promptIndex:n,forceFull:o}),s=buildCodexPrompt({text:t,terminalRolePrompt:C,rolePrompt:E,roomContext:()=>J({force:e}),promptIndex:n,forceFullReminder:o}),a=ke;return Ee=Ee.then(()=>be.steer({threadId:W,turnId:a,input:s,images:Array.isArray(r.images)?r.images:[]})).catch(e=>{"rejected"===e?.delivery||"not_sent"===e?.delivery?(Fe.push({text:t,options:r,promptIndex:n,forceFullReminder:o}),Z||1!==Fe.length||Je()):Ne({kind:"error",message:"Codex steering delivery is uncertain; the message was not replayed automatically.",recoverable:!0})}),!0}return Fe.push({text:t,options:r,promptIndex:n,forceFullReminder:o}),Z||_e||(Q=!1,De()),1!==Fe.length||_e||Je(),!0},abort(){const e=Te,t=Z&&!ke&&!K;Q=!0,ue=!1,de=!1,Fe.length=0,je(ke);let r=Promise.resolve();if(be&&ke&&(r=be.interrupt({threadId:W,turnId:ke}).catch(()=>{})),K){try{K.kill("SIGTERM")}catch{}setTimeout(()=>{try{K?.kill("SIGKILL")}catch{}},1500)}else t&&Ue({kind:"result",subtype:"aborted",sessionId:W,model:fe,costUsd:null,usage:null,numTurns:0,durationMs:void 0,denials:0,resultText:null});return r.then(()=>e).catch(()=>e).then(()=>{})},end(){if(Y=!0,Z=!1,me&&re(me),Ne.cancel(),Fe.length=0,je(ke),K)try{K.kill()}catch{}try{be?.end()}catch{}ge?.then(e=>e.close()).catch(()=>{})},setModel:e=>!(!e||Z||(fe=String(e),Pe.setModel(fe),0)),setMode:e=>!(Z||!CODEX_MODE_CONFIG[e]||(j=e,L=codexConfigForMode(j),k=L.sandbox,W=null,B=0,xe=null,we=!1,0)),setEffort:e=>!(Z||!EFFORT_LEVELS.has(e)||(he=e,Ne({kind:"effort",level:he}),0)),clearContext:()=>!Z&&(W=null,B=0,xe=null,we=!1,!0),async compactContext(){if(Z||_e)return!1;Q=!1,_e=!0;let e=null,t=!1;try{if(!await ze()||Z)return!1;const r=new Promise((t,r)=>{e=setTimeout(()=>{Ie=null,r(new Error("Codex did not start the compaction turn"))},5e3),Ie={resolve:t,reject:r}});await be.compact({threadId:W}),t=!0;const n=await r;e&&clearTimeout(e);const o=await be.waitForTurn(n);je(o?.turn?.id||n);const s=o?.turn?.status;if("completed"===s)return!0;throw new Error(o?.turn?.error?.message||`compaction ${s||"failed"}`)}catch(e){return t||!["rejected","not_sent"].includes(e?.delivery)?($e(`Native Codex compaction status is uncertain; existing context was preserved: ${e?.message||e}`),null):($e(`Native Codex compaction unavailable; using bounded recap fallback: ${e?.message||e}`),!1)}finally{e&&clearTimeout(e),Ie=null,_e=!1,Fe.length&&Je()}},async accountUsage(){if(!await ze())return null;const[e,t]=await Promise.all([be.accountUsage().catch(()=>null),be.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 u}from"./codex-event-mapper.mjs";import{startCodexMcpHttp as d}from"./codex-mcp-http.mjs";import{CODEX_THINKPOOL_FIRST_TURN_PREAMBLE as c,buildThinkPoolTurnGuidance as p,createRoomContextSelector as m,usesFullThinkPoolReminder as f}from"./thinkpool-room-prompt.mjs";import{questionAnswerResponse as h}from"./question-response.mjs";import{codexReviewTarget as x,isCodexCompactCommand as g}from"./codex-commands.mjs";import{createCumulativeEventRelay as y}from"./cumulative-event-relay.mjs";import{stallDecision as v,stallEvent as b}from"./turn-stall.mjs";const w=new Set(["read-only","workspace-write","danger-full-access"]);export const EFFORT_LEVELS=new Set(["low","medium","high","xhigh","max"]);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 function codexConfigForMode(e){return CODEX_MODE_CONFIG[e]||CODEX_MODE_CONFIG.default}export function codexDefaultCollaborationMode(e,t){return e?{mode:"default",settings:{model:String(e),reasoning_effort:EFFORT_LEVELS.has(t)?t:null,developer_instructions:null}}:null}export function defaultModeForRuntime(e){return"codex"===e?"bypassPermissions":"default"}export function codexWritableDirsForSandbox(e,t=[]){return"read-only"===normalizeCodexSandbox(e)?[]:t}export function codexExtraWritableDirsForMode(e,t,r=[]){return"review"===e?[]:codexWritableDirsForSandbox(t,r)}export function readCodexDefaultModel({home:e=process.env.CODEX_HOME||o.join(n.homedir(),".codex"),fsImpl:t=r}={}){try{const r=t.readFileSync(o.join(e,"config.toml"),"utf8").split(/^\s*\[/m,1)[0].match(/^\s*model\s*=\s*["']([^"']+)["']\s*(?:#.*)?$/m);return r?.[1]?.trim()||null}catch{return null}}export function readCodexModels({home:e=process.env.CODEX_HOME||o.join(n.homedir(),".codex"),fsImpl:t=r}={}){try{const r=JSON.parse(t.readFileSync(o.join(e,"models_cache.json"),"utf8"));return(Array.isArray(r?.models)?r.models:[]).filter(e=>e?.slug&&"hide"!==e.visibility).sort((e,t)=>(Number(e.priority)||999)-(Number(t.priority)||999)).map(e=>({value:e.slug,displayName:e.display_name||e.slug,description:e.description||""}))}catch{return[]}}const k=new Map;function I(e,{home:t,fsImpl:r}){if(!e)return null;const n=`${t}\0${e}`,s=k.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 k.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=I(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=I(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)}}}export function normalizeCodexSandbox(e){return w.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. If open_main_terminal is unavailable, say so; never substitute an Ensemble child. Leaf, worker, Side, and managed Flow lanes work directly and must not delegate. Never use hidden in-process subagents."].join(" ");export function buildCodexPrompt({text:e,terminalRolePrompt:t,rolePrompt:r,roomContext:n,firstTurn:o=!1,promptIndex:s=0,forceFullReminder:a=!1}){const i="function"==typeof n?n():n,l=f({promptIndex:s,forceFull:a}),u=[o?c:"",l?t:"",p({text:e,promptIndex:s,forceFull:a}),l?r||CODEX_ROOM_CASCADE_REMINDER:"",i].map(e=>String(e||"").trim()).filter(Boolean);return u.length?`<thinkpool-context>\n${u.join("\n\n")}\n</thinkpool-context>\n\n${String(e??"")}`:String(e??"")}export function buildCodexExecArgs({sessionId:e,model:t,effort:r,sandbox:n,approvalPolicy:s="untrusted",providerConfig:a,mcpUrl:i,writableDirs:l=[],images:u=[],prompt:d}){const c=normalizeCodexSandbox(n),p=e?["exec","resume","--json","--skip-git-repo-check",..."danger-full-access"===c?["--dangerously-bypass-approvals-and-sandbox"]:["-c",`sandbox_mode="${c}"`]]:["exec","--json","--sandbox",c,"--skip-git-repo-check"];if(t&&p.push("-m",t),p.push("-c",`approval_policy="${s}"`),EFFORT_LEVELS.has(r)&&p.push("-c",`model_reasoning_effort="${r}"`),a&&p.push("-c",a),!e)for(const e of l)p.push("--add-dir",e);i&&(p.push("-c",`mcp_servers.thinkpool.url=${JSON.stringify(i)}`),p.push("-c","mcp_servers.thinkpool.required=true"));let m=!1;for(const e of u)o.isAbsolute(String(e||""))&&(p.push("--image",String(e)),m=!0);return m&&p.push("--"),e&&p.push(e),p.push(String(d??"")),p}export function codexExecFailedBeforeTurn({stderr:e="",eventTypes:t=[]}={}){if((Array.isArray(t)?t.map(e=>String(e||"")):[]).some(e=>e&&"thread.started"!==e))return!1;const r=String(e||"");return/timed out handshaking with MCP server/i.test(r)||/thread\/resume failed/i.test(r)&&/failed to initialize session/i.test(r)}const _=/\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:_.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 M(e){if(!e||"object"!=typeof e)return e;const t={...e};switch(e.type){case"agentMessage":return{...t,type:"agent_message"};case"commandExecution":return{...t,type:"command_execution",aggregated_output:e.aggregatedOutput||"",exit_code:e.exitCode};case"fileChange":return{...t,type:"file_change"};case"webSearch":return{...t,type:"web_search"};case"mcpToolCall":return{...t,type:"mcp_tool_call",arguments:e.arguments||{},result:e.result,error:e.error};case"reasoning":return{...t,type:"reasoning",text:[...e.summary||[],...e.content||[]].join("\n")};default:return t}}export function startCodexSession({cwd:e,model:c,effort:p="high",resume:h,env:w,sandbox:k,mode:I="default",onEvent:_,providerConfig:S,terminalRolePrompt:C,rolePrompt:E,roomContext:T,mcpServers:F,prepareCwd:R=null,requestPermission:O,appServerGate:N=i,appServerFactory:A=l,mcpHttpFactory:P=d,spawnImpl:U=t,admitStart:D=null,stallOptions:$={}}){let j=CODEX_MODE_CONFIG[I]?I:"default",L=codexConfigForMode(j);k=normalizeCodexSandbox(k||L.sandbox);const q=codexPublishAccess({cwd:e,env:{...process.env,...w||{}}}),X=q.env,G=h||null,z=!G||codexThreadCanResume(G,{home:X.CODEX_HOME||o.join(n.homedir(),".codex")});let W=z?G:null,B=W?1:0,H=0,V=!0;const J=m(T);let K=null,Q=!1,Y=!1,Z=!1;const ee="function"==typeof $.now?$.now:Date.now,te="function"==typeof $.setInterval?$.setInterval:setInterval,re="function"==typeof $.clearInterval?$.clearInterval:clearInterval,ne=Number.isFinite($.stallMs)?Math.max(1,Number($.stallMs)):Math.max(3e4,parseInt(X.TP_STALL_MS,10)||9e4),oe=Number.isFinite($.forceStopMs)?Math.max(ne,Number($.forceStopMs)):Math.max(3*ne,parseInt(X.TP_FORCE_STOP_MS,10)||3e5),se=Number.isFinite($.intervalMs)?Math.max(1,Number($.intervalMs)):5e3;let ae=ee(),ie=!1,le=!1,ue=!1,de=!1,ce=!0,pe=0,me=null,fe=c||null,he=EFFORT_LEVELS.has(p)?p:"high",xe=W?readCodexThreadUsage(W):null,ge=null;const ye=N({env:X});let ve=!ye.enabled,be=null,we=!1,ke=null,Ie=null,_e=!1;const Me=new Set,Se=new Map,Ce=new Map;let Ee=Promise.resolve(),Te=Promise.resolve();const Fe=[],Re=y(e=>{try{_?.(e)}catch{}}),Oe=()=>{ae=ee(),ie=!1},Ne=e=>{Oe(),Re(e)};Ne.cancel=()=>Re.cancel();const Ae=new u({onEvent:Ne,model:c||null,usageSnapshotForSession:e=>{const t=readCodexThreadUsage(e);return t&&(xe=t),t||xe}}),Pe=e=>{"turn.completed"!==e?.type&&"turn.failed"!==e?.type||(Z=!1),Ae.push(e)},Ue=e=>{Z=!1,Ne(e)},De=({retry:e=!1}={})=>{Z=!0,ae=ee(),ie=!1,ue=!1,de=!1,ce=!0,e||(le=!1)},$e=e=>Ne({kind:"note",text:e}),je=(e=ke)=>{const t=String(e||"");if(t)for(Me.add(t);Me.size>64;)Me.delete(Me.values().next().value)},Le=(e={})=>{const t=String(e.turnId||"");return!(!t||Y||Q||Me.has(t)||t!==String(ke||""))};async function qe(){const e=F?.thinkpool;return e?(ge||(ge=P({sdkServer:e})),ge):null}function Xe(e,t={}){if("thread/tokenUsage/updated"===e){if(t.threadId&&W&&String(t.threadId)!==String(W))return;const e=codexUsageSnapshotFromAppServer(t.tokenUsage);if(!e)return;if(xe=e,_e){const{used:t,max:r}=e.context;Ne({kind:"usage",ctx:{used:t,max:r,pct:Math.min(100,Math.max(0,Math.round(t/r*100))),over:t>r,model:fe}})}return}if("turn/started"===e&&t.turn?.id){const e=String(t.turn.id);if(Y||Q)return void je(e);if(Ie){const t=Ie;return Ie=null,void t.resolve(e)}return ke||(ke=e),void Oe()}if("turn/plan/updated"!==e&&"item/agentMessage/delta"!==e&&"item/started"!==e&&"item/completed"!==e&&"error"!==e||Le(t)){if(Oe(),"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 Ne({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||ke||"active"}`,r=Ce.get(e)||{cid:`codex-stream:${W||"thread"}:${e}`,text:""};return r.text+=String(t.delta),Ce.set(e,r),void Ne({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&&Se.set(r.id,r),"item/completed"===e&&(Se.set(r.id,r),"agentMessage"===r.type&&Ce.has(r.id))){const e=Ce.get(r.id);return Ce.delete(r.id),void Ne({kind:"assistant",blocks:[{type:"text",text:r.text||e.text}],parentToolUseId:null,replacesCid:e.cid})}return void Pe({type:"item/started"===e?"item.started":"item.completed",item:M(r)})}if("error"===e){const e=t.error?.message||t.message||"codex app-server error";Pe({type:"error",message:e})}}}async function Ge(e,t={}){if(!Le(t))return"item/tool/requestUserInput"===e?{answers:{}}:{decision:"decline"};const r=codexApprovalCard(e,t,Se.get(t.itemId));if(!r)throw new Error(`Unsupported Codex App Server request: ${e}`);let n="deny";pe++;try{n=await(O?.(r))}catch{}finally{pe=Math.max(0,pe-1),Oe()}return"item/tool/requestUserInput"===e?codexUserInputResponse(n,r.questions):codexApprovalResponse(n)}async function ze(){if(ve)return!1;if(!1===be?.alive)return we=!1,ve=!0,!1;if(be&&we)return!0;let t;try{t=await qe()}catch(e){$e(`thinkpool peer tools unavailable: ${e?.message||e}`)}try{return be||(be=A({cwd:e,env:X,args:a({providerConfig:S,mcpUrl:t?.url,writableDirs:codexExtraWritableDirsForMode(j,k,q.writableDirs)}),onNotification:Xe,onServerRequest:Ge,onClose:e=>{Y||ve||(we=!1,ve=!0,$e(`Codex App Server closed; later turns will use codex exec: ${e?.message||e}`))}}),await be.start(),Oe()),W=await be.startThread({threadId:B>0?W:null,cwd:e,model:fe,sandbox:k,approvalPolicy:L.approvalPolicy,config:{"features.default_mode_request_user_input":!0}}),Oe(),t?.url&&(await be.waitForMcpServer({threadId:W,name:"thinkpool"}),Oe()),we=!0,Pe({type:"thread.started",thread_id:W}),!0}catch{ve=!0;try{be?.end()}catch{}return be=null,we=!1,!1}}function We({force:e=!1}={}){const t=be,r=ke;if(t&&e){je(r),ve=!0,we=!1;try{t.end()}catch{}be===t&&(be=null)}else if(t&&r)je(r),Promise.resolve(t.interrupt({threadId:W,turnId:r})).catch(()=>{ve=!0,we=!1;try{t.end()}catch{}be===t&&(be=null)});else if(t){ve=!0,we=!1;try{t.end()}catch{}be===t&&(be=null)}if(K){const e=K;try{e.kill("SIGTERM")}catch{}setTimeout(()=>{if(K===e)try{e.kill("SIGKILL")}catch{}},1500)}}async function Be(e,t={}){if(Y||Q||de)return!0;if(!await ze())return!1;if(Y||Q||de)return!0;Ae.setUsageBaseline(W?readCodexThreadUsage(W):null),Z=!0;try{if(ce=!1,ke=await be.startTurn({threadId:W,input:e,images:Array.isArray(t.images)?t.images:[],model:fe,effort:he,approvalPolicy:L.approvalPolicy,collaborationMode:codexDefaultCollaborationMode(fe,he)}),Oe(),Q||Y){je(ke);try{await be.interrupt({threadId:W,turnId:ke})}catch{}return!0}const r=await be.waitForTurn(ke);je(r?.turn?.id||ke);const n=r?.turn?.status;Q?Ue({kind:"result",subtype:"aborted",sessionId:W,model:fe,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"interrupted"===n&&(ue||de)||("interrupted"===n?Ue({kind:"result",subtype:"aborted",sessionId:W,model:fe,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"failed"===n?(ue=!1,Pe({type:"turn.failed",message:r?.turn?.error?.message||"codex turn failed"})):(ue=!1,Pe({type:"turn.completed"})))}catch(e){ve=!0,we=!1,je(ke);try{be?.end()}catch{}be=null,Y||ue||de||Pe({type:"turn.failed",message:`codex app-server turn failed: ${e?.message||e}`})}finally{for(const e of Ce.values())e.text&&Ne({kind:"assistant",blocks:[{type:"text",text:e.text}],parentToolUseId:null,replacesCid:e.cid});ke=null,Z=!1,Se.clear(),Ce.clear()}return!0}async function He(e){if(Y||Q||de)return!0;if(!await ze())return!1;if(Y||Q||de)return!0;Ae.setUsageBaseline(W?readCodexThreadUsage(W):null),Z=!0;try{ce=!1;const t=await be.startReview({threadId:W,target:x(e)});if(ke=t?.turn?.id||t?.turnId,!ke)throw new Error("Codex review/start returned no turn id");if(Oe(),Q||Y){je(ke);try{await be.interrupt({threadId:W,turnId:ke})}catch{}return!0}const r=await be.waitForTurn(ke);je(r?.turn?.id||ke);const n=r?.turn?.status;Q?Ue({kind:"result",subtype:"aborted",sessionId:W,model:fe,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"interrupted"===n&&(ue||de)||("interrupted"===n?Ue({kind:"result",subtype:"aborted",sessionId:W,model:fe,costUsd:null,usage:null,numTurns:1,durationMs:r?.turn?.durationMs,denials:0,resultText:null}):"failed"===n?(ue=!1,Pe({type:"turn.failed",message:r?.turn?.error?.message||"codex review failed"})):(ue=!1,Pe({type:"turn.completed"})))}catch(e){ve=!0,we=!1,je(ke);try{be?.end()}catch{}be=null,Y||ue||de||Pe({type:"turn.failed",message:`codex review failed: ${e?.message||e}`})}finally{for(const e of Ce.values())e.text&&Ne({kind:"assistant",blocks:[{type:"text",text:e.text}],parentToolUseId:null,replacesCid:e.cid});ke=null,Z=!1,Se.clear(),Ce.clear()}return!0}async function Ve(t,n={}){if(Y||Q||de)return;let o;try{o=await qe()}catch(e){$e(`thinkpool peer tools unavailable: ${e?.message||e}`)}try{await(o?.handoff?.())}catch(e){$e(`thinkpool peer handoff failed: ${e?.message||e}`)}const a=buildCodexExecArgs({sessionId:0===B?null:W,model:fe,effort:he,sandbox:k,approvalPolicy:L.approvalPolicy,providerConfig:S,mcpUrl:o?.url,writableDirs:codexExtraWritableDirsForMode(j,k,q.writableDirs),images:Array.isArray(n.images)?n.images:[],prompt:t});return Ae.setUsageBaseline(W?readCodexThreadUsage(W):null),new Promise(t=>{let n;try{n=r.openSync("/dev/null","r")}catch{}const o={cwd:e,env:X,stdio:["ignore","pipe","pipe"]};if(null!=n&&(o.stdio=[n,"pipe","pipe"]),Z=!0,ce=!1,K=U("codex",a,o),null!=n)try{r.closeSync(n)}catch{}const i=[];s.createInterface({input:K.stdout,crlfDelay:1/0}).on("line",e=>{if(!e.trim())return;let t;try{t=JSON.parse(e)}catch{return}i.push(t.type),"thread.started"===t.type&&t.thread_id&&(W=W||t.thread_id),"turn.completed"!==t.type&&"turn.failed"!==t.type||(u=!0,ue=!1),Pe(t)});let l="",u=!1,d=!1;K.stderr.on("data",e=>{l+=e.toString(),l.length>800&&(l=l.slice(-800))}),K.on("error",e=>{d||(d=!0,K=null,ue||de||Ue({kind:"error",message:`codex failed to start: ${e.message}`,recoverable:!0}),t({preTurnInitFailure:!1}))}),K.on("close",e=>{if(d)return;d=!0,K=null,Z=!1;const r=`codex exec exited ${e}${l?": "+l.trim().slice(-300):""}`;0===e||null==e||u||!codexExecFailedBeforeTurn({stderr:l,eventTypes:i})||Q||de?((!ue&&!de||u||Q)&&(Q&&!u?Ue({kind:"result",subtype:"aborted",sessionId:W,model:fe,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null}):Q||u||0===e||null==e||Ue({kind:"error",message:r,recoverable:!0})),t({preTurnInitFailure:!1})):t({preTurnInitFailure:!0,message:r})})})}function Je(){if(Y)return;const e=Fe.shift();e&&(Te=Te.then(async()=>{De();const t=f({promptIndex:e.promptIndex,forceFull:e.forceFullReminder}),r=buildCodexPrompt({text:e.text,terminalRolePrompt:C,rolePrompt:E,roomContext:()=>J({force:t}),firstTurn:0===B,promptIndex:e.promptIndex,forceFullReminder:e.forceFullReminder}),n=/^\s*\/review(?:\s|$)/i.test(String(e.text||""));let o=!1,s=!1;for(;!Y&&!Q&&!de;){if(!(n?await He(e.text):await Be(r,e.options)))if(n)ue=!1,Ue({kind:"error",message:"Codex review is unavailable without the tested App Server runtime.",recoverable:!0});else{ue&&(ue=!1,o=!0,De({retry:!0}),Re({kind:"note",text:"retrying the stalled turn on a fresh connection"}));const t=await Ve(r,e.options);if(t?.preTurnInitFailure){if(!(s||Y||Q||de)){s=!0,De({retry:!0}),Re({kind:"note",text:"Codex initialization failed before the turn started; retrying once with a fresh thinkpool connection."});continue}Ue({kind:"error",message:t.message,recoverable:!0})}}if(!ue||o||de||Y||Q)break;ue=!1,o=!0,De({retry:!0}),Re({kind:"note",text:"retrying the stalled turn on a fresh connection"})}B++,Je()}))}return G&&!z&&queueMicrotask(()=>$e("The stopped Codex turn had no resumable context; continuing in a fresh thread.")),["0","false","off"].includes(String(X.TP_CODEX_APP_SERVER||"").trim().toLowerCase())||ye.enabled||queueMicrotask(()=>$e(`Codex App Server disabled: ${ye.reason}`)),me=te(()=>{const e=ee()-ae,t=v({turnActive:Z,awaitingUser:pe,quietMs:e,stallMs:ne,forceStopMs:oe,stalledSent:ie,stallRetried:le});if("none"===t)return;if("retry"===t&&!ce)return de=!0,ue=!1,Re({kind:"error",recoverable:!0,message:"Codex stopped responding after the turn began. The transport was stopped, but the prompt was not replayed automatically."}),Ue({kind:"result",subtype:"aborted",sessionId:W,model:fe,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null}),void We({force:!0});const r=b(t,e);if(r&&Re(r),"status"!==t){if("retry"===t)return le=!0,ue=!0,ae=ee(),ie=!1,void We();de=!0,ue=!1,Fe.length=0,Ue({kind:"result",subtype:"aborted",sessionId:W,model:fe,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null}),We({force:!0})}else ie=!0},se),me.unref?.(),{get sessionId(){return W},get usageSnapshot(){return xe},get turnActive(){return Z||_e},get canSteer(){return!(!be||!1===be.alive||!we||ve)},get started(){return B>0||Z},sendTurn(t,r={}){if(Y)return!1;if(!Z&&0===Fe.length&&!we&&!K){const e="function"==typeof D?D():{ok:!0};if(!1===e?.ok)return Ne({kind:"error",message:e.reason||"Host memory is critically low. This Codex runtime was not started.",recoverable:!0}),!1}const n=H++,o=V;if(V=g(t)||/^\s*\/(?:reset|clear)\b/i.test(String(t||"")),!Z&&0===B&&R)try{e=R()||e}catch{}if(Z&&be&&ke){Oe();const e=f({promptIndex:n,forceFull:o}),s=buildCodexPrompt({text:t,terminalRolePrompt:C,rolePrompt:E,roomContext:()=>J({force:e}),promptIndex:n,forceFullReminder:o}),a=ke;return Ee=Ee.then(()=>be.steer({threadId:W,turnId:a,input:s,images:Array.isArray(r.images)?r.images:[]})).catch(e=>{"rejected"===e?.delivery||"not_sent"===e?.delivery?(Fe.push({text:t,options:r,promptIndex:n,forceFullReminder:o}),Z||1!==Fe.length||Je()):Ne({kind:"error",message:"Codex steering delivery is uncertain; the message was not replayed automatically.",recoverable:!0})}),!0}return Fe.push({text:t,options:r,promptIndex:n,forceFullReminder:o}),Z||_e||(Q=!1,De()),1!==Fe.length||_e||Je(),!0},abort(){const e=Te,t=Z&&!ke&&!K;Q=!0,ue=!1,de=!1,Fe.length=0,je(ke);let r=Promise.resolve();if(be&&ke&&(r=be.interrupt({threadId:W,turnId:ke}).catch(()=>{})),K){try{K.kill("SIGTERM")}catch{}setTimeout(()=>{try{K?.kill("SIGKILL")}catch{}},1500)}else t&&Ue({kind:"result",subtype:"aborted",sessionId:W,model:fe,costUsd:null,usage:null,numTurns:0,durationMs:void 0,denials:0,resultText:null});return r.then(()=>e).catch(()=>e).then(()=>{})},end(){if(Y=!0,Z=!1,me&&re(me),Ne.cancel(),Fe.length=0,je(ke),K)try{K.kill()}catch{}try{be?.end()}catch{}ge?.then(e=>e.close()).catch(()=>{})},setModel:e=>!(!e||Z||(fe=String(e),Ae.setModel(fe),0)),setMode:e=>!(Z||!CODEX_MODE_CONFIG[e]||(j=e,L=codexConfigForMode(j),k=L.sandbox,W=null,B=0,xe=null,we=!1,0)),setEffort:e=>!(Z||!EFFORT_LEVELS.has(e)||(he=e,Ne({kind:"effort",level:he}),0)),clearContext:()=>!Z&&(W=null,B=0,xe=null,we=!1,!0),async compactContext(){if(Z||_e)return!1;Q=!1,_e=!0;let e=null,t=!1;try{if(!await ze()||Z)return!1;const r=new Promise((t,r)=>{e=setTimeout(()=>{Ie=null,r(new Error("Codex did not start the compaction turn"))},5e3),Ie={resolve:t,reject:r}});await be.compact({threadId:W}),t=!0;const n=await r;e&&clearTimeout(e);const o=await be.waitForTurn(n);je(o?.turn?.id||n);const s=o?.turn?.status;if("completed"===s)return!0;throw new Error(o?.turn?.error?.message||`compaction ${s||"failed"}`)}catch(e){return t||!["rejected","not_sent"].includes(e?.delivery)?($e(`Native Codex compaction status is uncertain; existing context was preserved: ${e?.message||e}`),null):($e(`Native Codex compaction unavailable; using bounded recap fallback: ${e?.message||e}`),!1)}finally{e&&clearTimeout(e),Ie=null,_e=!1,Fe.length&&Je()}},async accountUsage(){if(!await ze())return null;const[e,t]=await Promise.all([be.accountUsage().catch(()=>null),be.accountRateLimits().catch(()=>null)]);return{usage:e,limits:t}}}}
|
package/cross-terminal.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash as e}from"node:crypto";import{BLOCKED_REASON as t,projectLaneLifecycle as r}from"./lane-lifecycle.mjs";export const PEEK={defaultLines:20,maxLines:200,perTurnCap:10,rosterPerTurnCap:1,lineCap:200,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 n=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={},o=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,o-c),u=laneBusyOf(e),p=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,o=0;for(let i=(Array.isArray(e)?e.length:0)-1;i>=0&&o<t.failureWindow;i--){const t=e[i];if(t&&"object"==typeof t){if(o++,"result"===t.kind&&(!t.subtype||"success"===t.subtype)||"you"===t.kind)break;n(t)&&r++}}return r})(a,i);let f=null,g=null;return p>0?(f="BLOCKED",g="waiting for input"):e?.stalled||u&&!e?.compacting&&null!=d&&d>=i.stuckAfterMs?(f="STUCK",g="no events while busy"):h>=i.repeatedFailureCount&&(f="BLOCKED",g="repeated errors"),{busy:!!u,lastActionAt:c,lastActionAgeMs:d,statusFlag:f,statusReason:g,lifecycle:r({events:a,busy:!!u,pendingCount:p,pendingReason:m,stalled:"STUCK"===f,failed:h>=i.repeatedFailureCount&&!u,rawStatus:f||(u?"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 o=e=>`${e.lifecycle?.state||"Blocked"}${e.lifecycle?.reason?` (${e.lifecycle.reason})`:""} · ${formatLaneAge(e.lastActionAgeMs)}`,i=(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 i(`${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?i(`assistant: ${r.join(" ")}`,t):""}case"tool_result":return e.isError?i("⎿ error",t):"";case"result":return e.subtype&&"success"!==e.subtype?i(`turn ended — ${e.subtype}`,t):"";case"error":return i(`error: ${e.message||""}`,t);default:return""}};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 s=e=>`${e.ref}${e.name?` · "${e.name}"`:""}`;export const formatPeek=({selfId:e,sessions:t,terms:r,names:n={},terminal:a,lines:l,now:c=Date.now()}={})=>{const d=Math.min(PEEK.maxLines,Math.max(1,Number(l)||PEEK.defaultLines)),u=siblingsOf({selfId:e,sessions:t,terms:r,names:n,now:c});if(!u.length)return"No other terminals are open in this room right now.";if(!a)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`- ${s(e)} · ${e.kind} · ${e.cmd} · ${o(e)} — ${i(t,PEEK.rosterPreview)}`}).join("\n")}`;const p=resolveSibling(u,a);if(!p)return`No terminal matches "${a}". Call read_terminal with no argument to list the open terminals (refer to one by its name or ref).${isOrdinalRef(String(a||"").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 m;return m="agent"===p.kind?p.log.map(e=>digestLogEvent(e,PEEK.lineCap)).filter(Boolean).slice(-d).join("\n")||"(no activity yet)":cleanPtyTail(p.buf,d).join("\n")||"(no output yet)",`Terminal ${s(p)} (${p.kind} · ${p.cmd}) · ${o(p)} — last ${d} lines:\n${m}`};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 a=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 a)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:a=[],now:l=Date.now()}={},c=ROOMNOW)=>{const d=siblingsOf({selfId:e,sessions:t,terms:r,names:n,now:l}),u=[];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`- ${s(e)} · ${e.kind} · ${o(e)} — ${i(t,c.previewLen)}`});d.length>e.length&&t.push(`- … +${d.length-e.length} more (read_terminal lists all)`),u.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 p=Array.isArray(a)?a:[],m=p.slice(0,c.wtCap);if(m.length){const e=m.map(e=>`- ${i(e,c.previewLen+30)}`);p.length>m.length&&e.push(`- … +${p.length-m.length} more (\`git worktree list\` shows all)`),u.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 u.length?`ROOM NOW (live snapshot, this turn):\n${u.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 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."};if(o>=l.machineMax)return{ok:!1,reason:`Room is at the machine cap (${l.machineMax} live lanes) — close one before opening another.`};const c=maxSpawnedFor(i,l);if(n>=c)return{ok:!1,reason:`Dispatch ceiling reached (${c} lane${1===c?"":"s"} on the ${i} plan)${"plus"!==i?` — Plus raises it to ${l.plusMaxSpawned}.`:"."} Close a dispatched lane to open another.`};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 l=Object.freeze(["mode","model","name","provider","runtime","sliceType","task"]),c=new Set(["default","acceptEdits","bypassPermissions","plan","review"]),d=new Set(["claude","codex","hermes"]),u=new Set(["scaffold","feature","fix","review"]),p=/((?<![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,m=/(?:\/home\/|\/users\/|\/private\/|\/tmp\/|[a-z]:\\|\\\\)/gi,h=e=>Array.isArray(e)?e.map(h):e&&"object"==typeof e?Object.fromEntries(Object.keys(e).sort().map(t=>[t,h(e[t])])):e,f=(e,t)=>null==e?null:String(e).slice(0,t),g=(e,t)=>f(e,t)?.replace(p,"[credential redacted]").replace(m,"[host path redacted]")||"";export function normalizeDispatchArgs(e={},t={}){if(!e||"object"!=typeof e||Array.isArray(e)||Object.keys(e).some(e=>!l.includes(e)))throw new TypeError("Invalid dispatch arguments");const r=e.runtime||t.runtime||"claude",n=e.mode||("plan"===t.mode?"default":t.mode)||"default";if(!d.has(r)||!c.has(n)||e.sliceType&&!u.has(e.sliceType))throw new TypeError("Invalid dispatch arguments");return Object.freeze({name:f(e.name,80),task:f(e.task,12e3),model:f(e.model,160),sliceType:f(e.sliceType,24),runtime:r,provider:f(e.provider,160),mode:n})}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=(u={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(h(u))).digest("hex"));var u;const p=l.provider||("codex"===l.runtime?"OpenAI / Codex login":"hermes"===l.runtime?"Hermes ACP profile":"Anthropic / host default"),m=l.model||s.resolvedModel||"runtime default",f=g(l.name||l.task?.split(/\r?\n/)[0]||"Open one worker lane",120);return Object.freeze({version:1,fingerprint:d,purpose:f,packages:Object.freeze([{title:g(l.name||"Worker package",80),task:g(l.task||"Open idle for a later hand-off.",600)}]),runtime:Object.freeze({name:l.runtime,provider:g(s.providerName||p,120),model:g(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 ${g(s.providerName||p,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:u=null,limits:p=SPAWN}={}){return"allow"!==l?{ok:!1,code:"dispatch_canceled"}:c?{ok:!1,code:d&&d===u?"idempotent_replay":"approval_replayed"}:y({preview:e,approvedFingerprint:t,args:r,initiatorTerminalId:n,roomCode:o,bridgeAuthorityId:i,localAuthorityId:s,context:a,limits:p})}export function authorizeDirectDispatch({preview:e,args:t,initiatorTerminalId:r,roomCode:n,bridgeAuthorityId:o,localAuthorityId:i,context:s={},limits:a=SPAWN}={}){return y({preview:e,approvedFingerprint:e?.fingerprint,args:t,initiatorTerminalId:r,roomCode:n,bridgeAuthorityId:o,localAuthorityId:i,context:s,limits:a})}function y({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"} of your own still open — collect ${1===n.length?"it":"them"} with read_terminal, then close_terminal: ${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";export const PEEK={defaultLines:20,maxLines:200,perTurnCap:10,rosterPerTurnCap:1,lineCap:200,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 n=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={},o=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,o-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,o=0;for(let i=(Array.isArray(e)?e.length:0)-1;i>=0&&o<t.failureWindow;i--){const t=e[i];if(t&&"object"==typeof t){if(o++,"result"===t.kind&&(!t.subtype||"success"===t.subtype)||"you"===t.kind)break;n(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 o=e=>`${e.lifecycle?.state||"Blocked"}${e.lifecycle?.reason?` (${e.lifecycle.reason})`:""} · ${formatLaneAge(e.lastActionAgeMs)}`,i=(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 i(`${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?i(`assistant: ${r.join(" ")}`,t):""}case"tool_result":return e.isError?i("⎿ error",t):"";case"result":return e.subtype&&"success"!==e.subtype?i(`turn ended — ${e.subtype}`,t):"";case"error":return i(`error: ${e.message||""}`,t);default:return""}};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 s=e=>`${e.ref}${e.name?` · "${e.name}"`:""}`;export const formatPeek=({selfId:e,sessions:t,terms:r,names:n={},terminal:a,lines:l,now:c=Date.now()}={})=>{const d=Math.min(PEEK.maxLines,Math.max(1,Number(l)||PEEK.defaultLines)),p=siblingsOf({selfId:e,sessions:t,terms:r,names:n,now:c});if(!p.length)return"No other terminals are open in this room right now.";if(!a)return`Other terminals in this room (call read_terminal with a ref or name to read one):\n${p.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`- ${s(e)} · ${e.kind} · ${e.cmd} · ${o(e)} — ${i(t,PEEK.rosterPreview)}`}).join("\n")}`;const u=resolveSibling(p,a);if(!u)return`No terminal matches "${a}". Call read_terminal with no argument to list the open terminals (refer to one by its name or ref).${isOrdinalRef(String(a||"").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 m;return m="agent"===u.kind?u.log.map(e=>digestLogEvent(e,PEEK.lineCap)).filter(Boolean).slice(-d).join("\n")||"(no activity yet)":cleanPtyTail(u.buf,d).join("\n")||"(no output yet)",`Terminal ${s(u)} (${u.kind} · ${u.cmd}) · ${o(u)} — last ${d} lines:\n${m}`};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 a=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 a)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:a=[],now:l=Date.now()}={},c=ROOMNOW)=>{const d=siblingsOf({selfId:e,sessions:t,terms:r,names:n,now:l}),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`- ${s(e)} · ${e.kind} · ${o(e)} — ${i(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(a)?a:[],m=u.slice(0,c.wtCap);if(m.length){const e=m.map(e=>`- ${i(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 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."};if(o>=l.machineMax)return{ok:!1,reason:`Room is at the machine cap (${l.machineMax} live lanes) — close one before opening another.`};const c=maxSpawnedFor(i,l);if(n>=c)return{ok:!1,reason:`Dispatch ceiling reached (${c} lane${1===c?"":"s"} on the ${i} plan)${"plus"!==i?` — Plus raises it to ${l.plusMaxSpawned}.`:"."} Close a dispatched lane to open another.`};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 l=Object.freeze(["mode","model","name","provider","runtime","sliceType","task"]),c=new Set(["default","acceptEdits","bypassPermissions","plan","review"]),d=new Set(["claude","codex","hermes"]),p=new Set(["scaffold","feature","fix","review"]),u=/((?<![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,m=/(?:\/home\/|\/users\/|\/private\/|\/tmp\/|[a-z]:\\|\\\\)/gi,h=e=>Array.isArray(e)?e.map(h):e&&"object"==typeof e?Object.fromEntries(Object.keys(e).sort().map(t=>[t,h(e[t])])):e,f=(e,t)=>null==e?null:String(e).slice(0,t),g=(e,t)=>f(e,t)?.replace(u,"[credential redacted]").replace(m,"[host path redacted]")||"";export function normalizeDispatchArgs(e={},t={}){if(!e||"object"!=typeof e||Array.isArray(e)||Object.keys(e).some(e=>!l.includes(e)))throw new TypeError("Invalid dispatch arguments");const r=e.runtime||t.runtime||"claude",n=e.mode||("plan"===t.mode?"default":t.mode)||"default";if(!d.has(r)||!c.has(n)||e.sliceType&&!p.has(e.sliceType))throw new TypeError("Invalid dispatch arguments");return Object.freeze({name:f(e.name,80),task:f(e.task,12e3),model:f(e.model,160),sliceType:f(e.sliceType,24),runtime:r,provider:f(e.provider,160),mode:n})}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(h(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",f=g(l.name||l.task?.split(/\r?\n/)[0]||"Open one worker lane",120);return Object.freeze({version:1,fingerprint:d,purpose:f,packages:Object.freeze([{title:g(l.name||"Worker package",80),task:g(l.task||"Open idle for a later hand-off.",600)}]),runtime:Object.freeze({name:l.runtime,provider:g(s.providerName||u,120),model:g(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 ${g(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"}:y({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 y({preview:e,approvedFingerprint:e?.fingerprint,args:t,initiatorTerminalId:r,roomCode:n,bridgeAuthorityId:o,localAuthorityId:i,context:s,limits:a})}function y({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"} of your own still open — collect ${1===n.length?"it":"them"} with read_terminal, then close_terminal: ${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}};
|