thinkpool-pair 0.7.416 → 0.7.418

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{randomUUID as e}from"node:crypto";import{createRequire as t}from"node:module";import{readFileSync as o}from"node:fs";import{dirname as n,join as s}from"node:path";import{query as r}from"@anthropic-ai/claude-agent-sdk";import{sanitizeSession as i}from"./transcript-sanitize.mjs";import{reviewGatePreToolDecision as a}from"./flow-review-gate.mjs";import{crossPostNeedsCard as l}from"./cross-terminal.mjs";import{correctContext as c}from"./context-windows.mjs";import{normalizeClaudeCommandCatalog as d}from"./claude-command-catalog.mjs";import{evidenceForToolResult as u}from"./evidence-citations.mjs";import{THINKPOOL_CASCADE_RULE as p,THINKPOOL_REMOTE_DELIVERY_RULES as m,THINKPOOL_RUNTIME_AUTHORITY_RULE as h,THINKPOOL_RUNTIME_TURN_REMINDER as f,buildThinkPoolTurnGuidance as y,createRoomContextSelector as k,normalizeThinkPoolTurnCause as w,usesFullThinkPoolReminder as g}from"./thinkpool-room-prompt.mjs";import{stallDecision as b,stallEvent as v,isCompactTurn as _}from"./turn-stall.mjs";import{createSameTargetResilienceController as T,formatResilienceTrace as S}from"./provider-resilience.mjs";import{catastrophicPreToolHookDecision as E}from"./catastrophic-command-guard.mjs";const N=t(import.meta.url);export async function claudeOneShot({prompt:e,model:t="claude-haiku-4-5",cwd:o,env:n,timeoutMs:s=8e3}={}){const i=new AbortController,a=setTimeout(()=>{try{i.abort()}catch{}},s);try{const s=r({prompt:e,options:{model:t,...o?{cwd:o}:{},env:n,maxTurns:1,permissionMode:"bypassPermissions",settingSources:[],strictMcpConfig:!0,mcpServers:{},abortController:i}});let a="";for await(const e of s){if("assistant"===e.type)for(const t of e.message?.content||[])"text"===t.type&&(a+=t.text);if("result"===e.type)break}return a.trim()}finally{clearTimeout(a)}}const O=(()=>{try{let e=n(N.resolve("@anthropic-ai/claude-agent-sdk"));for(let t=0;t<8;t++){try{const t=JSON.parse(o(s(e,"package.json"),"utf8"));if("@anthropic-ai/claude-agent-sdk"===t.name)return t.version}catch{}const t=n(e);if(t===e)break;e=t}}catch{}return"unknown"})(),R=/\brm\s+\S|\brmdir\s+\S|\bgit\s+(push\s+(-f|--force)|reset\s+--hard|clean\s+-[a-z]*f)|\bdrop\s+(table|database)\b|\b(mkfs|dd)\b|\bsudo\b|>\s*\/dev\/|\bchmod\s+-R|\bchown\s+-R|\bkillall\b|\btruncate\b/i,A=new Set(["Read","Grep","Glob","NotebookRead","TodoRead","LS"]),D=new Set(["WebFetch","WebSearch"]),x=new Set(["Edit","Write","MultiEdit","NotebookEdit","TodoWrite"]);export function classifyRisk(e,t){if("Bash"===e){const e=t&&(t.command??t.cmd)||"";return R.test(e)?"high":"medium"}return A.has(e)?"low":D.has(e)?"network":(x.has(e),"medium")}const P=/(^|\/)\.claude\/SESSIONS\/|(^|\/)CLAUDE\.md$/;export function isSafeDocWrite(e,t){if(!x.has(e))return!1;const o=t&&(t.file_path||t.notebook_path)||"";return P.test(o)}export function autoAllow({toolName:e,input:t,mode:o="default",alwaysAllow:n=new Set}){const s=classifyRisk(e,t);return"low"===s||"bypassPermissions"===o||"acceptEdits"===o&&x.has(e)&&"high"!==s||isSafeDocWrite(e,t)||n.has(`${e}:${s}`)}export function askUserQuestionHookOutput(e){const t=e&&"object"==typeof e?e.decision:e,o="string"==typeof t&&t.startsWith("answer:")?t.slice(7):"",n=e&&"object"==typeof e?e.responder:null,s="string"==typeof n?.name&&n.name.trim()?n.name.trim():"string"==typeof n?.id&&n.id?`room member ${n.id}`:"The user";return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:o?`${s} answered in the thinkpool room — ${o}. Treat this as their selection and continue; do not call AskUserQuestion again for the same question.`:"The user dismissed the question in the thinkpool room without selecting. Ask in plain prose, or proceed with a sensible default."}}}export function askUserQuestionRegression(e,t){return Array.isArray(e)?e.includes("AskUserQuestion")?null:`[SDK-REGRESSION] agent SDK v${t||"unknown"} init tools[] is missing 'AskUserQuestion' — the multiple-choice question card is disabled. A caret SDK bump likely changed the canUseTool gate; pin a known-good SDK in bridge/package.json + republish.`:null}function I(){const e=[];let t=null,o=!1;return{stream:async function*(){for(;!o;)e.length?yield e.shift():await new Promise(e=>{t=e})}(),push:n=>!o&&(e.push({type:"user",message:{role:"user",content:n}}),t&&(t(),t=null),!0),end(){o=!0,t&&(t(),t=null)}}}const C=(e=[])=>e.map(e=>"text"===e.type?{type:"text",text:e.text}:"thinking"===e.type?{type:"thinking",text:e.thinking||"",reasoningKind:"thought"}:"tool_use"===e.type?{type:"tool_use",id:e.id,name:e.name,input:e.input}:{type:e.type}).filter(Boolean),M=new Set(["default","acceptEdits","plan","bypassPermissions"]),U=["You are Claude in a thinkpool Code room, driven live from a phone or browser — NOT a local terminal. Keep using the room's features.",f,"TERMINAL HIERARCHY: obey your authoritative TERMINAL ROLE. A person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal — NEVER spawn_terminal — even for ordinary work or a handoff. If the wording includes new or separate terminal, main-terminal routing wins. Use spawn_terminal only for agent-decided bounded worker slices or when the person explicitly asks for a worker, sub-terminal, Ensemble lane, or delegated slice. If open_main_terminal is unavailable, say so; never substitute an Ensemble child. Leaf, worker, Side, and managed Flow lanes work directly. Never use built-in invisible Task/Agent subagents or hijack a busy sibling.","WORKTREES: parallel lanes share one repo — before code edits run `git worktree list`; if linked worktrees exist, take your OWN worktree + branch, never the shared checkout or a branch another lane is on.","BUILD WORKFLOW (default, no magic word): right-size within your TERMINAL ROLE — a trivial ask or delegated slice you just do; a conductor-capable role with a genuinely decomposable build FIRST writes a short plan in chat, THEN fans worker slices into visible spawn_terminal lanes and verifies them. Worker/leaf/Side/managed Flow roles do not fan out. A person-requested new or separate terminal uses open_main_terminal. Never plan-mode/ExitPlanMode; plans live in chat and lanes in the existing list."].join(" ");export function startClaudeSession({cwd:t,model:o,effort:n="high",resume:s,env:f,mode:N="default",onEvent:R,requestPermission:A,mcpServers:D,crossPostGate:x,crossRoomPostGate:P,didSpawnTarget:L=null,terminalRolePrompt:W,rolePrompt:F,blockSubagents:j=!1,onSubmitPlan:$=null,onLaneDone:q=null,onReviewVerdict:G=null,reviewGate:B=null,lazy:H=!1,roomContext:K=null,suggest:Q=!0,prepareCwd:Y=null,admitStart:z=null,resilienceObserver:J=null,resilience:V=null}){const X=k(K);let Z=0,ee=!0;const te=(e,{promptIndex:t=0,forceFull:o=!1,turnCause:n=null}={})=>{const s=g({promptIndex:t,forceFull:o,turnCause:n}),r=X({force:s}),i=String(W||"").trim();return`<system-reminder>\n${s&&i?`${i}\n\n`:""}${s?U:y({text:e,promptIndex:t,forceFull:o,turnCause:n})}${r?`\n\n${r}`:""}\n</system-reminder>`},oe=new AbortController;let ne=I(),se=s||null,re=s||null,ie=null,ae=null,le=null,ce=null,de=!1,ue=!1,pe=null,me=!1,he=!1,fe=!1,ye=null,ke=M.has(N)?N:"default";const we=new Set,ge=new Map,be=new Set(["low","medium","high","xhigh","max"]);let ve=be.has(n)?n:"high",_e=0,Te=0,Se=o||null,Ee=null,Ne=null,Oe=Promise.resolve(),Re=!1,Ae=!1;const De=e=>new Promise(t=>setTimeout(t,e)),xe=Math.max(3e4,parseInt(process.env.TP_STALL_MS,10)||9e4);let Pe=!1,Ie=Date.now(),Ce=!1;const Me=/connection closed|connection reset|econnreset|etimedout|socket hang up|fetch failed|network error|socket destroyed/i;let Ue=0;const Le=(e,t={})=>{try{J?.({reason:e,restartCount:Ue,...t})}catch{}},We=!(!V?.policy?.enabled||!V?.providerId||"anthropic"===V.providerId);let Fe=null,je=null,$e=!1,qe=0,Ge=!1,Be=null;const He=Math.max(3*xe,parseInt(process.env.TP_FORCE_STOP_MS,10)||3e5);let Ke=!1,Qe=!1;const Ye=Math.max(He,parseInt(process.env.TP_COMPACT_FORCE_STOP_MS,10)||12e5);let ze=!1,Je=0;const Ve=A;A=async e=>{Je++;try{return await(Ve?.(e))}finally{Je=Math.max(0,Je-1),Ie=Date.now()}};let Xe=!1,Ze=null,et=null,tt=!1,ot="",nt=null;const st=Math.max(1200,parseInt(process.env.TP_SUGGEST_FALLBACK_MS,10)||2500),rt=e=>{try{R?.(e)}catch{}},it=e=>{Ie=Date.now(),e&&"stalled"!==e.kind&&(Ce=!1),!e||"compaction"!==e.kind&&"result"!==e.kind&&"error"!==e.kind||(ze=!1),rt(e)},at=e=>{try{V?.onRecord?.(e)}catch{}"retrying"!==e?.outcome&&"cap_blocked"!==e?.outcome&&"circuit_open"!==e?.outcome||it({kind:"note",text:S(e)})},lt=()=>{if(null!=je){try{(V?.clearTimer||clearTimeout)(je)}catch{}je=null}},ct=()=>{if(lt(),!Fe)return;const e=Number(V?.policy?.timeoutMs);if(!Number.isFinite(e)||e<=0)return;const t=V?.setTimer||setTimeout;je=t(()=>{if(je=null,!de&&Fe&&Pe){Fe.failure({message:"timeout"}),Pe=!1;try{Ee?.abort()}catch{}gt()}},e)},dt=async()=>{if(!Fe)return!0;let e=null;try{e=await Fe.preflight()}catch{return!1}return!0===e?.admitted},ut=setInterval(()=>{const e=Date.now()-Ie,t=b({turnActive:Pe,awaitingUser:Je,quietMs:e,stallMs:xe,forceStopMs:He,stalledSent:Ce,stallRetried:Qe,compacting:ze,compactForceStopMs:Ye});if("none"===t)return;const o=v(t,e);if(o&&rt(o),"status"!==t){if("retry"===t){if(Ke=!0,Fe){Le("resilience_stall",{quietMs:e}),Fe.failure({message:"timeout"}),Pe=!1;try{Ee?.abort()}catch{}return void gt()}return Le("stall_replay",{quietMs:e}),void wt(e)}Ke=!0,Pe=!1}else Ce=!0},5e3);ut.unref?.();const pt=e=>{setTimeout(()=>{Promise.resolve(ye?.setPermissionMode?.(e)).catch(t=>console.error(`[claude-session] setPermissionMode(${e}) failed:`,t?.message||t))},0)},mt={abortController:oe,permissionMode:ke,hooks:{PreToolUse:[{hooks:[async o=>{const n=o.tool_name,s=o.tool_input,r=E({toolName:n,input:s,cwd:t});if(r)return r;const i=o.effort?.level;i&&i!==ve&&(ve=i,it({kind:"effort",level:ve}));const c="Write"===n||"Edit"===n||"MultiEdit"===n||"NotebookEdit"===n;if(j&&c&&/(?:^|[/\\])FLOW_PLAN\.json$/i.test(s?.file_path||s?.notebook_path||"")){const e=s?.content??s?.new_string??"";let t={ok:!1,message:"Plan submission is not wired for this session."};try{t=$&&await $(e)||t}catch(e){t={ok:!1,message:`Plan submission failed: ${e?.message||e}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.message}}}if(j&&("Task"===n||"Agent"===n||"Bash"===n||c))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Bash"===n?"Flow conductors do NOT run Bash — it pops a permission card and stalls the flow. Use the Grep tool (not `grep`/`rg`), the Glob tool (not `find`/`ls`), and Read (not `cat`/`head`) — those run with no prompt. Then DECOMPOSE and submit by Writing your task-graph JSON to the file FLOW_PLAN.json.":c?'Flow conductors do NOT write project or plan-document files. Do NOT use ExitPlanMode and do NOT call submit_flow_plan (both hang here). To SUBMIT your decomposition, use the Write tool with file_path "FLOW_PLAN.json" and content = your task-graph JSON ({"summary":"…","tasks":[…]}). That single Write IS how you submit — the room ingests it directly. Do not write any other file.':"Flow conductors do NOT spawn subagents — it stalls the flow on a permission card. Inspect the codebase yourself with Read/Grep/Glob (no prompt). Then DECOMPOSE and submit by Writing your task-graph JSON to the file FLOW_PLAN.json. Do not call Task/Agent again."}};if(G&&("Write"===n||"Edit"===n)&&/(?:^|[/\\])FLOW_REVIEW(\.[a-zA-Z0-9]+)?$/.test(s?.file_path||"")){let e={ok:!1,message:"verdict signal failed"};try{e=await G(s?.content??s?.new_string??"")||e}catch(t){e={ok:!1,message:`verdict signal failed: ${t?.message||t}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.message}}}if(q&&("Write"===n||"Edit"===n)&&/(?:^|[/\\])FLOW_DONE(\.[a-zA-Z0-9]+)?$/.test(s?.file_path||"")){let e={ok:!1,message:"done signal failed"};try{e=await q(s?.content??s?.new_string??"")||e}catch(t){e={ok:!1,message:`done signal failed: ${t?.message||t}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.message}}}const d=a({reviewGate:B,toolName:n,toolInput:s});if(d)return d;if("mcp__thinkpool__read_terminal"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (read-only thinkpool cross-terminal read)."}};if(/^mcp__thinkpool__preview_(start|capture|inspect|stop)$/.test(n))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (contained bridge-owned viewport preview)."}};if("mcp__thinkpool__submit_flow_plan"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (Flow plan submission — broadcasts the task-graph for human approval)."}};if("mcp__thinkpool__list_sessions"===n||"mcp__thinkpool__read_session"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (read-only thinkpool cross-session read — your own rooms)."}};if("mcp__thinkpool__close_terminal"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (thinkpool cross-terminal close — only self-spawned lanes)."}};if("mcp__thinkpool__spawn_terminal"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (autonomous thinkpool worker; bounded by room caps and isolated in its own worktree)."}};if("mcp__thinkpool__open_main_terminal"===n){const t=s?.mode||ke;if("bypassPermissions"!==t||"bypassPermissions"===ke)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Auto-approved (open a fresh thinkpool terminal in ${t} mode — inherited, no escalation; bounded by room caps).`}};let o="deny";try{o=await(A?.({id:e(),toolName:n,input:{...s,mode:t},risk:"high"}))??"deny"}catch{o="deny"}const r="allow"===o;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:r?"allow":"deny",permissionDecisionReason:r?"Bypass terminal creation approved in the thinkpool room — the new terminal runs autonomously.":"Bypass terminal creation denied in the room — do not retry as bypass; open it without mode:bypassPermissions or ask what to do."}}}if("mcp__thinkpool__post_to_terminal"===n){const t=x?x():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-terminal post not allowed right now."}};const o=!!L&&!!L(s?.terminal);if(!l({mode:ke,spawnedByMe:o}))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"bypassPermissions"===ke?"Auto-approved (cross-terminal post in bypassPermissions mode — bypass means bypass).":"Auto-approved (cross-terminal post into a lane you spawned — parent→child orchestration, no per-post tap)."}};let r="deny";try{r=await(A?.({id:e(),toolName:n,input:s,risk:"high"}))??"deny"}catch{r="deny"}const i="allow"===r;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:i?"allow":"deny",permissionDecisionReason:i?"Cross-terminal post approved in the thinkpool room.":"Cross-terminal post denied in the room — do not retry; ask what to do instead."}}}if("mcp__thinkpool__post_to_session"===n){const t=P?P():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-room post not allowed right now."}};let o="deny";try{o=await(A?.({id:e(),toolName:n,input:s,risk:"high"}))??"deny"}catch{o="deny"}const r="allow"===o;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:r?"allow":"deny",permissionDecisionReason:r?"Cross-room post approved in the sending room — the target room will be asked to accept it.":"Cross-room post denied in the room — do not retry; ask what to do instead."}}}if("ExitPlanMode"===n){if("plan"!==ke)return pt(ke),it({kind:"mode",mode:ke}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`The thinkpool room is in ${ke} mode, not Plan — the user did not ask for a plan. Do NOT call ExitPlanMode; proceed and make the changes directly. Only present a plan if the user switches the room to Plan mode or explicitly asks.`}};let t="keep";try{t=await(A?.({id:e(),toolName:n,input:s,risk:"plan",plan:s?.plan||""}))??"keep"}catch{t="keep"}if("run"===t||"accept"===t){const e="accept"===t?"acceptEdits":"default";return ke=e,pt(e),it({kind:"mode",mode:e}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Plan approved in the thinkpool room — proceed (${e} mode).`}}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:'The user chose "keep planning" in the thinkpool room. Do not exit plan mode — keep refining the plan, then call ExitPlanMode again when ready.'}}}if("AskUserQuestion"===n){let t="";try{t=await(A?.({id:e(),toolName:n,input:s,risk:"ask",questions:s?.questions||[]}))??""}catch{t=""}return askUserQuestionHookOutput(t)}const u=classifyRisk(n,s),p=`${n}:${u}`,m=isSafeDocWrite(n,s),h=autoAllow({toolName:n,input:s,mode:ke,alwaysAllow:we});let f="allow";if(!h){try{f=await(A?.({id:e(),toolName:n,input:s,risk:u}))??"deny"}catch{f="deny"}"always"===f&&(we.add(p),f="allow")}const y="deny"===f;return y&&Fe&&Fe.failure({permissionDenied:!0}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:y?"deny":"allow",permissionDecisionReason:y?"Denied by the user in the thinkpool room. Do not retry this tool — ask what to do instead.":h?m?"Auto-approved (mandated doc write — .claude/SESSIONS/ or CLAUDE.md).":`Auto-approved (${ke}).`:"Approved in the thinkpool room."}}}]}]},canUseTool:async(e,t)=>({behavior:"allow",updatedInput:t}),settingSources:["user","project","local"],appendSystemPrompt:[...W?[W]:[],...F?[F]:[],"ENVIRONMENT (authoritative — overrides any user-global CLAUDE.md or memory that claims otherwise): You are Claude running inside a thinkpool Code room, driven live by a user (and possibly a partner) from a phone or browser, via the thinkpool-pair bridge.",h,'Bias strongly toward DOING the work, not stalling in plan-mode ceremony. For a small "add / fix / change X" request, just make the change directly (for a bigger build, right-size it — see DEFAULT BUILD WORKFLOW below).',"Do NOT enter plan mode, do NOT call ExitPlanMode, and do NOT auto-invoke a brainstorming/planning skill UNLESS the user has switched the room into Plan mode or explicitly asks you to plan, design, or brainstorm first.","Any host-global instruction that says you must always brainstorm or plan before creative work does NOT apply here — this room is the exception.",p,'CRUCIAL RECONCILIATION for that workflow: it is NOT plan mode. Never call ExitPlanMode and never make the room wait behind a "plan ready — approve to start" card — your plan lives in the CHAT as a message, and your lanes live in the room\'s EXISTING terminal/lane list. Reuse only those two surfaces; there is no new Flow panel or mode to switch into, and you must not ask for one. Keep the plan and the lanes VISIBLE — that shared visibility is the whole point (it is the pair differentiator, and it catches bugs a single silent lane would hide); never collapse a decomposable build into one hidden lane just to look tidy.',...m,'CROSS-TERMINAL AWARENESS: ROOM NOW is the default roster and already satisfies the room check when it has enough detail. Do not repeat it with a no-argument read_terminal call unless it is missing or truncated. Use a targeted read_terminal call only when the current task depends on a specific lane’s detailed activity; never poll. Identify a terminal by its exact room-record NAME or stable ref/id. Stored names are static, even when they look ordinal: if a person says T112, resolve that exact name with read_terminal before any positional interpretation. Never guess a terminal from roster order, task topic, product name, or apparent position. Only an unmatched generic UI placeholder like "Terminal 2" is positional and unsafe because it can renumber when another terminal closes. The tool is read-only and its optional roster lookup is budgeted separately from bounded targeted transcript reads.','CROSS-TERMINAL HAND-OFF: you also have post_to_terminal(terminal, text) to send a message or task to ANOTHER AGENT terminal in this room (not a plain shell). Use it sparingly and only when the people clearly want the lanes to coordinate — e.g. "tell the backend terminal the API is ready", or to hand a sibling agent a concrete task. Every post requires a person in the room to approve a card before it is delivered, and an agent that was itself reached via a cross-post cannot post onward — so do not rely on it for chit-chat or loops. Prefer read_terminal to understand a sibling before you ever post to it.',"TERMINAL CREATION CONTRACT: main terminals and workers use different tools. A person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal(name?, task?, model?) — even for ordinary work or a handoff and even without the words Cascade or conductor. If the wording includes new or separate terminal, main-terminal routing wins. Never use spawn_terminal for that request, and if open_main_terminal is unavailable say so instead of substituting. Use spawn_terminal(name?, task?, model?, sliceType?) only for agent-decided bounded WORKER SUB-TERMINALS or when the person explicitly asks for a worker, sub-terminal, Ensemble lane, or delegated slice. Workers never receive the creation tools and never conduct. Do not dump work into busy siblings. Spawned workers are always autonomous in bypassPermissions and never ask the room for an approval card; the bridge still enforces room caps, hop limits, the kill-switch, and isolated linked worktrees. Wait for ROOM NOW or a completion signal instead of polling; after a worker finishes, collect it with one targeted read_terminal call and leave it visible until a person dismisses it with the Ensemble X. Never call close_terminal merely because work finished. Main terminals are independent, keep their requested permission mode, and are not owned/closed through Ensemble.","CROSS-SESSION AWARENESS: the Ensemble reaches across your SESSIONS, not just the terminals in this room. list_sessions() lists your OTHER thinkpool Code rooms — both your own rooms running on this machine AND your partner's rooms in the same pair, reachable over the per-pair bus (a room on the partner's machine shows its host). read_session(session, terminal?) reads recent activity inside one (omit `terminal` to list that room's terminals, or pass a ref/name to read that lane). Both are READ-ONLY — they never change another session, and they reach ONLY your own rooms and rooms you share with your partner, never a stranger's. Reach for them when work spans rooms — \"what's the other project up to\", \"pick up where the other session left off\", or to check a long-running task elsewhere before you act here.","CROSS-SESSION HAND-OFF: post_to_session(session, text, terminal?) sends a task or message to an agent in ANOTHER of your rooms — your own, or your partner's over the pair bus. Use it sparingly and only when the people clearly want the rooms to coordinate — e.g. hand the API room's agent a concrete follow-up once the frontend is ready. It is dual-consent: a person in YOUR room approves sending, and a person in the TARGET room approves receiving, before anything is delivered — so never rely on it for chit-chat or loops, and an agent that was itself reached via a cross-room post cannot post onward to a third room. It spends real model tokens in the other room (maybe on the other person's machine), so prefer read_session to understand a room before you ever post into it, and only post one concrete hand-off at a time. Outbound list/read/post tools need the thinkpool account bridge; a standalone owner room can still receive a paired hand-off directly and will always raise its own approval card before delivery.","SUBAGENT POLICY: in this room, a main terminal delegates worker slices through visible spawn_terminal Ensemble lanes. A person-requested new or separate terminal is created with open_main_terminal, never Ensemble. Worker, leaf, Side, and managed Flow lanes do their assigned work directly. Do NOT reach for built-in Task/Agent subagents: an in-process subagent is invisible to the room, cannot be peered at or steered, and its work is lost to the Ensemble.",'RESEARCH LANE: you have a `research` tool that runs a REAL multi-source web search + adversarial verification and returns each claim marked HELD or REJECTED with citations. Reach for it when the people would genuinely benefit from looking something external up or settling a question of current fact — pricing, "is X still maintained / deprecated", "is that benchmark real", a debate over facts you are not sure of. Do NOT run it unprompted or for things you already know: first OFFER in plain language ("want me to spawn a research lane on that and check it?"), and only call `research(question)` once they agree — it spends real budget (plan-gated Free 5 / Plus 100 runs a month) and takes ~a minute. When it returns, present the held/rejected findings clearly and invite both people to weigh the sources, flagging any held claim that rests on a source they might not trust — that shared scrutiny is the point.',"WORKTREES: parallel lanes share one machine and usually one repo. Run `git worktree list` before your first code edit; if linked worktrees exist, the shared main checkout is contended (and may be guard-blocked) — do your work in your OWN worktree on your OWN branch (`git worktree add <dir> -b <branch>`), and never edit a checkout or ride a branch another lane is using.",'WRITE PLANS INTO THE CHAT: whenever you form or revise a plan — because the room is in Plan mode, or because someone asked you to plan, design, or think it through first — write the actual plan out as a normal message in the room as you develop it: the approach, the concrete steps, the files you will touch, the open questions. The room does NOT surface plan files at all, and the plan-approval card does not reliably carry the plan text, so a plan that lives only in a plan file or only inside ExitPlanMode is INVISIBLE to the people you are working with — they just see "plan ready" with no content. The chat is the canonical place your plan lives; put it there so the room can read and react to it before you proceed.'].join(" "),includePartialMessages:!0,promptSuggestions:!0};"1"===process.env.TP_MCP_STRICT&&(mt.strictMcpConfig=!0,mt.mcpServers={}),D&&Object.keys(D).length&&(mt.mcpServers={...mt.mcpServers||{},...D}),t&&(mt.cwd=t),o&&(mt.model=o),mt.effort=ve,mt.env={...f||process.env,CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION:"1"};const ht=async()=>{if(!Q||"worker_completion"===ae)return;const e=(ot||"").trim().slice(-1500);if(e&&!de)try{let o=await claudeOneShot({prompt:`You are predicting the user's NEXT chat message in a live coding session, to prefill their composer. Given the assistant's latest reply below, output the single most likely next user message — short and natural (often just "proceed", "go with option A", "yes do that", or a brief follow-up). One line, <=12 words, imperative, no preamble, no quotes, no markdown.\n\nAssistant's latest reply:\n"""\n${e}\n"""\n\nNext user message:`,model:"claude-haiku-4-5",cwd:t,env:mt.env,timeoutMs:8e3});o=o.trim().split("\n")[0].replace(/^["'`]+|["'`]+$/g,"").trim().slice(0,140),!o||tt||de||/^(sure|of course|certainly|let me know|i can help|happy to)\b/i.test(o)||(it({kind:"suggestion",text:o,source:"haiku"}),process.stderr.write(` ◆ [suggestion] haiku fallback: ${JSON.stringify(o)}\n`))}catch{}},ft=()=>{const e="function"==typeof z?z():{ok:!0};return!1!==e?.ok||(it({kind:"error",message:e.reason||"Host memory is critically low. This agent runtime was not started.",recoverable:!0}),!1)},yt=async({admitted:e=!1}={})=>{if(Ae)return!1;if(!ue&&!e&&!ft())return!1;if(null==pe&&(pe=Date.now()),ue=!0,Ne)try{Ne()}catch{}Oe=new Promise(e=>{Ne=e});const n=new AbortController;Ee=n;const a=()=>{try{n.abort()}catch{}};oe.signal.addEventListener("abort",a,{once:!0});try{if(se){const e=i(t||process.cwd(),se);e.blocks&&process.stderr.write(`\n ◆ healed ${e.blocks} malformed tool block(s) in the transcript before resume.\n`)}ye=r({prompt:ne.stream,options:{...mt,abortController:n,...se?{resume:se}:{}}});for await(const e of ye){if(de)break;switch(e.type){case"system":if("thinking_tokens"===e.subtype){_e+Te===0&&it({kind:"thinking_tokens",tokens:e.estimated_tokens,delta:e.estimated_tokens_delta});break}if("compact_boundary"===e.subtype){ee=!0,it({kind:"compaction",trigger:e.compact_metadata?.trigger||"auto",preTokens:e.compact_metadata?.pre_tokens??null}),(async()=>{try{const e=await(ye?.getContextUsage?.());e&&(it({kind:"usage",ctx:c({used:e.totalTokens,max:e.maxTokens,pct:Math.round(e.percentage),model:e.model})}),e.model&&(Se=e.model))}catch{}})();break}if(e.session_id&&(se=e.session_id),me||(me=!0,process.stderr.write(`\n ◆ session ready in ${Date.now()-pe}ms — MCP ${"1"===process.env.TP_MCP_STRICT?"OFF":"on"}${s?", resume":", fresh"}.\n`)),Se=mt.model||e.model||o||Se,it({kind:"system",sessionId:se,model:mt.model||e.model||o||null,commands:d({slashCommands:e.slash_commands,skills:e.skills})}),!fe&&Array.isArray(e.tools)){fe=!0;const t=askUserQuestionRegression(e.tools,O);t&&(process.stderr.write(`\n ⚠⚠ ${t}\n`),it({kind:"error",message:t}))}he||(he=!0,Promise.resolve(ye?.supportedModels?.()).then(e=>{const t=(e||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);t.length&&it({kind:"models",models:t})}).catch(()=>{}));break;case"assistant":lt(),Fe?.visibleOutput();for(const t of e.message?.content||[])"tool_use"===t?.type&&t.id&&ge.set(t.id,{at:Date.now(),name:t.name,input:t.input});{const t=(e.message?.content||[]).filter(e=>"text"===e?.type).map(e=>e.text).join("\n").trim();t&&(ot=t)}it({kind:"assistant",blocks:C(e.message?.content),parentToolUseId:e.parent_tool_use_id||null});break;case"user":for(const t of e.message?.content||[])if("tool_result"===t?.type){lt(),Fe?.visibleOutput({tool:!0});const o=ge.get(t.tool_use_id);null!=o&&ge.delete(t.tool_use_id);const n=u(o?.name,t.content);it({kind:"tool_result",toolUseId:t.tool_use_id,content:t.content,...n?{evidence:n}:{},isError:!!t.is_error,durationMs:null!=o?.at?Date.now()-o.at:void 0,parentToolUseId:e.parent_tool_use_id||null})}break;case"stream_event":{const t=e.event;"message_start"===t?.type?(_e+=Te,Te=t.message?.usage?.output_tokens||0,it({kind:"thinking_tokens",tokens:_e+Te})):"message_delta"===t?.type&&t.usage&&(Te=t.usage.output_tokens??Te,it({kind:"thinking_tokens",tokens:_e+Te}));break}case"result":if(lt(),e.session_id&&(se=e.session_id),e.is_error&&Array.isArray(e.errors)&&e.errors.some(e=>/no conversation found/i.test(String(e)))&&(se||re)&&Ue<3){Ue++;const e=Pe;Pe=!1,se=null,re=null,it({kind:"note",text:"previous session not found — continuing on a fresh one"});const t=ne;ne=I();try{t.end()}catch{}const o=e?ie:null;Be=setTimeout(()=>{Be=null,de||(yt(),null!=o&&(Pe=!0,Ie=Date.now(),Ce=!1,ne.push([{type:"text",text:o},{type:"text",text:le||te(o,{forceFull:!0})}])))},300);break}if(Xe&&("aborted"===e.subtype||"error_during_execution"===e.subtype)){qe===Ze&&(Pe=!1);break}if(e.is_error&&Fe){if($e)break;Fe.failure({message:Array.isArray(e.errors)?e.errors.join(" "):e.result,status:e.status??e.statusCode,code:e.code}),Pe=!1,gt();break}if(_e=0,Te=0,Pe=!1,Re&&(Re=!1,setTimeout(()=>{de||kt()},0)),"success"===e.subtype&&(Ue=0,se&&(re=se)),"success"===e.subtype&&(Fe?.success(),Fe=null),Ke=!1,Qe=!1,e.modelUsage&&"object"==typeof e.modelUsage){let t=null,o=-1;for(const[n,s]of Object.entries(e.modelUsage)){const e=s?.outputTokens??0;e>o&&(o=e,t=n)}t&&(Se=t)}{const t="string"==typeof e.result?e.result.replace(/\s+/g," ").trim().slice(0,200):"";it({kind:"result",subtype:e.subtype,sessionId:se,model:Se,costUsd:e.total_cost_usd,usage:e.usage,numTurns:e.num_turns,durationMs:e.duration_ms??null,denials:Array.isArray(e.permission_denials)?e.permission_denials.length:0,resultText:t||null})}nt&&clearTimeout(nt),"aborted"!==e.subtype&&"worker_completion"!==ae&&(nt=setTimeout(()=>{nt=null,tt||de||ht()},st)),(async()=>{let t=null;try{const e=await(ye?.getContextUsage?.());e&&(t=c({used:e.totalTokens,max:e.maxTokens,pct:Math.round(e.percentage),model:e.model}),e.model&&(Se=e.model))}catch{}const o=e.usage||{};it({kind:"usage",costUsd:e.total_cost_usd??null,tokens:(o.input_tokens||0)+(o.output_tokens||0),ctx:t})})();break;case"prompt_suggestion":nt&&(clearTimeout(nt),nt=null),e.suggestion&&(tt=!0,it({kind:"suggestion",text:e.suggestion}))}}}catch(e){if(lt(),de)return;if(n.signal.aborted)return;const t=e?.message||String(e);if(Fe&&Pe)return Fe.failure({message:t,status:e?.status??e?.statusCode,code:e?.code}),Pe=!1,void gt();if(Pe=!1,it({kind:"error",message:t}),Me.test(t)&&Ue<3){Ue++,Le("stream_reconnect",{failureClass:"network"}),it({kind:"note",text:`connection dropped — reconnecting (${Ue}/3)`});const e=ne;ne=I();try{e.end()}catch{}return void(Be=setTimeout(()=>{Be=null,de||yt()},Math.min(1e3*Ue,4e3)))}if(/no conversation found/i.test(t)&&se&&Ue<3){Ue++,se=null,re=null;const e=ne;ne=I();try{e.end()}catch{}return void(Be=setTimeout(()=>{Be=null,de||yt()},300))}de=!0}finally{oe.signal.removeEventListener("abort",a),Ee===n&&(Ee=null);try{await(ye?.return?.())}catch{}Ne&&(Ne(),Ne=null)}},kt=async()=>{if(de||Ae||!ue)return;const e=Oe,t=ne;if(ne=I(),Ee)try{Ee.abort()}catch{}try{t.end()}catch{}try{await e}catch{}await De(300),se=re,de||Ae||yt()},wt=async e=>{if(de)return;Qe=!0;const t=Pe&&!_(ie)?ie:null;Pe=!1;const o=Oe,n=ne;if(ne=I(),Ee)try{Ee.abort()}catch{}try{n.end()}catch{}try{await o}catch{}await De(300),se=re,de||(yt(),null!=t&&(Pe=!0,Ie=Date.now(),Ce=!1,ne.push(/^\s*\//.test(t)?[{type:"text",text:t}]:[{type:"text",text:t},{type:"text",text:le||te(t,{forceFull:!0})}]),rt({kind:"note",text:"retrying the stalled turn on a fresh connection"})))},gt=()=>{if(de||Ge||$e)return;const e=Fe,t=qe,o=ce;$e=!0;const n=Oe,s=ne;ne=I();try{s.end()}catch{}Be=setTimeout(async()=>{Be=null;try{await n}catch{}if(!de&&$e&&Fe===e&&qe===t)return await dt()?void(!de&&$e&&Fe===e&&qe===t&&($e=!1,Pe=!0,Ie=Date.now(),Ce=!1,yt(),o&&ne.push(o),ct())):($e=!1,void bt())},0)},bt=()=>{lt(),Pe=!1,Fe=null,ue=!1,it({kind:"error",message:"The configured provider could not complete this turn. Nothing else was sent.",recoverable:!0})};return H||We||yt(),{sendTurn(e,n={}){if(de||Ae||Ge||$e)return!1;if(!ue&&!ft())return!1;if(!ue&&Y)try{const e=Y();e&&(t=e,mt.cwd=e)}catch{}Pe=!0,tt=!1,ie=String(e),ae=w(n?.turnCause),nt&&(clearTimeout(nt),nt=null),Ie=Date.now(),Ce=!1,Qe=!1,Ke=!1;const s=String(e),r=Z++,i=ee;if(ee=/^\s*\/(?:compact|clear|reset)\b/i.test(s),le=/^\s*\//.test(s)?null:te(s,{promptIndex:r,forceFull:i,turnCause:ae}),ze=_(s),ce=/^\s*\//.test(s)?[{type:"text",text:s}]:[{type:"text",text:s},{type:"text",text:le}],qe++,Fe=(()=>{if(!We)return null;try{const e=T({runtime:"claude",providers:V.providers||[],providerId:V.providerId,model:V.model||mt.model||o,requestedModel:V.requestedModel||V.model||mt.model||o,policy:V.policy,bridgeHostId:V.bridgeHostId,circuit:V.circuit,capGate:V.capGate,traceId:V.traceId,turnRev:"function"==typeof V.turnRev?V.turnRev():V.turnRev,onRecord:at});return e.start(),e}catch{return null}})(),Fe){const e=Fe,t=qe,o=ce;dt().then(n=>{!de&&Pe&&Fe===e&&qe===t&&(n?(ue||yt({admitted:!0}),ne.push(o),ct()):bt())}).catch(()=>{!de&&Pe&&Fe===e&&qe===t&&bt()})}else ue||yt({admitted:!0}),ne.push(ce)},warm(){We||ue||de||Ae||yt()},get started(){return ue},async setMode(e){M.has(e)&&!de&&(ke=e,pt(e),it({kind:"mode",mode:ke}))},async setModel(e){mt.model=e,Se=e,it({kind:"note",text:`model → ${e}`}),ue&&!de&&(Pe?Re=!0:await kt())},setEffort:async e=>!(!be.has(e)||de||(ve=e,mt.effort=e,it({kind:"effort",level:e}),ue&&(Pe?(Re=!0,0):(await kt(),0)))),async listModels(){try{const e=(await(ye?.supportedModels?.())||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);e.length&&it({kind:"models",models:e}),it({kind:"note",text:e.length?`models: ${e.map(e=>e.value).join(", ")}`:"no model list available"})}catch{it({kind:"note",text:"usage: /model <name>"})}},async park(){if(de||Ae||Pe||Ge||$e||ze)return!1;if(!ue)return!0;Ae=!0;const e=Oe,t=ne;ne=I(),ue=!1,nt&&(clearTimeout(nt),nt=null);try{if(Ee)try{Ee.abort()}catch{}try{t.end()}catch{}try{await e}catch{}return ye=null,re&&(se=re),!de}finally{Ae=!1}},async abort(){if(!Ge){Ge=!0;try{const e=$e,t=e?Oe:null;(Pe||e)&&(qe++,e||($e=!1),lt(),Fe?.failure({aborted:!0}),e&&(clearTimeout(Be),Be=null,ue=!1),Xe=!0,Ze=qe,clearTimeout(et),et=setTimeout(()=>{Xe=!1,Ze=null},6e3));try{await(ye?.interrupt?.())}catch{}if(t)try{await t}catch{}e&&($e=!1),(Pe||e)&&(Pe=!1,it({kind:"result",subtype:"aborted",sessionId:se}))}finally{Ge=!1}}},end(){de=!0,lt(),clearInterval(ut),clearTimeout(et),clearTimeout(Be),nt&&clearTimeout(nt),ne.end();try{oe.abort()}catch{}},get sessionId(){return se},get mode(){return ke},get turnActive(){return Pe}}}
1
+ import{randomUUID as e}from"node:crypto";import{createRequire as t}from"node:module";import{readFileSync as o}from"node:fs";import{dirname as n,join as s}from"node:path";import{query as r}from"@anthropic-ai/claude-agent-sdk";import{sanitizeSession as i}from"./transcript-sanitize.mjs";import{reviewGatePreToolDecision as a}from"./flow-review-gate.mjs";import{crossPostNeedsCard as l}from"./cross-terminal.mjs";import{correctContext as c}from"./context-windows.mjs";import{normalizeClaudeCommandCatalog as d}from"./claude-command-catalog.mjs";import{evidenceForToolResult as u}from"./evidence-citations.mjs";import{THINKPOOL_CASCADE_RULE as p,THINKPOOL_REMOTE_DELIVERY_RULES as m,THINKPOOL_RUNTIME_AUTHORITY_RULE as h,THINKPOOL_RUNTIME_TURN_REMINDER as f,buildThinkPoolTurnGuidance as y,createRoomContextSelector as k,normalizeThinkPoolTurnCause as w,usesFullThinkPoolReminder as g}from"./thinkpool-room-prompt.mjs";import{stallDecision as b,stallEvent as v,isCompactTurn as _}from"./turn-stall.mjs";import{createSameTargetResilienceController as T,formatResilienceTrace as S}from"./provider-resilience.mjs";import{catastrophicPreToolHookDecision as E}from"./catastrophic-command-guard.mjs";const N=t(import.meta.url);export async function claudeOneShot({prompt:e,model:t="claude-haiku-4-5",cwd:o,env:n,timeoutMs:s=8e3}={}){const i=new AbortController,a=setTimeout(()=>{try{i.abort()}catch{}},s);try{const s=r({prompt:e,options:{model:t,...o?{cwd:o}:{},env:n,maxTurns:1,permissionMode:"bypassPermissions",settingSources:[],strictMcpConfig:!0,mcpServers:{},abortController:i}});let a="";for await(const e of s){if("assistant"===e.type)for(const t of e.message?.content||[])"text"===t.type&&(a+=t.text);if("result"===e.type)break}return a.trim()}finally{clearTimeout(a)}}const O=(()=>{try{let e=n(N.resolve("@anthropic-ai/claude-agent-sdk"));for(let t=0;t<8;t++){try{const t=JSON.parse(o(s(e,"package.json"),"utf8"));if("@anthropic-ai/claude-agent-sdk"===t.name)return t.version}catch{}const t=n(e);if(t===e)break;e=t}}catch{}return"unknown"})(),R=/\brm\s+\S|\brmdir\s+\S|\bgit\s+(push\s+(-f|--force)|reset\s+--hard|clean\s+-[a-z]*f)|\bdrop\s+(table|database)\b|\b(mkfs|dd)\b|\bsudo\b|>\s*\/dev\/|\bchmod\s+-R|\bchown\s+-R|\bkillall\b|\btruncate\b/i,A=new Set(["Read","Grep","Glob","NotebookRead","TodoRead","LS"]),D=new Set(["WebFetch","WebSearch"]),x=new Set(["Edit","Write","MultiEdit","NotebookEdit","TodoWrite"]);export function classifyRisk(e,t){if("Bash"===e){const e=t&&(t.command??t.cmd)||"";return R.test(e)?"high":"medium"}return A.has(e)?"low":D.has(e)?"network":(x.has(e),"medium")}const P=/(^|\/)\.claude\/SESSIONS\/|(^|\/)CLAUDE\.md$/;export function isSafeDocWrite(e,t){if(!x.has(e))return!1;const o=t&&(t.file_path||t.notebook_path)||"";return P.test(o)}export function autoAllow({toolName:e,input:t,mode:o="default",alwaysAllow:n=new Set}){const s=classifyRisk(e,t);return"low"===s||"bypassPermissions"===o||"acceptEdits"===o&&x.has(e)&&"high"!==s||isSafeDocWrite(e,t)||n.has(`${e}:${s}`)}export function askUserQuestionHookOutput(e){const t=e&&"object"==typeof e?e.decision:e,o="string"==typeof t&&t.startsWith("answer:")?t.slice(7):"",n=e&&"object"==typeof e?e.responder:null,s="string"==typeof n?.name&&n.name.trim()?n.name.trim():"string"==typeof n?.id&&n.id?`room member ${n.id}`:"The user";return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:o?`${s} answered in the thinkpool room — ${o}. Treat this as their selection and continue; do not call AskUserQuestion again for the same question.`:"The user dismissed the question in the thinkpool room without selecting. Ask in plain prose, or proceed with a sensible default."}}}export function askUserQuestionRegression(e,t){return Array.isArray(e)?e.includes("AskUserQuestion")?null:`[SDK-REGRESSION] agent SDK v${t||"unknown"} init tools[] is missing 'AskUserQuestion' — the multiple-choice question card is disabled. A caret SDK bump likely changed the canUseTool gate; pin a known-good SDK in bridge/package.json + republish.`:null}function I(){const e=[];let t=null,o=!1;return{stream:async function*(){for(;!o;)e.length?yield e.shift():await new Promise(e=>{t=e})}(),push:n=>!o&&(e.push({type:"user",message:{role:"user",content:n}}),t&&(t(),t=null),!0),end(){o=!0,t&&(t(),t=null)}}}const C=(e=[])=>e.map(e=>"text"===e.type?{type:"text",text:e.text}:"thinking"===e.type?{type:"thinking",text:e.thinking||"",reasoningKind:"thought"}:"tool_use"===e.type?{type:"tool_use",id:e.id,name:e.name,input:e.input}:{type:e.type}).filter(Boolean),M=new Set(["default","acceptEdits","plan","bypassPermissions"]),U=["You are Claude in a thinkpool Code room, driven live from a phone or browser — NOT a local terminal. Keep using the room's features.",f,"TERMINAL HIERARCHY: obey your authoritative TERMINAL ROLE. A person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal — NEVER spawn_terminal — even for ordinary work or a handoff. If the wording includes new or separate terminal, main-terminal routing wins. Use spawn_terminal only for agent-decided bounded worker slices or when the person explicitly asks for a worker, sub-terminal, Ensemble lane, or delegated slice. If open_main_terminal is unavailable, say so; never substitute an Ensemble child. Leaf, worker, Side, and managed Flow lanes work directly. Never use built-in invisible Task/Agent subagents or hijack a busy sibling.","WORKTREES: parallel lanes share one repo — before code edits run `git worktree list`; if linked worktrees exist, take your OWN worktree + branch, never the shared checkout or a branch another lane is on.","BUILD WORKFLOW (default, no magic word): right-size within your TERMINAL ROLE — a trivial ask or delegated slice you just do; a conductor-capable role with a genuinely decomposable build FIRST writes a short plan in chat, THEN fans worker slices into visible spawn_terminal lanes and verifies them. Worker/leaf/Side/managed Flow roles do not fan out. A person-requested new or separate terminal uses open_main_terminal. Never plan-mode/ExitPlanMode; plans live in chat and lanes in the existing list."].join(" ");export function startClaudeSession({cwd:t,model:o,effort:n="high",resume:s,env:f,mode:N="default",onEvent:R,requestPermission:A,mcpServers:D,crossPostGate:x,crossRoomPostGate:P,didSpawnTarget:L=null,terminalRolePrompt:W,rolePrompt:F,blockSubagents:j=!1,onSubmitPlan:$=null,onLaneDone:q=null,onReviewVerdict:G=null,reviewGate:B=null,lazy:H=!1,roomContext:K=null,suggest:Q=!0,prepareCwd:Y=null,admitStart:z=null,resilienceObserver:J=null,resilience:V=null}){const X=k(K);let Z=0,ee=!0;const te=(e,{promptIndex:t=0,forceFull:o=!1,turnCause:n=null}={})=>{const s=g({promptIndex:t,forceFull:o,turnCause:n}),r=X({force:s}),i=String(W||"").trim();return`<system-reminder>\n${s&&i?`${i}\n\n`:""}${s?U:y({text:e,promptIndex:t,forceFull:o,turnCause:n})}${r?`\n\n${r}`:""}\n</system-reminder>`},oe=new AbortController;let ne=I(),se=s||null,re=s||null,ie=null,ae=null,le=null,ce=null,de=!1,ue=!1,pe=null,me=!1,he=!1,fe=!1,ye=null,ke=M.has(N)?N:"default";const we=new Set,ge=new Map,be=new Set(["low","medium","high","xhigh","max"]);let ve=be.has(n)?n:"high",_e=0,Te=0,Se=o||null,Ee=null,Ne=null,Oe=Promise.resolve(),Re=!1,Ae=!1;const De=e=>new Promise(t=>setTimeout(t,e)),xe=Math.max(3e4,parseInt(process.env.TP_STALL_MS,10)||9e4);let Pe=!1,Ie=Date.now(),Ce=!1;const Me=/connection closed|connection reset|econnreset|etimedout|socket hang up|fetch failed|network error|socket destroyed/i;let Ue=0;const Le=(e,t={})=>{try{J?.({reason:e,restartCount:Ue,...t})}catch{}},We=!(!V?.policy?.enabled||!V?.providerId||"anthropic"===V.providerId);let Fe=null,je=null,$e=!1,qe=0,Ge=!1,Be=null;const He=Math.max(3*xe,parseInt(process.env.TP_FORCE_STOP_MS,10)||3e5);let Ke=!1,Qe=!1;const Ye=Math.max(He,parseInt(process.env.TP_COMPACT_FORCE_STOP_MS,10)||12e5);let ze=!1,Je=0;const Ve=A;A=async e=>{Je++;try{return await(Ve?.(e))}finally{Je=Math.max(0,Je-1),Ie=Date.now()}};let Xe=!1,Ze=null,et=null,tt=!1,ot="",nt=null;const st=Math.max(1200,parseInt(process.env.TP_SUGGEST_FALLBACK_MS,10)||2500),rt=e=>{try{R?.(e)}catch{}},it=e=>{Ie=Date.now(),e&&"stalled"!==e.kind&&(Ce=!1),!e||"compaction"!==e.kind&&"result"!==e.kind&&"error"!==e.kind||(ze=!1),rt(e)},at=e=>{try{V?.onRecord?.(e)}catch{}"retrying"!==e?.outcome&&"cap_blocked"!==e?.outcome&&"circuit_open"!==e?.outcome||it({kind:"note",text:S(e)})},lt=()=>{if(null!=je){try{(V?.clearTimer||clearTimeout)(je)}catch{}je=null}},ct=()=>{if(lt(),!Fe)return;const e=Number(V?.policy?.timeoutMs);if(!Number.isFinite(e)||e<=0)return;const t=V?.setTimer||setTimeout;je=t(()=>{if(je=null,!de&&Fe&&Pe){Fe.failure({message:"timeout"}),Pe=!1;try{Ee?.abort()}catch{}gt()}},e)},dt=async()=>{if(!Fe)return!0;let e=null;try{e=await Fe.preflight()}catch{return!1}return!0===e?.admitted},ut=setInterval(()=>{const e=Date.now()-Ie,t=b({turnActive:Pe,awaitingUser:Je,quietMs:e,stallMs:xe,forceStopMs:He,stalledSent:Ce,stallRetried:Qe,compacting:ze,compactForceStopMs:Ye});if("none"===t)return;const o=v(t,e);if(o&&rt(o),"status"!==t){if("retry"===t){if(Ke=!0,Fe){Le("resilience_stall",{quietMs:e}),Fe.failure({message:"timeout"}),Pe=!1;try{Ee?.abort()}catch{}return void gt()}return Le("stall_replay",{quietMs:e}),void wt(e)}Ke=!0,Pe=!1}else Ce=!0},5e3);ut.unref?.();const pt=e=>{setTimeout(()=>{Promise.resolve(ye?.setPermissionMode?.(e)).catch(t=>console.error(`[claude-session] setPermissionMode(${e}) failed:`,t?.message||t))},0)},mt={abortController:oe,permissionMode:ke,hooks:{PreToolUse:[{hooks:[async o=>{const n=o.tool_name,s=o.tool_input,r=E({toolName:n,input:s,cwd:t});if(r)return r;const i=o.effort?.level;i&&i!==ve&&(ve=i,it({kind:"effort",level:ve}));const c="Write"===n||"Edit"===n||"MultiEdit"===n||"NotebookEdit"===n;if(j&&c&&/(?:^|[/\\])FLOW_PLAN\.json$/i.test(s?.file_path||s?.notebook_path||"")){const e=s?.content??s?.new_string??"";let t={ok:!1,message:"Plan submission is not wired for this session."};try{t=$&&await $(e)||t}catch(e){t={ok:!1,message:`Plan submission failed: ${e?.message||e}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.message}}}if(j&&("Task"===n||"Agent"===n||"Bash"===n||c))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Bash"===n?"Flow conductors do NOT run Bash — it pops a permission card and stalls the flow. Use the Grep tool (not `grep`/`rg`), the Glob tool (not `find`/`ls`), and Read (not `cat`/`head`) — those run with no prompt. Then DECOMPOSE and submit by Writing your task-graph JSON to the file FLOW_PLAN.json.":c?'Flow conductors do NOT write project or plan-document files. Do NOT use ExitPlanMode and do NOT call submit_flow_plan (both hang here). To SUBMIT your decomposition, use the Write tool with file_path "FLOW_PLAN.json" and content = your task-graph JSON ({"summary":"…","tasks":[…]}). That single Write IS how you submit — the room ingests it directly. Do not write any other file.':"Flow conductors do NOT spawn subagents — it stalls the flow on a permission card. Inspect the codebase yourself with Read/Grep/Glob (no prompt). Then DECOMPOSE and submit by Writing your task-graph JSON to the file FLOW_PLAN.json. Do not call Task/Agent again."}};if(G&&("Write"===n||"Edit"===n)&&/(?:^|[/\\])FLOW_REVIEW(\.[a-zA-Z0-9]+)?$/.test(s?.file_path||"")){let e={ok:!1,message:"verdict signal failed"};try{e=await G(s?.content??s?.new_string??"")||e}catch(t){e={ok:!1,message:`verdict signal failed: ${t?.message||t}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.message}}}if(q&&("Write"===n||"Edit"===n)&&/(?:^|[/\\])FLOW_DONE(\.[a-zA-Z0-9]+)?$/.test(s?.file_path||"")){let e={ok:!1,message:"done signal failed"};try{e=await q(s?.content??s?.new_string??"")||e}catch(t){e={ok:!1,message:`done signal failed: ${t?.message||t}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.message}}}const d=a({reviewGate:B,toolName:n,toolInput:s});if(d)return d;if("mcp__thinkpool__read_terminal"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (read-only thinkpool cross-terminal read)."}};if(/^mcp__thinkpool__preview_(start|capture|inspect|stop)$/.test(n))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (contained bridge-owned viewport preview)."}};if("mcp__thinkpool__attach_file"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (workspace-contained file attachment to this thinkpool room)."}};if("mcp__thinkpool__submit_flow_plan"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (Flow plan submission — broadcasts the task-graph for human approval)."}};if("mcp__thinkpool__list_sessions"===n||"mcp__thinkpool__read_session"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (read-only thinkpool cross-session read — your own rooms)."}};if("mcp__thinkpool__close_terminal"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (thinkpool cross-terminal close — only self-spawned lanes)."}};if("mcp__thinkpool__spawn_terminal"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (autonomous thinkpool worker; bounded by room caps and isolated in its own worktree)."}};if("mcp__thinkpool__open_main_terminal"===n){const t=s?.mode||ke;if("bypassPermissions"!==t||"bypassPermissions"===ke)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Auto-approved (open a fresh thinkpool terminal in ${t} mode — inherited, no escalation; bounded by room caps).`}};let o="deny";try{o=await(A?.({id:e(),toolName:n,input:{...s,mode:t},risk:"high"}))??"deny"}catch{o="deny"}const r="allow"===o;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:r?"allow":"deny",permissionDecisionReason:r?"Bypass terminal creation approved in the thinkpool room — the new terminal runs autonomously.":"Bypass terminal creation denied in the room — do not retry as bypass; open it without mode:bypassPermissions or ask what to do."}}}if("mcp__thinkpool__post_to_terminal"===n){const t=x?x():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-terminal post not allowed right now."}};const o=!!L&&!!L(s?.terminal);if(!l({mode:ke,spawnedByMe:o}))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"bypassPermissions"===ke?"Auto-approved (cross-terminal post in bypassPermissions mode — bypass means bypass).":"Auto-approved (cross-terminal post into a lane you spawned — parent→child orchestration, no per-post tap)."}};let r="deny";try{r=await(A?.({id:e(),toolName:n,input:s,risk:"high"}))??"deny"}catch{r="deny"}const i="allow"===r;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:i?"allow":"deny",permissionDecisionReason:i?"Cross-terminal post approved in the thinkpool room.":"Cross-terminal post denied in the room — do not retry; ask what to do instead."}}}if("mcp__thinkpool__post_to_session"===n){const t=P?P():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-room post not allowed right now."}};let o="deny";try{o=await(A?.({id:e(),toolName:n,input:s,risk:"high"}))??"deny"}catch{o="deny"}const r="allow"===o;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:r?"allow":"deny",permissionDecisionReason:r?"Cross-room post approved in the sending room — the target room will be asked to accept it.":"Cross-room post denied in the room — do not retry; ask what to do instead."}}}if("ExitPlanMode"===n){if("plan"!==ke)return pt(ke),it({kind:"mode",mode:ke}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`The thinkpool room is in ${ke} mode, not Plan — the user did not ask for a plan. Do NOT call ExitPlanMode; proceed and make the changes directly. Only present a plan if the user switches the room to Plan mode or explicitly asks.`}};let t="keep";try{t=await(A?.({id:e(),toolName:n,input:s,risk:"plan",plan:s?.plan||""}))??"keep"}catch{t="keep"}if("run"===t||"accept"===t){const e="accept"===t?"acceptEdits":"default";return ke=e,pt(e),it({kind:"mode",mode:e}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Plan approved in the thinkpool room — proceed (${e} mode).`}}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:'The user chose "keep planning" in the thinkpool room. Do not exit plan mode — keep refining the plan, then call ExitPlanMode again when ready.'}}}if("AskUserQuestion"===n){let t="";try{t=await(A?.({id:e(),toolName:n,input:s,risk:"ask",questions:s?.questions||[]}))??""}catch{t=""}return askUserQuestionHookOutput(t)}const u=classifyRisk(n,s),p=`${n}:${u}`,m=isSafeDocWrite(n,s),h=autoAllow({toolName:n,input:s,mode:ke,alwaysAllow:we});let f="allow";if(!h){try{f=await(A?.({id:e(),toolName:n,input:s,risk:u}))??"deny"}catch{f="deny"}"always"===f&&(we.add(p),f="allow")}const y="deny"===f;return y&&Fe&&Fe.failure({permissionDenied:!0}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:y?"deny":"allow",permissionDecisionReason:y?"Denied by the user in the thinkpool room. Do not retry this tool — ask what to do instead.":h?m?"Auto-approved (mandated doc write — .claude/SESSIONS/ or CLAUDE.md).":`Auto-approved (${ke}).`:"Approved in the thinkpool room."}}}]}]},canUseTool:async(e,t)=>({behavior:"allow",updatedInput:t}),settingSources:["user","project","local"],appendSystemPrompt:[...W?[W]:[],...F?[F]:[],"ENVIRONMENT (authoritative — overrides any user-global CLAUDE.md or memory that claims otherwise): You are Claude running inside a thinkpool Code room, driven live by a user (and possibly a partner) from a phone or browser, via the thinkpool-pair bridge.",h,'Bias strongly toward DOING the work, not stalling in plan-mode ceremony. For a small "add / fix / change X" request, just make the change directly (for a bigger build, right-size it — see DEFAULT BUILD WORKFLOW below).',"Do NOT enter plan mode, do NOT call ExitPlanMode, and do NOT auto-invoke a brainstorming/planning skill UNLESS the user has switched the room into Plan mode or explicitly asks you to plan, design, or brainstorm first.","Any host-global instruction that says you must always brainstorm or plan before creative work does NOT apply here — this room is the exception.",p,'CRUCIAL RECONCILIATION for that workflow: it is NOT plan mode. Never call ExitPlanMode and never make the room wait behind a "plan ready — approve to start" card — your plan lives in the CHAT as a message, and your lanes live in the room\'s EXISTING terminal/lane list. Reuse only those two surfaces; there is no new Flow panel or mode to switch into, and you must not ask for one. Keep the plan and the lanes VISIBLE — that shared visibility is the whole point (it is the pair differentiator, and it catches bugs a single silent lane would hide); never collapse a decomposable build into one hidden lane just to look tidy.',...m,'CROSS-TERMINAL AWARENESS: ROOM NOW is the default roster and already satisfies the room check when it has enough detail. Do not repeat it with a no-argument read_terminal call unless it is missing or truncated. Use a targeted read_terminal call only when the current task depends on a specific lane’s detailed activity; never poll. Identify a terminal by its exact room-record NAME or stable ref/id. Stored names are static, even when they look ordinal: if a person says T112, resolve that exact name with read_terminal before any positional interpretation. Never guess a terminal from roster order, task topic, product name, or apparent position. Only an unmatched generic UI placeholder like "Terminal 2" is positional and unsafe because it can renumber when another terminal closes. The tool is read-only and its optional roster lookup is budgeted separately from bounded targeted transcript reads.','CROSS-TERMINAL HAND-OFF: you also have post_to_terminal(terminal, text) to send a message or task to ANOTHER AGENT terminal in this room (not a plain shell). Use it sparingly and only when the people clearly want the lanes to coordinate — e.g. "tell the backend terminal the API is ready", or to hand a sibling agent a concrete task. Every post requires a person in the room to approve a card before it is delivered, and an agent that was itself reached via a cross-post cannot post onward — so do not rely on it for chit-chat or loops. Prefer read_terminal to understand a sibling before you ever post to it.',"TERMINAL CREATION CONTRACT: main terminals and workers use different tools. A person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal(name?, task?, model?) — even for ordinary work or a handoff and even without the words Cascade or conductor. If the wording includes new or separate terminal, main-terminal routing wins. Never use spawn_terminal for that request, and if open_main_terminal is unavailable say so instead of substituting. Use spawn_terminal(name?, task?, model?, sliceType?) only for agent-decided bounded WORKER SUB-TERMINALS or when the person explicitly asks for a worker, sub-terminal, Ensemble lane, or delegated slice. Workers never receive the creation tools and never conduct. Do not dump work into busy siblings. Spawned workers are always autonomous in bypassPermissions and never ask the room for an approval card; the bridge still enforces room caps, hop limits, the kill-switch, and isolated linked worktrees. Wait for ROOM NOW or a completion signal instead of polling; after a worker finishes, collect it with one targeted read_terminal call and leave it visible until a person dismisses it with the Ensemble X. Never call close_terminal merely because work finished. Main terminals are independent, keep their requested permission mode, and are not owned/closed through Ensemble.","CROSS-SESSION AWARENESS: the Ensemble reaches across your SESSIONS, not just the terminals in this room. list_sessions() lists your OTHER thinkpool Code rooms — both your own rooms running on this machine AND your partner's rooms in the same pair, reachable over the per-pair bus (a room on the partner's machine shows its host). read_session(session, terminal?) reads recent activity inside one (omit `terminal` to list that room's terminals, or pass a ref/name to read that lane). Both are READ-ONLY — they never change another session, and they reach ONLY your own rooms and rooms you share with your partner, never a stranger's. Reach for them when work spans rooms — \"what's the other project up to\", \"pick up where the other session left off\", or to check a long-running task elsewhere before you act here.","CROSS-SESSION HAND-OFF: post_to_session(session, text, terminal?) sends a task or message to an agent in ANOTHER of your rooms — your own, or your partner's over the pair bus. Use it sparingly and only when the people clearly want the rooms to coordinate — e.g. hand the API room's agent a concrete follow-up once the frontend is ready. It is dual-consent: a person in YOUR room approves sending, and a person in the TARGET room approves receiving, before anything is delivered — so never rely on it for chit-chat or loops, and an agent that was itself reached via a cross-room post cannot post onward to a third room. It spends real model tokens in the other room (maybe on the other person's machine), so prefer read_session to understand a room before you ever post into it, and only post one concrete hand-off at a time. Outbound list/read/post tools need the thinkpool account bridge; a standalone owner room can still receive a paired hand-off directly and will always raise its own approval card before delivery.","SUBAGENT POLICY: in this room, a main terminal delegates worker slices through visible spawn_terminal Ensemble lanes. A person-requested new or separate terminal is created with open_main_terminal, never Ensemble. Worker, leaf, Side, and managed Flow lanes do their assigned work directly. Do NOT reach for built-in Task/Agent subagents: an in-process subagent is invisible to the room, cannot be peered at or steered, and its work is lost to the Ensemble.",'RESEARCH LANE: you have a `research` tool that runs a REAL multi-source web search + adversarial verification and returns each claim marked HELD or REJECTED with citations. Reach for it when the people would genuinely benefit from looking something external up or settling a question of current fact — pricing, "is X still maintained / deprecated", "is that benchmark real", a debate over facts you are not sure of. Do NOT run it unprompted or for things you already know: first OFFER in plain language ("want me to spawn a research lane on that and check it?"), and only call `research(question)` once they agree — it spends real budget (plan-gated Free 5 / Plus 100 runs a month) and takes ~a minute. When it returns, present the held/rejected findings clearly and invite both people to weigh the sources, flagging any held claim that rests on a source they might not trust — that shared scrutiny is the point.',"WORKTREES: parallel lanes share one machine and usually one repo. Run `git worktree list` before your first code edit; if linked worktrees exist, the shared main checkout is contended (and may be guard-blocked) — do your work in your OWN worktree on your OWN branch (`git worktree add <dir> -b <branch>`), and never edit a checkout or ride a branch another lane is using.",'WRITE PLANS INTO THE CHAT: whenever you form or revise a plan — because the room is in Plan mode, or because someone asked you to plan, design, or think it through first — write the actual plan out as a normal message in the room as you develop it: the approach, the concrete steps, the files you will touch, the open questions. The room does NOT surface plan files at all, and the plan-approval card does not reliably carry the plan text, so a plan that lives only in a plan file or only inside ExitPlanMode is INVISIBLE to the people you are working with — they just see "plan ready" with no content. The chat is the canonical place your plan lives; put it there so the room can read and react to it before you proceed.'].join(" "),includePartialMessages:!0,promptSuggestions:!0};"1"===process.env.TP_MCP_STRICT&&(mt.strictMcpConfig=!0,mt.mcpServers={}),D&&Object.keys(D).length&&(mt.mcpServers={...mt.mcpServers||{},...D}),t&&(mt.cwd=t),o&&(mt.model=o),mt.effort=ve,mt.env={...f||process.env,CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION:"1"};const ht=async()=>{if(!Q||"worker_completion"===ae)return;const e=(ot||"").trim().slice(-1500);if(e&&!de)try{let o=await claudeOneShot({prompt:`You are predicting the user's NEXT chat message in a live coding session, to prefill their composer. Given the assistant's latest reply below, output the single most likely next user message — short and natural (often just "proceed", "go with option A", "yes do that", or a brief follow-up). One line, <=12 words, imperative, no preamble, no quotes, no markdown.\n\nAssistant's latest reply:\n"""\n${e}\n"""\n\nNext user message:`,model:"claude-haiku-4-5",cwd:t,env:mt.env,timeoutMs:8e3});o=o.trim().split("\n")[0].replace(/^["'`]+|["'`]+$/g,"").trim().slice(0,140),!o||tt||de||/^(sure|of course|certainly|let me know|i can help|happy to)\b/i.test(o)||(it({kind:"suggestion",text:o,source:"haiku"}),process.stderr.write(` ◆ [suggestion] haiku fallback: ${JSON.stringify(o)}\n`))}catch{}},ft=()=>{const e="function"==typeof z?z():{ok:!0};return!1!==e?.ok||(it({kind:"error",message:e.reason||"Host memory is critically low. This agent runtime was not started.",recoverable:!0}),!1)},yt=async({admitted:e=!1}={})=>{if(Ae)return!1;if(!ue&&!e&&!ft())return!1;if(null==pe&&(pe=Date.now()),ue=!0,Ne)try{Ne()}catch{}Oe=new Promise(e=>{Ne=e});const n=new AbortController;Ee=n;const a=()=>{try{n.abort()}catch{}};oe.signal.addEventListener("abort",a,{once:!0});try{if(se){const e=i(t||process.cwd(),se);e.blocks&&process.stderr.write(`\n ◆ healed ${e.blocks} malformed tool block(s) in the transcript before resume.\n`)}ye=r({prompt:ne.stream,options:{...mt,abortController:n,...se?{resume:se}:{}}});for await(const e of ye){if(de)break;switch(e.type){case"system":if("thinking_tokens"===e.subtype){_e+Te===0&&it({kind:"thinking_tokens",tokens:e.estimated_tokens,delta:e.estimated_tokens_delta});break}if("compact_boundary"===e.subtype){ee=!0,it({kind:"compaction",trigger:e.compact_metadata?.trigger||"auto",preTokens:e.compact_metadata?.pre_tokens??null}),(async()=>{try{const e=await(ye?.getContextUsage?.());e&&(it({kind:"usage",ctx:c({used:e.totalTokens,max:e.maxTokens,pct:Math.round(e.percentage),model:e.model})}),e.model&&(Se=e.model))}catch{}})();break}if(e.session_id&&(se=e.session_id),me||(me=!0,process.stderr.write(`\n ◆ session ready in ${Date.now()-pe}ms — MCP ${"1"===process.env.TP_MCP_STRICT?"OFF":"on"}${s?", resume":", fresh"}.\n`)),Se=mt.model||e.model||o||Se,it({kind:"system",sessionId:se,model:mt.model||e.model||o||null,commands:d({slashCommands:e.slash_commands,skills:e.skills})}),!fe&&Array.isArray(e.tools)){fe=!0;const t=askUserQuestionRegression(e.tools,O);t&&(process.stderr.write(`\n ⚠⚠ ${t}\n`),it({kind:"error",message:t}))}he||(he=!0,Promise.resolve(ye?.supportedModels?.()).then(e=>{const t=(e||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);t.length&&it({kind:"models",models:t})}).catch(()=>{}));break;case"assistant":lt(),Fe?.visibleOutput();for(const t of e.message?.content||[])"tool_use"===t?.type&&t.id&&ge.set(t.id,{at:Date.now(),name:t.name,input:t.input});{const t=(e.message?.content||[]).filter(e=>"text"===e?.type).map(e=>e.text).join("\n").trim();t&&(ot=t)}it({kind:"assistant",blocks:C(e.message?.content),parentToolUseId:e.parent_tool_use_id||null});break;case"user":for(const t of e.message?.content||[])if("tool_result"===t?.type){lt(),Fe?.visibleOutput({tool:!0});const o=ge.get(t.tool_use_id);null!=o&&ge.delete(t.tool_use_id);const n=u(o?.name,t.content);it({kind:"tool_result",toolUseId:t.tool_use_id,content:t.content,...n?{evidence:n}:{},isError:!!t.is_error,durationMs:null!=o?.at?Date.now()-o.at:void 0,parentToolUseId:e.parent_tool_use_id||null})}break;case"stream_event":{const t=e.event;"message_start"===t?.type?(_e+=Te,Te=t.message?.usage?.output_tokens||0,it({kind:"thinking_tokens",tokens:_e+Te})):"message_delta"===t?.type&&t.usage&&(Te=t.usage.output_tokens??Te,it({kind:"thinking_tokens",tokens:_e+Te}));break}case"result":if(lt(),e.session_id&&(se=e.session_id),e.is_error&&Array.isArray(e.errors)&&e.errors.some(e=>/no conversation found/i.test(String(e)))&&(se||re)&&Ue<3){Ue++;const e=Pe;Pe=!1,se=null,re=null,it({kind:"note",text:"previous session not found — continuing on a fresh one"});const t=ne;ne=I();try{t.end()}catch{}const o=e?ie:null;Be=setTimeout(()=>{Be=null,de||(yt(),null!=o&&(Pe=!0,Ie=Date.now(),Ce=!1,ne.push([{type:"text",text:o},{type:"text",text:le||te(o,{forceFull:!0})}])))},300);break}if(Xe&&("aborted"===e.subtype||"error_during_execution"===e.subtype)){qe===Ze&&(Pe=!1);break}if(e.is_error&&Fe){if($e)break;Fe.failure({message:Array.isArray(e.errors)?e.errors.join(" "):e.result,status:e.status??e.statusCode,code:e.code}),Pe=!1,gt();break}if(_e=0,Te=0,Pe=!1,Re&&(Re=!1,setTimeout(()=>{de||kt()},0)),"success"===e.subtype&&(Ue=0,se&&(re=se)),"success"===e.subtype&&(Fe?.success(),Fe=null),Ke=!1,Qe=!1,e.modelUsage&&"object"==typeof e.modelUsage){let t=null,o=-1;for(const[n,s]of Object.entries(e.modelUsage)){const e=s?.outputTokens??0;e>o&&(o=e,t=n)}t&&(Se=t)}{const t="string"==typeof e.result?e.result.replace(/\s+/g," ").trim().slice(0,200):"";it({kind:"result",subtype:e.subtype,sessionId:se,model:Se,costUsd:e.total_cost_usd,usage:e.usage,numTurns:e.num_turns,durationMs:e.duration_ms??null,denials:Array.isArray(e.permission_denials)?e.permission_denials.length:0,resultText:t||null})}nt&&clearTimeout(nt),"aborted"!==e.subtype&&"worker_completion"!==ae&&(nt=setTimeout(()=>{nt=null,tt||de||ht()},st)),(async()=>{let t=null;try{const e=await(ye?.getContextUsage?.());e&&(t=c({used:e.totalTokens,max:e.maxTokens,pct:Math.round(e.percentage),model:e.model}),e.model&&(Se=e.model))}catch{}const o=e.usage||{};it({kind:"usage",costUsd:e.total_cost_usd??null,tokens:(o.input_tokens||0)+(o.output_tokens||0),ctx:t})})();break;case"prompt_suggestion":nt&&(clearTimeout(nt),nt=null),e.suggestion&&(tt=!0,it({kind:"suggestion",text:e.suggestion}))}}}catch(e){if(lt(),de)return;if(n.signal.aborted)return;const t=e?.message||String(e);if(Fe&&Pe)return Fe.failure({message:t,status:e?.status??e?.statusCode,code:e?.code}),Pe=!1,void gt();if(Pe=!1,it({kind:"error",message:t}),Me.test(t)&&Ue<3){Ue++,Le("stream_reconnect",{failureClass:"network"}),it({kind:"note",text:`connection dropped — reconnecting (${Ue}/3)`});const e=ne;ne=I();try{e.end()}catch{}return void(Be=setTimeout(()=>{Be=null,de||yt()},Math.min(1e3*Ue,4e3)))}if(/no conversation found/i.test(t)&&se&&Ue<3){Ue++,se=null,re=null;const e=ne;ne=I();try{e.end()}catch{}return void(Be=setTimeout(()=>{Be=null,de||yt()},300))}de=!0}finally{oe.signal.removeEventListener("abort",a),Ee===n&&(Ee=null);try{await(ye?.return?.())}catch{}Ne&&(Ne(),Ne=null)}},kt=async()=>{if(de||Ae||!ue)return;const e=Oe,t=ne;if(ne=I(),Ee)try{Ee.abort()}catch{}try{t.end()}catch{}try{await e}catch{}await De(300),se=re,de||Ae||yt()},wt=async e=>{if(de)return;Qe=!0;const t=Pe&&!_(ie)?ie:null;Pe=!1;const o=Oe,n=ne;if(ne=I(),Ee)try{Ee.abort()}catch{}try{n.end()}catch{}try{await o}catch{}await De(300),se=re,de||(yt(),null!=t&&(Pe=!0,Ie=Date.now(),Ce=!1,ne.push(/^\s*\//.test(t)?[{type:"text",text:t}]:[{type:"text",text:t},{type:"text",text:le||te(t,{forceFull:!0})}]),rt({kind:"note",text:"retrying the stalled turn on a fresh connection"})))},gt=()=>{if(de||Ge||$e)return;const e=Fe,t=qe,o=ce;$e=!0;const n=Oe,s=ne;ne=I();try{s.end()}catch{}Be=setTimeout(async()=>{Be=null;try{await n}catch{}if(!de&&$e&&Fe===e&&qe===t)return await dt()?void(!de&&$e&&Fe===e&&qe===t&&($e=!1,Pe=!0,Ie=Date.now(),Ce=!1,yt(),o&&ne.push(o),ct())):($e=!1,void bt())},0)},bt=()=>{lt(),Pe=!1,Fe=null,ue=!1,it({kind:"error",message:"The configured provider could not complete this turn. Nothing else was sent.",recoverable:!0})};return H||We||yt(),{sendTurn(e,n={}){if(de||Ae||Ge||$e)return!1;if(!ue&&!ft())return!1;if(!ue&&Y)try{const e=Y();e&&(t=e,mt.cwd=e)}catch{}Pe=!0,tt=!1,ie=String(e),ae=w(n?.turnCause),nt&&(clearTimeout(nt),nt=null),Ie=Date.now(),Ce=!1,Qe=!1,Ke=!1;const s=String(e),r=Z++,i=ee;if(ee=/^\s*\/(?:compact|clear|reset)\b/i.test(s),le=/^\s*\//.test(s)?null:te(s,{promptIndex:r,forceFull:i,turnCause:ae}),ze=_(s),ce=/^\s*\//.test(s)?[{type:"text",text:s}]:[{type:"text",text:s},{type:"text",text:le}],qe++,Fe=(()=>{if(!We)return null;try{const e=T({runtime:"claude",providers:V.providers||[],providerId:V.providerId,model:V.model||mt.model||o,requestedModel:V.requestedModel||V.model||mt.model||o,policy:V.policy,bridgeHostId:V.bridgeHostId,circuit:V.circuit,capGate:V.capGate,traceId:V.traceId,turnRev:"function"==typeof V.turnRev?V.turnRev():V.turnRev,onRecord:at});return e.start(),e}catch{return null}})(),Fe){const e=Fe,t=qe,o=ce;dt().then(n=>{!de&&Pe&&Fe===e&&qe===t&&(n?(ue||yt({admitted:!0}),ne.push(o),ct()):bt())}).catch(()=>{!de&&Pe&&Fe===e&&qe===t&&bt()})}else ue||yt({admitted:!0}),ne.push(ce)},warm(){We||ue||de||Ae||yt()},get started(){return ue},async setMode(e){M.has(e)&&!de&&(ke=e,pt(e),it({kind:"mode",mode:ke}))},async setModel(e){mt.model=e,Se=e,it({kind:"note",text:`model → ${e}`}),ue&&!de&&(Pe?Re=!0:await kt())},setEffort:async e=>!(!be.has(e)||de||(ve=e,mt.effort=e,it({kind:"effort",level:e}),ue&&(Pe?(Re=!0,0):(await kt(),0)))),async listModels(){try{const e=(await(ye?.supportedModels?.())||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);e.length&&it({kind:"models",models:e}),it({kind:"note",text:e.length?`models: ${e.map(e=>e.value).join(", ")}`:"no model list available"})}catch{it({kind:"note",text:"usage: /model <name>"})}},async park(){if(de||Ae||Pe||Ge||$e||ze)return!1;if(!ue)return!0;Ae=!0;const e=Oe,t=ne;ne=I(),ue=!1,nt&&(clearTimeout(nt),nt=null);try{if(Ee)try{Ee.abort()}catch{}try{t.end()}catch{}try{await e}catch{}return ye=null,re&&(se=re),!de}finally{Ae=!1}},async abort(){if(!Ge){Ge=!0;try{const e=$e,t=e?Oe:null;(Pe||e)&&(qe++,e||($e=!1),lt(),Fe?.failure({aborted:!0}),e&&(clearTimeout(Be),Be=null,ue=!1),Xe=!0,Ze=qe,clearTimeout(et),et=setTimeout(()=>{Xe=!1,Ze=null},6e3));try{await(ye?.interrupt?.())}catch{}if(t)try{await t}catch{}e&&($e=!1),(Pe||e)&&(Pe=!1,it({kind:"result",subtype:"aborted",sessionId:se}))}finally{Ge=!1}}},end(){de=!0,lt(),clearInterval(ut),clearTimeout(et),clearTimeout(Be),nt&&clearTimeout(nt),ne.end();try{oe.abort()}catch{}},get sessionId(){return se},get mode(){return ke},get turnActive(){return Pe}}}
@@ -1 +1 @@
1
- import{PEEK as e,cleanPtyTail as r,digestLogEvent as n,formatLaneAge as t,resolveSibling as a,siblingRef as o}from"./cross-terminal.mjs";const i=(e,r)=>{if(e?.error)throw new Error(`${r}: ${e.error.message||e.error}`);return e?.data},s=e=>{const r="number"==typeof e?e:Date.parse(String(e||""));return Number.isFinite(r)&&r>0?r:null},l=e=>`${e.ref}${e.name?` · "${e.name}"`:""}`;export const cloudTerminalRoster=(e,r=Date.now())=>(Array.isArray(e)?e:[]).filter(e=>e?.id).map(e=>{const n="pty"===e.kind?"shell":"agent",t=s(e.last_active_at);return{id:String(e.id),ref:o(e.id),name:String(e.name||""),kind:n,cmd:String(e.agent||("shell"===n?"shell":"think"===e.kind?"think":"agent")),lastActionAt:t,lastActionAgeMs:null==t?null:Math.max(0,r-t),sortOrder:Number.isFinite(Number(e.sort_order))?Number(e.sort_order):Number.MAX_SAFE_INTEGER}}).sort((e,r)=>e.sortOrder-r.sortOrder||e.id.localeCompare(r.id));export const formatCloudTerminalRoster=({room:e,terminals:r,now:n=Date.now()}={})=>{const a=cloudTerminalRoster(r,n);return a.length?`Cloud fallback for room ${e} · partner bridge offline (snapshots may lag the host-local event log).\nDurable terminals (call read_session again with a ref or name to read one):\n${a.map(e=>`- ${l(e)} · ${e.kind} · ${e.cmd} · bridge offline · ${t(e.lastActionAgeMs)}`).join("\n")}`:`Room ${e} is paired with you, but its host bridge is offline and no durable terminal rows are available in the cloud.`};export const formatCloudAgentTranscript=({room:r,terminal:a,snapshot:o,lines:i,now:m=Date.now()}={})=>{const d=Math.min(e.maxLines,Math.max(1,Number(i)||e.defaultLines)),c=o?.payload,u=!0===c?.__txsnap&&String(c.term||"")===a.id&&Array.isArray(c.events),f=u?s(c.ts)||s(o?.created_at):null,h=u?c.events.map(r=>n(r,e.lineCap)).filter(Boolean).slice(-d).join("\n"):"",p=null==f?"unknown snapshot time":`snapshot saved ${t(Math.max(0,m-f))}`,b=u&&c.handoff&&"object"==typeof c.handoff?c.handoff:null,g=b?["handoff "+(b.sdkSessionId?`warm (${$=b.sdkSessionId,"string"==typeof $&&$.length>12?`${$.slice(0,8)}…`:$||"?"})`:"cold"),b.branch,b.sha?b.sha.slice(0,10):null,b.worktree?`worktree ${b.worktree}`:null].filter(Boolean).join(" · "):null;var $;return`Cloud fallback for room ${r} · partner bridge offline · ${p} (may lag the host-local event log).\nTerminal ${l(a)} (${a.kind} · ${a.cmd}) — last ${d} readable lines:\n`+(g?`${g}\n`:"")+(h||"(no durable structured transcript snapshot is available)")};export const formatCloudShellTranscript=({room:n,terminal:t,rows:a,lines:o,archived:i=!1}={})=>{const s=Math.min(e.maxLines,Math.max(1,Number(o)||e.defaultLines)),m=(Array.isArray(a)?a:[]).slice().sort((e,r)=>Number(e.seq)-Number(r.seq)),d=r(m.map(e=>e?.line||"").join("\n"),s).join("\n");return`Cloud fallback for room ${n} · partner bridge offline${i?" · archived scrollback":""} (may lag the host-local event log).\nTerminal ${l(t)} (${t.kind} · ${t.cmd}) — last ${s} readable lines:\n`+(d||"(no durable shell transcript is available)")};export async function readCloudSessionTranscript({sb:r,targetRoom:n,terminal:t,lines:o,now:s=Date.now()}={}){if(!r?.from)throw new Error("cloud transcript client is unavailable");const l=String(n||"").toUpperCase().trim();if(!l)throw new Error("cloud transcript room is missing");const m=Math.min(e.maxLines,Math.max(1,Number(o)||e.defaultLines)),d=await r.from("code_terminals").select("id,name,agent,kind,last_active_at,sort_order").eq("session_code",l).order("sort_order",{ascending:!0}).order("id",{ascending:!0}).limit(100),c=i(d,"durable terminal roster")||[];if(!t)return formatCloudTerminalRoster({room:l,terminals:c,now:s});const u=cloudTerminalRoster(c,s),f=a(u,t);if(!f)return`${formatCloudTerminalRoster({room:l,terminals:c,now:s})}\nNo durable terminal matches "${t}". Use a name or stable ref from the roster above.`;if("agent"===f.kind){const e=await r.from("code_messages").select("payload,created_at").eq("session_code",l).eq("id",`tx:${f.id}`).maybeSingle(),n=i(e,"durable structured transcript");return formatCloudAgentTranscript({room:l,terminal:f,snapshot:n,lines:m,now:s})}const h=await r.from("code_terminal_lines").select("seq,line").eq("terminal_id",f.id).order("seq",{ascending:!1}).limit(m),p=i(h,"durable shell transcript")||[];if(p.length)return formatCloudShellTranscript({room:l,terminal:f,rows:p,lines:m});const b=await r.from("code_terminal_lines_archive").select("seq,line").eq("session_code",l).eq("terminal_id",f.id).order("seq",{ascending:!1}).limit(m),g=i(b,"archived shell transcript")||[];return formatCloudShellTranscript({room:l,terminal:f,rows:g,lines:m,archived:g.length>0})}
1
+ import{PEEK as e,cleanPtyTail as r,digestLogEvent as t,formatLaneAge as n,resolveSibling as a,siblingRef as o}from"./cross-terminal.mjs";const i=(e,r)=>{if(e?.error)throw new Error(`${r}: ${e.error.message||e.error}`);return e?.data},s=e=>{const r="number"==typeof e?e:Date.parse(String(e||""));return Number.isFinite(r)&&r>0?r:null},l=e=>`${e.ref}${e.name?` · "${e.name}"`:""}`;export const cloudTerminalRoster=(e,r=Date.now())=>(Array.isArray(e)?e:[]).filter(e=>e?.id).map(e=>{const t="pty"===e.kind?"shell":"agent",n=s(e.last_active_at);return{id:String(e.id),ref:o(e.id),name:String(e.name||""),kind:t,cmd:String(e.agent||("shell"===t?"shell":"think"===e.kind?"think":"agent")),lastActionAt:n,lastActionAgeMs:null==n?null:Math.max(0,r-n),sortOrder:Number.isFinite(Number(e.sort_order))?Number(e.sort_order):Number.MAX_SAFE_INTEGER}}).sort((e,r)=>e.sortOrder-r.sortOrder||e.id.localeCompare(r.id));export const formatCloudTerminalRoster=({room:e,terminals:r,now:t=Date.now()}={})=>{const a=cloudTerminalRoster(r,t);return a.length?`Cloud fallback for room ${e} · partner bridge offline (snapshots may lag the host-local event log).\nDurable terminals (call read_session again with a ref or name to read one):\n${a.map(e=>`- ${l(e)} · ${e.kind} · ${e.cmd} · bridge offline · ${n(e.lastActionAgeMs)}`).join("\n")}`:`Room ${e} is paired with you, but its host bridge is offline and no durable terminal rows are available in the cloud.`};export const formatCloudAgentTranscript=({room:r,terminal:a,snapshot:o,lines:i,now:m=Date.now()}={})=>{const d=Math.min(e.maxLines,Math.max(1,Number(i)||e.defaultLines)),c=o?.payload,u=!0===c?.__txsnap&&String(c.term||"")===a.id&&Array.isArray(c.events),f=u?s(c.ts)||s(o?.created_at):null,h=u?c.events.map(r=>t(r,e.lineCap)).filter(Boolean).slice(-d).join("\n"):"";return`Cloud fallback for room ${r} · partner bridge offline · ${null==f?"unknown snapshot time":`snapshot saved ${n(Math.max(0,m-f))}`} (may lag the host-local event log).\nTerminal ${l(a)} (${a.kind} · ${a.cmd}) — last ${d} readable lines:\n`+(h||"(no durable structured transcript snapshot is available)")};export const formatCloudShellTranscript=({room:t,terminal:n,rows:a,lines:o,archived:i=!1}={})=>{const s=Math.min(e.maxLines,Math.max(1,Number(o)||e.defaultLines)),m=(Array.isArray(a)?a:[]).slice().sort((e,r)=>Number(e.seq)-Number(r.seq)),d=r(m.map(e=>e?.line||"").join("\n"),s).join("\n");return`Cloud fallback for room ${t} · partner bridge offline${i?" · archived scrollback":""} (may lag the host-local event log).\nTerminal ${l(n)} (${n.kind} · ${n.cmd}) — last ${s} readable lines:\n`+(d||"(no durable shell transcript is available)")};export async function readCloudSessionTranscript({sb:r,targetRoom:t,terminal:n,lines:o,now:s=Date.now()}={}){if(!r?.from)throw new Error("cloud transcript client is unavailable");const l=String(t||"").toUpperCase().trim();if(!l)throw new Error("cloud transcript room is missing");const m=Math.min(e.maxLines,Math.max(1,Number(o)||e.defaultLines)),d=await r.from("code_terminals").select("id,name,agent,kind,last_active_at,sort_order").eq("session_code",l).order("sort_order",{ascending:!0}).order("id",{ascending:!0}).limit(100),c=i(d,"durable terminal roster")||[];if(!n)return formatCloudTerminalRoster({room:l,terminals:c,now:s});const u=cloudTerminalRoster(c,s),f=a(u,n);if(!f)return`${formatCloudTerminalRoster({room:l,terminals:c,now:s})}\nNo durable terminal matches "${n}". Use a name or stable ref from the roster above.`;if("agent"===f.kind){const e=await r.from("code_messages").select("payload,created_at").eq("session_code",l).eq("id",`tx:${f.id}`).maybeSingle(),t=i(e,"durable structured transcript");return formatCloudAgentTranscript({room:l,terminal:f,snapshot:t,lines:m,now:s})}const h=await r.from("code_terminal_lines").select("seq,line").eq("terminal_id",f.id).order("seq",{ascending:!1}).limit(m),p=i(h,"durable shell transcript")||[];if(p.length)return formatCloudShellTranscript({room:l,terminal:f,rows:p,lines:m});const b=await r.from("code_terminal_lines_archive").select("seq,line").eq("session_code",l).eq("terminal_id",f.id).order("seq",{ascending:!1}).limit(m),g=i(b,"archived shell transcript")||[];return formatCloudShellTranscript({room:l,terminal:f,rows:g,lines:m,archived:g.length>0})}
@@ -184,9 +184,25 @@ def nous_only_model_state(self, state):
184
184
  if provider != "nous":
185
185
  raise RuntimeError("thinkpool Hermes requires the Nous Portal provider")
186
186
  result = _build_model_state(self, state)
187
- for item in list(getattr(result, "available_models", None) or []):
188
- if not str(getattr(item, "model_id", "") or "").lower().startswith("nous:"):
189
- raise RuntimeError("thinkpool Hermes received a non-Nous ACP model")
187
+ if result is None:
188
+ return result
189
+ # Hermes 0.20.5 intentionally advertises one mixed catalog containing every
190
+ # authenticated provider. The catalog is presentation state, not proof that
191
+ # this session changed provider. Project it onto the already-validated Nous
192
+ # session instead of treating unrelated catalog entries as provider drift.
193
+ available = list(getattr(result, "available_models", None) or [])
194
+ nous_models = [
195
+ item for item in available
196
+ if str(getattr(item, "model_id", "") or "").strip().lower().startswith("nous:")
197
+ ]
198
+ current_model_id = str(getattr(result, "current_model_id", "") or "").strip()
199
+ if current_model_id and not current_model_id.lower().startswith("nous:"):
200
+ raise RuntimeError("thinkpool Hermes received a non-Nous active ACP model")
201
+ if current_model_id and current_model_id not in {
202
+ str(getattr(item, "model_id", "") or "").strip() for item in nous_models
203
+ }:
204
+ raise RuntimeError("thinkpool Hermes active Nous model is absent from the ACP catalog")
205
+ result.available_models = nous_models
190
206
  return result
191
207
  acp_adapter.server.HermesACPAgent._build_model_state = nous_only_model_state
192
208
 
package/hermes-policy.mjs CHANGED
@@ -1 +1 @@
1
- import{PEER_MCP_TOOLS as e,PEER_READ_MCP_TOOLS as r}from"./cross-terminal.mjs";export const HERMES_POLICY_VERSION=1;export const HERMES_QUESTION_MCP_TOOL="request_user_input";export const MCP_FLIGHT_RECORDER_TOOL="read_mcp_flight_recorder";export const PROJECT_INTELLIGENCE_TOOL="project_intelligence";export const CODING_TOOLS=Object.freeze(["web_search","web_extract","terminal","process","read_file","write_file","patch","search_files","vision_analyze","skills_list","skill_view","skill_manage","browser_navigate","browser_snapshot","browser_click","browser_type","browser_scroll","browser_back","browser_press","browser_get_images","browser_vision","browser_console","browser_cdp","browser_dialog","todo","memory","execute_code"]);const o=Object.freeze(["read_file","search_files"]);export const ESSENTIAL_CODING_TOOLS=Object.freeze(["terminal","process","read_file","write_file","patch","search_files"]);const i=Object.freeze({ordinary:[...e,"request_user_input",MCP_FLIGHT_RECORDER_TOOL,"project_intelligence","spawn_terminal","close_terminal"],plan:[],conductor:["submit_flow_plan"],builder:["mark_flow_done","project_intelligence"],reviewer:["submit_flow_review","run_review_check","read_review_file"],"manual-review":["run_review_check","read_review_file"]});export function hermesRoleFor({flowRole:e,sliceType:r}={}){return"conductor"===e?"conductor":"reviewer"===e?"reviewer":"review"===r?"manual-review":"builder"===e?"builder":"ordinary"}export function hermesPolicyForRole(r,{mcpTools:t}={}){if(!Object.hasOwn(i,r))throw new Error(`Unknown Hermes role policy: ${r}`);const s=Array.isArray(t)?t.map(String).filter(Boolean):i[r],n=i[r],l="ordinary"===r?[...e,"request_user_input",MCP_FLIGHT_RECORDER_TOOL,"project_intelligence"]:n;for(const e of l)if(!s.includes(e))throw new Error(`Hermes ${r} policy is missing required thinkpool tool ${e}`);const _="plan"===r||"conductor"===r||"reviewer"===r||"manual-review"===r,c=_?o:CODING_TOOLS,a=_?o:ESSENTIAL_CODING_TOOLS;return Object.freeze({version:1,role:r,builtinTools:c,requiredBuiltinTools:a,mcpServer:"thinkpool",mcpTools:[...new Set(s)].sort()})}export function hermesRequiredMcpTools(r,{canSpawnWorkers:o=!1}={}){return"ordinary"===r?[...e,"request_user_input",MCP_FLIGHT_RECORDER_TOOL,"project_intelligence",...o?["spawn_terminal","close_terminal"]:[]]:[...i[r]]}export const HERMES_PLAN_SAFE_MCP_TOOLS=r;export function hermesExactInventory(e,r={}){const o=hermesPolicyForRole(e,r);return Object.freeze({builtinTools:[...o.builtinTools].sort(),requiredBuiltinTools:[...o.requiredBuiltinTools].sort(),mcpTools:[...o.mcpTools].sort(),allBuiltinTools:[...CODING_TOOLS,"delegate_task","session_search"].sort()})}export function hermesPolicyEnv(e,r={}){return JSON.stringify(hermesPolicyForRole(e,r))}
1
+ import{PEER_MCP_TOOLS as e,PEER_READ_MCP_TOOLS as r}from"./cross-terminal.mjs";import{ROOM_FILE_DELIVERY_TOOL as o}from"./room-file-delivery.mjs";export const HERMES_POLICY_VERSION=1;export const HERMES_QUESTION_MCP_TOOL="request_user_input";export const MCP_FLIGHT_RECORDER_TOOL="read_mcp_flight_recorder";export const PROJECT_INTELLIGENCE_TOOL="project_intelligence";export const CODING_TOOLS=Object.freeze(["web_search","web_extract","terminal","process","read_file","write_file","patch","search_files","vision_analyze","skills_list","skill_view","skill_manage","browser_navigate","browser_snapshot","browser_click","browser_type","browser_scroll","browser_back","browser_press","browser_get_images","browser_vision","browser_console","browser_cdp","browser_dialog","todo","memory","execute_code"]);const i=Object.freeze(["read_file","search_files"]);export const ESSENTIAL_CODING_TOOLS=Object.freeze(["terminal","process","read_file","write_file","patch","search_files"]);const t=Object.freeze({ordinary:[...e,"request_user_input",MCP_FLIGHT_RECORDER_TOOL,"project_intelligence",o,"spawn_terminal","close_terminal"],plan:[],conductor:["submit_flow_plan"],builder:["mark_flow_done","project_intelligence"],reviewer:["submit_flow_review","run_review_check","read_review_file"],"manual-review":["run_review_check","read_review_file"]});export function hermesRoleFor({flowRole:e,sliceType:r}={}){return"conductor"===e?"conductor":"reviewer"===e?"reviewer":"review"===r?"manual-review":"builder"===e?"builder":"ordinary"}export function hermesPolicyForRole(r,{mcpTools:s}={}){if(!Object.hasOwn(t,r))throw new Error(`Unknown Hermes role policy: ${r}`);const n=Array.isArray(s)?s.map(String).filter(Boolean):t[r],l=t[r],_="ordinary"===r?[...e,"request_user_input",MCP_FLIGHT_RECORDER_TOOL,"project_intelligence",o]:l;for(const e of _)if(!n.includes(e))throw new Error(`Hermes ${r} policy is missing required thinkpool tool ${e}`);const c="plan"===r||"conductor"===r||"reviewer"===r||"manual-review"===r,a=c?i:CODING_TOOLS,p=c?i:ESSENTIAL_CODING_TOOLS;return Object.freeze({version:1,role:r,builtinTools:a,requiredBuiltinTools:p,mcpServer:"thinkpool",mcpTools:[...new Set(n)].sort()})}export function hermesRequiredMcpTools(r,{canSpawnWorkers:i=!1}={}){return"ordinary"===r?[...e,"request_user_input",MCP_FLIGHT_RECORDER_TOOL,"project_intelligence",o,...i?["spawn_terminal","close_terminal"]:[]]:[...t[r]]}export const HERMES_PLAN_SAFE_MCP_TOOLS=r;export function hermesExactInventory(e,r={}){const o=hermesPolicyForRole(e,r);return Object.freeze({builtinTools:[...o.builtinTools].sort(),requiredBuiltinTools:[...o.requiredBuiltinTools].sort(),mcpTools:[...o.mcpTools].sort(),allBuiltinTools:[...CODING_TOOLS,"delegate_task","session_search"].sort()})}export function hermesPolicyEnv(e,r={}){return JSON.stringify(hermesPolicyForRole(e,r))}
@@ -1 +1 @@
1
- import e from"node:fs";import t from"node:path";import{randomUUID as o}from"node:crypto";import{AcpClient as n}from"./acp-client.mjs";import{HermesEventMapper as s,hermesToolFor as r}from"./hermes-event-mapper.mjs";import{probeHermesRuntime as i}from"./hermes-probe.mjs";import{HERMES_PLAN_SAFE_MCP_TOOLS as l,HERMES_QUESTION_MCP_TOOL as a,hermesExactInventory as c,hermesPolicyEnv as m,hermesRoleFor as d}from"./hermes-policy.mjs";import{startCodexMcpHttp as u}from"./codex-mcp-http.mjs";import{autoAllow as p,classifyRisk as f}from"./claude-session.mjs";import{crossPostNeedsCard as h}from"./cross-terminal.mjs";import{buildThinkPoolTurnGuidance as g,createRoomContextSelector as w,usesFullThinkPoolReminder as _}from"./thinkpool-room-prompt.mjs";import{createCumulativeEventRelay as y}from"./cumulative-event-relay.mjs";import{HERMES_REASONING_EFFORT_IDS as E}from"./reasoning-effort.mjs";import{inspectCatastrophicTool as I}from"./catastrophic-command-guard.mjs";import{hermesProjectSkillEnv as S}from"./runtime-skill-parity.mjs";export const HERMES_COMMAND="thinkpool";export const HERMES_ACP_PROTOCOL_VERSION=1;export const HERMES_SUPPORTED_MODES=new Set(["default","acceptEdits","plan","bypassPermissions"]);export const HERMES_EFFORT_LEVELS=new Set(E);export const HERMES_EFFORT_CONFIG_ID="thinkpool_reasoning_effort";const k=new Set([...l,"read_review_file"]),b=/(?:TOKEN|SECRET|PASSWORD|PRIVATE_KEY|API_KEY|ACCESS_KEY|CREDENTIAL)/i,x=new Set(["agent_message_chunk","agent_thought_chunk","tool_call","tool_call_update","plan"]);export const hermesChildEnv=(e={})=>Object.fromEntries(Object.entries(e).filter(([e])=>!b.test(e)));const v=o=>{const n=t.extname(o).toLowerCase();return{type:"image",mimeType:".png"===n?"image/png":".webp"===n?"image/webp":".gif"===n?"image/gif":"image/jpeg",data:e.readFileSync(o).toString("base64")}},C=e=>(e?.availableModels||[]).map(e=>({value:e.modelId,displayName:e.name||e.modelId,description:e.description||""})),R=e=>new n(e);export function buildHermesPromptText({text:e,firstTurn:t=!1,terminalRolePrompt:o,rolePrompt:n,roomContext:s,promptIndex:r=0,forceFullReminder:i=!1,turnCause:l=null}={}){const a="function"==typeof s?s():s,c=!!(o||n||a),m=_({promptIndex:r,forceFull:i,turnCause:l}),d=[t||m?o:"",c?g({text:e,promptIndex:r,forceFull:i,turnCause:l}):"",t||m?n:"",a].filter(Boolean).join("\n\n"),u=String(e??"");return d?`${d}\n\n${u}`:u}const H=(e,t=[])=>{if("deny"===e||!e)return{outcome:"cancelled"};const o=("always"===e?["allow_always","allow_session","allow_once"]:["allow_once","allow_session","allow_always"]).map(e=>t.find(t=>t.kind===e||t.optionId===e)).find(Boolean)||t.find(e=>String(e.kind||"").startsWith("allow"));return o?{outcome:"selected",optionId:o.optionId}:{outcome:"cancelled"}};export function startHermesSession({cwd:e,model:n,resume:g,env:E=process.env,mode:b="default",onEvent:$,requestPermission:T,roomContext:P,terminalRolePrompt:M,rolePrompt:F,mcpServers:O,requiredMcpTools:q=[],prepareCwd:j=null,command:A="thinkpool",args:N=["acp"],clientFactory:D=R,mcpHttpFactory:L=u,lazy:V=!1,hermesRole:B=null,crossPostGate:U=null,didSpawnTarget:z=null,crossRoomPostGate:G=null,effort:K="high",admitStart:Y=null,onTurnStart:W=null}={}){let J=e;const Q=n||null;let X=Q,Z=HERMES_SUPPORTED_MODES.has(b)?b:"default",ee=g||null,te=null,oe=null,ne=null,se=null,re=!1,ie=!1,le=!1,ae=!1,ce=!0,me=0,de=!0;const ue=w(P);let pe="",fe=Promise.resolve(),he=0;const ge=new Set;let we=()=>{},_e=!1,ye=null,Ee=!1,Ie=!1,Se=!1,ke=null===K?null:HERMES_EFFORT_LEVELS.has(K)?K:"high";const be=[];let xe=!1,ve=!1;const Ce=B||d({}),Re=()=>"plan"===Z?"plan":Ce,He=()=>"plan"===Z?q.filter(e=>k.has(e)):q,$e=e=>"acceptEdits"===e?"accept_edits":"bypassPermissions"===e?"dont_ask":"default",Te=y(e=>{try{$?.(e)}catch{}});async function Pe(e,t,o){if("session/request_permission"!==e)throw Object.assign(new Error(`Unsupported ACP client method: ${e}`),{code:-32601});const n=r(t.toolCall||oe?.tools.get(t.toolCallId)||{}),s=(e=>{const t=String(e||"").toLowerCase();return[...l,"post_to_terminal","post_to_session",a].find(e=>t===e||t===`mcp__thinkpool__${e}`||t===`mcp_thinkpool_${e}`)||null})(n.name),i={id:`hermes-perm:${o}`,toolName:s?`mcp__thinkpool__${s}`:n.name,input:n.input,risk:s?.startsWith("post_to_")?"high":f(n.name,n.input)};if(I({toolName:i.toolName,input:i.input,cwd:J}).blocked)return{outcome:{outcome:"cancelled"}};if(l.includes(s))return{outcome:H("allow",t.options)};if(s===a)return{outcome:H("allow",t.options)};if("post_to_terminal"===s){if(!(U?U():{ok:!0}).ok)return{outcome:{outcome:"cancelled"}};const e=!!z&&!!z(n.input?.terminal);if(!h({mode:Z,spawnedByMe:e}))return{outcome:H("allow",t.options)}}if("post_to_session"===s){if(!(G?G():{ok:!0}).ok)return{outcome:{outcome:"cancelled"}};let e="deny";try{e=await(T?.(i))}catch{}return{outcome:H(e,t.options)}}if("plan"===Z)return{outcome:{outcome:"cancelled"}};if(p({toolName:i.toolName,input:i.input,mode:Z}))return{outcome:H("allow",t.options)};let c="deny";try{c=await(T?.(i))}catch{}return{outcome:H(c,t.options)}}function Me(e,t){if("session/update"!==e)return;const o=t?.update||t;ye&&"agent_message_chunk"===o?.sessionUpdate&&"text"===o?.content?.type?ye.push(String(o.content.text||"")):_e&&x.has(o?.sessionUpdate)||oe?.push(t)}async function Fe(){const e=[...new Set((Array.isArray(He())?He():[]).map(e=>String(e||"").trim()).filter(Boolean))];if(!e.length&&"plan"!==Re())return{inventory:"",missing:[],forbidden:[]};const t=c(Re(),{mcpTools:e}),n=t.builtinTools,s=t.requiredBuiltinTools,r=t.mcpTools,i=[];ye=i;try{await te.request("session/prompt",{sessionId:ee,prompt:[{type:"text",text:"/tools"}],messageId:o()},3e4)}finally{ye=null}const l=i.join(""),a=e=>new RegExp(`(?:^|[^a-z0-9_])${e}(?:$|[^a-z0-9_])`,"i").test(l),m=[...l.matchAll(/\bmcp(?:__|_)[a-z0-9_]+/gi)].map(e=>e[0]),d=new Set(r.flatMap(e=>[`mcp__thinkpool__${e}`,`mcp_thinkpool_${e}`])),u=[...new Set(m.filter(e=>!d.has(e)))];return{inventory:l,missing:[...s.filter(e=>!a(e)),...r.filter(e=>!a(`mcp__thinkpool__${e}`)&&!a(`mcp_thinkpool_${e}`))],forbidden:[...t.allBuiltinTools.filter(e=>!n.includes(e)&&a(e)),...u]}}async function Oe(){const e=await Fe();if(!e.missing.length&&!e.forbidden.length)return e;const t=[e.missing.length?`missing ${e.missing.join(", ")}`:"",e.forbidden.length?`forbidden ${e.forbidden.join(", ")}`:""].filter(Boolean).join("; ");throw new Error(`Hermes thinkpool MCP readiness failed; ${t}`)}async function qe(){if(re)throw new Error("Hermes session is closed");if(ae)throw new Error("Hermes ACP process crashed; this lane must be restarted before sending another turn");if(te?.alive&&oe)return;if(se)return se;const e="function"==typeof Y?Y():{ok:!0};if(!1===e?.ok)throw new Error(e.reason||"Host memory is critically low. This Hermes runtime was not started.");return se=(async()=>{if(!le&&j)try{J=j()||J}catch{}const e=O?.thinkpool;e&&!ne&&(ne=await L({sdkServer:e}));let o=hermesChildEnv(E),n=A,r=N;if("thinkpool"===A&&D===R){const e=i({command:A,env:o,strictBootstrap:!0});if(!e.available)throw new Error(`Hermes profile safety check failed: ${e.reason||"runtime unavailable"}`);n=e.python,r=[e.bootstrap],o={...o,...S(J),HERMES_HOME:e.profile,THINKPOOL_HERMES_ACP_POLICY:m(Re(),{mcpTools:He()})}}let l=!1;we=()=>{l=!0};const a={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"thinkpool-pair",title:"thinkpool Code",version:"1"}};let c;for(let e=0;e<2;e++){l=!1,we=()=>{l=!0},te=D({command:n,args:r,cwd:J,env:o,onNotification:Me,onRequest:Pe,onStderr:e=>{pe=(pe+e).slice(-2e3)},onClose:e=>{re||ae||l||(ae=!0,ie=!1,Te({kind:"error",message:`Hermes ACP closed unexpectedly: ${e?.message||e}`,recoverable:!0}))}}),te.start();try{c=await te.request("initialize",a,15e3);break}catch(t){if(Ie||0!==e||!/^initialize timed out\b/i.test(String(t?.message||t)))throw t;we();const o=te;te=null,o?.end(),pe=""}}if(1!==c?.protocolVersion)throw new Error(`Unsupported Hermes ACP protocol ${c?.protocolVersion??"unknown"}; expected 1`);const d={cwd:t.resolve(J),mcpServers:ne?[(u=ne.url,{type:"http",name:"thinkpool",url:u,headers:[]})]:[]};var u;let p;if(oe=new s({onEvent:Te,sessionId:ee,model:X}),ee){if(!c?.agentCapabilities?.sessionCapabilities?.resume)throw new Error(`Hermes session ${ee} cannot be resumed by this ACP release; no fresh session was substituted`);try{_e=!0,p=await te.request("session/resume",{...d,sessionId:ee},3e4)}catch(e){throw new Error(`Hermes session ${ee} is not available; no fresh session was substituted (${e?.message||e})`)}finally{_e=!1}}else p=await te.request("session/new",d,3e4);if(ee||(ee=p?.sessionId||null),!ee)throw new Error("Hermes ACP did not return a session id");let f=await Fe(),h=f.missing;if(h.length&&c?.agentCapabilities?.sessionCapabilities?.resume){try{_e=!0,p=await te.request("session/resume",{...d,sessionId:ee},3e4)}finally{_e=!1}f=await Fe(),h=f.missing}if(h.length||f.forbidden.length){const e=[h.length?`missing ${h.join(", ")}`:"",f.forbidden.length?`forbidden ${f.forbidden.join(", ")}`:""].filter(Boolean).join("; ");throw new Error(`Hermes thinkpool MCP readiness failed; ${e}`)}X=Q||p?.models?.currentModelId||null||X,Q&&(await te.request("session/set_model",{sessionId:ee,modelId:X}),await Oe()),ke&&await te.request("session/set_config_option",{sessionId:ee,configId:HERMES_EFFORT_CONFIG_ID,value:ke});const g=p?.models?{...p.models,currentModelId:X}:X?{currentModelId:X,availableModels:[]}:p?.models;Se?(oe.sessionId=ee,oe.model=X,Se=!1):oe.startSession({sessionId:ee,models:g,modes:p?.modes,commands:[]}),le=!0;const w=$e(Z);p?.modes?.availableModes?.some(e=>e.id===w)&&p.modes.currentModeId!==w&&await te.request("session/set_mode",{sessionId:ee,modeId:w}),Te({kind:"capabilities",runtime:"hermes",protocol:"acp",protocolVersion:c?.protocolVersion,capabilities:c?.agentCapabilities||{},models:C(p?.models),flow:"thinkpool"===A&&D===R})})().catch(async e=>{ae=!0,te?.end();try{await(ne?.close())}catch{}throw ne=null,Ie||Te({kind:"error",message:`Hermes ACP startup failed: ${e?.message||e}${pe?`: ${pe.trim().slice(-240)}`:""}`,recoverable:!0}),e}).finally(()=>{se=null,Ie=!1}),se}function je(){oe?oe.finishTurn({stopReason:"cancelled"}):Te({kind:"result",subtype:"aborted",sessionId:ee,model:X,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null})}function Ae(e,t={},{promptIndex:o=0,forceFull:n=!1}={}){const s=String(e);if(/^\s*\//.test(s))return[{type:"text",text:s}];const r=t?.turnCause||null,i=_({promptIndex:o,forceFull:n,turnCause:r}),l=[{type:"text",text:buildHermesPromptText({text:s,firstTurn:ce,terminalRolePrompt:M,rolePrompt:F,roomContext:()=>ue({force:i}),promptIndex:o,forceFullReminder:n,turnCause:r})}];for(const e of Array.isArray(t.images)?t.images:[])try{l.push(v(e))}catch{}return l}async function Ne(e,t={},{steering:n=!1,turnId:s=he,promptIndex:r=0,forceFull:i=!1}={}){try{await qe()}catch(e){if(ge.has(s))return{stopReason:"cancelled"};throw e}if(ge.has(s))return{stopReason:"cancelled"};const l=n?`/steer ${String(e)}`:String(e);let a;try{a=await te.request("session/prompt",{sessionId:ee,prompt:Ae(l,t,{promptIndex:r,forceFull:i}),messageId:o()},0)}catch(e){if(ge.has(s))return re||await async function(){const e=te;we(),te=null,oe=null,e?.end(),await qe()}(),{stopReason:"cancelled"};throw e}if(!n){if(ge.has(s))return a;ie=!1,ce=!1;const t=/^\s*\/compact\b/i.test(String(e||""))?oe.compactOutcome():null;t&&Te({kind:"compaction",trigger:"manual",...t});const o=String(e||"").match(/^\s*\/reasoning\s+(low|medium|high|xhigh|max|none|reset)\s*$/i);if(o){const e=o[1].toLowerCase();("reset"===e?/Session reasoning reset to model default/i.test(oe.text):new RegExp(`Session reasoning set to ${e}`,"i").test(oe.text))&&(ke="reset"===e?null:e,Te({kind:"effort",level:ke}))}ve=be.length>0&&!re&&!ge.has(s),oe.finishTurn({stopReason:a?.stopReason,usage:a?.usage}),ve&&async function(){if(!(xe||re||ie)){xe=!0;try{for(;be.length&&!re&&!ie;){ve=!1;const e=be.shift(),t=++he;ie=!0;try{W?.(e.options||{})}catch{}try{await Ne(e.text,e.options,{steering:!1,turnId:t,promptIndex:e.promptIndex,forceFull:e.forceFull})}catch(e){ie=!1,Te({kind:"error",message:`Hermes queued turn failed: ${e?.message||e}`,recoverable:!0})}}}finally{xe=!1,ve=!1}}}()}return a}return V||queueMicrotask(()=>{qe().catch(()=>{})}),{get sessionId(){return ee},get turnActive(){return ie},get queuedDepth(){return be.length},get canSteer(){return!!te?.alive},get started(){return le},get models(){return[]},get effort(){return ke},sendTurn(e,t={}){if(re)return!1;if(!te?.alive&&!se){const e="function"==typeof Y?Y():{ok:!0};if(!1===e?.ok)return Te({kind:"error",message:e.reason||"Host memory is critically low. This Hermes runtime was not started.",recoverable:!0}),!1}const o=me++,n=de;de=/^\s*\/(?:compact|reset|clear)\b/i.test(String(e||"")),ae&&!re&&(we(),te?.end(),te=null,oe=null,ae=!1,pe="");const s=String(e||"").match(/^\s*\/queue\s+([\s\S]+)$/i);if(ve)return be.push({text:s?s[1]:String(e||""),options:t,promptIndex:o,forceFull:n}),Te({kind:"queue-add",queued:!0,depth:be.length}),!0;if(ie)return s?(be.push({text:s[1],options:t,promptIndex:o,forceFull:n}),Te({kind:"queue-add",queued:!0,depth:be.length}),!0):(Ne(e,t,{steering:!0,turnId:he,promptIndex:o,forceFull:n}).catch(e=>Te({kind:"error",message:`Hermes steering failed: ${e?.message||e}`,recoverable:!0})),!0);const r=++he;return ie=!0,fe=fe.then(()=>Ne(e,t,{steering:!1,turnId:r,promptIndex:o,forceFull:n})).catch(e=>{ie=!1,Te({kind:"error",message:`Hermes turn failed: ${e?.message||e}`,recoverable:!0})}),!0},async park(){if(re||ie||be.length||ve||xe||Ee||se)return!1;try{await fe}catch{}if(re||ie||be.length||ve||xe||Ee||se)return!1;const e=te;we(),te=null,oe=null,le=!1,ae=!1,pe="";try{e?.end()}catch{return!1}return!0},async abort(){if(!ie)return;be.length=0,ve=!1;const e=he;return ge.add(e),ge.size>32&&ge.delete(ge.values().next().value),ie=!1,ce=!1,se?(Ie=!0,we(),te?.end(),je(),void await fe.catch(()=>{})):ee&&te?.alive?(je(),await te.notify("session/cancel",{sessionId:ee}).catch(e=>{ae=!0,te?.end(),Te({kind:"error",message:`Hermes cancellation delivery failed; ACP process stopped: ${e?.message||e}`,recoverable:!0})}),void await fe.catch(()=>{})):(je(),void await fe.catch(()=>{}))},end(){re=!0,ie=!1,Te.cancel(),be.length=0,ve=!1,ee&&te?.alive?te.request("session/close",{sessionId:ee},1500).catch(()=>{}).finally(()=>te?.end()):te?.end(),ne?.close().catch(()=>{})},setModel(e){if(!e||ie||Ee)return!1;const t=String(e);return Ee=!0,qe().then(()=>te.request("session/set_model",{sessionId:ee,modelId:t})).then(async()=>{await Oe(),re||(X=t,oe&&(oe.model=X),Te({kind:"model-switch",status:"success",model:X,requested:t}))}).catch(e=>{re||Te({kind:"model-switch",status:"failed",model:X,requested:t,message:`Hermes model switch failed: ${e?.message||e}`})}).finally(()=>{Ee=!1}),!0},setMode(e){if(ie||!HERMES_SUPPORTED_MODES.has(e))return!1;const t=Z;if("plan"===t!=("plan"===e)){if(Z=e,Se=le,le){we();const e=te;te=null,oe=null,le=!1,ae=!1,pe="",e?.end()}return qe().then(()=>Te({kind:"mode",mode:Z})).catch(e=>{Z=t,Se=!1,Te({kind:"error",message:`Hermes mode switch failed: ${e?.message||e}`,recoverable:!0})}),!0}return qe().then(()=>te.request("session/set_mode",{sessionId:ee,modeId:$e(e)})).then(()=>{Z=e,Te({kind:"mode",mode:Z})}).catch(e=>Te({kind:"error",message:`Hermes mode switch failed: ${e?.message||e}`,recoverable:!0})),!0},setEffort(e){if(ie||!HERMES_EFFORT_LEVELS.has(e))return!1;const t=String(e);return qe().then(()=>te.request("session/set_config_option",{sessionId:ee,configId:HERMES_EFFORT_CONFIG_ID,value:t})).then(()=>{ke=t,Te({kind:"effort",level:ke})}).catch(e=>Te({kind:"error",message:`Hermes reasoning change failed: ${e?.message||e}`,recoverable:!0})),!0},clearContext(){return!ie&&this.sendTurn("/reset")},warm(){qe().catch(()=>{})}}}
1
+ import e from"node:fs";import t from"node:path";import{randomUUID as o}from"node:crypto";import{AcpClient as n}from"./acp-client.mjs";import{HermesEventMapper as s,hermesToolFor as r}from"./hermes-event-mapper.mjs";import{probeHermesRuntime as i}from"./hermes-probe.mjs";import{HERMES_PLAN_SAFE_MCP_TOOLS as l,HERMES_QUESTION_MCP_TOOL as a,hermesExactInventory as c,hermesPolicyEnv as m,hermesRoleFor as d}from"./hermes-policy.mjs";import{startCodexMcpHttp as u}from"./codex-mcp-http.mjs";import{autoAllow as p,classifyRisk as f}from"./claude-session.mjs";import{crossPostNeedsCard as h}from"./cross-terminal.mjs";import{buildThinkPoolTurnGuidance as g,createRoomContextSelector as w,usesFullThinkPoolReminder as _}from"./thinkpool-room-prompt.mjs";import{createCumulativeEventRelay as y}from"./cumulative-event-relay.mjs";import{HERMES_REASONING_EFFORT_IDS as E}from"./reasoning-effort.mjs";import{inspectCatastrophicTool as I}from"./catastrophic-command-guard.mjs";import{hermesProjectSkillEnv as S}from"./runtime-skill-parity.mjs";import{ROOM_FILE_DELIVERY_TOOL as k}from"./room-file-delivery.mjs";export const HERMES_COMMAND="thinkpool";export const HERMES_ACP_PROTOCOL_VERSION=1;export const HERMES_SUPPORTED_MODES=new Set(["default","acceptEdits","plan","bypassPermissions"]);export const HERMES_EFFORT_LEVELS=new Set(E);export const HERMES_EFFORT_CONFIG_ID="thinkpool_reasoning_effort";const b=new Set([...l,"read_review_file"]),v=/(?:TOKEN|SECRET|PASSWORD|PRIVATE_KEY|API_KEY|ACCESS_KEY|CREDENTIAL)/i,x=new Set(["agent_message_chunk","agent_thought_chunk","tool_call","tool_call_update","plan"]);export const hermesChildEnv=(e={})=>Object.fromEntries(Object.entries(e).filter(([e])=>!v.test(e)));const C=o=>{const n=t.extname(o).toLowerCase();return{type:"image",mimeType:".png"===n?"image/png":".webp"===n?"image/webp":".gif"===n?"image/gif":"image/jpeg",data:e.readFileSync(o).toString("base64")}},R=e=>(e?.availableModels||[]).map(e=>({value:e.modelId,displayName:e.name||e.modelId,description:e.description||""})),H=e=>new n(e);export function buildHermesPromptText({text:e,firstTurn:t=!1,terminalRolePrompt:o,rolePrompt:n,roomContext:s,promptIndex:r=0,forceFullReminder:i=!1,turnCause:l=null}={}){const a="function"==typeof s?s():s,c=!!(o||n||a),m=_({promptIndex:r,forceFull:i,turnCause:l}),d=[t||m?o:"",c?g({text:e,promptIndex:r,forceFull:i,turnCause:l}):"",t||m?n:"",a].filter(Boolean).join("\n\n"),u=String(e??"");return d?`${d}\n\n${u}`:u}const $=(e,t=[])=>{if("deny"===e||!e)return{outcome:"cancelled"};const o=("always"===e?["allow_always","allow_session","allow_once"]:["allow_once","allow_session","allow_always"]).map(e=>t.find(t=>t.kind===e||t.optionId===e)).find(Boolean)||t.find(e=>String(e.kind||"").startsWith("allow"));return o?{outcome:"selected",optionId:o.optionId}:{outcome:"cancelled"}};export function startHermesSession({cwd:e,model:n,resume:g,env:E=process.env,mode:v="default",onEvent:T,requestPermission:P,roomContext:M,terminalRolePrompt:F,rolePrompt:O,mcpServers:q,requiredMcpTools:j=[],prepareCwd:A=null,command:N="thinkpool",args:D=["acp"],clientFactory:L=H,mcpHttpFactory:V=u,lazy:B=!1,hermesRole:U=null,crossPostGate:z=null,didSpawnTarget:G=null,crossRoomPostGate:K=null,effort:Y="high",admitStart:W=null,onTurnStart:J=null}={}){let Q=e;const X=n||null;let Z=X,ee=HERMES_SUPPORTED_MODES.has(v)?v:"default",te=g||null,oe=null,ne=null,se=null,re=null,ie=!1,le=!1,ae=!1,ce=!1,me=!0,de=0,ue=!0;const pe=w(M);let fe="",he=Promise.resolve(),ge=0;const we=new Set;let _e=()=>{},ye=!1,Ee=null,Ie=!1,Se=!1,ke=!1,be=null===Y?null:HERMES_EFFORT_LEVELS.has(Y)?Y:"high";const ve=[];let xe=!1,Ce=!1;const Re=U||d({}),He=()=>"plan"===ee?"plan":Re,$e=()=>"plan"===ee?j.filter(e=>b.has(e)):j,Te=e=>"acceptEdits"===e?"accept_edits":"bypassPermissions"===e?"dont_ask":"default",Pe=y(e=>{try{T?.(e)}catch{}});async function Me(e,t,o){if("session/request_permission"!==e)throw Object.assign(new Error(`Unsupported ACP client method: ${e}`),{code:-32601});const n=r(t.toolCall||ne?.tools.get(t.toolCallId)||{}),s=(e=>{const t=String(e||"").toLowerCase();return[...l,"post_to_terminal","post_to_session",a,k].find(e=>t===e||t===`mcp__thinkpool__${e}`||t===`mcp_thinkpool_${e}`)||null})(n.name),i={id:`hermes-perm:${o}`,toolName:s?`mcp__thinkpool__${s}`:n.name,input:n.input,risk:s?.startsWith("post_to_")?"high":f(n.name,n.input)};if(I({toolName:i.toolName,input:i.input,cwd:Q}).blocked)return{outcome:{outcome:"cancelled"}};if(l.includes(s))return{outcome:$("allow",t.options)};if(s===a)return{outcome:$("allow",t.options)};if(s===k)return{outcome:$("allow",t.options)};if("post_to_terminal"===s){if(!(z?z():{ok:!0}).ok)return{outcome:{outcome:"cancelled"}};const e=!!G&&!!G(n.input?.terminal);if(!h({mode:ee,spawnedByMe:e}))return{outcome:$("allow",t.options)}}if("post_to_session"===s){if(!(K?K():{ok:!0}).ok)return{outcome:{outcome:"cancelled"}};let e="deny";try{e=await(P?.(i))}catch{}return{outcome:$(e,t.options)}}if("plan"===ee)return{outcome:{outcome:"cancelled"}};if(p({toolName:i.toolName,input:i.input,mode:ee}))return{outcome:$("allow",t.options)};let c="deny";try{c=await(P?.(i))}catch{}return{outcome:$(c,t.options)}}function Fe(e,t){if("session/update"!==e)return;const o=t?.update||t;Ee&&"agent_message_chunk"===o?.sessionUpdate&&"text"===o?.content?.type?Ee.push(String(o.content.text||"")):ye&&x.has(o?.sessionUpdate)||ne?.push(t)}async function Oe(){const e=[...new Set((Array.isArray($e())?$e():[]).map(e=>String(e||"").trim()).filter(Boolean))];if(!e.length&&"plan"!==He())return{inventory:"",missing:[],forbidden:[]};const t=c(He(),{mcpTools:e}),n=t.builtinTools,s=t.requiredBuiltinTools,r=t.mcpTools,i=[];Ee=i;try{await oe.request("session/prompt",{sessionId:te,prompt:[{type:"text",text:"/tools"}],messageId:o()},3e4)}finally{Ee=null}const l=i.join(""),a=e=>new RegExp(`(?:^|[^a-z0-9_])${e}(?:$|[^a-z0-9_])`,"i").test(l),m=[...l.matchAll(/\bmcp(?:__|_)[a-z0-9_]+/gi)].map(e=>e[0]),d=new Set(r.flatMap(e=>[`mcp__thinkpool__${e}`,`mcp_thinkpool_${e}`])),u=[...new Set(m.filter(e=>!d.has(e)))];return{inventory:l,missing:[...s.filter(e=>!a(e)),...r.filter(e=>!a(`mcp__thinkpool__${e}`)&&!a(`mcp_thinkpool_${e}`))],forbidden:[...t.allBuiltinTools.filter(e=>!n.includes(e)&&a(e)),...u]}}async function qe(){const e=await Oe();if(!e.missing.length&&!e.forbidden.length)return e;const t=[e.missing.length?`missing ${e.missing.join(", ")}`:"",e.forbidden.length?`forbidden ${e.forbidden.join(", ")}`:""].filter(Boolean).join("; ");throw new Error(`Hermes thinkpool MCP readiness failed; ${t}`)}async function je(){if(ie)throw new Error("Hermes session is closed");if(ce)throw new Error("Hermes ACP process crashed; this lane must be restarted before sending another turn");if(oe?.alive&&ne)return;if(re)return re;const e="function"==typeof W?W():{ok:!0};if(!1===e?.ok)throw new Error(e.reason||"Host memory is critically low. This Hermes runtime was not started.");return re=(async()=>{if(!ae&&A)try{Q=A()||Q}catch{}const e=q?.thinkpool;e&&!se&&(se=await V({sdkServer:e}));let o=hermesChildEnv(E),n=N,r=D;if("thinkpool"===N&&L===H){const e=i({command:N,env:o,strictBootstrap:!0});if(!e.available)throw new Error(`Hermes profile safety check failed: ${e.reason||"runtime unavailable"}`);n=e.python,r=[e.bootstrap],o={...o,...S(Q),HERMES_HOME:e.profile,THINKPOOL_HERMES_ACP_POLICY:m(He(),{mcpTools:$e()})}}let l=!1;_e=()=>{l=!0};const a={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"thinkpool-pair",title:"thinkpool Code",version:"1"}};let c;for(let e=0;e<2;e++){l=!1,_e=()=>{l=!0},oe=L({command:n,args:r,cwd:Q,env:o,onNotification:Fe,onRequest:Me,onStderr:e=>{fe=(fe+e).slice(-2e3)},onClose:e=>{ie||ce||l||(ce=!0,le=!1,Pe({kind:"error",message:`Hermes ACP closed unexpectedly: ${e?.message||e}`,recoverable:!0}))}}),oe.start();try{c=await oe.request("initialize",a,15e3);break}catch(t){if(Se||0!==e||!/^initialize timed out\b/i.test(String(t?.message||t)))throw t;_e();const o=oe;oe=null,o?.end(),fe=""}}if(1!==c?.protocolVersion)throw new Error(`Unsupported Hermes ACP protocol ${c?.protocolVersion??"unknown"}; expected 1`);const d={cwd:t.resolve(Q),mcpServers:se?[(u=se.url,{type:"http",name:"thinkpool",url:u,headers:[]})]:[]};var u;let p;if(ne=new s({onEvent:Pe,sessionId:te,model:Z}),te){if(!c?.agentCapabilities?.sessionCapabilities?.resume)throw new Error(`Hermes session ${te} cannot be resumed by this ACP release; no fresh session was substituted`);try{ye=!0,p=await oe.request("session/resume",{...d,sessionId:te},3e4)}catch(e){throw new Error(`Hermes session ${te} is not available; no fresh session was substituted (${e?.message||e})`)}finally{ye=!1}}else p=await oe.request("session/new",d,3e4);if(te||(te=p?.sessionId||null),!te)throw new Error("Hermes ACP did not return a session id");let f=await Oe(),h=f.missing;if(h.length&&c?.agentCapabilities?.sessionCapabilities?.resume){try{ye=!0,p=await oe.request("session/resume",{...d,sessionId:te},3e4)}finally{ye=!1}f=await Oe(),h=f.missing}if(h.length||f.forbidden.length){const e=[h.length?`missing ${h.join(", ")}`:"",f.forbidden.length?`forbidden ${f.forbidden.join(", ")}`:""].filter(Boolean).join("; ");throw new Error(`Hermes thinkpool MCP readiness failed; ${e}`)}Z=X||p?.models?.currentModelId||null||Z,X&&(await oe.request("session/set_model",{sessionId:te,modelId:Z}),await qe()),be&&await oe.request("session/set_config_option",{sessionId:te,configId:HERMES_EFFORT_CONFIG_ID,value:be});const g=p?.models?{...p.models,currentModelId:Z}:Z?{currentModelId:Z,availableModels:[]}:p?.models;ke?(ne.sessionId=te,ne.model=Z,ke=!1):ne.startSession({sessionId:te,models:g,modes:p?.modes,commands:[]}),ae=!0;const w=Te(ee);p?.modes?.availableModes?.some(e=>e.id===w)&&p.modes.currentModeId!==w&&await oe.request("session/set_mode",{sessionId:te,modeId:w}),Pe({kind:"capabilities",runtime:"hermes",protocol:"acp",protocolVersion:c?.protocolVersion,capabilities:c?.agentCapabilities||{},models:R(p?.models),flow:"thinkpool"===N&&L===H})})().catch(async e=>{ce=!0,oe?.end();try{await(se?.close())}catch{}throw se=null,Se||Pe({kind:"error",message:`Hermes ACP startup failed: ${e?.message||e}${fe?`: ${fe.trim().slice(-240)}`:""}`,recoverable:!0}),e}).finally(()=>{re=null,Se=!1}),re}function Ae(){ne?ne.finishTurn({stopReason:"cancelled"}):Pe({kind:"result",subtype:"aborted",sessionId:te,model:Z,costUsd:null,usage:null,numTurns:1,durationMs:void 0,denials:0,resultText:null})}function Ne(e,t={},{promptIndex:o=0,forceFull:n=!1}={}){const s=String(e);if(/^\s*\//.test(s))return[{type:"text",text:s}];const r=t?.turnCause||null,i=_({promptIndex:o,forceFull:n,turnCause:r}),l=[{type:"text",text:buildHermesPromptText({text:s,firstTurn:me,terminalRolePrompt:F,rolePrompt:O,roomContext:()=>pe({force:i}),promptIndex:o,forceFullReminder:n,turnCause:r})}];for(const e of Array.isArray(t.images)?t.images:[])try{l.push(C(e))}catch{}return l}async function De(e,t={},{steering:n=!1,turnId:s=ge,promptIndex:r=0,forceFull:i=!1}={}){try{await je()}catch(e){if(we.has(s))return{stopReason:"cancelled"};throw e}if(we.has(s))return{stopReason:"cancelled"};const l=n?`/steer ${String(e)}`:String(e);let a;try{a=await oe.request("session/prompt",{sessionId:te,prompt:Ne(l,t,{promptIndex:r,forceFull:i}),messageId:o()},0)}catch(e){if(we.has(s))return ie||await async function(){const e=oe;_e(),oe=null,ne=null,e?.end(),await je()}(),{stopReason:"cancelled"};throw e}if(!n){if(we.has(s))return a;le=!1,me=!1;const t=/^\s*\/compact\b/i.test(String(e||""))?ne.compactOutcome():null;t&&Pe({kind:"compaction",trigger:"manual",...t});const o=String(e||"").match(/^\s*\/reasoning\s+(low|medium|high|xhigh|max|none|reset)\s*$/i);if(o){const e=o[1].toLowerCase();("reset"===e?/Session reasoning reset to model default/i.test(ne.text):new RegExp(`Session reasoning set to ${e}`,"i").test(ne.text))&&(be="reset"===e?null:e,Pe({kind:"effort",level:be}))}Ce=ve.length>0&&!ie&&!we.has(s),ne.finishTurn({stopReason:a?.stopReason,usage:a?.usage}),Ce&&async function(){if(!(xe||ie||le)){xe=!0;try{for(;ve.length&&!ie&&!le;){Ce=!1;const e=ve.shift(),t=++ge;le=!0;try{J?.(e.options||{})}catch{}try{await De(e.text,e.options,{steering:!1,turnId:t,promptIndex:e.promptIndex,forceFull:e.forceFull})}catch(e){le=!1,Pe({kind:"error",message:`Hermes queued turn failed: ${e?.message||e}`,recoverable:!0})}}}finally{xe=!1,Ce=!1}}}()}return a}return B||queueMicrotask(()=>{je().catch(()=>{})}),{get sessionId(){return te},get turnActive(){return le},get queuedDepth(){return ve.length},get canSteer(){return!!oe?.alive},get started(){return ae},get models(){return[]},get effort(){return be},sendTurn(e,t={}){if(ie)return!1;if(!oe?.alive&&!re){const e="function"==typeof W?W():{ok:!0};if(!1===e?.ok)return Pe({kind:"error",message:e.reason||"Host memory is critically low. This Hermes runtime was not started.",recoverable:!0}),!1}const o=de++,n=ue;ue=/^\s*\/(?:compact|reset|clear)\b/i.test(String(e||"")),ce&&!ie&&(_e(),oe?.end(),oe=null,ne=null,ce=!1,fe="");const s=String(e||"").match(/^\s*\/queue\s+([\s\S]+)$/i);if(Ce)return ve.push({text:s?s[1]:String(e||""),options:t,promptIndex:o,forceFull:n}),Pe({kind:"queue-add",queued:!0,depth:ve.length}),!0;if(le)return s?(ve.push({text:s[1],options:t,promptIndex:o,forceFull:n}),Pe({kind:"queue-add",queued:!0,depth:ve.length}),!0):(De(e,t,{steering:!0,turnId:ge,promptIndex:o,forceFull:n}).catch(e=>Pe({kind:"error",message:`Hermes steering failed: ${e?.message||e}`,recoverable:!0})),!0);const r=++ge;return le=!0,he=he.then(()=>De(e,t,{steering:!1,turnId:r,promptIndex:o,forceFull:n})).catch(e=>{le=!1,Pe({kind:"error",message:`Hermes turn failed: ${e?.message||e}`,recoverable:!0})}),!0},async park(){if(ie||le||ve.length||Ce||xe||Ie||re)return!1;try{await he}catch{}if(ie||le||ve.length||Ce||xe||Ie||re)return!1;const e=oe;_e(),oe=null,ne=null,ae=!1,ce=!1,fe="";try{e?.end()}catch{return!1}return!0},async abort(){if(!le)return;ve.length=0,Ce=!1;const e=ge;return we.add(e),we.size>32&&we.delete(we.values().next().value),le=!1,me=!1,re?(Se=!0,_e(),oe?.end(),Ae(),void await he.catch(()=>{})):te&&oe?.alive?(Ae(),await oe.notify("session/cancel",{sessionId:te}).catch(e=>{ce=!0,oe?.end(),Pe({kind:"error",message:`Hermes cancellation delivery failed; ACP process stopped: ${e?.message||e}`,recoverable:!0})}),void await he.catch(()=>{})):(Ae(),void await he.catch(()=>{}))},end(){ie=!0,le=!1,Pe.cancel(),ve.length=0,Ce=!1,te&&oe?.alive?oe.request("session/close",{sessionId:te},1500).catch(()=>{}).finally(()=>oe?.end()):oe?.end(),se?.close().catch(()=>{})},setModel(e){if(!e||le||Ie)return!1;const t=String(e);return Ie=!0,je().then(()=>oe.request("session/set_model",{sessionId:te,modelId:t})).then(async()=>{await qe(),ie||(Z=t,ne&&(ne.model=Z),Pe({kind:"model-switch",status:"success",model:Z,requested:t}))}).catch(e=>{ie||Pe({kind:"model-switch",status:"failed",model:Z,requested:t,message:`Hermes model switch failed: ${e?.message||e}`})}).finally(()=>{Ie=!1}),!0},setMode(e){if(le||!HERMES_SUPPORTED_MODES.has(e))return!1;const t=ee;if("plan"===t!=("plan"===e)){if(ee=e,ke=ae,ae){_e();const e=oe;oe=null,ne=null,ae=!1,ce=!1,fe="",e?.end()}return je().then(()=>Pe({kind:"mode",mode:ee})).catch(e=>{ee=t,ke=!1,Pe({kind:"error",message:`Hermes mode switch failed: ${e?.message||e}`,recoverable:!0})}),!0}return je().then(()=>oe.request("session/set_mode",{sessionId:te,modeId:Te(e)})).then(()=>{ee=e,Pe({kind:"mode",mode:ee})}).catch(e=>Pe({kind:"error",message:`Hermes mode switch failed: ${e?.message||e}`,recoverable:!0})),!0},setEffort(e){if(le||!HERMES_EFFORT_LEVELS.has(e))return!1;const t=String(e);return je().then(()=>oe.request("session/set_config_option",{sessionId:te,configId:HERMES_EFFORT_CONFIG_ID,value:t})).then(()=>{be=t,Pe({kind:"effort",level:be})}).catch(e=>Pe({kind:"error",message:`Hermes reasoning change failed: ${e?.message||e}`,recoverable:!0})),!0},clearContext(){return!le&&this.sendTurn("/reset")},warm(){je().catch(()=>{})}}}
@@ -1 +1 @@
1
- import{execFileSync as e}from"node:child_process";const t=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/,n=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/,r=new Set(["claude","codex","hermes"]),i=new Set(["default","acceptEdits","plan","review","bypassPermissions"]),o=new Set(["main","worker","side","flow-conductor","flow-builder","flow-reviewer","scheduled"]),a=new Set(["clean","dirty","unavailable"]),l=/(?:\r|\n|(?:^|[\\/])(?:Users|home|private|tmp|var|workspace)(?:[\\/]|$)|\.thinkpool[\\/]|(?:api[_-]?key|authorization|bearer|password|secret)\b)/i,u=1e5;function s(e){if("string"!=typeof e)return null;const n=e.trim();return t.test(n)?n:null}function d(e,t=120){if("string"!=typeof e)return null;const n=e.replace(/\s+/g," ").trim();return!n||n.length>t||l.test(n)?null:n}function c(e){if("string"!=typeof e)return null;const t=e.trim().toLowerCase();return n.test(t)?t:null}const f=/^[A-Za-z0-9][A-Za-z0-9._/-]{0,110}$/;function g(e){if("string"!=typeof e)return null;const t=e.trim();return"HEAD"===t||t.includes("..")||/^[0-9a-f]{7,64}$/i.test(t)?null:f.test(t)?t:null}function p(e={}){return"conductor"===e.flowRole?"flow-conductor":"reviewer"===e.flowRole||"review"===e.sliceType?"flow-reviewer":e.flowSessionId||e.flowTaskKey||"builder"===e.flowRole?"flow-builder":e.scheduleRunId?"scheduled":e.sideParent?"side":e.spawnedBy?"worker":"main"}function h(e){return new Set(String(e||"").split("\0").filter(Boolean))}export function readLaneWorkGit(t,n=e,r=null){if("string"!=typeof t||!t.trim())return{worktreeState:"unavailable"};let i=null,o=null;try{i=c(n("git",["-C",t,"rev-parse","HEAD"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]})),o=function(e,t){try{return g(t("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}))}catch{return null}}(t,n)}catch{return{worktreeState:"unavailable"}}try{const e=n("git",["-C",t,"status","--porcelain=v1","--untracked-files=all"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}),a={...i?{headSha:i}:{},...o?{branch:o}:{},worktreeState:String(e||"").trim()?"dirty":"clean"},l="clean"===r?.worktreeState?c(r?.headSha):null;if(l){if(i&&(a.headChanged=i!==l,a.headChanged)){const e=function(e,t,n){try{return d(n("git",["-C",e,"log","-1","--format=%s",t],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}))}catch{return null}}(t,i,n);e&&(a.headSubject=e)}const e=function(e,t,n){try{const r=n("git",["-C",e,"diff","--name-only","-z","--no-renames",t,"--"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}),i=n("git",["-C",e,"ls-files","--others","--exclude-standard","-z"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}),o=h(r);for(const e of h(i))o.add(e);return Math.min(o.size,u)}catch{return null}}(t,l,n);null!==e&&(a.changedFileCount=e)}return a}catch{return{...i?{headSha:i}:{},...o?{branch:o}:{},worktreeState:"unavailable"}}}export function normalizeLaneWorkSnapshot(e){if(!e||"object"!=typeof e||Array.isArray(e)||![1,2].includes(e.version))return null;const t=s(e.terminalId),n=Number.isSafeInteger(e.turnRev)&&e.turnRev>0?e.turnRev:null,l="string"==typeof e.capturedAt&&Number.isFinite(Date.parse(e.capturedAt))?new Date(e.capturedAt).toISOString():null,f=e.identity,p=r.has(f?.runtime)?f.runtime:null,h=o.has(f?.laneRole)?f.laneRole:null,w=a.has(e.git?.worktreeState)?e.git.worktreeState:null;if(!(t&&n&&l&&p&&h&&w))return null;const m={runtime:p,laneRole:h},S=d(f.model),y=i.has(f.mode)?f.mode:null,k=s(f.parentTerminalId),b=s(f.flowId),v=s(f.flowTaskKey),I=s(f.sdkSessionId);S&&(m.model=S),y&&(m.mode=y),k&&(m.parentTerminalId=k),b&&(m.flowId=b),v&&(m.flowTaskKey=v),I&&(m.sdkSessionId=I);const C={worktreeState:w},A=c(e.git?.headSha),R=g(e.git?.branch),z="boolean"==typeof e.git?.headChanged?e.git.headChanged:null,F=!0===z?d(e.git?.headSubject):null,T=Number.isSafeInteger(e.git?.changedFileCount)&&e.git.changedFileCount>=0&&e.git.changedFileCount<=u?e.git.changedFileCount:null;return A&&(C.headSha=A),R&&(C.branch=R),null!==z&&(C.headChanged=z),F&&(C.headSubject=F),null!==T&&(C.changedFileCount=T),{version:e.version,terminalId:t,turnRev:n,capturedAt:l,identity:m,git:C}}export function buildLaneWorkSnapshot(t,{now:n=Date.now(),gitFacts:r}={}){const i=t?.sideParent||("string"!=typeof t?.spawnedBy||t.spawnedBy.startsWith("flow:")?null:t.spawnedBy),o={runtime:t?.runtime,model:t?.model,mode:t?.mode,laneRole:p(t),parentTerminalId:i,flowId:t?.flowSessionId,flowTaskKey:t?.flowTaskKey,sdkSessionId:t?.session?.sessionId||null};return normalizeLaneWorkSnapshot({version:2,terminalId:t?.id,turnRev:Number(t?._turnRev),capturedAt:new Date(n).toISOString(),identity:o,git:r||readLaneWorkGit(t?.cwd,e,t?._turnGitStart)})}export function workerCompletionGitFacts(e){const t=normalizeLaneWorkSnapshot(e);return t?{...t.git}:null}
1
+ import{execFileSync as e}from"node:child_process";const t=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/,n=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/,r=new Set(["claude","codex","hermes"]),o=new Set(["default","acceptEdits","plan","review","bypassPermissions"]),i=new Set(["main","worker","side","flow-conductor","flow-builder","flow-reviewer","scheduled"]),a=new Set(["clean","dirty","unavailable"]),l=/(?:\r|\n|(?:^|[\\/])(?:Users|home|private|tmp|var|workspace)(?:[\\/]|$)|\.thinkpool[\\/]|(?:api[_-]?key|authorization|bearer|password|secret)\b)/i,u=1e5;function d(e){if("string"!=typeof e)return null;const n=e.trim();return t.test(n)?n:null}function s(e,t=120){if("string"!=typeof e)return null;const n=e.replace(/\s+/g," ").trim();return!n||n.length>t||l.test(n)?null:n}function c(e){if("string"!=typeof e)return null;const t=e.trim().toLowerCase();return n.test(t)?t:null}function f(e={}){return"conductor"===e.flowRole?"flow-conductor":"reviewer"===e.flowRole||"review"===e.sliceType?"flow-reviewer":e.flowSessionId||e.flowTaskKey||"builder"===e.flowRole?"flow-builder":e.scheduleRunId?"scheduled":e.sideParent?"side":e.spawnedBy?"worker":"main"}function g(e){return new Set(String(e||"").split("\0").filter(Boolean))}export function readLaneWorkGit(t,n=e,r=null){if("string"!=typeof t||!t.trim())return{worktreeState:"unavailable"};let o=null;try{o=c(n("git",["-C",t,"rev-parse","HEAD"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}))}catch{return{worktreeState:"unavailable"}}try{const e=n("git",["-C",t,"status","--porcelain=v1","--untracked-files=all"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}),i={...o?{headSha:o}:{},worktreeState:String(e||"").trim()?"dirty":"clean"},a="clean"===r?.worktreeState?c(r?.headSha):null;if(a){if(o&&(i.headChanged=o!==a,i.headChanged)){const e=function(e,t,n){try{return s(n("git",["-C",e,"log","-1","--format=%s",t],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}))}catch{return null}}(t,o,n);e&&(i.headSubject=e)}const e=function(e,t,n){try{const r=n("git",["-C",e,"diff","--name-only","-z","--no-renames",t,"--"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}),o=n("git",["-C",e,"ls-files","--others","--exclude-standard","-z"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}),i=g(r);for(const e of g(o))i.add(e);return Math.min(i.size,u)}catch{return null}}(t,a,n);null!==e&&(i.changedFileCount=e)}return i}catch{return{...o?{headSha:o}:{},worktreeState:"unavailable"}}}export function normalizeLaneWorkSnapshot(e){if(!e||"object"!=typeof e||Array.isArray(e)||![1,2].includes(e.version))return null;const t=d(e.terminalId),n=Number.isSafeInteger(e.turnRev)&&e.turnRev>0?e.turnRev:null,l="string"==typeof e.capturedAt&&Number.isFinite(Date.parse(e.capturedAt))?new Date(e.capturedAt).toISOString():null,f=e.identity,g=r.has(f?.runtime)?f.runtime:null,p=i.has(f?.laneRole)?f.laneRole:null,h=a.has(e.git?.worktreeState)?e.git.worktreeState:null;if(!(t&&n&&l&&g&&p&&h))return null;const w={runtime:g,laneRole:p},m=s(f.model),S=o.has(f.mode)?f.mode:null,y=d(f.parentTerminalId),k=d(f.flowId),v=d(f.flowTaskKey);m&&(w.model=m),S&&(w.mode=S),y&&(w.parentTerminalId=y),k&&(w.flowId=k),v&&(w.flowTaskKey=v);const b={worktreeState:h},C=c(e.git?.headSha),I="boolean"==typeof e.git?.headChanged?e.git.headChanged:null,R=!0===I?s(e.git?.headSubject):null,A=Number.isSafeInteger(e.git?.changedFileCount)&&e.git.changedFileCount>=0&&e.git.changedFileCount<=u?e.git.changedFileCount:null;return C&&(b.headSha=C),null!==I&&(b.headChanged=I),R&&(b.headSubject=R),null!==A&&(b.changedFileCount=A),{version:e.version,terminalId:t,turnRev:n,capturedAt:l,identity:w,git:b}}export function buildLaneWorkSnapshot(t,{now:n=Date.now(),gitFacts:r}={}){const o=t?.sideParent||("string"!=typeof t?.spawnedBy||t.spawnedBy.startsWith("flow:")?null:t.spawnedBy),i={runtime:t?.runtime,model:t?.model,mode:t?.mode,laneRole:f(t),parentTerminalId:o,flowId:t?.flowSessionId,flowTaskKey:t?.flowTaskKey};return normalizeLaneWorkSnapshot({version:2,terminalId:t?.id,turnRev:Number(t?._turnRev),capturedAt:new Date(n).toISOString(),identity:i,git:r||readLaneWorkGit(t?.cwd,e,t?._turnGitStart)})}export function workerCompletionGitFacts(e){const t=normalizeLaneWorkSnapshot(e);return t?{...t.git}:null}
package/lane-worktree.mjs CHANGED
@@ -1 +1 @@
1
- import{execFileSync as r}from"node:child_process";import e from"node:path";import t from"node:fs";const o=[".env.local",".env.development.local"];export function linkLocalEnvIntoWorktree({root:r,dir:n,fsImpl:i=t}={}){const a=[];for(const t of o){const o=e.join(r,t),s=e.join(n,t);try{if(!i.existsSync?.(o)||i.existsSync?.(s))continue;i.symlinkSync?.(o,s),a.push(t)}catch{}}return a}export function createManagedLaneWorktree({terminalId:r,cwd:o=process.cwd(),baseSha:i=null,git:a=n,fsImpl:s=t}={}){const c=String(r||""),l=c.replace(/[^a-zA-Z0-9]/g,"").slice(0,8);if(!l)throw new Error("terminal id required for managed worktree");const m=String(a(["rev-parse","--show-toplevel"],o)||"").trim();if(!m)throw new Error("not a git repository");const d=e.join(m,".thinkpool","worktrees",`terminal-${l}`),h=`thinkpool/terminal/${l}`,p=null==i?function({root:r,git:e}){for(const t of["origin/HEAD","origin/main","origin/master","main","master","HEAD"])try{if(String(e(["rev-parse","--verify","--quiet",t],r)||"").trim())return t}catch{}return"HEAD"}({root:m,git:a}):function({root:r,baseSha:e,git:t}){const o=String(e||"").trim().toLowerCase();if(!/^[a-f0-9]{40}$/.test(o))throw new Error("exact base SHA required for checkpoint branch");let n="";try{n=String(t(["rev-parse","--verify",`${o}^{commit}`],r)||"").trim().toLowerCase()}catch{}if(n!==o)throw new Error("checkpoint base SHA is unavailable in this repository");return o}({root:m,baseSha:i,git:a});return s.mkdirSync(e.dirname(d),{recursive:!0}),a(["worktree","add","-b",h,d,p],m),linkLocalEnvIntoWorktree({root:m,dir:d,fsImpl:s}),{terminalId:c,root:m,dir:d,branch:h,...null==i?{}:{baseSha:p}}}export function checkpointManagedLaneWorktree({terminalId:r,managedWorktree:t,git:o=n}={}){const i=function(r,t){const o=String(r||""),n=o.replace(/[^a-zA-Z0-9]/g,"").slice(0,8),i=t&&"object"==typeof t?t:null;if(!o||!n||!i||i.terminalId!==o)return null;const a=e.resolve(String(i.root||"")),s=e.resolve(String(i.dir||"")),c=String(i.branch||""),l=e.join(a,".thinkpool","worktrees",`terminal-${n}`);return a&&s===l&&c===`thinkpool/terminal/${n}`?{id:o,short:n,root:a,dir:s,branch:c}:null}(r,t);if(!i)return{ok:!1,reason:"terminal does not own an isolated managed worktree"};let a=!1,s=null;try{if(String(o(["status","--porcelain=v1","--untracked-files=all"],i.dir)||"").trim()&&(o(["add","-A"],i.dir),o(["-c","user.name=thinkpool bridge","-c","user.email=bridge@thinkpool.local","commit","-m",`chore(handoff): checkpoint ${i.short}`],i.dir),a=!0),s=String(o(["rev-parse","HEAD"],i.dir)||"").trim().toLowerCase(),!/^[a-f0-9]{40}$/.test(s))throw new Error("checkpoint commit SHA is invalid");return o(["push","--set-upstream","origin",`HEAD:refs/heads/${i.branch}`],i.dir),{ok:!0,branch:i.branch,sha:s,committed:a,pushed:!0}}catch(r){return{ok:!1,branch:i.branch,...s?{sha:s}:{},committed:a,pushed:!1,reason:r?.message||String(r)}}}export function restoreManagedLaneWorktreeFromCheckpoint({terminalId:r,cwd:o=process.cwd(),branch:i,sha:a,git:s=n,fsImpl:c=t}={}){const l=String(r||""),m=l.replace(/[^a-zA-Z0-9]/g,"").slice(0,8),d=`thinkpool/terminal/${m}`,h=String(a||"").trim().toLowerCase();if(!m||i!==d||!/^[a-f0-9]{40}$/.test(h))return{ok:!1,reason:"handoff checkpoint identity is invalid"};try{const r=String(s(["rev-parse","--show-toplevel"],o)||"").trim();if(!r)throw new Error("destination is not a git repository");const t=e.join(r,".thinkpool","worktrees",`terminal-${m}`);if(c.mkdirSync(e.dirname(t),{recursive:!0}),s(["fetch","--no-tags","origin",`refs/heads/${d}`],r),String(s(["rev-parse","--verify","FETCH_HEAD^{commit}"],r)||"").trim().toLowerCase()!==h)throw new Error("pushed checkpoint does not match the handoff commit");return s(["worktree","add","-B",d,t,h],r),linkLocalEnvIntoWorktree({root:r,dir:t,fsImpl:c}),{ok:!0,managedWorktree:{terminalId:l,root:r,dir:t,branch:d,baseSha:h}}}catch(r){return{ok:!1,reason:r?.message||String(r)}}}export function removeManagedLaneWorktree({terminalId:r,managedWorktree:t,git:o=n}={}){const i=String(r||""),a=t&&"object"==typeof t?t:null;if(!i||!a||a.terminalId!==i)return{removed:!1,reason:"not managed by this terminal"};const s=e.resolve(String(a.root||"")),c=e.resolve(String(a.dir||"")),l=String(a.branch||""),m=e.join(s,".thinkpool","worktrees"),d=i.replace(/[^a-zA-Z0-9]/g,"").slice(0,8);if(!s||c===m||!c.startsWith(m+e.sep))return{removed:!1,reason:"path outside managed worktrees"};if(!d||!e.basename(c).includes(d)||!l.startsWith(`thinkpool/terminal/${d}`))return{removed:!1,reason:"ownership marker mismatch"};try{o(["worktree","remove",c,"--force"],s)}catch{}try{o(["branch","-D",l],s)}catch{}return{removed:!0,dir:c,branch:l}}function n(e,t){return r("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],encoding:"utf8",timeout:3e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}
1
+ import{execFileSync as r}from"node:child_process";import e from"node:path";import t from"node:fs";const o=[".env.local",".env.development.local"];export function linkLocalEnvIntoWorktree({root:r,dir:n,fsImpl:i=t}={}){const a=[];for(const t of o){const o=e.join(r,t),s=e.join(n,t);try{if(!i.existsSync?.(o)||i.existsSync?.(s))continue;i.symlinkSync?.(o,s),a.push(t)}catch{}}return a}export function createManagedLaneWorktree({terminalId:r,cwd:o=process.cwd(),baseSha:i=null,git:a=n,fsImpl:s=t}={}){const c=String(r||""),l=c.replace(/[^a-zA-Z0-9]/g,"").slice(0,8);if(!l)throw new Error("terminal id required for managed worktree");const m=String(a(["rev-parse","--show-toplevel"],o)||"").trim();if(!m)throw new Error("not a git repository");const d=e.join(m,".thinkpool","worktrees",`terminal-${l}`),p=`thinkpool/terminal/${l}`,h=null==i?function({root:r,git:e}){for(const t of["origin/HEAD","origin/main","origin/master","main","master","HEAD"])try{if(String(e(["rev-parse","--verify","--quiet",t],r)||"").trim())return t}catch{}return"HEAD"}({root:m,git:a}):function({root:r,baseSha:e,git:t}){const o=String(e||"").trim().toLowerCase();if(!/^[a-f0-9]{40}$/.test(o))throw new Error("exact base SHA required for checkpoint branch");let n="";try{n=String(t(["rev-parse","--verify",`${o}^{commit}`],r)||"").trim().toLowerCase()}catch{}if(n!==o)throw new Error("checkpoint base SHA is unavailable in this repository");return o}({root:m,baseSha:i,git:a});return s.mkdirSync(e.dirname(d),{recursive:!0}),a(["worktree","add","-b",p,d,h],m),linkLocalEnvIntoWorktree({root:m,dir:d,fsImpl:s}),{terminalId:c,root:m,dir:d,branch:p,...null==i?{}:{baseSha:h}}}export function removeManagedLaneWorktree({terminalId:r,managedWorktree:t,git:o=n}={}){const i=String(r||""),a=t&&"object"==typeof t?t:null;if(!i||!a||a.terminalId!==i)return{removed:!1,reason:"not managed by this terminal"};const s=e.resolve(String(a.root||"")),c=e.resolve(String(a.dir||"")),l=String(a.branch||""),m=e.join(s,".thinkpool","worktrees"),d=i.replace(/[^a-zA-Z0-9]/g,"").slice(0,8);if(!s||c===m||!c.startsWith(m+e.sep))return{removed:!1,reason:"path outside managed worktrees"};if(!d||!e.basename(c).includes(d)||!l.startsWith(`thinkpool/terminal/${d}`))return{removed:!1,reason:"ownership marker mismatch"};try{o(["worktree","remove",c,"--force"],s)}catch{}try{o(["branch","-D",l],s)}catch{}return{removed:!0,dir:c,branch:l}}function n(e,t){return r("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],encoding:"utf8",timeout:3e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "thinkpool-pair",
3
- "version": "0.7.416",
3
+ "version": "0.7.418",
4
4
  "description": "Connect Claude Code, Codex, or Hermes on your computer to a thinkpool Code room.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",
@@ -33,6 +33,7 @@
33
33
  "thinkpool-room-prompt.mjs",
34
34
  "thinkpool-prompt-contracts.mjs",
35
35
  "thinkpool-capabilities.json",
36
+ "room-file-delivery.mjs",
36
37
  "codex-app-server.mjs",
37
38
  "codex-images.mjs",
38
39
  "codex-mcp-http.mjs",
@@ -127,8 +128,6 @@
127
128
  "past-work-search.mjs",
128
129
  "account-briefs.mjs",
129
130
  "voice-briefs.mjs",
130
- "handoff-out.mjs",
131
- "handoff-in.mjs",
132
131
  "review-check.mjs",
133
132
  "flow-review-gate.mjs",
134
133
  "flow-review-reflect.mjs",
@@ -141,6 +140,7 @@
141
140
  "serve-consent.mjs",
142
141
  "reap-terminal.mjs",
143
142
  "terminal-row-reconcile.mjs",
143
+ "terminal-close-auth.mjs",
144
144
  "switch-provider.mjs",
145
145
  "service.mjs",
146
146
  "supervisor-ready.mjs",
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "format": 1,
3
3
  "package": "thinkpool-pair",
4
- "version": "0.7.416",
4
+ "version": "0.7.418",
5
5
  "kind": "minified",
6
6
  "minifiedModules": 141,
7
- "sourceModuleBytes": 1885969,
8
- "artifactModuleBytes": 855898,
7
+ "sourceModuleBytes": 1857777,
8
+ "artifactModuleBytes": 847137,
9
9
  "files": {
10
- "package.json": "72a8b838920ded3d70ffbbfaf57f348ad3b9c2c3b0d10d100894e12c5bc260eb",
10
+ "package.json": "86affd2860d4676dc156c9dedfca00bab317d2cc33cd8b354a686d235196df22",
11
11
  "LICENSE": "8a030197ca1cad9669909ca14c9ad15cf48d9fe551da526ccaf1fca993eddb23",
12
- "bridge.mjs": "21be572b46d31791b95af67a08f108043539a41db02fb7995215ffa5d67e0b88",
12
+ "bridge.mjs": "1fec92d5d2c732e4e0f5a3cc1f7fd601512a4df0448cdb8edd2847346d204ec4",
13
13
  "bridge-service.sh": "b64f27c473ca8f3a49190fd08c23947ab14ca9958d70b6fa53c7bddc2be91403",
14
14
  "command-guidance.mjs": "b9b967b59ff4e77c9613abb0f28858bf3ac5b106a509e471039777b53bec3e29",
15
15
  "abort-turn-barrier.mjs": "3734a5b7e2e940ec6d7fa8b5b04935e1429a23d1bd9e92b2ac2a2ecd9f77c75e",
@@ -25,19 +25,20 @@
25
25
  "byok-detect.mjs": "f31f2ca426737581a97c391b3cecfc75f0207cfa31f51c6bf4a9148309c9625d",
26
26
  "context-contract.mjs": "ffebb435dc5d75c289329bf16ab909df9d634a2b508154c250c6b25906a02a91",
27
27
  "context-windows.mjs": "80af664f84d7e95ef2b0a2a3131090ac4ccd522709448ac9a0d96c378bbec0f7",
28
- "claude-session.mjs": "858f37d0fa1e5fd4a92a4a6d32c2ec1a9e111f949549d7e81ba66d3226a48f11",
28
+ "claude-session.mjs": "62af55078e681c94cff4847d7741049630211679c5dd46fee1b60c4811daf852",
29
29
  "terminal-name.mjs": "f39bb8d1e148ab9a74cbb96438d31e524d6597b8035f00d7a906c28c306c0cf8",
30
30
  "claude-command-catalog.mjs": "36bd4342b2ae94b43a0072533ef2d1648c7473003964bbad433fdb1a8b2bfec1",
31
31
  "codex-session.mjs": "38c84d43680066b1a5f724575a9bade87bd14a8020bad030ec9990f75fdaa3be",
32
32
  "question-response.mjs": "35a7ba53d3eb117717c18004d2a8441f8f37665b231a3c44f4bd9321ff59dd57",
33
33
  "thinkpool-room-prompt.mjs": "b8cc82ccf4262f6431c2047bbff31ac29c47a0d6c68a64640a2c24d94df4a746",
34
34
  "thinkpool-prompt-contracts.mjs": "051602d7d2fe9b34df92957bd3922c5eeebedbcc60c892adf415243887d8c62f",
35
- "thinkpool-capabilities.json": "372365d50ecbb7c369ecb3c951513ed7f3a2424339a27ef0252c99b9fd6055d0",
35
+ "thinkpool-capabilities.json": "e56254ae9ae0c3091d122514047b1d3895e023f1a8d37f839c5d3c89326dc8fe",
36
+ "room-file-delivery.mjs": "a33300b7f12152e8d016771aabbd4616896dec4bf7a3762e059d271e107a1b6a",
36
37
  "codex-app-server.mjs": "d50e30ba6cb2a383c90d89186bc7a13f4caf900c977dd501572468986009470e",
37
38
  "codex-images.mjs": "31605d6d8b3dd6b73395da63d1b0c513445c95ffa2f4306ee466f201d633ffc0",
38
39
  "codex-mcp-http.mjs": "7472543648a9bb575ce20dc3e3270c2da84174c6ea6e9faf87dfaafb95b6212a",
39
- "lane-worktree.mjs": "7183930e6d8a76d793bf2fe2ea578c0aca5589044ace739143c04697ea5b51ee",
40
- "lane-work-snapshot.mjs": "85af98593d5372d50b133aa20317503491925624af2b781fc0e780b88bbde3ed",
40
+ "lane-worktree.mjs": "9dd70a4f089f8867ad5d6a77e912734dbb396c327c0231b7fae883f7603d5ea2",
41
+ "lane-work-snapshot.mjs": "ba40233059ea86ba2e08d0b61763427baa9602eb6edf6c445a6b22fd15af212c",
41
42
  "branch-checkpoint.mjs": "6301c39df24b0343aacb05c13aad4a37dcce1c1acee3ffdf7465fc51db6acaa2",
42
43
  "bridge-identity.mjs": "71437cba17c22d7190afda94a677cb636526c472c6c1a4e226000b571c255d8d",
43
44
  "rotation-lock.mjs": "ce2da6d9e72f18fc78d7300e07844f3d588810a8136109a77b232bff2d41e65d",
@@ -51,15 +52,15 @@
51
52
  "acp-client.mjs": "9e7919ff79825883820019ff7a0ca578f120853ed61c7caab21a8ffc3a67ffc9",
52
53
  "acp-event-mapper.mjs": "bcef2d7b5b940a4ee1dc5053e2283ac962dd0567c7fd87f8fb6e16b083be5847",
53
54
  "acp-runtime-adapter.mjs": "b0e65df88a2e5f64ad3bcb123843daca5ae30e32ac33aceee31ca4f4c167f38b",
54
- "hermes-session.mjs": "b3d521ea59297edb58ecfcc0daad3c0df88d96131cadc455fa36fc1cca954210",
55
+ "hermes-session.mjs": "7945658a9ef2ddd47914cd20d328d3d6c6553476a2a2743b63afaed819d29d68",
55
56
  "opencode-session.mjs": "0828568fe8ad2110fb75363b501b69730627889aa8191fc460513f80c72ba337",
56
57
  "opencode-policy.mjs": "3c76d26162a26a6ea15d4f123155be5ca0ee10efe2cc1bc74659750ccc62d277",
57
58
  "opencode-probe.mjs": "08aa692d27873ece9aec2907641ae8e6d0f776f6f0e9e0dafb865fd890ce3bfd",
58
59
  "runtime-adapter.mjs": "0500660893b12b202848b1a0da9b00ab86f6be425aa4820eb680d10537a95cba",
59
60
  "runtime-compatibility-profile.mjs": "137730baf95d315723872e8df80e66305bccb909e3c6cb81ae753ea9adadac84",
60
61
  "hermes-model-cache.mjs": "aee23efdebe1aa5e10053f291a9153981fe9b45065c293c9519ca73477251e72",
61
- "hermes-policy.mjs": "df6dd384ab130b3626045816b6ac4c1d2aecde37fb7b7a4be0c1bffc375fd8ff",
62
- "hermes-acp-bootstrap.py": "f6e389610d4621e57242afdd7ca9d87bc4488f899bc641a813c0072ea0e7345a",
62
+ "hermes-policy.mjs": "f4dbb4cc2d7bc612fccb08b32054a3eb2c8319d5824cc399a630d3dca4556113",
63
+ "hermes-acp-bootstrap.py": "e2abdad97bdf06fcf5b73d3b78ba8dd2f518e307001056b029e2bf5ee1887406",
63
64
  "hermes-event-mapper.mjs": "7c714e15d06d970c4d602e755461bacf8f4d4136a8afc03406e8b3207ff84cdc",
64
65
  "hermes-probe.mjs": "3fc419707f0df9342bc3a5fbfbba2ec2ba1511309dfb1ad8cc79f6f8da4e6b3d",
65
66
  "hermes-setup.mjs": "50840b3e0101dc94aa2cd6dd2456efd8377e30bd5d797a00d360fae28e13dddb",
@@ -102,7 +103,7 @@
102
103
  "side-lane.mjs": "306d451e2d163ecdf40030d886a338770b11bc57952543a107e422f95ca49d45",
103
104
  "worker-completion.mjs": "72210efc40e5b3861e60fedff9cd455956563c6874270617e85573e58b5586a0",
104
105
  "cross-terminal.mjs": "1e8b3320b0bd79ee8d532cc2fbf1825e46428c1c4c5efbb3877c69e1e8e3a21e",
105
- "cloud-session-transcript.mjs": "5d831340b30f23b6f1caed90ce5b89ffc7eba37ada708b0811ab8b44060e3f9b",
106
+ "cloud-session-transcript.mjs": "1e8b3000d628eac0cff171901d6fed13983528b42e23e277583ef65bf8f9fa2b",
106
107
  "pair-bus.mjs": "cbc28cee7f4f06b2213091e0b7b07d61c1d01f0ff207c5c6d808cd616ece221e",
107
108
  "direct-pair-room.mjs": "92557b54307da2ca31f0a0d090e44b019a23b1ab32a7dfd6cbcb9d55fd761736",
108
109
  "lane-lifecycle.mjs": "9b5ae3d105c30e3ad37f1f1f792200da2dd4d2bb5c4979a2a69618373e58f1c8",
@@ -127,8 +128,6 @@
127
128
  "past-work-search.mjs": "766f4e669364bd9c3c3667135c502719dbbaf550bf074bda4394ab106f33f415",
128
129
  "account-briefs.mjs": "6f5353800bdbb9e4d14c2581b71efa631fab0d47b8e1c32eac968b5e91eb8178",
129
130
  "voice-briefs.mjs": "255dbaa66a683fa8713f1383ccf8101df6c347ddd9708ac636720b549de31573",
130
- "handoff-out.mjs": "2e568ceeb2b570ae4c0991b00147fa9bb369f33566a52e263c8d3693838c50ae",
131
- "handoff-in.mjs": "981c368589460176c7308b6497216192e744cf017c4cae83f4c236328714e360",
132
131
  "review-check.mjs": "e16c45fcbbe731b67c5aa1796daffc711e4a5734dbedda282a5e01db0602722e",
133
132
  "flow-review-gate.mjs": "0ef351065269bf2cc6112707064024cf2b916890a80fb94404ebca3a7905754b",
134
133
  "flow-review-reflect.mjs": "61b39e32ad21501b76c1d9267dd5cdf35017afe7e1333b305e72392bc0304628",
@@ -140,12 +139,13 @@
140
139
  "serve-dir.mjs": "1ab4cbdff02ddfd726cde4a021503ec2f24b47091e9950237d42d5827e5674ce",
141
140
  "serve-consent.mjs": "f6c5e9f42f452525a83ed5005bc9e65156ddec6fb2cd83deccc81b86f20c6825",
142
141
  "reap-terminal.mjs": "76d6ed14316d26d0d8b246d54cfdbde1f246badee91524b4caca8151f1440ccd",
143
- "terminal-row-reconcile.mjs": "b6f4022f03d908445f404ca1f8479c780ed645bf855428a2726ac2db682ab4ed",
142
+ "terminal-row-reconcile.mjs": "7992fb6a1e854fb3a5fbb1978ef972f691ad2298803fdb416c3b8e83e5f2cdb4",
143
+ "terminal-close-auth.mjs": "ea3d3614a113c38e62a11902aa0d4dbb441e2869aa395cdb6e9b9649160d109c",
144
144
  "switch-provider.mjs": "9805d59df49e1272ffd5ef7e3d2260f6e93c76d32265b78e461287ef500f5b71",
145
145
  "service.mjs": "412ee48ad7b1dd281063f30f2519b077aa4cc92305e6780ac226293756f6e6f8",
146
146
  "supervisor-ready.mjs": "7d5e4ebe3c7a93e0888dd335fb4556a670e55a80a89b861c8a44feac159cd840",
147
147
  "presence.mjs": "2516ebb4474a8f45dd881530335c2174af9cde44be8eed6896ff8c62497b6e2b",
148
- "account.mjs": "d1854d230d622f2b3c00eec44636985d8b924fca7c3ddb5b8cbf65d777fdc012",
148
+ "account.mjs": "baf751dfb696d85035f00214390148ad4f7418636ef3ea84e86197f09dedc33d",
149
149
  "auth-store.mjs": "c4d41ee7cdc34c2002c6dd50d32e53ace0a3f03a116ffa930ed94a437e247625",
150
150
  "key-shape.mjs": "a4113293d52eeba39b05e70a3e0345abc1ddc181b4f236b413bde0ae11a3f646",
151
151
  "supabase-key.mjs": "041bde6cf50b15f6426daaf738374abc9647861d8c1dd3d85cedc45684271888",
@@ -0,0 +1 @@
1
+ import{createHash as e,randomUUID as t}from"node:crypto";import o from"node:fs/promises";import i from"node:path";export const ROOM_FILE_DELIVERY_TOOL="attach_file";export const ROOM_FILE_MAX_BYTES=26214400;const a=Object.freeze({".csv":"text/csv",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".gif":"image/gif",".html":"text/html",".jpeg":"image/jpeg",".jpg":"image/jpeg",".json":"application/json",".md":"text/markdown",".pdf":"application/pdf",".png":"image/png",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".rtf":"application/rtf",".svg":"image/svg+xml",".txt":"text/plain",".webp":"image/webp",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".zip":"application/zip"});export async function prepareRoomFile({cwd:t,filePath:r,name:n,maxBytes:p=26214400}={}){if(!t||!r)throw new Error("A workspace and file path are required.");const s=await o.realpath(t),l=i.isAbsolute(r)?r:i.resolve(s,r),m=await o.realpath(l);if(!((e,t)=>t===e||t.startsWith(`${e}${i.sep}`))(s,m)||m===s)throw new Error("The file must be inside this terminal workspace.");const c=await o.stat(m);if(!c.isFile())throw new Error("The requested path is not a file.");if(c.size>p)throw new Error(`The file exceeds the ${Math.floor(p/1024/1024)} MB room limit.`);const f=await o.readFile(m),d=(h=n||m,([...i.basename(String(h||"file"))].filter(e=>{const t=e.codePointAt(0);return t>=32&&127!==t}).join("").trim()||"file").slice(-80));var h;const w=i.extname(d||m).toLowerCase().replace(/[^.a-z0-9]/g,"").slice(0,12);return{bytes:f,displayName:d,extension:w,mediaType:a[w]||"application/octet-stream",sha256:e("sha256").update(f).digest("hex")}}export function priorRoomFileReceipt(e,t){for(let o=(e||[]).length-1;o>=0;o--)for(const i of e[o]?.files||[])if(i?.sha256===t&&i?.path)return i;return null}export async function uploadRoomFile({storage:e,room:o,cwd:i,filePath:a,name:r,priorEvents:n=[],id:p=t()}={}){if(!e?.from||!o)throw new Error("Room attachment storage is unavailable.");const s=await prepareRoomFile({cwd:i,filePath:a,name:r}),l=priorRoomFileReceipt(n,s.sha256);if(l)return{file:l,reused:!0};const m=`code/${o}/${p}${s.extension}`,{error:c}=await e.from("session-attachments").upload(m,s.bytes,{contentType:s.mediaType,upsert:!1});if(c)throw new Error(`Room attachment upload failed: ${c.message||c}`);return{reused:!1,file:{id:p,name:s.displayName,path:m,mediaType:s.mediaType,size:s.bytes.length,sha256:s.sha256}}}
@@ -0,0 +1 @@
1
+ const e=(e,n=160)=>"string"==typeof e?e.replace(/\0/g,"").trim().slice(0,n):"";export function authorizeTerminalClose({entry:n,payload:r,now:o=Date.now()}={}){if(!n)return{ok:!1,reason:"missing-session"};if(!n.closeToken)return{ok:!1,reason:"missing-capability"};if(!r?.closeToken||r.closeToken!==n.closeToken)return{ok:!1,reason:"invalid-capability"};const t=e(r.requestId,100);return t?{ok:!0,receipt:{version:1,source:"room-ui",requestId:t,requestedBy:e(r.by,120)||null,reason:e(r.reason,80)||"remove-terminal",acceptedAt:Number(o)||Date.now()}}:{ok:!1,reason:"missing-request-id"}}export function internalTerminalCloseReceipt({source:n,reason:r,requestedBy:o,requestId:t,parentId:s,now:i=Date.now()}={}){return{version:1,source:e(n,80)||"bridge-internal",requestId:e(t,100)||null,requestedBy:e(o,120)||null,reason:e(r,80)||"internal-close",parentId:e(s,100)||null,acceptedAt:Number(i)||Date.now()}}
@@ -1 +1 @@
1
- import{reapTerminalRow as r}from"./reap-terminal.mjs";const e=(r={})=>({reaped:[],...r});export async function reconcileTerminalRows({room:o,hostId:t,liveIds:n=[],token:s,supabaseUrl:a,anonKey:i,shuttingDown:u=!1,fetchImpl:c=fetch,onFailure:d}={}){if(u)return e({reason:"shutdown"});if(!s)return e({reason:"anon"});if(!o)return e({reason:"no-room"});if(!t)return e({reason:"no-host-id"});const h=r=>{try{d?.(r)}catch{}return e(r)};try{const e=`${a}/rest/v1/code_terminals?select=id,host_id&session_code=eq.${encodeURIComponent(o)}&host_id=eq.${encodeURIComponent(t)}`,u=await c(e,{headers:{apikey:i,Authorization:`Bearer ${s}`}});if(!u?.ok)return h({reason:"error",error:`list HTTP ${u?.status??"unknown"}`,status:u?.status});const d=await u.json(),p=new Set(n||[]),f=(Array.isArray(d)?d:[]).filter(r=>r?.id&&r.host_id===t&&!p.has(r.id)).map(r=>r.id),l=[];for(const e of f){const o=await r({id:e,token:s,supabaseUrl:a,anonKey:i,fetchImpl:c});if(!o.reaped)return h({reason:"error",error:`delete ${o.error||o.reason}`,status:o.status,reaped:l});l.push(e)}return{reason:"ok",reaped:l}}catch(r){return h({reason:"error",error:r?.message||String(r)})}}
1
+ const e=(e={})=>({reaped:[],...e});export async function reconcileTerminalRows({room:r,hostId:o,liveIds:n=[],token:t,supabaseUrl:s,anonKey:a,shuttingDown:i=!1,fetchImpl:c=fetch,onFailure:d}={}){if(i)return e({reason:"shutdown"});if(!t)return e({reason:"anon"});if(!r)return e({reason:"no-room"});if(!o)return e({reason:"no-host-id"});const u=r=>{try{d?.(r)}catch{}return e(r)};try{const e=`${s}/rest/v1/code_terminals?select=id,host_id&session_code=eq.${encodeURIComponent(r)}&host_id=eq.${encodeURIComponent(o)}`,i=await c(e,{headers:{apikey:a,Authorization:`Bearer ${t}`}});if(!i?.ok)return u({reason:"error",error:`list HTTP ${i?.status??"unknown"}`,status:i?.status});const d=await i.json(),h=new Set(n||[]);return{reason:"ok",reaped:[],dormant:(Array.isArray(d)?d:[]).filter(e=>e?.id&&e.host_id===o&&!h.has(e.id)).map(e=>e.id)}}catch(e){return u({reason:"error",error:e?.message||String(e)})}}