thinkpool-pair 0.7.417 → 0.7.419
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bridge.mjs +1 -1
- package/claude-session.mjs +1 -1
- package/hermes-acp-bootstrap.py +19 -3
- package/hermes-policy.mjs +1 -1
- package/hermes-session.mjs +1 -1
- package/package.json +3 -1
- package/publish-manifest.json +16 -14
- package/recap.mjs +1 -1
- package/room-file-delivery.mjs +1 -0
- package/side-lane.mjs +1 -1
- package/terminal-close-auth.mjs +1 -0
- package/terminal-row-reconcile.mjs +1 -1
- package/thinkpool-capabilities.json +28 -1
package/claude-session.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID as e}from"node:crypto";import{createRequire as t}from"node:module";import{readFileSync as o}from"node:fs";import{dirname as n,join as s}from"node:path";import{query as r}from"@anthropic-ai/claude-agent-sdk";import{sanitizeSession as i}from"./transcript-sanitize.mjs";import{reviewGatePreToolDecision as a}from"./flow-review-gate.mjs";import{crossPostNeedsCard as l}from"./cross-terminal.mjs";import{correctContext as c}from"./context-windows.mjs";import{normalizeClaudeCommandCatalog as d}from"./claude-command-catalog.mjs";import{evidenceForToolResult as u}from"./evidence-citations.mjs";import{THINKPOOL_CASCADE_RULE as p,THINKPOOL_REMOTE_DELIVERY_RULES as m,THINKPOOL_RUNTIME_AUTHORITY_RULE as h,THINKPOOL_RUNTIME_TURN_REMINDER as f,buildThinkPoolTurnGuidance as y,createRoomContextSelector as k,normalizeThinkPoolTurnCause as w,usesFullThinkPoolReminder as g}from"./thinkpool-room-prompt.mjs";import{stallDecision as b,stallEvent as v,isCompactTurn as _}from"./turn-stall.mjs";import{createSameTargetResilienceController as T,formatResilienceTrace as S}from"./provider-resilience.mjs";import{catastrophicPreToolHookDecision as E}from"./catastrophic-command-guard.mjs";const N=t(import.meta.url);export async function claudeOneShot({prompt:e,model:t="claude-haiku-4-5",cwd:o,env:n,timeoutMs:s=8e3}={}){const i=new AbortController,a=setTimeout(()=>{try{i.abort()}catch{}},s);try{const s=r({prompt:e,options:{model:t,...o?{cwd:o}:{},env:n,maxTurns:1,permissionMode:"bypassPermissions",settingSources:[],strictMcpConfig:!0,mcpServers:{},abortController:i}});let a="";for await(const e of s){if("assistant"===e.type)for(const t of e.message?.content||[])"text"===t.type&&(a+=t.text);if("result"===e.type)break}return a.trim()}finally{clearTimeout(a)}}const O=(()=>{try{let e=n(N.resolve("@anthropic-ai/claude-agent-sdk"));for(let t=0;t<8;t++){try{const t=JSON.parse(o(s(e,"package.json"),"utf8"));if("@anthropic-ai/claude-agent-sdk"===t.name)return t.version}catch{}const t=n(e);if(t===e)break;e=t}}catch{}return"unknown"})(),R=/\brm\s+\S|\brmdir\s+\S|\bgit\s+(push\s+(-f|--force)|reset\s+--hard|clean\s+-[a-z]*f)|\bdrop\s+(table|database)\b|\b(mkfs|dd)\b|\bsudo\b|>\s*\/dev\/|\bchmod\s+-R|\bchown\s+-R|\bkillall\b|\btruncate\b/i,A=new Set(["Read","Grep","Glob","NotebookRead","TodoRead","LS"]),D=new Set(["WebFetch","WebSearch"]),x=new Set(["Edit","Write","MultiEdit","NotebookEdit","TodoWrite"]);export function classifyRisk(e,t){if("Bash"===e){const e=t&&(t.command??t.cmd)||"";return R.test(e)?"high":"medium"}return A.has(e)?"low":D.has(e)?"network":(x.has(e),"medium")}const P=/(^|\/)\.claude\/SESSIONS\/|(^|\/)CLAUDE\.md$/;export function isSafeDocWrite(e,t){if(!x.has(e))return!1;const o=t&&(t.file_path||t.notebook_path)||"";return P.test(o)}export function autoAllow({toolName:e,input:t,mode:o="default",alwaysAllow:n=new Set}){const s=classifyRisk(e,t);return"low"===s||"bypassPermissions"===o||"acceptEdits"===o&&x.has(e)&&"high"!==s||isSafeDocWrite(e,t)||n.has(`${e}:${s}`)}export function askUserQuestionHookOutput(e){const t=e&&"object"==typeof e?e.decision:e,o="string"==typeof t&&t.startsWith("answer:")?t.slice(7):"",n=e&&"object"==typeof e?e.responder:null,s="string"==typeof n?.name&&n.name.trim()?n.name.trim():"string"==typeof n?.id&&n.id?`room member ${n.id}`:"The user";return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:o?`${s} answered in the thinkpool room — ${o}. Treat this as their selection and continue; do not call AskUserQuestion again for the same question.`:"The user dismissed the question in the thinkpool room without selecting. Ask in plain prose, or proceed with a sensible default."}}}export function askUserQuestionRegression(e,t){return Array.isArray(e)?e.includes("AskUserQuestion")?null:`[SDK-REGRESSION] agent SDK v${t||"unknown"} init tools[] is missing 'AskUserQuestion' — the multiple-choice question card is disabled. A caret SDK bump likely changed the canUseTool gate; pin a known-good SDK in bridge/package.json + republish.`:null}function I(){const e=[];let t=null,o=!1;return{stream:async function*(){for(;!o;)e.length?yield e.shift():await new Promise(e=>{t=e})}(),push:n=>!o&&(e.push({type:"user",message:{role:"user",content:n}}),t&&(t(),t=null),!0),end(){o=!0,t&&(t(),t=null)}}}const C=(e=[])=>e.map(e=>"text"===e.type?{type:"text",text:e.text}:"thinking"===e.type?{type:"thinking",text:e.thinking||"",reasoningKind:"thought"}:"tool_use"===e.type?{type:"tool_use",id:e.id,name:e.name,input:e.input}:{type:e.type}).filter(Boolean),M=new Set(["default","acceptEdits","plan","bypassPermissions"]),U=["You are Claude in a thinkpool Code room, driven live from a phone or browser — NOT a local terminal. Keep using the room's features.",f,"TERMINAL HIERARCHY: obey your authoritative TERMINAL ROLE. A person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal — NEVER spawn_terminal — even for ordinary work or a handoff. If the wording includes new or separate terminal, main-terminal routing wins. Use spawn_terminal only for agent-decided bounded worker slices or when the person explicitly asks for a worker, sub-terminal, Ensemble lane, or delegated slice. If open_main_terminal is unavailable, say so; never substitute an Ensemble child. Leaf, worker, Side, and managed Flow lanes work directly. Never use built-in invisible Task/Agent subagents or hijack a busy sibling.","WORKTREES: parallel lanes share one repo — before code edits run `git worktree list`; if linked worktrees exist, take your OWN worktree + branch, never the shared checkout or a branch another lane is on.","BUILD WORKFLOW (default, no magic word): right-size within your TERMINAL ROLE — a trivial ask or delegated slice you just do; a conductor-capable role with a genuinely decomposable build FIRST writes a short plan in chat, THEN fans worker slices into visible spawn_terminal lanes and verifies them. Worker/leaf/Side/managed Flow roles do not fan out. A person-requested new or separate terminal uses open_main_terminal. Never plan-mode/ExitPlanMode; plans live in chat and lanes in the existing list."].join(" ");export function startClaudeSession({cwd:t,model:o,effort:n="high",resume:s,env:f,mode:N="default",onEvent:R,requestPermission:A,mcpServers:D,crossPostGate:x,crossRoomPostGate:P,didSpawnTarget:L=null,terminalRolePrompt:W,rolePrompt:F,blockSubagents:j=!1,onSubmitPlan:$=null,onLaneDone:q=null,onReviewVerdict:G=null,reviewGate:B=null,lazy:H=!1,roomContext:K=null,suggest:Q=!0,prepareCwd:Y=null,admitStart:z=null,resilienceObserver:J=null,resilience:V=null}){const X=k(K);let Z=0,ee=!0;const te=(e,{promptIndex:t=0,forceFull:o=!1,turnCause:n=null}={})=>{const s=g({promptIndex:t,forceFull:o,turnCause:n}),r=X({force:s}),i=String(W||"").trim();return`<system-reminder>\n${s&&i?`${i}\n\n`:""}${s?U:y({text:e,promptIndex:t,forceFull:o,turnCause:n})}${r?`\n\n${r}`:""}\n</system-reminder>`},oe=new AbortController;let ne=I(),se=s||null,re=s||null,ie=null,ae=null,le=null,ce=null,de=!1,ue=!1,pe=null,me=!1,he=!1,fe=!1,ye=null,ke=M.has(N)?N:"default";const we=new Set,ge=new Map,be=new Set(["low","medium","high","xhigh","max"]);let ve=be.has(n)?n:"high",_e=0,Te=0,Se=o||null,Ee=null,Ne=null,Oe=Promise.resolve(),Re=!1,Ae=!1;const De=e=>new Promise(t=>setTimeout(t,e)),xe=Math.max(3e4,parseInt(process.env.TP_STALL_MS,10)||9e4);let Pe=!1,Ie=Date.now(),Ce=!1;const Me=/connection closed|connection reset|econnreset|etimedout|socket hang up|fetch failed|network error|socket destroyed/i;let Ue=0;const Le=(e,t={})=>{try{J?.({reason:e,restartCount:Ue,...t})}catch{}},We=!(!V?.policy?.enabled||!V?.providerId||"anthropic"===V.providerId);let Fe=null,je=null,$e=!1,qe=0,Ge=!1,Be=null;const He=Math.max(3*xe,parseInt(process.env.TP_FORCE_STOP_MS,10)||3e5);let Ke=!1,Qe=!1;const Ye=Math.max(He,parseInt(process.env.TP_COMPACT_FORCE_STOP_MS,10)||12e5);let ze=!1,Je=0;const Ve=A;A=async e=>{Je++;try{return await(Ve?.(e))}finally{Je=Math.max(0,Je-1),Ie=Date.now()}};let Xe=!1,Ze=null,et=null,tt=!1,ot="",nt=null;const st=Math.max(1200,parseInt(process.env.TP_SUGGEST_FALLBACK_MS,10)||2500),rt=e=>{try{R?.(e)}catch{}},it=e=>{Ie=Date.now(),e&&"stalled"!==e.kind&&(Ce=!1),!e||"compaction"!==e.kind&&"result"!==e.kind&&"error"!==e.kind||(ze=!1),rt(e)},at=e=>{try{V?.onRecord?.(e)}catch{}"retrying"!==e?.outcome&&"cap_blocked"!==e?.outcome&&"circuit_open"!==e?.outcome||it({kind:"note",text:S(e)})},lt=()=>{if(null!=je){try{(V?.clearTimer||clearTimeout)(je)}catch{}je=null}},ct=()=>{if(lt(),!Fe)return;const e=Number(V?.policy?.timeoutMs);if(!Number.isFinite(e)||e<=0)return;const t=V?.setTimer||setTimeout;je=t(()=>{if(je=null,!de&&Fe&&Pe){Fe.failure({message:"timeout"}),Pe=!1;try{Ee?.abort()}catch{}gt()}},e)},dt=async()=>{if(!Fe)return!0;let e=null;try{e=await Fe.preflight()}catch{return!1}return!0===e?.admitted},ut=setInterval(()=>{const e=Date.now()-Ie,t=b({turnActive:Pe,awaitingUser:Je,quietMs:e,stallMs:xe,forceStopMs:He,stalledSent:Ce,stallRetried:Qe,compacting:ze,compactForceStopMs:Ye});if("none"===t)return;const o=v(t,e);if(o&&rt(o),"status"!==t){if("retry"===t){if(Ke=!0,Fe){Le("resilience_stall",{quietMs:e}),Fe.failure({message:"timeout"}),Pe=!1;try{Ee?.abort()}catch{}return void gt()}return Le("stall_replay",{quietMs:e}),void wt(e)}Ke=!0,Pe=!1}else Ce=!0},5e3);ut.unref?.();const pt=e=>{setTimeout(()=>{Promise.resolve(ye?.setPermissionMode?.(e)).catch(t=>console.error(`[claude-session] setPermissionMode(${e}) failed:`,t?.message||t))},0)},mt={abortController:oe,permissionMode:ke,hooks:{PreToolUse:[{hooks:[async o=>{const n=o.tool_name,s=o.tool_input,r=E({toolName:n,input:s,cwd:t});if(r)return r;const i=o.effort?.level;i&&i!==ve&&(ve=i,it({kind:"effort",level:ve}));const c="Write"===n||"Edit"===n||"MultiEdit"===n||"NotebookEdit"===n;if(j&&c&&/(?:^|[/\\])FLOW_PLAN\.json$/i.test(s?.file_path||s?.notebook_path||"")){const e=s?.content??s?.new_string??"";let t={ok:!1,message:"Plan submission is not wired for this session."};try{t=$&&await $(e)||t}catch(e){t={ok:!1,message:`Plan submission failed: ${e?.message||e}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.message}}}if(j&&("Task"===n||"Agent"===n||"Bash"===n||c))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Bash"===n?"Flow conductors do NOT run Bash — it pops a permission card and stalls the flow. Use the Grep tool (not `grep`/`rg`), the Glob tool (not `find`/`ls`), and Read (not `cat`/`head`) — those run with no prompt. Then DECOMPOSE and submit by Writing your task-graph JSON to the file FLOW_PLAN.json.":c?'Flow conductors do NOT write project or plan-document files. Do NOT use ExitPlanMode and do NOT call submit_flow_plan (both hang here). To SUBMIT your decomposition, use the Write tool with file_path "FLOW_PLAN.json" and content = your task-graph JSON ({"summary":"…","tasks":[…]}). That single Write IS how you submit — the room ingests it directly. Do not write any other file.':"Flow conductors do NOT spawn subagents — it stalls the flow on a permission card. Inspect the codebase yourself with Read/Grep/Glob (no prompt). Then DECOMPOSE and submit by Writing your task-graph JSON to the file FLOW_PLAN.json. Do not call Task/Agent again."}};if(G&&("Write"===n||"Edit"===n)&&/(?:^|[/\\])FLOW_REVIEW(\.[a-zA-Z0-9]+)?$/.test(s?.file_path||"")){let e={ok:!1,message:"verdict signal failed"};try{e=await G(s?.content??s?.new_string??"")||e}catch(t){e={ok:!1,message:`verdict signal failed: ${t?.message||t}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.message}}}if(q&&("Write"===n||"Edit"===n)&&/(?:^|[/\\])FLOW_DONE(\.[a-zA-Z0-9]+)?$/.test(s?.file_path||"")){let e={ok:!1,message:"done signal failed"};try{e=await q(s?.content??s?.new_string??"")||e}catch(t){e={ok:!1,message:`done signal failed: ${t?.message||t}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.message}}}const d=a({reviewGate:B,toolName:n,toolInput:s});if(d)return d;if("mcp__thinkpool__read_terminal"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (read-only thinkpool cross-terminal read)."}};if(/^mcp__thinkpool__preview_(start|capture|inspect|stop)$/.test(n))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (contained bridge-owned viewport preview)."}};if("mcp__thinkpool__submit_flow_plan"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (Flow plan submission — broadcasts the task-graph for human approval)."}};if("mcp__thinkpool__list_sessions"===n||"mcp__thinkpool__read_session"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (read-only thinkpool cross-session read — your own rooms)."}};if("mcp__thinkpool__close_terminal"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (thinkpool cross-terminal close — only self-spawned lanes)."}};if("mcp__thinkpool__spawn_terminal"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (autonomous thinkpool worker; bounded by room caps and isolated in its own worktree)."}};if("mcp__thinkpool__open_main_terminal"===n){const t=s?.mode||ke;if("bypassPermissions"!==t||"bypassPermissions"===ke)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Auto-approved (open a fresh thinkpool terminal in ${t} mode — inherited, no escalation; bounded by room caps).`}};let o="deny";try{o=await(A?.({id:e(),toolName:n,input:{...s,mode:t},risk:"high"}))??"deny"}catch{o="deny"}const r="allow"===o;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:r?"allow":"deny",permissionDecisionReason:r?"Bypass terminal creation approved in the thinkpool room — the new terminal runs autonomously.":"Bypass terminal creation denied in the room — do not retry as bypass; open it without mode:bypassPermissions or ask what to do."}}}if("mcp__thinkpool__post_to_terminal"===n){const t=x?x():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-terminal post not allowed right now."}};const o=!!L&&!!L(s?.terminal);if(!l({mode:ke,spawnedByMe:o}))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"bypassPermissions"===ke?"Auto-approved (cross-terminal post in bypassPermissions mode — bypass means bypass).":"Auto-approved (cross-terminal post into a lane you spawned — parent→child orchestration, no per-post tap)."}};let r="deny";try{r=await(A?.({id:e(),toolName:n,input:s,risk:"high"}))??"deny"}catch{r="deny"}const i="allow"===r;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:i?"allow":"deny",permissionDecisionReason:i?"Cross-terminal post approved in the thinkpool room.":"Cross-terminal post denied in the room — do not retry; ask what to do instead."}}}if("mcp__thinkpool__post_to_session"===n){const t=P?P():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-room post not allowed right now."}};let o="deny";try{o=await(A?.({id:e(),toolName:n,input:s,risk:"high"}))??"deny"}catch{o="deny"}const r="allow"===o;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:r?"allow":"deny",permissionDecisionReason:r?"Cross-room post approved in the sending room — the target room will be asked to accept it.":"Cross-room post denied in the room — do not retry; ask what to do instead."}}}if("ExitPlanMode"===n){if("plan"!==ke)return pt(ke),it({kind:"mode",mode:ke}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`The thinkpool room is in ${ke} mode, not Plan — the user did not ask for a plan. Do NOT call ExitPlanMode; proceed and make the changes directly. Only present a plan if the user switches the room to Plan mode or explicitly asks.`}};let t="keep";try{t=await(A?.({id:e(),toolName:n,input:s,risk:"plan",plan:s?.plan||""}))??"keep"}catch{t="keep"}if("run"===t||"accept"===t){const e="accept"===t?"acceptEdits":"default";return ke=e,pt(e),it({kind:"mode",mode:e}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Plan approved in the thinkpool room — proceed (${e} mode).`}}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:'The user chose "keep planning" in the thinkpool room. Do not exit plan mode — keep refining the plan, then call ExitPlanMode again when ready.'}}}if("AskUserQuestion"===n){let t="";try{t=await(A?.({id:e(),toolName:n,input:s,risk:"ask",questions:s?.questions||[]}))??""}catch{t=""}return askUserQuestionHookOutput(t)}const u=classifyRisk(n,s),p=`${n}:${u}`,m=isSafeDocWrite(n,s),h=autoAllow({toolName:n,input:s,mode:ke,alwaysAllow:we});let f="allow";if(!h){try{f=await(A?.({id:e(),toolName:n,input:s,risk:u}))??"deny"}catch{f="deny"}"always"===f&&(we.add(p),f="allow")}const y="deny"===f;return y&&Fe&&Fe.failure({permissionDenied:!0}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:y?"deny":"allow",permissionDecisionReason:y?"Denied by the user in the thinkpool room. Do not retry this tool — ask what to do instead.":h?m?"Auto-approved (mandated doc write — .claude/SESSIONS/ or CLAUDE.md).":`Auto-approved (${ke}).`:"Approved in the thinkpool room."}}}]}]},canUseTool:async(e,t)=>({behavior:"allow",updatedInput:t}),settingSources:["user","project","local"],appendSystemPrompt:[...W?[W]:[],...F?[F]:[],"ENVIRONMENT (authoritative — overrides any user-global CLAUDE.md or memory that claims otherwise): You are Claude running inside a thinkpool Code room, driven live by a user (and possibly a partner) from a phone or browser, via the thinkpool-pair bridge.",h,'Bias strongly toward DOING the work, not stalling in plan-mode ceremony. For a small "add / fix / change X" request, just make the change directly (for a bigger build, right-size it — see DEFAULT BUILD WORKFLOW below).',"Do NOT enter plan mode, do NOT call ExitPlanMode, and do NOT auto-invoke a brainstorming/planning skill UNLESS the user has switched the room into Plan mode or explicitly asks you to plan, design, or brainstorm first.","Any host-global instruction that says you must always brainstorm or plan before creative work does NOT apply here — this room is the exception.",p,'CRUCIAL RECONCILIATION for that workflow: it is NOT plan mode. Never call ExitPlanMode and never make the room wait behind a "plan ready — approve to start" card — your plan lives in the CHAT as a message, and your lanes live in the room\'s EXISTING terminal/lane list. Reuse only those two surfaces; there is no new Flow panel or mode to switch into, and you must not ask for one. Keep the plan and the lanes VISIBLE — that shared visibility is the whole point (it is the pair differentiator, and it catches bugs a single silent lane would hide); never collapse a decomposable build into one hidden lane just to look tidy.',...m,'CROSS-TERMINAL AWARENESS: ROOM NOW is the default roster and already satisfies the room check when it has enough detail. Do not repeat it with a no-argument read_terminal call unless it is missing or truncated. Use a targeted read_terminal call only when the current task depends on a specific lane’s detailed activity; never poll. Identify a terminal by its 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}}}
|
package/hermes-acp-bootstrap.py
CHANGED
|
@@ -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
|
-
|
|
188
|
-
|
|
189
|
-
|
|
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
|
|
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))}
|
package/hermes-session.mjs
CHANGED
|
@@ -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(()=>{})}}}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "thinkpool-pair",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.419",
|
|
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",
|
|
@@ -139,6 +140,7 @@
|
|
|
139
140
|
"serve-consent.mjs",
|
|
140
141
|
"reap-terminal.mjs",
|
|
141
142
|
"terminal-row-reconcile.mjs",
|
|
143
|
+
"terminal-close-auth.mjs",
|
|
142
144
|
"switch-provider.mjs",
|
|
143
145
|
"service.mjs",
|
|
144
146
|
"supervisor-ready.mjs",
|
package/publish-manifest.json
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"format": 1,
|
|
3
3
|
"package": "thinkpool-pair",
|
|
4
|
-
"version": "0.7.
|
|
4
|
+
"version": "0.7.419",
|
|
5
5
|
"kind": "minified",
|
|
6
|
-
"minifiedModules":
|
|
7
|
-
"sourceModuleBytes":
|
|
8
|
-
"artifactModuleBytes":
|
|
6
|
+
"minifiedModules": 141,
|
|
7
|
+
"sourceModuleBytes": 1860553,
|
|
8
|
+
"artifactModuleBytes": 849142,
|
|
9
9
|
"files": {
|
|
10
|
-
"package.json": "
|
|
10
|
+
"package.json": "713ba27ddaa97a593c27206fe62ec4b2c7a3a8d6f3925778319fc0ea54b363c1",
|
|
11
11
|
"LICENSE": "8a030197ca1cad9669909ca14c9ad15cf48d9fe551da526ccaf1fca993eddb23",
|
|
12
|
-
"bridge.mjs": "
|
|
12
|
+
"bridge.mjs": "e5a1ccea71b516549814936808830ec70a5efefd9bbf0190ba8db23504428ebe",
|
|
13
13
|
"bridge-service.sh": "b64f27c473ca8f3a49190fd08c23947ab14ca9958d70b6fa53c7bddc2be91403",
|
|
14
14
|
"command-guidance.mjs": "b9b967b59ff4e77c9613abb0f28858bf3ac5b106a509e471039777b53bec3e29",
|
|
15
15
|
"abort-turn-barrier.mjs": "3734a5b7e2e940ec6d7fa8b5b04935e1429a23d1bd9e92b2ac2a2ecd9f77c75e",
|
|
@@ -25,14 +25,15 @@
|
|
|
25
25
|
"byok-detect.mjs": "f31f2ca426737581a97c391b3cecfc75f0207cfa31f51c6bf4a9148309c9625d",
|
|
26
26
|
"context-contract.mjs": "ffebb435dc5d75c289329bf16ab909df9d634a2b508154c250c6b25906a02a91",
|
|
27
27
|
"context-windows.mjs": "80af664f84d7e95ef2b0a2a3131090ac4ccd522709448ac9a0d96c378bbec0f7",
|
|
28
|
-
"claude-session.mjs": "
|
|
28
|
+
"claude-session.mjs": "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": "
|
|
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",
|
|
@@ -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": "
|
|
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": "
|
|
62
|
-
"hermes-acp-bootstrap.py": "
|
|
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",
|
|
@@ -94,12 +95,12 @@
|
|
|
94
95
|
"event-delivery-queue.mjs": "9fd955766e5b6ff3209c59bf916f469784061cfee75b50ae519208d135603fff",
|
|
95
96
|
"mcp-flight-recorder.mjs": "30bf77f4d567f0449856d6da09f7a0a9c8d7e12c5dcaf200dc9e511a331425be",
|
|
96
97
|
"plan-meters.mjs": "f7f5aeb3d6a3462b754d3724367bbb331643ba58108e29e91b2aca2f613ab499",
|
|
97
|
-
"recap.mjs": "
|
|
98
|
+
"recap.mjs": "10e67aa933fa8bac4059878167d578f87db3184d7affd168c46c5134c6e97c8b",
|
|
98
99
|
"transcript-sanitize.mjs": "c7f4718f25f97c05bc7b4ad8e09f18cbda152c53ad6593af1ab99f0c132dbf01",
|
|
99
100
|
"agent-output-hygiene.mjs": "914b04daa5b60342b5e44737cfba99f2c8ac292826db1fe501f653814454c835",
|
|
100
101
|
"session-search.mjs": "d606fbab5c47357071e4919107aa00ad090f6e7d7e6dc929e0ac5a4d0cb2c538",
|
|
101
102
|
"session-store.mjs": "fa3f7a27a8a7c49bb89364fb28c9c2680f7f487d4b4125329ab4a0ba9362bd8c",
|
|
102
|
-
"side-lane.mjs": "
|
|
103
|
+
"side-lane.mjs": "6a6bc6d8041872ba4472d70fd1cece62607417982a72b8721f4fbed77655cc6d",
|
|
103
104
|
"worker-completion.mjs": "72210efc40e5b3861e60fedff9cd455956563c6874270617e85573e58b5586a0",
|
|
104
105
|
"cross-terminal.mjs": "1e8b3320b0bd79ee8d532cc2fbf1825e46428c1c4c5efbb3877c69e1e8e3a21e",
|
|
105
106
|
"cloud-session-transcript.mjs": "1e8b3000d628eac0cff171901d6fed13983528b42e23e277583ef65bf8f9fa2b",
|
|
@@ -138,7 +139,8 @@
|
|
|
138
139
|
"serve-dir.mjs": "1ab4cbdff02ddfd726cde4a021503ec2f24b47091e9950237d42d5827e5674ce",
|
|
139
140
|
"serve-consent.mjs": "f6c5e9f42f452525a83ed5005bc9e65156ddec6fb2cd83deccc81b86f20c6825",
|
|
140
141
|
"reap-terminal.mjs": "76d6ed14316d26d0d8b246d54cfdbde1f246badee91524b4caca8151f1440ccd",
|
|
141
|
-
"terminal-row-reconcile.mjs": "
|
|
142
|
+
"terminal-row-reconcile.mjs": "7992fb6a1e854fb3a5fbb1978ef972f691ad2298803fdb416c3b8e83e5f2cdb4",
|
|
143
|
+
"terminal-close-auth.mjs": "ea3d3614a113c38e62a11902aa0d4dbb441e2869aa395cdb6e9b9649160d109c",
|
|
142
144
|
"switch-provider.mjs": "9805d59df49e1272ffd5ef7e3d2260f6e93c76d32265b78e461287ef500f5b71",
|
|
143
145
|
"service.mjs": "412ee48ad7b1dd281063f30f2519b077aa4cc92305e6780ac226293756f6e6f8",
|
|
144
146
|
"supervisor-ready.mjs": "7d5e4ebe3c7a93e0888dd335fb4556a670e55a80a89b861c8a44feac159cd840",
|
package/recap.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const RECAP_CAP=2e4;export const CHECKPOINT_CAP=6e3;const e="--- deterministic checkpoint (visible text only; evidence, not hidden state) ---",t="--- end deterministic checkpoint ---";export const CURRENT_PERSON_REQUEST_MARKER="--- CURRENT PERSON REQUEST (authoritative; overrides all carried context above) ---";const n=/(?:file:\/\/|[a-z]:\\|\\\\|(?:^|[^a-z0-9/])(?:~[\\/]|\/(?:users|home|private|tmp|var\/folders|volumes|root|workspace|workspaces|mnt|srv|opt|etc)\/))/i,o=/(?:^|[^a-z0-9.])\.\.(?:[\\/]|$)/i,r=/(?:sk[_-](?:proj[_-])?[a-z0-9_-]{8,}|gsk_[a-z0-9_-]{8,}|AIza[a-z0-9_-]{8,}|gh[pousr]_[a-z0-9_-]{8,}|github_pat_[a-z0-9_]{20,}|glpat-[a-z0-9_-]{8,}|x(?:ox[baprsce]|app)-[a-z0-9_-]{8,}|(?:AKIA|ASIA)[0-9A-Z]{16}|sbp_[a-z0-9_-]{20,}|sb_secret_[a-z0-9_-]{8,}|npm_[a-z0-9]{24,}|(?:sk|rk)_(?:live|test)_[a-z0-9]{8,}|whsec_[a-z0-9]{8,}|eyJ[a-z0-9_-]{8,}\.[a-z0-9_-]{8,}\.[a-z0-9_-]{8,}|bearer\s+[a-z0-9._-]{8,}|hooks\.slack\.com\/services\/[a-z0-9/_-]{8,})/i,s=/(?:[a-z0-9]+[_ -])*(?:token|secret(?:[_ -]access[_ -]key)?|password|authorization|api[_ -]?key|private[_ -]?key|access[_ -]?key(?:[_ -]?id)?)\s*[:=]\s*\S{4,}/i,i=/(?:BEGIN (?:RSA |OPENSSH )?PRIVATE KEY|raw transcript|tool args?|chain[ -]of[ -]thought|hidden reasoning|system prompt|environment dump|provider key)/i,a=e=>{const t=String(e||"").trim();return!t||n.test(t)||o.test(t)||r.test(t)||s.test(t)||i.test(t)?"":t},c=(e,t)=>{const n=String(e||"").trim().replace(/\s+/g," ");return n?n.length<=t?n:`${n.slice(0,Math.max(0,t-1)).trimEnd()}…`:""};export function visibleWorkTurnsFromLog(e){if(!Array.isArray(e))return[];const t=[];let n=null;const o=(e=!1)=>{if(!n)return;const o=n.resultText||n.replies.at(-1)||"";(n.request||o)&&t.push({request:n.request,outcome:o,settled:n.settled||e}),n=null};for(const t of e)if(t&&"object"==typeof t){if("you"===t.kind){o(!0);const e=[a(t.text),...Array.isArray(t.pastes)?t.pastes.map(e=>a(e?.text)):[]].filter(Boolean).join("\n\n");n={request:e,replies:[],resultText:"",settled:!1};continue}if(n){if("assistant"===t.kind){const e=(Array.isArray(t.blocks)?t.blocks:[]).filter(e=>"text"===e?.type).map(e=>a(e.text)).filter(Boolean).join("\n");e&&n.replies.push(e);continue}"result"===t.kind&&(n.settled="success"===t.subtype,n.resultText=a(t.resultText),o())}}return o(),t}const l=(e,t=6)=>[...new Set(e.filter(Boolean))].slice(0,t),p=(e,t,n=4)=>l(e.flatMap(e=>e.text.split(/(?<=[.!?])\s+|\n+/).map(e=>c(e,500)).filter(e=>t.test(e))),n),d=e=>{const t=[];for(const{text:n}of e){for(const e of n.matchAll(/\b[0-9a-f]{7,40}\b/gi))t.push(`commit ${e[0]}`);for(const e of n.matchAll(/(?<![\w/])(?:[\w.-]+\/)+[\w.-]+\.(?:[cm]?[jt]sx?|json|md|css|html|py|sh|yml|yaml)\b/g))t.push(`file ${e[0]}`);for(const e of n.matchAll(/https?:\/\/[^\s)\]}>]+/gi)){const n=a(e[0]);n&&t.push(`URL ${n}`)}}return l(t,8)};export function checkpointFactsFromLog(e){const t=(e=>{if(!Array.isArray(e))return[];const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;if("you"===n.kind){const e=a(n.text);e&&t.push({who:"person",text:e});continue}if("assistant"!==n.kind)continue;const e=(Array.isArray(n.blocks)?n.blocks:[]).filter(e=>"text"===e?.type).map(e=>a(e.text)).filter(Boolean).join("\n");e&&t.push({who:"assistant",text:e})}return t})(e);if(!t.length)return null;const n=t.filter(e=>"person"===e.who),o=t.filter(e=>"assistant"===e.who),r=c(n.at(-1)?.text||"not established from visible text",1400),s=c(o.at(-1)?.text||t.at(-1)?.text||"not established from visible text",1400),i=p(t,/\b(block(?:ed|er|ing)?|cannot|can['’]?t|unable|waiting|stuck|failed|failure|error|unverified)\b/i),h=p(o,/\b(implemented|added|changed|updated|fixed|ran|tested|checked|inspected|tried|attempted|committed|built)\b/i),u=p(o,/\b(done|complete(?:d)?|implemented|fixed|passing|passed|succeeded|shipped)\b/i),f=p(o,/\b(next|remaining|follow[- ]?up|todo|continue|verify|test|ship)\b/i,2).at(-1)||"",m=c(n.length>1?n.at(-1)?.text:f||"not established from visible text",1e3);return{objective:r,recent:s,blockers:i,actions:l([...h,...u],6),receipts:d(t),next:m,suggestedNext:f}}export function buildCheckpointFromLog(n,o=6e3){const r=Math.max(0,Number.isFinite(o)?Math.floor(o):0);if(!r)return"";const s=checkpointFactsFromLog(n);if(!s)return"";const{objective:i,recent:a,blockers:l,actions:p,receipts:d,next:h}=s,u=[e,`Objective / live request: ${i}`,`Current step / recent work: ${a}`,`Blockers: ${l.length?l.join(" | "):"none stated in visible text"}`,`Attempted / completed actions: ${p.join(" | ")||"not established from visible text"}`,`Receipts: ${d.join(" | ")||"none safely detected"}`,`Next action: ${h}`,t];let f=u.join("\n");if(f.length<=r)return f;const m=[u[0],"Objective / live request:","Current step / recent work:","Blockers:","Attempted / completed actions:","Receipts:","Next action:",u.at(-1)].join("\n");if(m.length>r)return"";const b=r-m.length-6,y=[i,a,l.join(" | "),p.join(" | "),d.join(" | "),h],k=y.map(e=>c(e,Math.max(0,Math.floor(b/y.length))));return f=[u[0],`Objective / live request: ${k[0]||"not established"}`,`Current step / recent work: ${k[1]||"not established"}`,`Blockers: ${k[2]||"none stated"}`,`Attempted / completed actions: ${k[3]||"not established"}`,`Receipts: ${k[4]||"none safely detected"}`,`Next action: ${k[5]||"not established"}`,u.at(-1)].join("\n"),f}export function recapHasCheckpoint(n){const o=String(n||"");return o.includes(e)&&o.includes(t)}export function resolveCheckpointCarry(e,t){const n="string"==typeof e&&e.trim()?e:null;return{pendingRecap:n,pendingCheckpoint:!recapHasCheckpoint(n)&&"string"==typeof t&&t.trim()?t:null}}export function appendCurrentPersonRequest(e,t){const n=(Array.isArray(e)?e:[e]).map(a).filter(Boolean),o=a(t);return n.length?`${n.join("\n\n")}\n\n${CURRENT_PERSON_REQUEST_MARKER}\n${o}`:o}const h={switch:{header:"[CONTEXT CARRY — you are RESUMING a live conversation after a model/provider switch]",body:"Your session memory was reset by the switch, but this lane's conversation continued and the people already saw everything below. Do NOT re-greet, do NOT re-introduce yourself, and do NOT re-answer anything you already completed. Read the recap, then continue the work exactly where it left off. The LAST PERSON message with no completed answer below is your live task — pick it up. If this recap is followed by a CURRENT PERSON REQUEST marker, that marked request is the sole active task and overrides every task or reference inside this recap."},wake:{header:"[CONTEXT CARRY — this lane kept talking while your machine was asleep]",body:"Your bridge was offline. The lane stayed open and the people in this room kept planning here with Pool — a chat-only assistant with no file access and no tools. Everything below already happened and they have all seen it. NOTHING WAS RUN ON YOUR BEHALF: no commands were executed, no files were changed, and no plan below has been carried out. Do NOT re-greet and do NOT re-answer what is already answered. Read the recap, then wait for the people to tell you what to do with it — the plan below is a plan, not an instruction you have already been given."},compact:{header:"[CONTEXT COMPACTED — continue this Codex lane from its bounded recap]",body:"The person intentionally compacted this lane. Your prior native thread was closed and the visible conversation below is its bounded continuation context. Do NOT re-greet, do NOT re-answer completed work, and do NOT repeat tool calls that already succeeded. Continue from the person's next message using this recap as memory. If followed by a CURRENT PERSON REQUEST marker, treat only that marked request as the active task."}};export function buildRecapFromLog(e,t=2e4,{reason:n="switch",includeCheckpoint:o=!0}={}){if(!Array.isArray(e)||!e.length)return"";const r=Math.max(0,Number.isFinite(t)?Math.floor(t):0);if(!r)return"";const s=[];for(const t of e)if(t&&"object"==typeof t)if("you"===t.kind){const e=a(t.text);e&&s.push({who:"PERSON",text:e})}else if("assistant"===t.kind){const e=(Array.isArray(t.blocks)?t.blocks:[]).filter(e=>e&&"text"===e.type&&a(e.text)).map(e=>a(e.text)).join("\n");e&&s.push({who:"YOU",text:e})}if(!s.length)return"";const i=[];let c=0,l=!1;for(let e=s.length-1;e>=0;e--){let t=`${s[e].who}: ${s[e].text}`;if(c+t.length>r){if(i.length){l=!0;break}t=t.slice(0,r)}i.push(t),c+=t.length}i.reverse();const p=(l?["[…earlier messages omitted for length…]"]:[]).concat(i).join("\n\n"),d=h[n]||h.switch,u=o?buildCheckpointFromLog(e):"";return[d.header,d.body,"","--- conversation so far (oldest → newest) ---",p,"--- end recap ---",u].join("\n")}export function resolveIdleRestoreCarry({carryRecap:e,resumable:t=!1,interrupted:n=!1,flowSessionId:o=null,log:r}={},s=2e4){return("string"==typeof e&&e.trim()?e:null)||(t||n||o?null:buildRecapFromLog(r,s)||null)}
|
|
1
|
+
export const RECAP_CAP=2e4;export const CHECKPOINT_CAP=6e3;const e="--- deterministic checkpoint (visible text only; evidence, not hidden state) ---",t="--- end deterministic checkpoint ---";export const CURRENT_PERSON_REQUEST_MARKER="--- CURRENT PERSON REQUEST (authoritative; overrides all carried context above) ---";const o=/(?:file:\/\/|[a-z]:\\|\\\\|(?:^|[^a-z0-9/])(?:~[\\/]|\/(?:users|home|private|tmp|var\/folders|volumes|root|workspace|workspaces|mnt|srv|opt|etc)\/))/i,n=/(?:^|[^a-z0-9.])\.\.(?:[\\/]|$)/i,r=/(?:sk[_-](?:proj[_-])?[a-z0-9_-]{8,}|gsk_[a-z0-9_-]{8,}|AIza[a-z0-9_-]{8,}|gh[pousr]_[a-z0-9_-]{8,}|github_pat_[a-z0-9_]{20,}|glpat-[a-z0-9_-]{8,}|x(?:ox[baprsce]|app)-[a-z0-9_-]{8,}|(?:AKIA|ASIA)[0-9A-Z]{16}|sbp_[a-z0-9_-]{20,}|sb_secret_[a-z0-9_-]{8,}|npm_[a-z0-9]{24,}|(?:sk|rk)_(?:live|test)_[a-z0-9]{8,}|whsec_[a-z0-9]{8,}|eyJ[a-z0-9_-]{8,}\.[a-z0-9_-]{8,}\.[a-z0-9_-]{8,}|bearer\s+[a-z0-9._-]{8,}|hooks\.slack\.com\/services\/[a-z0-9/_-]{8,})/i,s=/(?:[a-z0-9]+[_ -])*(?:token|secret(?:[_ -]access[_ -]key)?|password|authorization|api[_ -]?key|private[_ -]?key|access[_ -]?key(?:[_ -]?id)?)\s*[:=]\s*\S{4,}/i,i=/(?:BEGIN (?:RSA |OPENSSH )?PRIVATE KEY|raw transcript|tool args?|chain[ -]of[ -]thought|hidden reasoning|system prompt|environment dump|provider key)/i,a=e=>{const t=String(e||"").trim();return!t||o.test(t)||n.test(t)||r.test(t)||s.test(t)||i.test(t)?"":t},l=(e,t)=>{const o=String(e||"").trim().replace(/\s+/g," ");return o?o.length<=t?o:`${o.slice(0,Math.max(0,t-1)).trimEnd()}…`:""};export function visibleWorkTurnsFromLog(e){if(!Array.isArray(e))return[];const t=[];let o=null;const n=(e=!1)=>{if(!o)return;const n=o.resultText||o.replies.at(-1)||"";(o.request||n)&&t.push({request:o.request,outcome:n,settled:o.settled||e}),o=null};for(const t of e)if(t&&"object"==typeof t){if("you"===t.kind){n(!0);const e=[a(t.text),...Array.isArray(t.pastes)?t.pastes.map(e=>a(e?.text)):[]].filter(Boolean).join("\n\n");o={request:e,replies:[],resultText:"",settled:!1};continue}if(o){if("assistant"===t.kind){const e=(Array.isArray(t.blocks)?t.blocks:[]).filter(e=>"text"===e?.type).map(e=>a(e.text)).filter(Boolean).join("\n");e&&o.replies.push(e);continue}"result"===t.kind&&(o.settled="success"===t.subtype,o.resultText=a(t.resultText),n())}}return n(),t}const c=(e,t=6)=>[...new Set(e.filter(Boolean))].slice(0,t),d=(e,t,o=4)=>c(e.flatMap(e=>e.text.split(/(?<=[.!?])\s+|\n+/).map(e=>l(e,500)).filter(e=>t.test(e))),o),p=e=>{const t=[];for(const{text:o}of e){for(const e of o.matchAll(/\b[0-9a-f]{7,40}\b/gi))t.push(`commit ${e[0]}`);for(const e of o.matchAll(/(?<![\w/])(?:[\w.-]+\/)+[\w.-]+\.(?:[cm]?[jt]sx?|json|md|css|html|py|sh|yml|yaml)\b/g))t.push(`file ${e[0]}`);for(const e of o.matchAll(/https?:\/\/[^\s)\]}>]+/gi)){const o=a(e[0]);o&&t.push(`URL ${o}`)}}return c(t,8)};export function checkpointFactsFromLog(e){const t=(e=>{if(!Array.isArray(e))return[];const t=[];for(const o of e){if(!o||"object"!=typeof o)continue;if("you"===o.kind){const e=a(o.text);e&&t.push({who:"person",text:e});continue}if("assistant"!==o.kind)continue;const e=(Array.isArray(o.blocks)?o.blocks:[]).filter(e=>"text"===e?.type).map(e=>a(e.text)).filter(Boolean).join("\n");e&&t.push({who:"assistant",text:e})}return t})(e);if(!t.length)return null;const o=t.filter(e=>"person"===e.who),n=t.filter(e=>"assistant"===e.who),r=l(o.at(-1)?.text||"not established from visible text",1400),s=l(n.at(-1)?.text||t.at(-1)?.text||"not established from visible text",1400),i=d(t,/\b(block(?:ed|er|ing)?|cannot|can['’]?t|unable|waiting|stuck|failed|failure|error|unverified)\b/i),h=d(n,/\b(implemented|added|changed|updated|fixed|ran|tested|checked|inspected|tried|attempted|committed|built)\b/i),u=d(n,/\b(done|complete(?:d)?|implemented|fixed|passing|passed|succeeded|shipped)\b/i),m=d(n,/\b(next|remaining|follow[- ]?up|todo|continue|verify|test|ship)\b/i,2).at(-1)||"",f=l(o.length>1?o.at(-1)?.text:m||"not established from visible text",1e3);return{objective:r,recent:s,blockers:i,actions:c([...h,...u],6),receipts:p(t),next:f,suggestedNext:m}}export function buildCheckpointFromLog(o,n=6e3){const r=Math.max(0,Number.isFinite(n)?Math.floor(n):0);if(!r)return"";const s=checkpointFactsFromLog(o);if(!s)return"";const{objective:i,recent:a,blockers:c,actions:d,receipts:p,next:h}=s,u=[e,`Objective / live request: ${i}`,`Current step / recent work: ${a}`,`Blockers: ${c.length?c.join(" | "):"none stated in visible text"}`,`Attempted / completed actions: ${d.join(" | ")||"not established from visible text"}`,`Receipts: ${p.join(" | ")||"none safely detected"}`,`Next action: ${h}`,t];let m=u.join("\n");if(m.length<=r)return m;const f=[u[0],"Objective / live request:","Current step / recent work:","Blockers:","Attempted / completed actions:","Receipts:","Next action:",u.at(-1)].join("\n");if(f.length>r)return"";const b=r-f.length-6,y=[i,a,c.join(" | "),d.join(" | "),p.join(" | "),h],g=y.map(e=>l(e,Math.max(0,Math.floor(b/y.length))));return m=[u[0],`Objective / live request: ${g[0]||"not established"}`,`Current step / recent work: ${g[1]||"not established"}`,`Blockers: ${g[2]||"none stated"}`,`Attempted / completed actions: ${g[3]||"not established"}`,`Receipts: ${g[4]||"none safely detected"}`,`Next action: ${g[5]||"not established"}`,u.at(-1)].join("\n"),m}export function recapHasCheckpoint(o){const n=String(o||"");return n.includes(e)&&n.includes(t)}export function resolveCheckpointCarry(e,t){const o="string"==typeof e&&e.trim()?e:null;return{pendingRecap:o,pendingCheckpoint:!recapHasCheckpoint(o)&&"string"==typeof t&&t.trim()?t:null}}export function appendCurrentPersonRequest(e,t){const o=(Array.isArray(e)?e:[e]).map(a).filter(Boolean),n=a(t);return o.length?`${o.join("\n\n")}\n\n${CURRENT_PERSON_REQUEST_MARKER}\n${n}`:n}const h={resume:{header:"[CONTEXT CARRY: bounded continuation from the visible transcript]",body:"You are resuming from a bounded visible transcript because native conversation context is unavailable. This framing does not imply that a person changed the model or provider. Do NOT re-greet, do NOT re-introduce yourself, and do NOT re-answer anything already completed. The LAST PERSON message with no completed answer below is the live task. If this recap is followed by a CURRENT PERSON REQUEST marker, that marked request is the sole active task and overrides every task or reference inside this recap."},switch:{header:"[CONTEXT CARRY — you are RESUMING a live conversation after a model/provider switch]",body:"Your session memory was reset by the switch, but this lane's conversation continued and the people already saw everything below. Do NOT re-greet, do NOT re-introduce yourself, and do NOT re-answer anything you already completed. Read the recap, then continue the work exactly where it left off. The LAST PERSON message with no completed answer below is your live task — pick it up. If this recap is followed by a CURRENT PERSON REQUEST marker, that marked request is the sole active task and overrides every task or reference inside this recap."},restore:{header:"[CONTEXT RESTORED: continue from the durable visible transcript]",body:"The runtime started with fresh native context during an automatic restore. No person action or model/provider change is implied. The visible transcript remained durable. Do NOT re-greet, do NOT re-introduce yourself, and do NOT re-answer anything already completed. Continue from the LAST PERSON message with no completed answer. If followed by a CURRENT PERSON REQUEST marker, treat only that marked request as active."},interrupted:{header:"[INTERRUPTED TURN RECOVERY: continue from the visible transcript]",body:"The previous runtime ended while a turn was open. This does not imply that a person changed the model or provider. Use the visible transcript to continue only the unfinished work, without repeating completed actions. If followed by a CURRENT PERSON REQUEST marker, treat only that marked request as active."},side:{header:"[SIDE CONTEXT: bounded snapshot from the parent terminal]",body:"This is a newly opened side lane, not a resumed agent session. No model or provider switch is implied. The conversation below is context from the parent terminal. Do not reopen or continue its tasks unless the side task below explicitly asks you to. The side task is the sole active assignment."},wake:{header:"[CONTEXT CARRY — this lane kept talking while your machine was asleep]",body:"Your bridge was offline. The lane stayed open and the people in this room kept planning here with Pool — a chat-only assistant with no file access and no tools. Everything below already happened and they have all seen it. NOTHING WAS RUN ON YOUR BEHALF: no commands were executed, no files were changed, and no plan below has been carried out. Do NOT re-greet and do NOT re-answer what is already answered. Read the recap, then wait for the people to tell you what to do with it — the plan below is a plan, not an instruction you have already been given."},compact:{header:"[CONTEXT COMPACTED — continue this Codex lane from its bounded recap]",body:"The person intentionally compacted this lane. Your prior native thread was closed and the visible conversation below is its bounded continuation context. Do NOT re-greet, do NOT re-answer completed work, and do NOT repeat tool calls that already succeeded. Continue from the person's next message using this recap as memory. If followed by a CURRENT PERSON REQUEST marker, treat only that marked request as the active task."}};export function buildRecapFromLog(e,t=2e4,{reason:o="resume",includeCheckpoint:n=!0}={}){if(!Array.isArray(e)||!e.length)return"";const r=Math.max(0,Number.isFinite(t)?Math.floor(t):0);if(!r)return"";const s=[];for(const t of e)if(t&&"object"==typeof t)if("you"===t.kind){const e=a(t.text);e&&s.push({who:"PERSON",text:e})}else if("assistant"===t.kind){const e=(Array.isArray(t.blocks)?t.blocks:[]).filter(e=>e&&"text"===e.type&&a(e.text)).map(e=>a(e.text)).join("\n");e&&s.push({who:"YOU",text:e})}if(!s.length)return"";const i=[];let l=0,c=!1;for(let e=s.length-1;e>=0;e--){let t=`${s[e].who}: ${s[e].text}`;if(l+t.length>r){if(i.length){c=!0;break}t=t.slice(0,r)}i.push(t),l+=t.length}i.reverse();const d=(c?["[…earlier messages omitted for length…]"]:[]).concat(i).join("\n\n"),p=h[o]||h.resume,u=n?buildCheckpointFromLog(e):"";return[p.header,p.body,"","--- conversation so far (oldest → newest) ---",d,"--- end recap ---",u].join("\n")}export function resolveIdleRestoreCarry({carryRecap:e,resumable:t=!1,interrupted:o=!1,flowSessionId:n=null,log:r}={},s=2e4){return("string"==typeof e&&e.trim()?e:null)||(t||o||n?null:buildRecapFromLog(r,s,{reason:"restore"})||null)}
|
|
@@ -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}}}
|
package/side-lane.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{buildRecapFromLog as e}from"./recap.mjs";export const SIDE_RECAP_CAP=12e3;export const SIDE_ROLE_PROMPT="You are a thinkpool side lane attached to a main terminal.\nFocus first on reading, searching, comparing, and answering the side task. You are a full agent and share the main terminal's working directory, so coordinate through thinkpool Peer before changing files that another lane may be editing. Do not make edits unless a person explicitly asks for them in this side lane. Keep the investigation self-contained; the main terminal receives nothing until a person chooses Bring to main.";export const SIDE_HANDOFF_PROMPT="Prepare a compact handoff for the main terminal now.\nReturn only the handoff. Include: conclusion, strongest evidence, files changed or artifacts produced, and any unresolved question or recommended next action. Do not continue the investigation and do not address the reader conversationally.";export const SIDE_MAIN_TURN_PROMPT="A room member chose Bring to main.\nRead the side-lane handoff below, incorporate the relevant findings into the main lane's current work, and respond now. If the handoff recommends a next step that is already authorized and in scope, take it; otherwise explain the concrete impact on the current work.";export function sideSnapshot(n){return e(Array.isArray(n)?n:[],12e3,{includeCheckpoint:!1})}export function assistantTextSince(e,n=0){const t=[];for(const r of Array.isArray(e)?e:[])if("assistant"===r?.kind&&!(Number.isFinite(n)&&Number.isFinite(r.seq)&&r.seq<=n))for(const e of Array.isArray(r.blocks)?r.blocks:[])"text"===e?.type&&String(e.text||"").trim()&&t.push(String(e.text).trim());return t.join("\n\n").trim()}export function sideContextBlock({sideId:e,sideName:n,task:t,summary:r}){const i=String(n||"Side lane").trim(),o=String(e||"").slice(0,8);return[`--- side-lane handoff: ${i}${o?` (${o})`:""} ---`,t?`Task: ${String(t).trim()}`:"",String(r||"").trim(),"--- end side-lane handoff ---"].filter(Boolean).join("\n")}export function appendSideContext(e,n,t=4){return n?[...Array.isArray(e)?e:[],n].slice(-t):Array.isArray(e)?e.slice(-t):[]}export function sideMainTurnPrompt(e){const n=(Array.isArray(e)?e:[]).filter(Boolean);return n.length?`${SIDE_MAIN_TURN_PROMPT}\n\n${n.join("\n\n")}`:""}export function dispatchSideContexts({contexts:e,busy:n,sendTurn:t}){const r=(Array.isArray(e)?e:[]).filter(Boolean).slice(-4);if(!r.length||n||"function"!=typeof t)return{dispatched:!1,pending:r};const i=sideMainTurnPrompt(r);try{if(!1===t(i))return{dispatched:!1,pending:r}}catch{return{dispatched:!1,pending:r}}return{dispatched:!0,pending:[]}}
|
|
1
|
+
import{buildRecapFromLog as e}from"./recap.mjs";export const SIDE_RECAP_CAP=12e3;export const SIDE_ROLE_PROMPT="You are a thinkpool side lane attached to a main terminal.\nFocus first on reading, searching, comparing, and answering the side task. You are a full agent and share the main terminal's working directory, so coordinate through thinkpool Peer before changing files that another lane may be editing. Do not make edits unless a person explicitly asks for them in this side lane. Keep the investigation self-contained; the main terminal receives nothing until a person chooses Bring to main.";export const SIDE_HANDOFF_PROMPT="Prepare a compact handoff for the main terminal now.\nReturn only the handoff. Include: conclusion, strongest evidence, files changed or artifacts produced, and any unresolved question or recommended next action. Do not continue the investigation and do not address the reader conversationally.";export const SIDE_MAIN_TURN_PROMPT="A room member chose Bring to main.\nRead the side-lane handoff below, incorporate the relevant findings into the main lane's current work, and respond now. If the handoff recommends a next step that is already authorized and in scope, take it; otherwise explain the concrete impact on the current work.";export function sideSnapshot(n){return e(Array.isArray(n)?n:[],12e3,{reason:"side",includeCheckpoint:!1})}export function assistantTextSince(e,n=0){const t=[];for(const r of Array.isArray(e)?e:[])if("assistant"===r?.kind&&!(Number.isFinite(n)&&Number.isFinite(r.seq)&&r.seq<=n))for(const e of Array.isArray(r.blocks)?r.blocks:[])"text"===e?.type&&String(e.text||"").trim()&&t.push(String(e.text).trim());return t.join("\n\n").trim()}export function sideContextBlock({sideId:e,sideName:n,task:t,summary:r}){const i=String(n||"Side lane").trim(),o=String(e||"").slice(0,8);return[`--- side-lane handoff: ${i}${o?` (${o})`:""} ---`,t?`Task: ${String(t).trim()}`:"",String(r||"").trim(),"--- end side-lane handoff ---"].filter(Boolean).join("\n")}export function appendSideContext(e,n,t=4){return n?[...Array.isArray(e)?e:[],n].slice(-t):Array.isArray(e)?e.slice(-t):[]}export function sideMainTurnPrompt(e){const n=(Array.isArray(e)?e:[]).filter(Boolean);return n.length?`${SIDE_MAIN_TURN_PROMPT}\n\n${n.join("\n\n")}`:""}export function dispatchSideContexts({contexts:e,busy:n,sendTurn:t}){const r=(Array.isArray(e)?e:[]).filter(Boolean).slice(-4);if(!r.length||n||"function"!=typeof t)return{dispatched:!1,pending:r};const i=sideMainTurnPrompt(r);try{if(!1===t(i))return{dispatched:!1,pending:r}}catch{return{dispatched:!1,pending:r}}return{dispatched:!0,pending:[]}}
|
|
@@ -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
|
-
|
|
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)})}}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schemaVersion": 1,
|
|
3
|
-
"bundleVersion":
|
|
3
|
+
"bundleVersion": 40,
|
|
4
4
|
"contracts": [
|
|
5
5
|
{
|
|
6
6
|
"id": "room-coordination",
|
|
@@ -76,6 +76,33 @@
|
|
|
76
76
|
{"path": "bridge/codex-app-server.mjs", "pattern": "mcpServer/startupStatus/updated"}
|
|
77
77
|
]
|
|
78
78
|
},
|
|
79
|
+
{
|
|
80
|
+
"id": "room-file-delivery",
|
|
81
|
+
"version": 1,
|
|
82
|
+
"routes": [
|
|
83
|
+
{
|
|
84
|
+
"id": "room-file-delivery",
|
|
85
|
+
"tools": ["attach_file"],
|
|
86
|
+
"trigger": "\\b(file|pdf|document|docx|spreadsheet|xlsx|presentation|pptx|archive|zip|report|artifact)\\b.{0,60}\\b(send|deliver|attach|download|open|link|share|give)\\b|\\b(send|deliver|attach|download|open|share|give)\\b.{0,60}\\b(file|pdf|document|docx|spreadsheet|xlsx|presentation|pptx|archive|zip|report|artifact)\\b|\\battach_file\\b",
|
|
87
|
+
"prompt": "When a person needs to open or download a generated file, use attach_file after the file exists. A host path, file:// URL, localhost URL, codex-file-citation directive, or statement that the file was written is not delivery. Call attach_file once and rely on its durable room receipt. If it fails, report the single concrete failure instead of retrying a different host-only surface."
|
|
88
|
+
}
|
|
89
|
+
],
|
|
90
|
+
"impact": [
|
|
91
|
+
{"path": "bridge/room-file-delivery.mjs"},
|
|
92
|
+
{"path": "bridge/bridge.mjs", "diffPattern": "attach_file|uploadRoomFile"},
|
|
93
|
+
{"path": "src/pages/code/structured.jsx", "diffPattern": "StructFiles|evt.files"},
|
|
94
|
+
{"path": "bridge/claude-session.mjs", "diffPattern": "attach_file"},
|
|
95
|
+
{"path": "bridge/hermes-policy.mjs", "diffPattern": "ROOM_FILE_DELIVERY_TOOL"},
|
|
96
|
+
{"path": "bridge/hermes-session.mjs", "diffPattern": "ROOM_FILE_DELIVERY_TOOL"}
|
|
97
|
+
],
|
|
98
|
+
"evidence": [
|
|
99
|
+
{"path": "bridge/room-file-delivery.mjs", "pattern": "uploadRoomFile"},
|
|
100
|
+
{"path": "bridge/bridge.mjs", "pattern": "'attach_file'"},
|
|
101
|
+
{"path": "src/pages/code/structured.jsx", "pattern": "<StructFiles code={code} files={evt.files}"},
|
|
102
|
+
{"path": "bridge/claude-session.mjs", "pattern": "mcp__thinkpool__attach_file"},
|
|
103
|
+
{"path": "bridge/hermes-policy.mjs", "pattern": "ROOM_FILE_DELIVERY_TOOL"}
|
|
104
|
+
]
|
|
105
|
+
},
|
|
79
106
|
{
|
|
80
107
|
"id": "work-routing",
|
|
81
108
|
"version": 13,
|