thinkpool-pair 0.7.386 → 0.7.388
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/cross-terminal.mjs +1 -1
- package/lane-work-snapshot.mjs +1 -1
- package/package.json +1 -1
- package/publish-manifest.json +11 -11
- package/thinkpool-capabilities.json +6 -6
- package/thinkpool-room-prompt.mjs +1 -1
- package/worker-completion.mjs +1 -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,usesFullThinkPoolReminder as g}from"./thinkpool-room-prompt.mjs";import{stallDecision as w,stallEvent as b,isCompactTurn as v}from"./turn-stall.mjs";import{createSameTargetResilienceController as _,formatResilienceTrace as T}from"./provider-resilience.mjs";const S=t(import.meta.url);export async function claudeOneShot({prompt:e,model:t="claude-haiku-4-5",cwd:o,env:n,timeoutMs:s=8e3}={}){const i=new AbortController,a=setTimeout(()=>{try{i.abort()}catch{}},s);try{const s=r({prompt:e,options:{model:t,...o?{cwd:o}:{},env:n,maxTurns:1,permissionMode:"bypassPermissions",settingSources:[],strictMcpConfig:!0,mcpServers:{},abortController:i}});let a="";for await(const e of s){if("assistant"===e.type)for(const t of e.message?.content||[])"text"===t.type&&(a+=t.text);if("result"===e.type)break}return a.trim()}finally{clearTimeout(a)}}const E=(()=>{try{let e=n(S.resolve("@anthropic-ai/claude-agent-sdk"));for(let t=0;t<8;t++){try{const t=JSON.parse(o(s(e,"package.json"),"utf8"));if("@anthropic-ai/claude-agent-sdk"===t.name)return t.version}catch{}const t=n(e);if(t===e)break;e=t}}catch{}return"unknown"})(),N=/\brm\s+\S|\brmdir\s+\S|\bgit\s+(push\s+(-f|--force)|reset\s+--hard|clean\s+-[a-z]*f)|\bdrop\s+(table|database)\b|\b(mkfs|dd)\b|\bsudo\b|>\s*\/dev\/|\bchmod\s+-R|\bchown\s+-R|\bkillall\b|\btruncate\b/i,O=new Set(["Read","Grep","Glob","NotebookRead","TodoRead","LS"]),R=new Set(["WebFetch","WebSearch"]),A=new Set(["Edit","Write","MultiEdit","NotebookEdit","TodoWrite"]);export function classifyRisk(e,t){if("Bash"===e){const e=t&&(t.command??t.cmd)||"";return N.test(e)?"high":"medium"}return O.has(e)?"low":R.has(e)?"network":(A.has(e),"medium")}const D=/(^|\/)\.claude\/SESSIONS\/|(^|\/)CLAUDE\.md$/;export function isSafeDocWrite(e,t){if(!A.has(e))return!1;const o=t&&(t.file_path||t.notebook_path)||"";return D.test(o)}export function autoAllow({toolName:e,input:t,mode:o="default",alwaysAllow:n=new Set}){const s=classifyRisk(e,t);return"low"===s||"bypassPermissions"===o||"acceptEdits"===o&&A.has(e)&&"high"!==s||isSafeDocWrite(e,t)||n.has(`${e}:${s}`)}export function askUserQuestionHookOutput(e){const t=e&&"object"==typeof e?e.decision:e,o="string"==typeof t&&t.startsWith("answer:")?t.slice(7):"",n=e&&"object"==typeof e?e.responder:null,s="string"==typeof n?.name&&n.name.trim()?n.name.trim():"string"==typeof n?.id&&n.id?`room member ${n.id}`:"The user";return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:o?`${s} answered in the thinkpool room — ${o}. Treat this as their selection and continue; do not call AskUserQuestion again for the same question.`:"The user dismissed the question in the thinkpool room without selecting. Ask in plain prose, or proceed with a sensible default."}}}export function askUserQuestionRegression(e,t){return Array.isArray(e)?e.includes("AskUserQuestion")?null:`[SDK-REGRESSION] agent SDK v${t||"unknown"} init tools[] is missing 'AskUserQuestion' — the multiple-choice question card is disabled. A caret SDK bump likely changed the canUseTool gate; pin a known-good SDK in bridge/package.json + republish.`:null}function x(){const e=[];let t=null,o=!1;return{stream:async function*(){for(;!o;)e.length?yield e.shift():await new Promise(e=>{t=e})}(),push:n=>!o&&(e.push({type:"user",message:{role:"user",content:n}}),t&&(t(),t=null),!0),end(){o=!0,t&&(t(),t=null)}}}const P=(e=[])=>e.map(e=>"text"===e.type?{type:"text",text:e.text}:"thinking"===e.type?{type:"thinking",text:e.thinking||"",reasoningKind:"thought"}:"tool_use"===e.type?{type:"tool_use",id:e.id,name:e.name,input:e.input}:{type:e.type}).filter(Boolean),I=new Set(["default","acceptEdits","plan","bypassPermissions"]),M=["You are Claude in a thinkpool Code room, driven live from a phone or browser — NOT a local terminal. Keep using the room's features.",f,"TERMINAL HIERARCHY: obey your authoritative TERMINAL ROLE. A person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal — NEVER spawn_terminal — even for ordinary work or a handoff. If the wording includes new or separate terminal, main-terminal routing wins. Use spawn_terminal only for agent-decided bounded worker slices or when the person explicitly asks for a worker, sub-terminal, Ensemble lane, or delegated slice. If open_main_terminal is unavailable, say so; never substitute an Ensemble child. Leaf, worker, Side, and managed Flow lanes work directly. Never use built-in invisible Task/Agent subagents or hijack a busy sibling.","WORKTREES: parallel lanes share one repo — before code edits run `git worktree list`; if linked worktrees exist, take your OWN worktree + branch, never the shared checkout or a branch another lane is on.","BUILD WORKFLOW (default, no magic word): right-size within your TERMINAL ROLE — a trivial ask or delegated slice you just do; a conductor-capable role with a genuinely decomposable build FIRST writes a short plan in chat, THEN fans worker slices into visible spawn_terminal lanes and verifies them. Worker/leaf/Side/managed Flow roles do not fan out. A person-requested new or separate terminal uses open_main_terminal. Never plan-mode/ExitPlanMode; plans live in chat and lanes in the existing list."].join(" ");export function startClaudeSession({cwd:t,model:o,effort:n="high",resume:s,env:f,mode:S="default",onEvent:N,requestPermission:O,mcpServers:R,crossPostGate:A,crossRoomPostGate:D,didSpawnTarget:U=null,terminalRolePrompt:C,rolePrompt:L,blockSubagents:W=!1,onSubmitPlan:F=null,onLaneDone:$=null,onReviewVerdict:j=null,reviewGate:q=null,lazy:G=!1,roomContext:B=null,suggest:H=!0,prepareCwd:K=null,admitStart:Q=null,resilienceObserver:Y=null,resilience:z=null}){const J=k(B);let V=0,X=!0;const Z=(e,{promptIndex:t=0,forceFull:o=!1}={})=>{const n=g({promptIndex:t,forceFull:o}),s=J({force:n}),r=String(C||"").trim();return`<system-reminder>\n${n&&r?`${r}\n\n`:""}${n?M:y({text:e,promptIndex:t,forceFull:o})}${s?`\n\n${s}`:""}\n</system-reminder>`},ee=new AbortController;let te=x(),oe=s||null,ne=s||null,se=null,re=null,ie=null,ae=!1,le=!1,ce=null,de=!1,ue=!1,pe=!1,me=null,he=I.has(S)?S:"default";const fe=new Set,ye=new Map,ke=new Set(["low","medium","high","xhigh","max"]);let ge=ke.has(n)?n:"high",we=0,be=0,ve=o||null,_e=null,Te=null,Se=Promise.resolve(),Ee=!1;const Ne=e=>new Promise(t=>setTimeout(t,e)),Oe=Math.max(3e4,parseInt(process.env.TP_STALL_MS,10)||9e4);let Re=!1,Ae=Date.now(),De=!1;const xe=/connection closed|connection reset|econnreset|etimedout|socket hang up|fetch failed|network error|socket destroyed/i;let Pe=0;const Ie=(e,t={})=>{try{Y?.({reason:e,restartCount:Pe,...t})}catch{}},Me=!(!z?.policy?.enabled||!z?.providerId||"anthropic"===z.providerId);let Ue=null,Ce=null,Le=!1,We=0,Fe=!1,$e=null;const je=Math.max(3*Oe,parseInt(process.env.TP_FORCE_STOP_MS,10)||3e5);let qe=!1,Ge=!1;const Be=Math.max(je,parseInt(process.env.TP_COMPACT_FORCE_STOP_MS,10)||12e5);let He=!1,Ke=0;const Qe=O;O=async e=>{Ke++;try{return await(Qe?.(e))}finally{Ke=Math.max(0,Ke-1),Ae=Date.now()}};let Ye=!1,ze=null,Je=null,Ve=!1,Xe="",Ze=null;const et=Math.max(1200,parseInt(process.env.TP_SUGGEST_FALLBACK_MS,10)||2500),tt=e=>{try{N?.(e)}catch{}},ot=e=>{Ae=Date.now(),e&&"stalled"!==e.kind&&(De=!1),!e||"compaction"!==e.kind&&"result"!==e.kind&&"error"!==e.kind||(He=!1),tt(e)},nt=e=>{try{z?.onRecord?.(e)}catch{}"retrying"!==e?.outcome&&"cap_blocked"!==e?.outcome&&"circuit_open"!==e?.outcome||ot({kind:"note",text:T(e)})},st=()=>{if(null!=Ce){try{(z?.clearTimer||clearTimeout)(Ce)}catch{}Ce=null}},rt=()=>{if(st(),!Ue)return;const e=Number(z?.policy?.timeoutMs);if(!Number.isFinite(e)||e<=0)return;const t=z?.setTimer||setTimeout;Ce=t(()=>{if(Ce=null,!ae&&Ue&&Re){Ue.failure({message:"timeout"}),Re=!1;try{_e?.abort()}catch{}ft()}},e)},it=async()=>{if(!Ue)return!0;let e=null;try{e=await Ue.preflight()}catch{return!1}return!0===e?.admitted},at=setInterval(()=>{const e=Date.now()-Ae,t=w({turnActive:Re,awaitingUser:Ke,quietMs:e,stallMs:Oe,forceStopMs:je,stalledSent:De,stallRetried:Ge,compacting:He,compactForceStopMs:Be});if("none"===t)return;const o=b(t,e);if(o&&tt(o),"status"!==t){if("retry"===t){if(qe=!0,Ue){Ie("resilience_stall",{quietMs:e}),Ue.failure({message:"timeout"}),Re=!1;try{_e?.abort()}catch{}return void ft()}return Ie("stall_replay",{quietMs:e}),void ht(e)}qe=!0,Re=!1}else De=!0},5e3);at.unref?.();const lt=e=>{setTimeout(()=>{Promise.resolve(me?.setPermissionMode?.(e)).catch(t=>console.error(`[claude-session] setPermissionMode(${e}) failed:`,t?.message||t))},0)},ct={abortController:ee,permissionMode:he,hooks:{PreToolUse:[{hooks:[async t=>{const o=t.tool_name,n=t.tool_input,s=t.effort?.level;s&&s!==ge&&(ge=s,ot({kind:"effort",level:ge}));const r="Write"===o||"Edit"===o||"MultiEdit"===o||"NotebookEdit"===o;if(W&&r&&/(?:^|[/\\])FLOW_PLAN\.json$/i.test(n?.file_path||n?.notebook_path||"")){const e=n?.content??n?.new_string??"";let t={ok:!1,message:"Plan submission is not wired for this session."};try{t=F&&await F(e)||t}catch(e){t={ok:!1,message:`Plan submission failed: ${e?.message||e}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.message}}}if(W&&("Task"===o||"Agent"===o||"Bash"===o||r))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Bash"===o?"Flow conductors do NOT run Bash — it pops a permission card and stalls the flow. Use the Grep tool (not `grep`/`rg`), the Glob tool (not `find`/`ls`), and Read (not `cat`/`head`) — those run with no prompt. Then DECOMPOSE and submit by Writing your task-graph JSON to the file FLOW_PLAN.json.":r?'Flow conductors do NOT write project or plan-document files. Do NOT use ExitPlanMode and do NOT call submit_flow_plan (both hang here). To SUBMIT your decomposition, use the Write tool with file_path "FLOW_PLAN.json" and content = your task-graph JSON ({"summary":"…","tasks":[…]}). That single Write IS how you submit — the room ingests it directly. Do not write any other file.':"Flow conductors do NOT spawn subagents — it stalls the flow on a permission card. Inspect the codebase yourself with Read/Grep/Glob (no prompt). Then DECOMPOSE and submit by Writing your task-graph JSON to the file FLOW_PLAN.json. Do not call Task/Agent again."}};if(j&&("Write"===o||"Edit"===o)&&/(?:^|[/\\])FLOW_REVIEW(\.[a-zA-Z0-9]+)?$/.test(n?.file_path||"")){let e={ok:!1,message:"verdict signal failed"};try{e=await j(n?.content??n?.new_string??"")||e}catch(t){e={ok:!1,message:`verdict signal failed: ${t?.message||t}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.message}}}if($&&("Write"===o||"Edit"===o)&&/(?:^|[/\\])FLOW_DONE(\.[a-zA-Z0-9]+)?$/.test(n?.file_path||"")){let e={ok:!1,message:"done signal failed"};try{e=await $(n?.content??n?.new_string??"")||e}catch(t){e={ok:!1,message:`done signal failed: ${t?.message||t}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.message}}}const i=a({reviewGate:q,toolName:o,toolInput:n});if(i)return i;if("mcp__thinkpool__read_terminal"===o)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (read-only thinkpool cross-terminal read)."}};if(/^mcp__thinkpool__preview_(start|capture|inspect|stop)$/.test(o))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (contained bridge-owned viewport preview)."}};if("mcp__thinkpool__submit_flow_plan"===o)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (Flow plan submission — broadcasts the task-graph for human approval)."}};if("mcp__thinkpool__list_sessions"===o||"mcp__thinkpool__read_session"===o)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (read-only thinkpool cross-session read — your own rooms)."}};if("mcp__thinkpool__close_terminal"===o)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (thinkpool cross-terminal close — only self-spawned lanes)."}};if("mcp__thinkpool__spawn_terminal"===o)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (autonomous thinkpool worker; bounded by room caps and isolated in its own worktree)."}};if("mcp__thinkpool__open_main_terminal"===o){const t=n?.mode||he;if("bypassPermissions"!==t||"bypassPermissions"===he)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Auto-approved (open a fresh thinkpool terminal in ${t} mode — inherited, no escalation; bounded by room caps).`}};let s="deny";try{s=await(O?.({id:e(),toolName:o,input:{...n,mode:t},risk:"high"}))??"deny"}catch{s="deny"}const r="allow"===s;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:r?"allow":"deny",permissionDecisionReason:r?"Bypass terminal creation approved in the thinkpool room — the new terminal runs autonomously.":"Bypass terminal creation denied in the room — do not retry as bypass; open it without mode:bypassPermissions or ask what to do."}}}if("mcp__thinkpool__post_to_terminal"===o){const t=A?A():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-terminal post not allowed right now."}};const s=!!U&&!!U(n?.terminal);if(!l({mode:he,spawnedByMe:s}))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"bypassPermissions"===he?"Auto-approved (cross-terminal post in bypassPermissions mode — bypass means bypass).":"Auto-approved (cross-terminal post into a lane you spawned — parent→child orchestration, no per-post tap)."}};let r="deny";try{r=await(O?.({id:e(),toolName:o,input:n,risk:"high"}))??"deny"}catch{r="deny"}const i="allow"===r;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:i?"allow":"deny",permissionDecisionReason:i?"Cross-terminal post approved in the thinkpool room.":"Cross-terminal post denied in the room — do not retry; ask what to do instead."}}}if("mcp__thinkpool__post_to_session"===o){const t=D?D():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-room post not allowed right now."}};let s="deny";try{s=await(O?.({id:e(),toolName:o,input:n,risk:"high"}))??"deny"}catch{s="deny"}const r="allow"===s;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:r?"allow":"deny",permissionDecisionReason:r?"Cross-room post approved in the sending room — the target room will be asked to accept it.":"Cross-room post denied in the room — do not retry; ask what to do instead."}}}if("ExitPlanMode"===o){if("plan"!==he)return lt(he),ot({kind:"mode",mode:he}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`The thinkpool room is in ${he} mode, not Plan — the user did not ask for a plan. Do NOT call ExitPlanMode; proceed and make the changes directly. Only present a plan if the user switches the room to Plan mode or explicitly asks.`}};let t="keep";try{t=await(O?.({id:e(),toolName:o,input:n,risk:"plan",plan:n?.plan||""}))??"keep"}catch{t="keep"}if("run"===t||"accept"===t){const e="accept"===t?"acceptEdits":"default";return he=e,lt(e),ot({kind:"mode",mode:e}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Plan approved in the thinkpool room — proceed (${e} mode).`}}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:'The user chose "keep planning" in the thinkpool room. Do not exit plan mode — keep refining the plan, then call ExitPlanMode again when ready.'}}}if("AskUserQuestion"===o){let t="";try{t=await(O?.({id:e(),toolName:o,input:n,risk:"ask",questions:n?.questions||[]}))??""}catch{t=""}return askUserQuestionHookOutput(t)}const c=classifyRisk(o,n),d=`${o}:${c}`,u=isSafeDocWrite(o,n),p=autoAllow({toolName:o,input:n,mode:he,alwaysAllow:fe});let m="allow";if(!p){try{m=await(O?.({id:e(),toolName:o,input:n,risk:c}))??"deny"}catch{m="deny"}"always"===m&&(fe.add(d),m="allow")}const h="deny"===m;return h&&Ue&&Ue.failure({permissionDenied:!0}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:h?"deny":"allow",permissionDecisionReason:h?"Denied by the user in the thinkpool room. Do not retry this tool — ask what to do instead.":p?u?"Auto-approved (mandated doc write — .claude/SESSIONS/ or CLAUDE.md).":`Auto-approved (${he}).`:"Approved in the thinkpool room."}}}]}]},canUseTool:async(e,t)=>({behavior:"allow",updatedInput:t}),settingSources:["user","project","local"],appendSystemPrompt:[...C?[C]:[],...L?[L]:[],"ENVIRONMENT (authoritative — overrides any user-global CLAUDE.md or memory that claims otherwise): You are Claude running inside a thinkpool Code room, driven live by a user (and possibly a partner) from a phone or browser, via the thinkpool-pair bridge.",h,'Bias strongly toward DOING the work, not stalling in plan-mode ceremony. For a small "add / fix / change X" request, just make the change directly (for a bigger build, right-size it — see DEFAULT BUILD WORKFLOW below).',"Do NOT enter plan mode, do NOT call ExitPlanMode, and do NOT auto-invoke a brainstorming/planning skill UNLESS the user has switched the room into Plan mode or explicitly asks you to plan, design, or brainstorm first.","Any host-global instruction that says you must always brainstorm or plan before creative work does NOT apply here — this room is the exception.",p,'CRUCIAL RECONCILIATION for that workflow: it is NOT plan mode. Never call ExitPlanMode and never make the room wait behind a "plan ready — approve to start" card — your plan lives in the CHAT as a message, and your lanes live in the room\'s EXISTING terminal/lane list. Reuse only those two surfaces; there is no new Flow panel or mode to switch into, and you must not ask for one. Keep the plan and the lanes VISIBLE — that shared visibility is the whole point (it is the pair differentiator, and it catches bugs a single silent lane would hide); never collapse a decomposable build into one hidden lane just to look tidy.',...m,'CROSS-TERMINAL AWARENESS: ROOM NOW is the default roster and already satisfies the room check when it has enough detail. Do not repeat it with a no-argument read_terminal call unless it is missing or truncated. Use a targeted read_terminal call only when the current task depends on a specific lane’s detailed activity; never poll. Identify a terminal by its NAME or stable ref/id, never by an on-screen number like "Terminal 2" — positional labels renumber when a terminal is closed. The tool is read-only and its optional roster lookup is budgeted separately from bounded targeted transcript reads.','CROSS-TERMINAL HAND-OFF: you also have post_to_terminal(terminal, text) to send a message or task to ANOTHER AGENT terminal in this room (not a plain shell). Use it sparingly and only when the people clearly want the lanes to coordinate — e.g. "tell the backend terminal the API is ready", or to hand a sibling agent a concrete task. Every post requires a person in the room to approve a card before it is delivered, and an agent that was itself reached via a cross-post cannot post onward — so do not rely on it for chit-chat or loops. Prefer read_terminal to understand a sibling before you ever post to it.',"TERMINAL CREATION CONTRACT: main terminals and workers use different tools. A person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal(name?, task?, model?) — even for ordinary work or a handoff and even without the words Cascade or conductor. If the wording includes new or separate terminal, main-terminal routing wins. Never use spawn_terminal for that request, and if open_main_terminal is unavailable say so instead of substituting. Use spawn_terminal(name?, task?, model?, sliceType?) only for agent-decided bounded WORKER SUB-TERMINALS or when the person explicitly asks for a worker, sub-terminal, Ensemble lane, or delegated slice. Workers never receive the creation tools and never conduct. Do not dump work into busy siblings. Spawned workers are always autonomous in bypassPermissions and never ask the room for an approval card; the bridge still enforces room caps, hop limits, the kill-switch, and isolated linked worktrees. Wait for ROOM NOW or a completion signal instead of polling; after a worker finishes, collect it with one targeted read_terminal call and close_terminal immediately. Main terminals are independent, keep their requested permission mode, and are not owned/closed through Ensemble.","CROSS-SESSION AWARENESS: the Ensemble reaches across your SESSIONS, not just the terminals in this room. list_sessions() lists your OTHER thinkpool Code rooms — both your own rooms running on this machine AND your partner's rooms in the same pair, reachable over the per-pair bus (a room on the partner's machine shows its host). read_session(session, terminal?) reads recent activity inside one (omit `terminal` to list that room's terminals, or pass a ref/name to read that lane). Both are READ-ONLY — they never change another session, and they reach ONLY your own rooms and rooms you share with your partner, never a stranger's. Reach for them when work spans rooms — \"what's the other project up to\", \"pick up where the other session left off\", or to check a long-running task elsewhere before you act here.","CROSS-SESSION HAND-OFF: post_to_session(session, text, terminal?) sends a task or message to an agent in ANOTHER of your rooms — your own, or your partner's over the pair bus. Use it sparingly and only when the people clearly want the rooms to coordinate — e.g. hand the API room's agent a concrete follow-up once the frontend is ready. It is dual-consent: a person in YOUR room approves sending, and a person in the TARGET room approves receiving, before anything is delivered — so never rely on it for chit-chat or loops, and an agent that was itself reached via a cross-room post cannot post onward to a third room. It spends real model tokens in the other room (maybe on the other person's machine), so prefer read_session to understand a room before you ever post into it, and only post one concrete hand-off at a time. Outbound list/read/post tools need the thinkpool account bridge; a standalone owner room can still receive a paired hand-off directly and will always raise its own approval card before delivery.","SUBAGENT POLICY: in this room, a main terminal delegates worker slices through visible spawn_terminal Ensemble lanes. A person-requested new or separate terminal is created with open_main_terminal, never Ensemble. Worker, leaf, Side, and managed Flow lanes do their assigned work directly. Do NOT reach for built-in Task/Agent subagents: an in-process subagent is invisible to the room, cannot be peered at or steered, and its work is lost to the Ensemble.",'RESEARCH LANE: you have a `research` tool that runs a REAL multi-source web search + adversarial verification and returns each claim marked HELD or REJECTED with citations. Reach for it when the people would genuinely benefit from looking something external up or settling a question of current fact — pricing, "is X still maintained / deprecated", "is that benchmark real", a debate over facts you are not sure of. Do NOT run it unprompted or for things you already know: first OFFER in plain language ("want me to spawn a research lane on that and check it?"), and only call `research(question)` once they agree — it spends real budget (plan-gated Free 5 / Plus 100 runs a month) and takes ~a minute. When it returns, present the held/rejected findings clearly and invite both people to weigh the sources, flagging any held claim that rests on a source they might not trust — that shared scrutiny is the point.',"WORKTREES: parallel lanes share one machine and usually one repo. Run `git worktree list` before your first code edit; if linked worktrees exist, the shared main checkout is contended (and may be guard-blocked) — do your work in your OWN worktree on your OWN branch (`git worktree add <dir> -b <branch>`), and never edit a checkout or ride a branch another lane is using.",'WRITE PLANS INTO THE CHAT: whenever you form or revise a plan — because the room is in Plan mode, or because someone asked you to plan, design, or think it through first — write the actual plan out as a normal message in the room as you develop it: the approach, the concrete steps, the files you will touch, the open questions. The room does NOT surface plan files at all, and the plan-approval card does not reliably carry the plan text, so a plan that lives only in a plan file or only inside ExitPlanMode is INVISIBLE to the people you are working with — they just see "plan ready" with no content. The chat is the canonical place your plan lives; put it there so the room can read and react to it before you proceed.'].join(" "),includePartialMessages:!0,promptSuggestions:!0};"1"===process.env.TP_MCP_STRICT&&(ct.strictMcpConfig=!0,ct.mcpServers={}),R&&Object.keys(R).length&&(ct.mcpServers={...ct.mcpServers||{},...R}),t&&(ct.cwd=t),o&&(ct.model=o),ct.effort=ge,ct.env={...f||process.env,CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION:"1"};const dt=async()=>{if(!H)return;const e=(Xe||"").trim().slice(-1500);if(e&&!ae)try{let o=await claudeOneShot({prompt:`You are predicting the user's NEXT chat message in a live coding session, to prefill their composer. Given the assistant's latest reply below, output the single most likely next user message — short and natural (often just "proceed", "go with option A", "yes do that", or a brief follow-up). One line, <=12 words, imperative, no preamble, no quotes, no markdown.\n\nAssistant's latest reply:\n"""\n${e}\n"""\n\nNext user message:`,model:"claude-haiku-4-5",cwd:t,env:ct.env,timeoutMs:8e3});o=o.trim().split("\n")[0].replace(/^["'`]+|["'`]+$/g,"").trim().slice(0,140),!o||Ve||ae||/^(sure|of course|certainly|let me know|i can help|happy to)\b/i.test(o)||(ot({kind:"suggestion",text:o,source:"haiku"}),process.stderr.write(` ◆ [suggestion] haiku fallback: ${JSON.stringify(o)}\n`))}catch{}},ut=()=>{const e="function"==typeof Q?Q():{ok:!0};return!1!==e?.ok||(ot({kind:"error",message:e.reason||"Host memory is critically low. This agent runtime was not started.",recoverable:!0}),!1)},pt=async({admitted:e=!1}={})=>{if(!le&&!e&&!ut())return!1;if(null==ce&&(ce=Date.now()),le=!0,Te)try{Te()}catch{}Se=new Promise(e=>{Te=e});const n=new AbortController;_e=n;const a=()=>{try{n.abort()}catch{}};ee.signal.addEventListener("abort",a,{once:!0});try{if(oe){const e=i(t||process.cwd(),oe);e.blocks&&process.stderr.write(`\n ◆ healed ${e.blocks} malformed tool block(s) in the transcript before resume.\n`)}me=r({prompt:te.stream,options:{...ct,abortController:n,...oe?{resume:oe}:{}}});for await(const e of me){if(ae)break;switch(e.type){case"system":if("thinking_tokens"===e.subtype){we+be===0&&ot({kind:"thinking_tokens",tokens:e.estimated_tokens,delta:e.estimated_tokens_delta});break}if("compact_boundary"===e.subtype){X=!0,ot({kind:"compaction",trigger:e.compact_metadata?.trigger||"auto",preTokens:e.compact_metadata?.pre_tokens??null}),(async()=>{try{const e=await(me?.getContextUsage?.());e&&(ot({kind:"usage",ctx:c({used:e.totalTokens,max:e.maxTokens,pct:Math.round(e.percentage),model:e.model})}),e.model&&(ve=e.model))}catch{}})();break}if(e.session_id&&(oe=e.session_id),de||(de=!0,process.stderr.write(`\n ◆ session ready in ${Date.now()-ce}ms — MCP ${"1"===process.env.TP_MCP_STRICT?"OFF":"on"}${s?", resume":", fresh"}.\n`)),ve=ct.model||e.model||o||ve,ot({kind:"system",sessionId:oe,model:ct.model||e.model||o||null,commands:d({slashCommands:e.slash_commands,skills:e.skills})}),!pe&&Array.isArray(e.tools)){pe=!0;const t=askUserQuestionRegression(e.tools,E);t&&(process.stderr.write(`\n ⚠⚠ ${t}\n`),ot({kind:"error",message:t}))}ue||(ue=!0,Promise.resolve(me?.supportedModels?.()).then(e=>{const t=(e||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);t.length&&ot({kind:"models",models:t})}).catch(()=>{}));break;case"assistant":st(),Ue?.visibleOutput();for(const t of e.message?.content||[])"tool_use"===t?.type&&t.id&&ye.set(t.id,{at:Date.now(),name:t.name,input:t.input});{const t=(e.message?.content||[]).filter(e=>"text"===e?.type).map(e=>e.text).join("\n").trim();t&&(Xe=t)}ot({kind:"assistant",blocks:P(e.message?.content),parentToolUseId:e.parent_tool_use_id||null});break;case"user":for(const t of e.message?.content||[])if("tool_result"===t?.type){st(),Ue?.visibleOutput({tool:!0});const o=ye.get(t.tool_use_id);null!=o&&ye.delete(t.tool_use_id);const n=u(o?.name,t.content);ot({kind:"tool_result",toolUseId:t.tool_use_id,content:t.content,...n?{evidence:n}:{},isError:!!t.is_error,durationMs:null!=o?.at?Date.now()-o.at:void 0,parentToolUseId:e.parent_tool_use_id||null})}break;case"stream_event":{const t=e.event;"message_start"===t?.type?(we+=be,be=t.message?.usage?.output_tokens||0,ot({kind:"thinking_tokens",tokens:we+be})):"message_delta"===t?.type&&t.usage&&(be=t.usage.output_tokens??be,ot({kind:"thinking_tokens",tokens:we+be}));break}case"result":if(st(),e.session_id&&(oe=e.session_id),e.is_error&&Array.isArray(e.errors)&&e.errors.some(e=>/no conversation found/i.test(String(e)))&&(oe||ne)&&Pe<3){Pe++;const e=Re;Re=!1,oe=null,ne=null,ot({kind:"note",text:"previous session not found — continuing on a fresh one"});const t=te;te=x();try{t.end()}catch{}const o=e?se:null;$e=setTimeout(()=>{$e=null,ae||(pt(),null!=o&&(Re=!0,Ae=Date.now(),De=!1,te.push([{type:"text",text:o},{type:"text",text:re||Z(o,{forceFull:!0})}])))},300);break}if(Ye&&("aborted"===e.subtype||"error_during_execution"===e.subtype)){We===ze&&(Re=!1);break}if(e.is_error&&Ue){if(Le)break;Ue.failure({message:Array.isArray(e.errors)?e.errors.join(" "):e.result,status:e.status??e.statusCode,code:e.code}),Re=!1,ft();break}if(we=0,be=0,Re=!1,Ee&&(Ee=!1,setTimeout(()=>{ae||mt()},0)),"success"===e.subtype&&(Pe=0,oe&&(ne=oe)),"success"===e.subtype&&(Ue?.success(),Ue=null),qe=!1,Ge=!1,e.modelUsage&&"object"==typeof e.modelUsage){let t=null,o=-1;for(const[n,s]of Object.entries(e.modelUsage)){const e=s?.outputTokens??0;e>o&&(o=e,t=n)}t&&(ve=t)}{const t="string"==typeof e.result?e.result.replace(/\s+/g," ").trim().slice(0,200):"";ot({kind:"result",subtype:e.subtype,sessionId:oe,model:ve,costUsd:e.total_cost_usd,usage:e.usage,numTurns:e.num_turns,durationMs:e.duration_ms??null,denials:Array.isArray(e.permission_denials)?e.permission_denials.length:0,resultText:t||null})}Ze&&clearTimeout(Ze),"aborted"!==e.subtype&&(Ze=setTimeout(()=>{Ze=null,Ve||ae||dt()},et)),(async()=>{let t=null;try{const e=await(me?.getContextUsage?.());e&&(t=c({used:e.totalTokens,max:e.maxTokens,pct:Math.round(e.percentage),model:e.model}),e.model&&(ve=e.model))}catch{}const o=e.usage||{};ot({kind:"usage",costUsd:e.total_cost_usd??null,tokens:(o.input_tokens||0)+(o.output_tokens||0),ctx:t})})();break;case"prompt_suggestion":Ze&&(clearTimeout(Ze),Ze=null),e.suggestion&&(Ve=!0,ot({kind:"suggestion",text:e.suggestion}))}}}catch(e){if(st(),ae)return;if(n.signal.aborted)return;const t=e?.message||String(e);if(Ue&&Re)return Ue.failure({message:t,status:e?.status??e?.statusCode,code:e?.code}),Re=!1,void ft();if(Re=!1,ot({kind:"error",message:t}),xe.test(t)&&Pe<3){Pe++,Ie("stream_reconnect",{failureClass:"network"}),ot({kind:"note",text:`connection dropped — reconnecting (${Pe}/3)`});const e=te;te=x();try{e.end()}catch{}return void($e=setTimeout(()=>{$e=null,ae||pt()},Math.min(1e3*Pe,4e3)))}if(/no conversation found/i.test(t)&&oe&&Pe<3){Pe++,oe=null,ne=null;const e=te;te=x();try{e.end()}catch{}return void($e=setTimeout(()=>{$e=null,ae||pt()},300))}ae=!0}finally{ee.signal.removeEventListener("abort",a),_e===n&&(_e=null);try{await(me?.return?.())}catch{}Te&&(Te(),Te=null)}},mt=async()=>{if(ae||!le)return;const e=Se,t=te;if(te=x(),_e)try{_e.abort()}catch{}try{t.end()}catch{}try{await e}catch{}await Ne(300),oe=ne,ae||pt()},ht=async e=>{if(ae)return;Ge=!0;const t=Re&&!v(se)?se:null;Re=!1;const o=Se,n=te;if(te=x(),_e)try{_e.abort()}catch{}try{n.end()}catch{}try{await o}catch{}await Ne(300),oe=ne,ae||(pt(),null!=t&&(Re=!0,Ae=Date.now(),De=!1,te.push(/^\s*\//.test(t)?[{type:"text",text:t}]:[{type:"text",text:t},{type:"text",text:re||Z(t,{forceFull:!0})}]),tt({kind:"note",text:"retrying the stalled turn on a fresh connection"})))},ft=()=>{if(ae||Fe||Le)return;const e=Ue,t=We,o=ie;Le=!0;const n=Se,s=te;te=x();try{s.end()}catch{}$e=setTimeout(async()=>{$e=null;try{await n}catch{}if(!ae&&Le&&Ue===e&&We===t)return await it()?void(!ae&&Le&&Ue===e&&We===t&&(Le=!1,Re=!0,Ae=Date.now(),De=!1,pt(),o&&te.push(o),rt())):(Le=!1,void yt())},0)},yt=()=>{st(),Re=!1,Ue=null,le=!1,ot({kind:"error",message:"The configured provider could not complete this turn. Nothing else was sent.",recoverable:!0})};return G||Me||pt(),{sendTurn(e){if(ae||Fe||Le)return!1;if(!le&&!ut())return!1;if(!le&&K)try{const e=K();e&&(t=e,ct.cwd=e)}catch{}Re=!0,Ve=!1,se=String(e),Ze&&(clearTimeout(Ze),Ze=null),Ae=Date.now(),De=!1,Ge=!1,qe=!1;const n=String(e),s=V++,r=X;if(X=/^\s*\/(?:compact|clear|reset)\b/i.test(n),re=/^\s*\//.test(n)?null:Z(n,{promptIndex:s,forceFull:r}),He=v(n),ie=/^\s*\//.test(n)?[{type:"text",text:n}]:[{type:"text",text:n},{type:"text",text:re}],We++,Ue=(()=>{if(!Me)return null;try{const e=_({runtime:"claude",providers:z.providers||[],providerId:z.providerId,model:z.model||ct.model||o,requestedModel:z.requestedModel||z.model||ct.model||o,policy:z.policy,bridgeHostId:z.bridgeHostId,circuit:z.circuit,capGate:z.capGate,traceId:z.traceId,turnRev:"function"==typeof z.turnRev?z.turnRev():z.turnRev,onRecord:nt});return e.start(),e}catch{return null}})(),Ue){const e=Ue,t=We,o=ie;it().then(n=>{!ae&&Re&&Ue===e&&We===t&&(n?(le||pt({admitted:!0}),te.push(o),rt()):yt())}).catch(()=>{!ae&&Re&&Ue===e&&We===t&&yt()})}else le||pt({admitted:!0}),te.push(ie)},warm(){Me||le||ae||pt()},get started(){return le},async setMode(e){I.has(e)&&!ae&&(he=e,lt(e),ot({kind:"mode",mode:he}))},async setModel(e){ct.model=e,ve=e,ot({kind:"note",text:`model → ${e}`}),le&&!ae&&(Re?Ee=!0:await mt())},setEffort:async e=>!(!ke.has(e)||ae||(ge=e,ct.effort=e,ot({kind:"effort",level:e}),le&&(Re?(Ee=!0,0):(await mt(),0)))),async listModels(){try{const e=(await(me?.supportedModels?.())||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);e.length&&ot({kind:"models",models:e}),ot({kind:"note",text:e.length?`models: ${e.map(e=>e.value).join(", ")}`:"no model list available"})}catch{ot({kind:"note",text:"usage: /model <name>"})}},async abort(){if(!Fe){Fe=!0;try{const e=Le,t=e?Se:null;(Re||e)&&(We++,e||(Le=!1),st(),Ue?.failure({aborted:!0}),e&&(clearTimeout($e),$e=null,le=!1),Ye=!0,ze=We,clearTimeout(Je),Je=setTimeout(()=>{Ye=!1,ze=null},6e3));try{await(me?.interrupt?.())}catch{}if(t)try{await t}catch{}e&&(Le=!1),(Re||e)&&(Re=!1,ot({kind:"result",subtype:"aborted",sessionId:oe}))}finally{Fe=!1}}},end(){ae=!0,st(),clearInterval(at),clearTimeout(Je),clearTimeout($e),Ze&&clearTimeout(Ze),te.end();try{ee.abort()}catch{}},get sessionId(){return oe},get mode(){return he},get turnActive(){return Re}}}
|
|
1
|
+
import{randomUUID as e}from"node:crypto";import{createRequire as t}from"node:module";import{readFileSync as o}from"node:fs";import{dirname as n,join as s}from"node:path";import{query as r}from"@anthropic-ai/claude-agent-sdk";import{sanitizeSession as i}from"./transcript-sanitize.mjs";import{reviewGatePreToolDecision as a}from"./flow-review-gate.mjs";import{crossPostNeedsCard as l}from"./cross-terminal.mjs";import{correctContext as c}from"./context-windows.mjs";import{normalizeClaudeCommandCatalog as d}from"./claude-command-catalog.mjs";import{evidenceForToolResult as u}from"./evidence-citations.mjs";import{THINKPOOL_CASCADE_RULE as p,THINKPOOL_REMOTE_DELIVERY_RULES as m,THINKPOOL_RUNTIME_AUTHORITY_RULE as h,THINKPOOL_RUNTIME_TURN_REMINDER as f,buildThinkPoolTurnGuidance as y,createRoomContextSelector as k,usesFullThinkPoolReminder as g}from"./thinkpool-room-prompt.mjs";import{stallDecision as w,stallEvent as b,isCompactTurn as v}from"./turn-stall.mjs";import{createSameTargetResilienceController as _,formatResilienceTrace as T}from"./provider-resilience.mjs";const S=t(import.meta.url);export async function claudeOneShot({prompt:e,model:t="claude-haiku-4-5",cwd:o,env:n,timeoutMs:s=8e3}={}){const i=new AbortController,a=setTimeout(()=>{try{i.abort()}catch{}},s);try{const s=r({prompt:e,options:{model:t,...o?{cwd:o}:{},env:n,maxTurns:1,permissionMode:"bypassPermissions",settingSources:[],strictMcpConfig:!0,mcpServers:{},abortController:i}});let a="";for await(const e of s){if("assistant"===e.type)for(const t of e.message?.content||[])"text"===t.type&&(a+=t.text);if("result"===e.type)break}return a.trim()}finally{clearTimeout(a)}}const E=(()=>{try{let e=n(S.resolve("@anthropic-ai/claude-agent-sdk"));for(let t=0;t<8;t++){try{const t=JSON.parse(o(s(e,"package.json"),"utf8"));if("@anthropic-ai/claude-agent-sdk"===t.name)return t.version}catch{}const t=n(e);if(t===e)break;e=t}}catch{}return"unknown"})(),N=/\brm\s+\S|\brmdir\s+\S|\bgit\s+(push\s+(-f|--force)|reset\s+--hard|clean\s+-[a-z]*f)|\bdrop\s+(table|database)\b|\b(mkfs|dd)\b|\bsudo\b|>\s*\/dev\/|\bchmod\s+-R|\bchown\s+-R|\bkillall\b|\btruncate\b/i,O=new Set(["Read","Grep","Glob","NotebookRead","TodoRead","LS"]),R=new Set(["WebFetch","WebSearch"]),A=new Set(["Edit","Write","MultiEdit","NotebookEdit","TodoWrite"]);export function classifyRisk(e,t){if("Bash"===e){const e=t&&(t.command??t.cmd)||"";return N.test(e)?"high":"medium"}return O.has(e)?"low":R.has(e)?"network":(A.has(e),"medium")}const D=/(^|\/)\.claude\/SESSIONS\/|(^|\/)CLAUDE\.md$/;export function isSafeDocWrite(e,t){if(!A.has(e))return!1;const o=t&&(t.file_path||t.notebook_path)||"";return D.test(o)}export function autoAllow({toolName:e,input:t,mode:o="default",alwaysAllow:n=new Set}){const s=classifyRisk(e,t);return"low"===s||"bypassPermissions"===o||"acceptEdits"===o&&A.has(e)&&"high"!==s||isSafeDocWrite(e,t)||n.has(`${e}:${s}`)}export function askUserQuestionHookOutput(e){const t=e&&"object"==typeof e?e.decision:e,o="string"==typeof t&&t.startsWith("answer:")?t.slice(7):"",n=e&&"object"==typeof e?e.responder:null,s="string"==typeof n?.name&&n.name.trim()?n.name.trim():"string"==typeof n?.id&&n.id?`room member ${n.id}`:"The user";return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:o?`${s} answered in the thinkpool room — ${o}. Treat this as their selection and continue; do not call AskUserQuestion again for the same question.`:"The user dismissed the question in the thinkpool room without selecting. Ask in plain prose, or proceed with a sensible default."}}}export function askUserQuestionRegression(e,t){return Array.isArray(e)?e.includes("AskUserQuestion")?null:`[SDK-REGRESSION] agent SDK v${t||"unknown"} init tools[] is missing 'AskUserQuestion' — the multiple-choice question card is disabled. A caret SDK bump likely changed the canUseTool gate; pin a known-good SDK in bridge/package.json + republish.`:null}function x(){const e=[];let t=null,o=!1;return{stream:async function*(){for(;!o;)e.length?yield e.shift():await new Promise(e=>{t=e})}(),push:n=>!o&&(e.push({type:"user",message:{role:"user",content:n}}),t&&(t(),t=null),!0),end(){o=!0,t&&(t(),t=null)}}}const P=(e=[])=>e.map(e=>"text"===e.type?{type:"text",text:e.text}:"thinking"===e.type?{type:"thinking",text:e.thinking||"",reasoningKind:"thought"}:"tool_use"===e.type?{type:"tool_use",id:e.id,name:e.name,input:e.input}:{type:e.type}).filter(Boolean),I=new Set(["default","acceptEdits","plan","bypassPermissions"]),M=["You are Claude in a thinkpool Code room, driven live from a phone or browser — NOT a local terminal. Keep using the room's features.",f,"TERMINAL HIERARCHY: obey your authoritative TERMINAL ROLE. A person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal — NEVER spawn_terminal — even for ordinary work or a handoff. If the wording includes new or separate terminal, main-terminal routing wins. Use spawn_terminal only for agent-decided bounded worker slices or when the person explicitly asks for a worker, sub-terminal, Ensemble lane, or delegated slice. If open_main_terminal is unavailable, say so; never substitute an Ensemble child. Leaf, worker, Side, and managed Flow lanes work directly. Never use built-in invisible Task/Agent subagents or hijack a busy sibling.","WORKTREES: parallel lanes share one repo — before code edits run `git worktree list`; if linked worktrees exist, take your OWN worktree + branch, never the shared checkout or a branch another lane is on.","BUILD WORKFLOW (default, no magic word): right-size within your TERMINAL ROLE — a trivial ask or delegated slice you just do; a conductor-capable role with a genuinely decomposable build FIRST writes a short plan in chat, THEN fans worker slices into visible spawn_terminal lanes and verifies them. Worker/leaf/Side/managed Flow roles do not fan out. A person-requested new or separate terminal uses open_main_terminal. Never plan-mode/ExitPlanMode; plans live in chat and lanes in the existing list."].join(" ");export function startClaudeSession({cwd:t,model:o,effort:n="high",resume:s,env:f,mode:S="default",onEvent:N,requestPermission:O,mcpServers:R,crossPostGate:A,crossRoomPostGate:D,didSpawnTarget:U=null,terminalRolePrompt:C,rolePrompt:L,blockSubagents:W=!1,onSubmitPlan:F=null,onLaneDone:$=null,onReviewVerdict:j=null,reviewGate:q=null,lazy:G=!1,roomContext:B=null,suggest:H=!0,prepareCwd:K=null,admitStart:Q=null,resilienceObserver:Y=null,resilience:z=null}){const J=k(B);let V=0,X=!0;const Z=(e,{promptIndex:t=0,forceFull:o=!1}={})=>{const n=g({promptIndex:t,forceFull:o}),s=J({force:n}),r=String(C||"").trim();return`<system-reminder>\n${n&&r?`${r}\n\n`:""}${n?M:y({text:e,promptIndex:t,forceFull:o})}${s?`\n\n${s}`:""}\n</system-reminder>`},ee=new AbortController;let te=x(),oe=s||null,ne=s||null,se=null,re=null,ie=null,ae=!1,le=!1,ce=null,de=!1,ue=!1,pe=!1,me=null,he=I.has(S)?S:"default";const fe=new Set,ye=new Map,ke=new Set(["low","medium","high","xhigh","max"]);let ge=ke.has(n)?n:"high",we=0,be=0,ve=o||null,_e=null,Te=null,Se=Promise.resolve(),Ee=!1;const Ne=e=>new Promise(t=>setTimeout(t,e)),Oe=Math.max(3e4,parseInt(process.env.TP_STALL_MS,10)||9e4);let Re=!1,Ae=Date.now(),De=!1;const xe=/connection closed|connection reset|econnreset|etimedout|socket hang up|fetch failed|network error|socket destroyed/i;let Pe=0;const Ie=(e,t={})=>{try{Y?.({reason:e,restartCount:Pe,...t})}catch{}},Me=!(!z?.policy?.enabled||!z?.providerId||"anthropic"===z.providerId);let Ue=null,Ce=null,Le=!1,We=0,Fe=!1,$e=null;const je=Math.max(3*Oe,parseInt(process.env.TP_FORCE_STOP_MS,10)||3e5);let qe=!1,Ge=!1;const Be=Math.max(je,parseInt(process.env.TP_COMPACT_FORCE_STOP_MS,10)||12e5);let He=!1,Ke=0;const Qe=O;O=async e=>{Ke++;try{return await(Qe?.(e))}finally{Ke=Math.max(0,Ke-1),Ae=Date.now()}};let Ye=!1,ze=null,Je=null,Ve=!1,Xe="",Ze=null;const et=Math.max(1200,parseInt(process.env.TP_SUGGEST_FALLBACK_MS,10)||2500),tt=e=>{try{N?.(e)}catch{}},ot=e=>{Ae=Date.now(),e&&"stalled"!==e.kind&&(De=!1),!e||"compaction"!==e.kind&&"result"!==e.kind&&"error"!==e.kind||(He=!1),tt(e)},nt=e=>{try{z?.onRecord?.(e)}catch{}"retrying"!==e?.outcome&&"cap_blocked"!==e?.outcome&&"circuit_open"!==e?.outcome||ot({kind:"note",text:T(e)})},st=()=>{if(null!=Ce){try{(z?.clearTimer||clearTimeout)(Ce)}catch{}Ce=null}},rt=()=>{if(st(),!Ue)return;const e=Number(z?.policy?.timeoutMs);if(!Number.isFinite(e)||e<=0)return;const t=z?.setTimer||setTimeout;Ce=t(()=>{if(Ce=null,!ae&&Ue&&Re){Ue.failure({message:"timeout"}),Re=!1;try{_e?.abort()}catch{}ft()}},e)},it=async()=>{if(!Ue)return!0;let e=null;try{e=await Ue.preflight()}catch{return!1}return!0===e?.admitted},at=setInterval(()=>{const e=Date.now()-Ae,t=w({turnActive:Re,awaitingUser:Ke,quietMs:e,stallMs:Oe,forceStopMs:je,stalledSent:De,stallRetried:Ge,compacting:He,compactForceStopMs:Be});if("none"===t)return;const o=b(t,e);if(o&&tt(o),"status"!==t){if("retry"===t){if(qe=!0,Ue){Ie("resilience_stall",{quietMs:e}),Ue.failure({message:"timeout"}),Re=!1;try{_e?.abort()}catch{}return void ft()}return Ie("stall_replay",{quietMs:e}),void ht(e)}qe=!0,Re=!1}else De=!0},5e3);at.unref?.();const lt=e=>{setTimeout(()=>{Promise.resolve(me?.setPermissionMode?.(e)).catch(t=>console.error(`[claude-session] setPermissionMode(${e}) failed:`,t?.message||t))},0)},ct={abortController:ee,permissionMode:he,hooks:{PreToolUse:[{hooks:[async t=>{const o=t.tool_name,n=t.tool_input,s=t.effort?.level;s&&s!==ge&&(ge=s,ot({kind:"effort",level:ge}));const r="Write"===o||"Edit"===o||"MultiEdit"===o||"NotebookEdit"===o;if(W&&r&&/(?:^|[/\\])FLOW_PLAN\.json$/i.test(n?.file_path||n?.notebook_path||"")){const e=n?.content??n?.new_string??"";let t={ok:!1,message:"Plan submission is not wired for this session."};try{t=F&&await F(e)||t}catch(e){t={ok:!1,message:`Plan submission failed: ${e?.message||e}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.message}}}if(W&&("Task"===o||"Agent"===o||"Bash"===o||r))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Bash"===o?"Flow conductors do NOT run Bash — it pops a permission card and stalls the flow. Use the Grep tool (not `grep`/`rg`), the Glob tool (not `find`/`ls`), and Read (not `cat`/`head`) — those run with no prompt. Then DECOMPOSE and submit by Writing your task-graph JSON to the file FLOW_PLAN.json.":r?'Flow conductors do NOT write project or plan-document files. Do NOT use ExitPlanMode and do NOT call submit_flow_plan (both hang here). To SUBMIT your decomposition, use the Write tool with file_path "FLOW_PLAN.json" and content = your task-graph JSON ({"summary":"…","tasks":[…]}). That single Write IS how you submit — the room ingests it directly. Do not write any other file.':"Flow conductors do NOT spawn subagents — it stalls the flow on a permission card. Inspect the codebase yourself with Read/Grep/Glob (no prompt). Then DECOMPOSE and submit by Writing your task-graph JSON to the file FLOW_PLAN.json. Do not call Task/Agent again."}};if(j&&("Write"===o||"Edit"===o)&&/(?:^|[/\\])FLOW_REVIEW(\.[a-zA-Z0-9]+)?$/.test(n?.file_path||"")){let e={ok:!1,message:"verdict signal failed"};try{e=await j(n?.content??n?.new_string??"")||e}catch(t){e={ok:!1,message:`verdict signal failed: ${t?.message||t}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.message}}}if($&&("Write"===o||"Edit"===o)&&/(?:^|[/\\])FLOW_DONE(\.[a-zA-Z0-9]+)?$/.test(n?.file_path||"")){let e={ok:!1,message:"done signal failed"};try{e=await $(n?.content??n?.new_string??"")||e}catch(t){e={ok:!1,message:`done signal failed: ${t?.message||t}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.message}}}const i=a({reviewGate:q,toolName:o,toolInput:n});if(i)return i;if("mcp__thinkpool__read_terminal"===o)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (read-only thinkpool cross-terminal read)."}};if(/^mcp__thinkpool__preview_(start|capture|inspect|stop)$/.test(o))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (contained bridge-owned viewport preview)."}};if("mcp__thinkpool__submit_flow_plan"===o)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (Flow plan submission — broadcasts the task-graph for human approval)."}};if("mcp__thinkpool__list_sessions"===o||"mcp__thinkpool__read_session"===o)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (read-only thinkpool cross-session read — your own rooms)."}};if("mcp__thinkpool__close_terminal"===o)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (thinkpool cross-terminal close — only self-spawned lanes)."}};if("mcp__thinkpool__spawn_terminal"===o)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (autonomous thinkpool worker; bounded by room caps and isolated in its own worktree)."}};if("mcp__thinkpool__open_main_terminal"===o){const t=n?.mode||he;if("bypassPermissions"!==t||"bypassPermissions"===he)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Auto-approved (open a fresh thinkpool terminal in ${t} mode — inherited, no escalation; bounded by room caps).`}};let s="deny";try{s=await(O?.({id:e(),toolName:o,input:{...n,mode:t},risk:"high"}))??"deny"}catch{s="deny"}const r="allow"===s;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:r?"allow":"deny",permissionDecisionReason:r?"Bypass terminal creation approved in the thinkpool room — the new terminal runs autonomously.":"Bypass terminal creation denied in the room — do not retry as bypass; open it without mode:bypassPermissions or ask what to do."}}}if("mcp__thinkpool__post_to_terminal"===o){const t=A?A():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-terminal post not allowed right now."}};const s=!!U&&!!U(n?.terminal);if(!l({mode:he,spawnedByMe:s}))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"bypassPermissions"===he?"Auto-approved (cross-terminal post in bypassPermissions mode — bypass means bypass).":"Auto-approved (cross-terminal post into a lane you spawned — parent→child orchestration, no per-post tap)."}};let r="deny";try{r=await(O?.({id:e(),toolName:o,input:n,risk:"high"}))??"deny"}catch{r="deny"}const i="allow"===r;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:i?"allow":"deny",permissionDecisionReason:i?"Cross-terminal post approved in the thinkpool room.":"Cross-terminal post denied in the room — do not retry; ask what to do instead."}}}if("mcp__thinkpool__post_to_session"===o){const t=D?D():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-room post not allowed right now."}};let s="deny";try{s=await(O?.({id:e(),toolName:o,input:n,risk:"high"}))??"deny"}catch{s="deny"}const r="allow"===s;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:r?"allow":"deny",permissionDecisionReason:r?"Cross-room post approved in the sending room — the target room will be asked to accept it.":"Cross-room post denied in the room — do not retry; ask what to do instead."}}}if("ExitPlanMode"===o){if("plan"!==he)return lt(he),ot({kind:"mode",mode:he}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`The thinkpool room is in ${he} mode, not Plan — the user did not ask for a plan. Do NOT call ExitPlanMode; proceed and make the changes directly. Only present a plan if the user switches the room to Plan mode or explicitly asks.`}};let t="keep";try{t=await(O?.({id:e(),toolName:o,input:n,risk:"plan",plan:n?.plan||""}))??"keep"}catch{t="keep"}if("run"===t||"accept"===t){const e="accept"===t?"acceptEdits":"default";return he=e,lt(e),ot({kind:"mode",mode:e}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Plan approved in the thinkpool room — proceed (${e} mode).`}}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:'The user chose "keep planning" in the thinkpool room. Do not exit plan mode — keep refining the plan, then call ExitPlanMode again when ready.'}}}if("AskUserQuestion"===o){let t="";try{t=await(O?.({id:e(),toolName:o,input:n,risk:"ask",questions:n?.questions||[]}))??""}catch{t=""}return askUserQuestionHookOutput(t)}const c=classifyRisk(o,n),d=`${o}:${c}`,u=isSafeDocWrite(o,n),p=autoAllow({toolName:o,input:n,mode:he,alwaysAllow:fe});let m="allow";if(!p){try{m=await(O?.({id:e(),toolName:o,input:n,risk:c}))??"deny"}catch{m="deny"}"always"===m&&(fe.add(d),m="allow")}const h="deny"===m;return h&&Ue&&Ue.failure({permissionDenied:!0}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:h?"deny":"allow",permissionDecisionReason:h?"Denied by the user in the thinkpool room. Do not retry this tool — ask what to do instead.":p?u?"Auto-approved (mandated doc write — .claude/SESSIONS/ or CLAUDE.md).":`Auto-approved (${he}).`:"Approved in the thinkpool room."}}}]}]},canUseTool:async(e,t)=>({behavior:"allow",updatedInput:t}),settingSources:["user","project","local"],appendSystemPrompt:[...C?[C]:[],...L?[L]:[],"ENVIRONMENT (authoritative — overrides any user-global CLAUDE.md or memory that claims otherwise): You are Claude running inside a thinkpool Code room, driven live by a user (and possibly a partner) from a phone or browser, via the thinkpool-pair bridge.",h,'Bias strongly toward DOING the work, not stalling in plan-mode ceremony. For a small "add / fix / change X" request, just make the change directly (for a bigger build, right-size it — see DEFAULT BUILD WORKFLOW below).',"Do NOT enter plan mode, do NOT call ExitPlanMode, and do NOT auto-invoke a brainstorming/planning skill UNLESS the user has switched the room into Plan mode or explicitly asks you to plan, design, or brainstorm first.","Any host-global instruction that says you must always brainstorm or plan before creative work does NOT apply here — this room is the exception.",p,'CRUCIAL RECONCILIATION for that workflow: it is NOT plan mode. Never call ExitPlanMode and never make the room wait behind a "plan ready — approve to start" card — your plan lives in the CHAT as a message, and your lanes live in the room\'s EXISTING terminal/lane list. Reuse only those two surfaces; there is no new Flow panel or mode to switch into, and you must not ask for one. Keep the plan and the lanes VISIBLE — that shared visibility is the whole point (it is the pair differentiator, and it catches bugs a single silent lane would hide); never collapse a decomposable build into one hidden lane just to look tidy.',...m,'CROSS-TERMINAL AWARENESS: ROOM NOW is the default roster and already satisfies the room check when it has enough detail. Do not repeat it with a no-argument read_terminal call unless it is missing or truncated. Use a targeted read_terminal call only when the current task depends on a specific lane’s detailed activity; never poll. Identify a terminal by its NAME or stable ref/id, never by an on-screen number like "Terminal 2" — positional labels renumber when a terminal is closed. The tool is read-only and its optional roster lookup is budgeted separately from bounded targeted transcript reads.','CROSS-TERMINAL HAND-OFF: you also have post_to_terminal(terminal, text) to send a message or task to ANOTHER AGENT terminal in this room (not a plain shell). Use it sparingly and only when the people clearly want the lanes to coordinate — e.g. "tell the backend terminal the API is ready", or to hand a sibling agent a concrete task. Every post requires a person in the room to approve a card before it is delivered, and an agent that was itself reached via a cross-post cannot post onward — so do not rely on it for chit-chat or loops. Prefer read_terminal to understand a sibling before you ever post to it.',"TERMINAL CREATION CONTRACT: main terminals and workers use different tools. A person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal(name?, task?, model?) — even for ordinary work or a handoff and even without the words Cascade or conductor. If the wording includes new or separate terminal, main-terminal routing wins. Never use spawn_terminal for that request, and if open_main_terminal is unavailable say so instead of substituting. Use spawn_terminal(name?, task?, model?, sliceType?) only for agent-decided bounded WORKER SUB-TERMINALS or when the person explicitly asks for a worker, sub-terminal, Ensemble lane, or delegated slice. Workers never receive the creation tools and never conduct. Do not dump work into busy siblings. Spawned workers are always autonomous in bypassPermissions and never ask the room for an approval card; the bridge still enforces room caps, hop limits, the kill-switch, and isolated linked worktrees. Wait for ROOM NOW or a completion signal instead of polling; after a worker finishes, collect it with one targeted read_terminal call and 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&&(ct.strictMcpConfig=!0,ct.mcpServers={}),R&&Object.keys(R).length&&(ct.mcpServers={...ct.mcpServers||{},...R}),t&&(ct.cwd=t),o&&(ct.model=o),ct.effort=ge,ct.env={...f||process.env,CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION:"1"};const dt=async()=>{if(!H)return;const e=(Xe||"").trim().slice(-1500);if(e&&!ae)try{let o=await claudeOneShot({prompt:`You are predicting the user's NEXT chat message in a live coding session, to prefill their composer. Given the assistant's latest reply below, output the single most likely next user message — short and natural (often just "proceed", "go with option A", "yes do that", or a brief follow-up). One line, <=12 words, imperative, no preamble, no quotes, no markdown.\n\nAssistant's latest reply:\n"""\n${e}\n"""\n\nNext user message:`,model:"claude-haiku-4-5",cwd:t,env:ct.env,timeoutMs:8e3});o=o.trim().split("\n")[0].replace(/^["'`]+|["'`]+$/g,"").trim().slice(0,140),!o||Ve||ae||/^(sure|of course|certainly|let me know|i can help|happy to)\b/i.test(o)||(ot({kind:"suggestion",text:o,source:"haiku"}),process.stderr.write(` ◆ [suggestion] haiku fallback: ${JSON.stringify(o)}\n`))}catch{}},ut=()=>{const e="function"==typeof Q?Q():{ok:!0};return!1!==e?.ok||(ot({kind:"error",message:e.reason||"Host memory is critically low. This agent runtime was not started.",recoverable:!0}),!1)},pt=async({admitted:e=!1}={})=>{if(!le&&!e&&!ut())return!1;if(null==ce&&(ce=Date.now()),le=!0,Te)try{Te()}catch{}Se=new Promise(e=>{Te=e});const n=new AbortController;_e=n;const a=()=>{try{n.abort()}catch{}};ee.signal.addEventListener("abort",a,{once:!0});try{if(oe){const e=i(t||process.cwd(),oe);e.blocks&&process.stderr.write(`\n ◆ healed ${e.blocks} malformed tool block(s) in the transcript before resume.\n`)}me=r({prompt:te.stream,options:{...ct,abortController:n,...oe?{resume:oe}:{}}});for await(const e of me){if(ae)break;switch(e.type){case"system":if("thinking_tokens"===e.subtype){we+be===0&&ot({kind:"thinking_tokens",tokens:e.estimated_tokens,delta:e.estimated_tokens_delta});break}if("compact_boundary"===e.subtype){X=!0,ot({kind:"compaction",trigger:e.compact_metadata?.trigger||"auto",preTokens:e.compact_metadata?.pre_tokens??null}),(async()=>{try{const e=await(me?.getContextUsage?.());e&&(ot({kind:"usage",ctx:c({used:e.totalTokens,max:e.maxTokens,pct:Math.round(e.percentage),model:e.model})}),e.model&&(ve=e.model))}catch{}})();break}if(e.session_id&&(oe=e.session_id),de||(de=!0,process.stderr.write(`\n ◆ session ready in ${Date.now()-ce}ms — MCP ${"1"===process.env.TP_MCP_STRICT?"OFF":"on"}${s?", resume":", fresh"}.\n`)),ve=ct.model||e.model||o||ve,ot({kind:"system",sessionId:oe,model:ct.model||e.model||o||null,commands:d({slashCommands:e.slash_commands,skills:e.skills})}),!pe&&Array.isArray(e.tools)){pe=!0;const t=askUserQuestionRegression(e.tools,E);t&&(process.stderr.write(`\n ⚠⚠ ${t}\n`),ot({kind:"error",message:t}))}ue||(ue=!0,Promise.resolve(me?.supportedModels?.()).then(e=>{const t=(e||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);t.length&&ot({kind:"models",models:t})}).catch(()=>{}));break;case"assistant":st(),Ue?.visibleOutput();for(const t of e.message?.content||[])"tool_use"===t?.type&&t.id&&ye.set(t.id,{at:Date.now(),name:t.name,input:t.input});{const t=(e.message?.content||[]).filter(e=>"text"===e?.type).map(e=>e.text).join("\n").trim();t&&(Xe=t)}ot({kind:"assistant",blocks:P(e.message?.content),parentToolUseId:e.parent_tool_use_id||null});break;case"user":for(const t of e.message?.content||[])if("tool_result"===t?.type){st(),Ue?.visibleOutput({tool:!0});const o=ye.get(t.tool_use_id);null!=o&&ye.delete(t.tool_use_id);const n=u(o?.name,t.content);ot({kind:"tool_result",toolUseId:t.tool_use_id,content:t.content,...n?{evidence:n}:{},isError:!!t.is_error,durationMs:null!=o?.at?Date.now()-o.at:void 0,parentToolUseId:e.parent_tool_use_id||null})}break;case"stream_event":{const t=e.event;"message_start"===t?.type?(we+=be,be=t.message?.usage?.output_tokens||0,ot({kind:"thinking_tokens",tokens:we+be})):"message_delta"===t?.type&&t.usage&&(be=t.usage.output_tokens??be,ot({kind:"thinking_tokens",tokens:we+be}));break}case"result":if(st(),e.session_id&&(oe=e.session_id),e.is_error&&Array.isArray(e.errors)&&e.errors.some(e=>/no conversation found/i.test(String(e)))&&(oe||ne)&&Pe<3){Pe++;const e=Re;Re=!1,oe=null,ne=null,ot({kind:"note",text:"previous session not found — continuing on a fresh one"});const t=te;te=x();try{t.end()}catch{}const o=e?se:null;$e=setTimeout(()=>{$e=null,ae||(pt(),null!=o&&(Re=!0,Ae=Date.now(),De=!1,te.push([{type:"text",text:o},{type:"text",text:re||Z(o,{forceFull:!0})}])))},300);break}if(Ye&&("aborted"===e.subtype||"error_during_execution"===e.subtype)){We===ze&&(Re=!1);break}if(e.is_error&&Ue){if(Le)break;Ue.failure({message:Array.isArray(e.errors)?e.errors.join(" "):e.result,status:e.status??e.statusCode,code:e.code}),Re=!1,ft();break}if(we=0,be=0,Re=!1,Ee&&(Ee=!1,setTimeout(()=>{ae||mt()},0)),"success"===e.subtype&&(Pe=0,oe&&(ne=oe)),"success"===e.subtype&&(Ue?.success(),Ue=null),qe=!1,Ge=!1,e.modelUsage&&"object"==typeof e.modelUsage){let t=null,o=-1;for(const[n,s]of Object.entries(e.modelUsage)){const e=s?.outputTokens??0;e>o&&(o=e,t=n)}t&&(ve=t)}{const t="string"==typeof e.result?e.result.replace(/\s+/g," ").trim().slice(0,200):"";ot({kind:"result",subtype:e.subtype,sessionId:oe,model:ve,costUsd:e.total_cost_usd,usage:e.usage,numTurns:e.num_turns,durationMs:e.duration_ms??null,denials:Array.isArray(e.permission_denials)?e.permission_denials.length:0,resultText:t||null})}Ze&&clearTimeout(Ze),"aborted"!==e.subtype&&(Ze=setTimeout(()=>{Ze=null,Ve||ae||dt()},et)),(async()=>{let t=null;try{const e=await(me?.getContextUsage?.());e&&(t=c({used:e.totalTokens,max:e.maxTokens,pct:Math.round(e.percentage),model:e.model}),e.model&&(ve=e.model))}catch{}const o=e.usage||{};ot({kind:"usage",costUsd:e.total_cost_usd??null,tokens:(o.input_tokens||0)+(o.output_tokens||0),ctx:t})})();break;case"prompt_suggestion":Ze&&(clearTimeout(Ze),Ze=null),e.suggestion&&(Ve=!0,ot({kind:"suggestion",text:e.suggestion}))}}}catch(e){if(st(),ae)return;if(n.signal.aborted)return;const t=e?.message||String(e);if(Ue&&Re)return Ue.failure({message:t,status:e?.status??e?.statusCode,code:e?.code}),Re=!1,void ft();if(Re=!1,ot({kind:"error",message:t}),xe.test(t)&&Pe<3){Pe++,Ie("stream_reconnect",{failureClass:"network"}),ot({kind:"note",text:`connection dropped — reconnecting (${Pe}/3)`});const e=te;te=x();try{e.end()}catch{}return void($e=setTimeout(()=>{$e=null,ae||pt()},Math.min(1e3*Pe,4e3)))}if(/no conversation found/i.test(t)&&oe&&Pe<3){Pe++,oe=null,ne=null;const e=te;te=x();try{e.end()}catch{}return void($e=setTimeout(()=>{$e=null,ae||pt()},300))}ae=!0}finally{ee.signal.removeEventListener("abort",a),_e===n&&(_e=null);try{await(me?.return?.())}catch{}Te&&(Te(),Te=null)}},mt=async()=>{if(ae||!le)return;const e=Se,t=te;if(te=x(),_e)try{_e.abort()}catch{}try{t.end()}catch{}try{await e}catch{}await Ne(300),oe=ne,ae||pt()},ht=async e=>{if(ae)return;Ge=!0;const t=Re&&!v(se)?se:null;Re=!1;const o=Se,n=te;if(te=x(),_e)try{_e.abort()}catch{}try{n.end()}catch{}try{await o}catch{}await Ne(300),oe=ne,ae||(pt(),null!=t&&(Re=!0,Ae=Date.now(),De=!1,te.push(/^\s*\//.test(t)?[{type:"text",text:t}]:[{type:"text",text:t},{type:"text",text:re||Z(t,{forceFull:!0})}]),tt({kind:"note",text:"retrying the stalled turn on a fresh connection"})))},ft=()=>{if(ae||Fe||Le)return;const e=Ue,t=We,o=ie;Le=!0;const n=Se,s=te;te=x();try{s.end()}catch{}$e=setTimeout(async()=>{$e=null;try{await n}catch{}if(!ae&&Le&&Ue===e&&We===t)return await it()?void(!ae&&Le&&Ue===e&&We===t&&(Le=!1,Re=!0,Ae=Date.now(),De=!1,pt(),o&&te.push(o),rt())):(Le=!1,void yt())},0)},yt=()=>{st(),Re=!1,Ue=null,le=!1,ot({kind:"error",message:"The configured provider could not complete this turn. Nothing else was sent.",recoverable:!0})};return G||Me||pt(),{sendTurn(e){if(ae||Fe||Le)return!1;if(!le&&!ut())return!1;if(!le&&K)try{const e=K();e&&(t=e,ct.cwd=e)}catch{}Re=!0,Ve=!1,se=String(e),Ze&&(clearTimeout(Ze),Ze=null),Ae=Date.now(),De=!1,Ge=!1,qe=!1;const n=String(e),s=V++,r=X;if(X=/^\s*\/(?:compact|clear|reset)\b/i.test(n),re=/^\s*\//.test(n)?null:Z(n,{promptIndex:s,forceFull:r}),He=v(n),ie=/^\s*\//.test(n)?[{type:"text",text:n}]:[{type:"text",text:n},{type:"text",text:re}],We++,Ue=(()=>{if(!Me)return null;try{const e=_({runtime:"claude",providers:z.providers||[],providerId:z.providerId,model:z.model||ct.model||o,requestedModel:z.requestedModel||z.model||ct.model||o,policy:z.policy,bridgeHostId:z.bridgeHostId,circuit:z.circuit,capGate:z.capGate,traceId:z.traceId,turnRev:"function"==typeof z.turnRev?z.turnRev():z.turnRev,onRecord:nt});return e.start(),e}catch{return null}})(),Ue){const e=Ue,t=We,o=ie;it().then(n=>{!ae&&Re&&Ue===e&&We===t&&(n?(le||pt({admitted:!0}),te.push(o),rt()):yt())}).catch(()=>{!ae&&Re&&Ue===e&&We===t&&yt()})}else le||pt({admitted:!0}),te.push(ie)},warm(){Me||le||ae||pt()},get started(){return le},async setMode(e){I.has(e)&&!ae&&(he=e,lt(e),ot({kind:"mode",mode:he}))},async setModel(e){ct.model=e,ve=e,ot({kind:"note",text:`model → ${e}`}),le&&!ae&&(Re?Ee=!0:await mt())},setEffort:async e=>!(!ke.has(e)||ae||(ge=e,ct.effort=e,ot({kind:"effort",level:e}),le&&(Re?(Ee=!0,0):(await mt(),0)))),async listModels(){try{const e=(await(me?.supportedModels?.())||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);e.length&&ot({kind:"models",models:e}),ot({kind:"note",text:e.length?`models: ${e.map(e=>e.value).join(", ")}`:"no model list available"})}catch{ot({kind:"note",text:"usage: /model <name>"})}},async abort(){if(!Fe){Fe=!0;try{const e=Le,t=e?Se:null;(Re||e)&&(We++,e||(Le=!1),st(),Ue?.failure({aborted:!0}),e&&(clearTimeout($e),$e=null,le=!1),Ye=!0,ze=We,clearTimeout(Je),Je=setTimeout(()=>{Ye=!1,ze=null},6e3));try{await(me?.interrupt?.())}catch{}if(t)try{await t}catch{}e&&(Le=!1),(Re||e)&&(Re=!1,ot({kind:"result",subtype:"aborted",sessionId:oe}))}finally{Fe=!1}}},end(){ae=!0,st(),clearInterval(at),clearTimeout(Je),clearTimeout($e),Ze&&clearTimeout(Ze),te.end();try{ee.abort()}catch{}},get sessionId(){return oe},get mode(){return he},get turnActive(){return Re}}}
|
package/cross-terminal.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash as e}from"node:crypto";import{BLOCKED_REASON as t,projectLaneLifecycle as r}from"./lane-lifecycle.mjs";export const PEEK={defaultLines:20,maxLines:200,perTurnCap:10,rosterPerTurnCap:1,lineCap:200,rosterPreview:100};export const readTerminalBudgetDecision=({targeted:e=!1,targetedCount:t=0,rosterCount:r=0}={},n=PEEK)=>{const o=Math.max(0,Number(t)||0),i=Math.max(0,Number(r)||0);return e?o>=n.perTurnCap?{ok:!1,targetedCount:o,rosterCount:i,reason:`Cross-terminal transcript read limit reached for this turn (${n.perTurnCap}). Stop polling and continue with the worker results already collected; a fresh accepted room turn resets the allowance.`}:{ok:!0,targetedCount:o+1,rosterCount:i}:i>=n.rosterPerTurnCap?{ok:!1,targetedCount:o,rosterCount:i,reason:`The full terminal roster was already read this turn (${n.rosterPerTurnCap}/${n.rosterPerTurnCap}). Use the current ROOM NOW snapshot or read one relevant terminal by ref or name.`}:{ok:!0,targetedCount:o,rosterCount:i+1}};export const readTerminalTurnBudgetDecision=({targeted:e=!1,targetedCount:t=0,rosterCount:r=0,budgetTurnRev:n=null,currentTurnRev:o=0}={},i=PEEK)=>{const s=Math.max(0,Number(o)||0),a=(null==n?null:Number.isFinite(Number(n))?Number(n):null)===s;return{...readTerminalBudgetDecision({targeted:e,targetedCount:a?t:0,rosterCount:a?r:0},i),budgetTurnRev:s}};export const LANE_STATUS={stuckAfterMs:9e4,repeatedFailureCount:2,failureWindow:12};const n=e=>!!e&&("error"===e.kind||"tool_result"===e.kind&&e.isError||"result"===e.kind&&e.subtype&&"success"!==e.subtype);export const laneBusyOf=(e={})=>"boolean"==typeof e?.busy?e.busy:"boolean"==typeof e?._busyAnn?e._busyAnn:e?.session?.turnActive??!1;export const settleLaneBusy=e=>!(!e||!1===e._busyAnn||(e._busyAnn=!1,0));export const settleLaneControl=(e,t=Date.now())=>!(!e||!0!==e._busyAnn||!settleLaneBusy(e)||(e._settledTurnRev=Number(e._turnRev)||null,e._turnSettledAt=Number(t)||Date.now(),e._turnStart=null,0));export const laneStatusOf=(e={},o=Date.now(),i=LANE_STATUS)=>{const s=Array.isArray(e?.log)?e.log:[],a=s.slice(-i.failureWindow);!e?.lastEvent||e.lastEvent===s[s.length-1]||e.lastEvent.cid&&e.lastEvent.cid===s[s.length-1]?.cid||a.push(e.lastEvent);let l=null;for(let e=a.length-1;e>=0;e--)if(Number.isFinite(a[e]?.ts)){l=a[e].ts;break}const c=Number.isFinite(e?.lastActionAt)?e.lastActionAt:l??null,d=null==c?null:Math.max(0,o-c),p=laneBusyOf(e),u=e?.pending instanceof Map?e.pending.size:Math.max(0,Number(e?.pendingCount)||0),m=e?.pending instanceof Map&&[...e.pending.values()].some(e=>"ask"===e?.payload?.risk)?t.NEEDS_INPUT:t.NEEDS_DECISION,h=((e,t=LANE_STATUS)=>{let r=0,o=0;for(let i=(Array.isArray(e)?e.length:0)-1;i>=0&&o<t.failureWindow;i--){const t=e[i];if(t&&"object"==typeof t){if(o++,"result"===t.kind&&(!t.subtype||"success"===t.subtype)||"you"===t.kind)break;n(t)&&r++}}return r})(a,i);let f=null,g=null;return u>0?(f="BLOCKED",g="waiting for input"):e?.stalled||p&&!e?.compacting&&null!=d&&d>=i.stuckAfterMs?(f="STUCK",g="no events while busy"):h>=i.repeatedFailureCount&&(f="BLOCKED",g="repeated errors"),{busy:!!p,lastActionAt:c,lastActionAgeMs:d,statusFlag:f,statusReason:g,lifecycle:r({events:a,busy:!!p,pendingCount:u,pendingReason:m,stalled:"STUCK"===f,failed:h>=i.repeatedFailureCount&&!p,rawStatus:f||(p?"busy":"idle")})}};export const formatLaneAge=e=>{if(!Number.isFinite(e))return"no activity";const t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s ago`;const r=Math.floor(t/60);if(r<60)return`${r}m ago`;const n=Math.floor(r/60);return n<24?`${n}h ago`:`${Math.floor(n/24)}d ago`};const o=e=>`${e.lifecycle?.state||"Blocked"}${e.lifecycle?.reason?` (${e.lifecycle.reason})`:""} · ${formatLaneAge(e.lastActionAgeMs)}`,i=(e,t)=>{const r=String(null==e?"":e).replace(/\s+/g," ").trim();return r.length>t?r.slice(0,t-1)+"…":r};export const digestLogEvent=(e,t=PEEK.lineCap)=>{if(!e||"object"!=typeof e)return"";switch(e.kind){case"you":return i(`${e.by||"someone"}: ${e.text||""}`,t);case"assistant":{const r=[];for(const t of Array.isArray(e.blocks)?e.blocks:[])"text"===t?.type&&String(t.text||"").trim()?r.push(String(t.text).trim()):"tool_use"===t?.type&&t.name&&r.push(`→ ${t.name}`);return r.length?i(`assistant: ${r.join(" ")}`,t):""}case"tool_result":return e.isError?i("⎿ error",t):"";case"result":return e.subtype&&"success"!==e.subtype?i(`turn ended — ${e.subtype}`,t):"";case"error":return i(`error: ${e.message||""}`,t);default:return""}};export const cleanPtyTail=(e,t)=>String(e||"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b[@-_][0-?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"").split(/\r?\n/).map(e=>e.replace(/\s+$/,"")).filter(e=>e.trim()).slice(-Math.max(1,t));export const siblingRef=e=>String(e).slice(0,8);export const siblingsOf=({selfId:e,sessions:t,terms:r,names:n={},now:o=Date.now()}={})=>{const i=e=>n&&n[e]||"",s=[];for(const[r,n]of t||new Map)r!==e&&s.push({id:r,ref:siblingRef(r),name:i(r),kind:"agent",cmd:n?.cmd||"claude",log:Array.isArray(n?.log)?n.log:[],...laneStatusOf(n,o)});for(const[t,n]of r||new Map)t!==e&&s.push({id:t,ref:siblingRef(t),name:i(t),kind:"shell",cmd:n?.cmd||"shell",buf:n?.buf||"",...laneStatusOf(n,o)});return s};export const isOrdinalRef=e=>/^(terminal\s*)?\d+$/i.test(e)||/^t\d+$/i.test(e);export const resolveSibling=(e,t)=>{const r=String(t||"").toLowerCase().trim();if(!r)return null;const n=Array.isArray(e)?e:[];return n.find(e=>String(e.id).toLowerCase()===r)||n.find(e=>String(e.name||"").toLowerCase()===r)||n.find(e=>String(e.ref).toLowerCase()===r)||(isOrdinalRef(r)?null:n.find(e=>r.length>=4&&String(e.id).toLowerCase().startsWith(r))||n.find(e=>e.name&&String(e.name).toLowerCase().includes(r))||n.find(e=>String(e.cmd).toLowerCase().includes(r))||null)};const s=e=>`${e.ref}${e.name?` · "${e.name}"`:""}`;export const formatPeek=({selfId:e,sessions:t,terms:r,names:n={},terminal:a,lines:l,now:c=Date.now()}={})=>{const d=Math.min(PEEK.maxLines,Math.max(1,Number(l)||PEEK.defaultLines)),p=siblingsOf({selfId:e,sessions:t,terms:r,names:n,now:c});if(!p.length)return"No other terminals are open in this room right now.";if(!a)return`Other terminals in this room (call read_terminal with a ref or name to read one):\n${p.map(e=>{let t;if("agent"===e.kind){const r=e.log.map(e=>digestLogEvent(e,PEEK.rosterPreview)).filter(Boolean);t=r[r.length-1]||"(no activity yet)"}else t=cleanPtyTail(e.buf,1)[0]||"(no output yet)";return`- ${s(e)} · ${e.kind} · ${e.cmd} · ${o(e)} — ${i(t,PEEK.rosterPreview)}`}).join("\n")}`;const u=resolveSibling(p,a);if(!u)return`No terminal matches "${a}". Call read_terminal with no argument to list the open terminals (refer to one by its name or ref).${isOrdinalRef(String(a||"").toLowerCase().trim())?" On-screen numbers like \"Terminal N\" shift when a terminal closes, so they can't identify a lane — use a terminal's name or ref instead.":""}`;let m;return m="agent"===u.kind?u.log.map(e=>digestLogEvent(e,PEEK.lineCap)).filter(Boolean).slice(-d).join("\n")||"(no activity yet)":cleanPtyTail(u.buf,d).join("\n")||"(no output yet)",`Terminal ${s(u)} (${u.kind} · ${u.cmd}) · ${o(u)} — last ${d} lines:\n${m}`};export const nativeClaudeProviderAccessFailed=e=>{let t="";try{t="string"==typeof e?e:JSON.stringify(e||"")}catch{t=String(e||"")}return/organization has disabled (?:claude(?: subscription access)?|subscription access)|(?:claude )?subscription access (?:has been |is )?disabled|invalid anthropic (?:api )?key|invalid x-api-key|not logged in to claude|(?:run|use) \/login[^\n]{0,80}claude|no valid anthropic (?:api )?key/i.test(t)};const a=Object.freeze(["nous:anthropic/claude-sonnet-4.6","nous:anthropic/claude-sonnet-4.5","nous:anthropic/claude-sonnet-4"]);export const preferredHermesClaudeReviewModel=(e=[])=>{const t=new Set((Array.isArray(e)?e:[]).map(e=>"string"==typeof e?e:e?.value||e?.slug).filter(Boolean));for(const e of a)if(t.has(e))return e;for(const e of t)if(/^nous:anthropic\/claude-sonnet-/i.test(e))return e;for(const e of t)if(/^nous:anthropic\/claude-haiku-/i.test(e))return e;for(const e of t)if(/^nous:anthropic\/claude-opus-/i.test(e))return e;return null};export const nativeClaudeFallbackHint=({parentRuntime:e,parentModels:t,targetRuntime:r,targetLog:n}={})=>{if("claude"!==r||!nativeClaudeProviderAccessFailed(n))return"";const o="thinkpool provider status: native Claude access failed at the account/provider level. Do not retry Sonnet, Opus, Haiku, or another model alias on the same native Claude provider during this task.",i="hermes"===e?preferredHermesClaudeReviewModel(t):null;return i?`\n\n${o} For a visible manual review fallback, spawn exactly one worker with runtime="hermes", model=${JSON.stringify(i)}, mode="default", and sliceType="review". This Hermes lane is permission-gated, not structurally read-only: instruct it not to edit, deny/stop any write request, and do not treat its review as a Flow safety proof. Never use Hermes delegate_task.`:`\n\n${o} Use a different available runtime/provider once, or report the blocker.`};export const ROOMNOW={laneCap:8,previewLen:70,wtCap:10};export const formatRoomNow=({selfId:e,sessions:t,terms:r,names:n={},worktrees:a=[],now:l=Date.now()}={},c=ROOMNOW)=>{const d=siblingsOf({selfId:e,sessions:t,terms:r,names:n,now:l}),p=[];if(d.length){const e=d.slice(0,c.laneCap),t=e.map(e=>{let t;if("agent"===e.kind){const r=e.log.map(e=>digestLogEvent(e,c.previewLen)).filter(Boolean);t=r[r.length-1]||"(no activity yet)"}else t=cleanPtyTail(e.buf,1)[0]||"(no output yet)";return`- ${s(e)} · ${e.kind} · ${o(e)} — ${i(t,c.previewLen)}`});d.length>e.length&&t.push(`- … +${d.length-e.length} more (read_terminal lists all)`),p.push(`Other lanes in this room right now (this is the roster; use targeted read_terminal only for needed detail):\n${t.join("\n")}`)}const u=Array.isArray(a)?a:[],m=u.slice(0,c.wtCap);if(m.length){const e=m.map(e=>`- ${i(e,c.previewLen+30)}`);u.length>m.length&&e.push(`- … +${u.length-m.length} more (\`git worktree list\` shows all)`),p.push(`Active git worktrees on this host (code edits go in your OWN worktree — never one another lane is on):\n${e.join("\n")}`)}return p.length?`ROOM NOW (live snapshot, this turn):\n${p.join("\n")}`:null};export const CROSSPOST={maxHop:1,perTurnCap:3};export const crossPostDecision=({hop:e=0,postCount:t=0,disabled:r=!1}={},n=CROSSPOST)=>{const o={...CROSSPOST,...n||{}};return r?{ok:!1,reason:"Cross-terminal posting is disabled in this room."}:e>=o.maxHop?{ok:!1,reason:"Cross-terminal hop limit reached — an agent reached via cross-post cannot itself post onward; a person must direct the next cross-terminal action."}:t>=o.perTurnCap?{ok:!1,reason:`Cross-terminal post limit reached for this turn (${o.perTurnCap}).`}:{ok:!0}};export const crossPostNeedsCard=({mode:e="default",spawnedByMe:t=!1}={})=>!("bypassPermissions"===e||!0===t);export const SPAWN={maxHop:1,perWindowCap:6,windowMs:6e5,freeMaxSpawned:3,plusMaxSpawned:6,machineMax:12};export const maxSpawnedFor=(e,t=SPAWN)=>{const r={...SPAWN,...t||{}};return"plus"===e?r.plusMaxSpawned:r.freeMaxSpawned};export const isActiveDispatchedWorker=e=>!(!e?.spawnedBy||"conductor"===e.flowRole||e.flowTaskKey&&e.flowDone);export const countActiveDispatchedWorkers=(e=[])=>[...e].filter(isActiveDispatchedWorker).length;export const machineCapacityDecision=({totalLive:e=0,disabled:t=!1}={},r=SPAWN)=>{const n={...SPAWN,...r||{}};return t?{ok:!1,reason:"Spawning terminals is disabled in this room."}:e>=n.machineMax?{ok:!1,reason:`Room is at the machine cap (${n.machineMax} live lanes) — close one before opening another.`}:{ok:!0}};export const activeWorkerCapacityDecision=({spawnedLive:e=0,totalLive:t=0,plan:r="free",disabled:n=!1}={},o=SPAWN)=>{const i={...SPAWN,...o||{}},s=machineCapacityDecision({totalLive:t,disabled:n},i);if(!s.ok)return s;const a=maxSpawnedFor(r,i);return e>=a?{ok:!1,reason:`Dispatch ceiling reached (${a} lane${1===a?"":"s"} on the ${r} plan)${"plus"!==r?` — Plus raises it to ${i.plusMaxSpawned}.`:"."} Close a dispatched lane to open another.`}:{ok:!0}};export const recentSpawnCount=(e,t,r=SPAWN.windowMs)=>(Array.isArray(e)?e:[]).filter(e=>Number.isFinite(e)&&e>t-r).length;export const spawnDecision=({hop:e=0,spawnTimes:t=[],now:r=0,spawnedLive:n=0,totalLive:o=0,plan:i="free",disabled:s=!1}={},a=SPAWN)=>{const l={...SPAWN,...a||{}};if(s)return{ok:!1,reason:"Spawning terminals is disabled in this room."};if(e>=l.maxHop)return{ok:!1,reason:"Spawn limit reached — a terminal reached via cross-terminal cannot itself open further terminals; a person must open the next lane."};const c=activeWorkerCapacityDecision({spawnedLive:n,totalLive:o,plan:i},l);if(!c.ok)return c;if(recentSpawnCount(t,r,l.windowMs)>=l.perWindowCap){const e=Math.round(l.windowMs/6e4);return{ok:!1,reason:`Spawn burst limit reached (${l.perWindowCap} in ${e} min) — this replenishes as the window slides forward, or instantly when a person types into this lane.`}}return{ok:!0}};const l=Object.freeze(["mode","model","name","provider","runtime","sliceType","task"]),c=new Set(["default","acceptEdits","bypassPermissions","plan","review"]),d=new Set(["claude","codex","hermes"]),p=new Set(["scaffold","feature","fix","review"]),u=/((?<![a-z0-9])sk-[a-z0-9_-]{8,}|(?<![a-z0-9])gsk_[a-z0-9_-]{8,}|(?<![a-z0-9])AIza[a-z0-9_-]{8,}|bearer\s+[a-z0-9._-]{8,})/gi,m=/(?:\/home\/|\/users\/|\/private\/|\/tmp\/|[a-z]:\\|\\\\)/gi,h=e=>Array.isArray(e)?e.map(h):e&&"object"==typeof e?Object.fromEntries(Object.keys(e).sort().map(t=>[t,h(e[t])])):e,f=(e,t)=>null==e?null:String(e).slice(0,t),g=(e,t)=>f(e,t)?.replace(u,"[credential redacted]").replace(m,"[host path redacted]")||"";export function normalizeDispatchArgs(e={},t={}){if(!e||"object"!=typeof e||Array.isArray(e)||Object.keys(e).some(e=>!l.includes(e)))throw new TypeError("Invalid dispatch arguments");const r=e.runtime||t.runtime||"claude",n=e.mode||("plan"===t.mode?"default":t.mode)||"default";if(!d.has(r)||!c.has(n)||e.sliceType&&!p.has(e.sliceType))throw new TypeError("Invalid dispatch arguments");return Object.freeze({name:f(e.name,80),task:f(e.task,12e3),model:f(e.model,160),sliceType:f(e.sliceType,24),runtime:r,provider:f(e.provider,160),mode:n})}export function dispatchCapSnapshot({hop:e=0,spawnTimes:t=[],now:r=0,spawnedLive:n=0,totalLive:o=0,plan:i="free",disabled:s=!1}={},a=SPAWN){const l={...SPAWN,...a||{}},c="plus"===i?"plus":"free",d=maxSpawnedFor(c,l);return Object.freeze({killSwitch:!0===s,hop:Object.freeze({used:Math.max(0,Number(e)||0),limit:l.maxHop}),width:Object.freeze({requested:1,live:Math.max(0,Number(n)||0),limit:d}),machine:Object.freeze({live:Math.max(0,Number(o)||0),limit:l.machineMax}),plan:Object.freeze({name:c,price:"plus"===c?"€5/mo":"€0",used:Math.max(0,Number(n)||0),limit:d}),burst:Object.freeze({used:recentSpawnCount(t,r,l.windowMs),limit:l.perWindowCap,windowMinutes:Math.round(l.windowMs/6e4)})})}export function buildDispatchPreview({args:t,initiatorTerminalId:r,roomCode:n,bridgeAuthorityId:o,localAuthorityId:i,context:s={},limits:a=SPAWN}={}){if(!(r&&n&&o&&i))throw new TypeError("Dispatch authority is incomplete");const l=normalizeDispatchArgs(t,{runtime:s.runtime,mode:s.mode}),c=dispatchCapSnapshot(s,a),d=(p={authority:Object.freeze({initiatorTerminalId:String(r),roomCode:String(n).toUpperCase(),bridgeAuthorityId:String(o),localAuthorityId:String(i)}),exactArgs:l,caps:c},e("sha256").update(JSON.stringify(h(p))).digest("hex"));var p;const u=l.provider||("codex"===l.runtime?"OpenAI / Codex login":"hermes"===l.runtime?"Hermes ACP profile":"Anthropic / host default"),m=l.model||s.resolvedModel||"runtime default",f=g(l.name||l.task?.split(/\r?\n/)[0]||"Open one worker lane",120);return Object.freeze({version:1,fingerprint:d,purpose:f,packages:Object.freeze([{title:g(l.name||"Worker package",80),task:g(l.task||"Open idle for a later hand-off.",600)}]),runtime:Object.freeze({name:l.runtime,provider:g(s.providerName||u,120),model:g(m,160),band:"Start: now–1 min · completion: task-dependent",execution:"Runs locally on the bridge machine; no cloud worker is created.",accountAndSpend:`Uses the host’s ${g(s.providerName||u,100)} account/BYOK. Provider usage is the spend source; thinkpool has no credit meter.`}),permissions:Object.freeze({mode:l.mode,consequence:"bypassPermissions"===l.mode?"Unattended local access within this worker’s sandbox and tool policy.":"review"===l.mode?"Read-only inspection of the pinned parent snapshot; writes and approval escapes are unavailable.":"plan"===l.mode?"Planning only; execution remains gated.":"Protected local actions keep their normal permission gates."}),worktree:"Automatically creates one visible lateral worker lane and an isolated git worktree on this machine.",caps:c})}export function authorizeDispatchApproval({preview:e,approvedFingerprint:t,args:r,initiatorTerminalId:n,roomCode:o,bridgeAuthorityId:i,localAuthorityId:s,context:a={},decision:l="allow",consumed:c=!1,permissionId:d=null,consumedPermissionId:p=null,limits:u=SPAWN}={}){return"allow"!==l?{ok:!1,code:"dispatch_canceled"}:c?{ok:!1,code:d&&d===p?"idempotent_replay":"approval_replayed"}:y({preview:e,approvedFingerprint:t,args:r,initiatorTerminalId:n,roomCode:o,bridgeAuthorityId:i,localAuthorityId:s,context:a,limits:u})}export function authorizeDirectDispatch({preview:e,args:t,initiatorTerminalId:r,roomCode:n,bridgeAuthorityId:o,localAuthorityId:i,context:s={},limits:a=SPAWN}={}){return y({preview:e,approvedFingerprint:e?.fingerprint,args:t,initiatorTerminalId:r,roomCode:n,bridgeAuthorityId:o,localAuthorityId:i,context:s,limits:a})}function y({preview:e,approvedFingerprint:t,args:r,initiatorTerminalId:n,roomCode:o,bridgeAuthorityId:i,localAuthorityId:s,context:a={},limits:l=SPAWN}={}){let c;try{c=buildDispatchPreview({args:r,initiatorTerminalId:n,roomCode:o,bridgeAuthorityId:i,localAuthorityId:s,context:a,limits:l})}catch{return{ok:!1,code:"invalid_dispatch"}}if(!e||e.fingerprint!==t)return{ok:!1,code:"approval_mismatch"};if(c.fingerprint!==e.fingerprint)return{ok:!1,code:"stale_dispatch"};const d=spawnDecision(a,l);return d.ok?{ok:!0,code:"approved",preview:c}:{ok:!1,code:"cap_denied",reason:d.reason}}export function verifyDurableDispatchAuthority({item:e,events:t=[],expected:r={}}={}){const n=e=>({ok:!1,code:e}),o=String(r.fingerprint||"");if(!e||e.id!==r.controlItemId)return n("control_item_mismatch");if(e.session_code!==String(r.roomCode||"").toUpperCase())return n("wrong_room");if("dispatch"!==e.action_kind||"approval"!==e.item_kind)return n("wrong_action");if("resolved"!==e.status||"approved"!==e.resolution_code||!e.resolved_by)return n("not_approved");if("either_member"!==e.resolution_policy||null!=e.required_actor_id)return n("wrong_resolution_policy");if(e.bridge_authority_id!==r.bridgeAuthorityId)return n("wrong_bridge_authority");if(e.local_authority_id!==r.localAuthorityId)return n("wrong_local_authority");if(!/^[0-9a-f]{64}$/.test(o))return n("invalid_fingerprint");if(!String(e.request_context?.action||"").includes(`fp:${o}`))return n("request_fingerprint_mismatch");if(e.resolution_payload?.dispatch_fingerprint!==o)return n("resolution_fingerprint_mismatch");const i=(Array.isArray(t)?t:[]).filter(t=>t?.item_id===e.id);if(1!==i.filter(t=>"resolved"===t.event_type&&t.actor_id===e.resolved_by&&t.payload?.resolution_payload?.dispatch_fingerprint===o&&"approved"===t.payload?.resolution_code).length)return n("resolution_event_mismatch");const s=i.filter(t=>"delivery_attempted"===t.event_type&&t.actor_id===e.resolved_by&&t.payload?.data?.dispatch_fingerprint===o);return 1!==s.length?n("delivery_attempt_mismatch"):i.some(e=>"delivered"===e.event_type||"delivery_failed"===e.event_type)?n("delivery_already_final"):{ok:!0,code:"durable_dispatch_authorized",fingerprint:o,humanActorId:e.resolved_by,attemptKey:s[0].correlation_key}}export const CLOSABLE_HINT_MAX=6;export const closeLaneDecision=({callerId:e,spawnedBy:t,busy:r}={})=>e&&t===e?r?{ok:!1,reason:"busy"}:{ok:!0}:{ok:!1,reason:"not-owner"};export const closableLanes=(e,t=[])=>(Array.isArray(t)?t:[]).filter(t=>t&&closeLaneDecision({callerId:e,spawnedBy:t.spawnedBy,busy:t.busy}).ok);export const formatClosableHint=(e,t=[],r=6)=>{const n=closableLanes(e,t);if(!n.length)return"";const o=n.slice(0,r),i=o.map(e=>`${e.ref}${e.name?` ("${e.name}")`:""}`).join(", "),s=n.length>o.length?` (+${n.length-o.length} more)`:"";return`\n\nYou have ${n.length} finished lane${1===n.length?"":"s"} of your own still open — collect ${1===n.length?"it":"them"} with read_terminal, then close_terminal: ${i}${s}`};export const CROSSROOM={peekPerTurnCap:5};export const PEER_READ_MCP_TOOLS=Object.freeze(["read_terminal","list_sessions","read_session"]);export const PEER_POST_MCP_TOOLS=Object.freeze(["post_to_terminal","post_to_session"]);export const PEER_MCP_TOOLS=Object.freeze([...PEER_READ_MCP_TOOLS,...PEER_POST_MCP_TOOLS]);export const formatPairRoster=(e,{thisRoom:t,error:r}={})=>{if(r)return String(r);const n=new Set,o=(Array.isArray(e)?e:[]).filter(e=>!(!e||!e.code||e.code===t||n.has(e.code)||(n.add(e.code),0)));return o.length?`Your other thinkpool Code sessions (call read_session with a room code to look inside one):\n${o.map(e=>`- ${e.code}${e.name?` · "${e.name}"`:""}${e.host?` · on ${e.host}`:""}${!1===e.online?" · partner bridge offline":""}`).join("\n")}`:"No other sessions of yours are open right now. (Cross-session reach is limited to rooms this account is running here, plus your partner's rooms in the same pair.)"};export const CROSSROOM_BUS={busTimeoutMs:4e3};export const pairKeyFor=(e,t)=>{const r=String(null==e?"":e).toLowerCase().trim(),n=String(null==t?"":t).toLowerCase().trim();return r&&n&&r!==n?r<n?`${r}.${n}`:`${n}.${r}`:null};export const pairTopic=e=>e?`tppair:${e}`:null;export const CROSSROOM_POST={maxRoomHop:1,crossRoomPostCap:1};export const crossRoomPostDecision=({roomHop:e=0,postCount:t=0,disabled:r=!1}={},n=CROSSROOM_POST)=>{const o={...CROSSROOM_POST,...n||{}};return r?{ok:!1,reason:"Cross-room posting is turned off on this bridge."}:e>=o.maxRoomHop?{ok:!1,reason:"Cross-room hop limit reached — a room reached via a cross-room post cannot itself post into another room; a person must direct the next cross-room action."}:t>=o.crossRoomPostCap?{ok:!1,reason:`Cross-room post limit reached for this turn (${o.crossRoomPostCap}).`}:{ok:!0}};
|
|
1
|
+
import{createHash as e}from"node:crypto";import{BLOCKED_REASON as t,projectLaneLifecycle as r}from"./lane-lifecycle.mjs";export const PEEK={defaultLines:20,maxLines:200,perTurnCap:10,rosterPerTurnCap:1,lineCap:200,rosterPreview:100};export const readTerminalBudgetDecision=({targeted:e=!1,targetedCount:t=0,rosterCount:r=0}={},n=PEEK)=>{const o=Math.max(0,Number(t)||0),i=Math.max(0,Number(r)||0);return e?o>=n.perTurnCap?{ok:!1,targetedCount:o,rosterCount:i,reason:`Cross-terminal transcript read limit reached for this turn (${n.perTurnCap}). Stop polling and continue with the worker results already collected; a fresh accepted room turn resets the allowance.`}:{ok:!0,targetedCount:o+1,rosterCount:i}:i>=n.rosterPerTurnCap?{ok:!1,targetedCount:o,rosterCount:i,reason:`The full terminal roster was already read this turn (${n.rosterPerTurnCap}/${n.rosterPerTurnCap}). Use the current ROOM NOW snapshot or read one relevant terminal by ref or name.`}:{ok:!0,targetedCount:o,rosterCount:i+1}};export const readTerminalTurnBudgetDecision=({targeted:e=!1,targetedCount:t=0,rosterCount:r=0,budgetTurnRev:n=null,currentTurnRev:o=0}={},i=PEEK)=>{const s=Math.max(0,Number(o)||0),a=(null==n?null:Number.isFinite(Number(n))?Number(n):null)===s;return{...readTerminalBudgetDecision({targeted:e,targetedCount:a?t:0,rosterCount:a?r:0},i),budgetTurnRev:s}};export const LANE_STATUS={stuckAfterMs:9e4,repeatedFailureCount:2,failureWindow:12};const n=e=>!!e&&("error"===e.kind||"tool_result"===e.kind&&e.isError||"result"===e.kind&&e.subtype&&"success"!==e.subtype);export const laneBusyOf=(e={})=>"boolean"==typeof e?.busy?e.busy:"boolean"==typeof e?._busyAnn?e._busyAnn:e?.session?.turnActive??!1;export const settleLaneBusy=e=>!(!e||!1===e._busyAnn||(e._busyAnn=!1,0));export const settleLaneControl=(e,t=Date.now())=>!(!e||!0!==e._busyAnn||!settleLaneBusy(e)||(e._settledTurnRev=Number(e._turnRev)||null,e._turnSettledAt=Number(t)||Date.now(),e._turnStart=null,0));export const laneStatusOf=(e={},o=Date.now(),i=LANE_STATUS)=>{const s=Array.isArray(e?.log)?e.log:[],a=s.slice(-i.failureWindow);!e?.lastEvent||e.lastEvent===s[s.length-1]||e.lastEvent.cid&&e.lastEvent.cid===s[s.length-1]?.cid||a.push(e.lastEvent);let l=null;for(let e=a.length-1;e>=0;e--)if(Number.isFinite(a[e]?.ts)){l=a[e].ts;break}const c=Number.isFinite(e?.lastActionAt)?e.lastActionAt:l??null,d=null==c?null:Math.max(0,o-c),p=laneBusyOf(e),u=e?.pending instanceof Map?e.pending.size:Math.max(0,Number(e?.pendingCount)||0),m=e?.pending instanceof Map&&[...e.pending.values()].some(e=>"ask"===e?.payload?.risk)?t.NEEDS_INPUT:t.NEEDS_DECISION,h=((e,t=LANE_STATUS)=>{let r=0,o=0;for(let i=(Array.isArray(e)?e.length:0)-1;i>=0&&o<t.failureWindow;i--){const t=e[i];if(t&&"object"==typeof t){if(o++,"result"===t.kind&&(!t.subtype||"success"===t.subtype)||"you"===t.kind)break;n(t)&&r++}}return r})(a,i);let f=null,g=null;return u>0?(f="BLOCKED",g="waiting for input"):e?.stalled||p&&!e?.compacting&&null!=d&&d>=i.stuckAfterMs?(f="STUCK",g="no events while busy"):h>=i.repeatedFailureCount&&(f="BLOCKED",g="repeated errors"),{busy:!!p,lastActionAt:c,lastActionAgeMs:d,statusFlag:f,statusReason:g,lifecycle:r({events:a,busy:!!p,pendingCount:u,pendingReason:m,stalled:"STUCK"===f,failed:h>=i.repeatedFailureCount&&!p,rawStatus:f||(p?"busy":"idle")})}};export const formatLaneAge=e=>{if(!Number.isFinite(e))return"no activity";const t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s ago`;const r=Math.floor(t/60);if(r<60)return`${r}m ago`;const n=Math.floor(r/60);return n<24?`${n}h ago`:`${Math.floor(n/24)}d ago`};const o=e=>`${e.lifecycle?.state||"Blocked"}${e.lifecycle?.reason?` (${e.lifecycle.reason})`:""} · ${formatLaneAge(e.lastActionAgeMs)}`,i=(e,t)=>{const r=String(null==e?"":e).replace(/\s+/g," ").trim();return r.length>t?r.slice(0,t-1)+"…":r};export const digestLogEvent=(e,t=PEEK.lineCap)=>{if(!e||"object"!=typeof e)return"";switch(e.kind){case"you":return i(`${e.by||"someone"}: ${e.text||""}`,t);case"assistant":{const r=[];for(const t of Array.isArray(e.blocks)?e.blocks:[])"text"===t?.type&&String(t.text||"").trim()?r.push(String(t.text).trim()):"tool_use"===t?.type&&t.name&&r.push(`→ ${t.name}`);return r.length?i(`assistant: ${r.join(" ")}`,t):""}case"tool_result":return e.isError?i("⎿ error",t):"";case"result":return e.subtype&&"success"!==e.subtype?i(`turn ended — ${e.subtype}`,t):"";case"error":return i(`error: ${e.message||""}`,t);default:return""}};export const cleanPtyTail=(e,t)=>String(e||"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b[@-_][0-?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"").split(/\r?\n/).map(e=>e.replace(/\s+$/,"")).filter(e=>e.trim()).slice(-Math.max(1,t));export const siblingRef=e=>String(e).slice(0,8);export const siblingsOf=({selfId:e,sessions:t,terms:r,names:n={},now:o=Date.now()}={})=>{const i=e=>n&&n[e]||"",s=[];for(const[r,n]of t||new Map)r!==e&&s.push({id:r,ref:siblingRef(r),name:i(r),kind:"agent",cmd:n?.cmd||"claude",log:Array.isArray(n?.log)?n.log:[],...laneStatusOf(n,o)});for(const[t,n]of r||new Map)t!==e&&s.push({id:t,ref:siblingRef(t),name:i(t),kind:"shell",cmd:n?.cmd||"shell",buf:n?.buf||"",...laneStatusOf(n,o)});return s};export const isOrdinalRef=e=>/^(terminal\s*)?\d+$/i.test(e)||/^t\d+$/i.test(e);export const resolveSibling=(e,t)=>{const r=String(t||"").toLowerCase().trim();if(!r)return null;const n=Array.isArray(e)?e:[];return n.find(e=>String(e.id).toLowerCase()===r)||n.find(e=>String(e.name||"").toLowerCase()===r)||n.find(e=>String(e.ref).toLowerCase()===r)||(isOrdinalRef(r)?null:n.find(e=>r.length>=4&&String(e.id).toLowerCase().startsWith(r))||n.find(e=>e.name&&String(e.name).toLowerCase().includes(r))||n.find(e=>String(e.cmd).toLowerCase().includes(r))||null)};const s=e=>`${e.ref}${e.name?` · "${e.name}"`:""}`;export const formatPeek=({selfId:e,sessions:t,terms:r,names:n={},terminal:a,lines:l,now:c=Date.now()}={})=>{const d=Math.min(PEEK.maxLines,Math.max(1,Number(l)||PEEK.defaultLines)),p=siblingsOf({selfId:e,sessions:t,terms:r,names:n,now:c});if(!p.length)return"No other terminals are open in this room right now.";if(!a)return`Other terminals in this room (call read_terminal with a ref or name to read one):\n${p.map(e=>{let t;if("agent"===e.kind){const r=e.log.map(e=>digestLogEvent(e,PEEK.rosterPreview)).filter(Boolean);t=r[r.length-1]||"(no activity yet)"}else t=cleanPtyTail(e.buf,1)[0]||"(no output yet)";return`- ${s(e)} · ${e.kind} · ${e.cmd} · ${o(e)} — ${i(t,PEEK.rosterPreview)}`}).join("\n")}`;const u=resolveSibling(p,a);if(!u)return`No terminal matches "${a}". Call read_terminal with no argument to list the open terminals (refer to one by its name or ref).${isOrdinalRef(String(a||"").toLowerCase().trim())?" On-screen numbers like \"Terminal N\" shift when a terminal closes, so they can't identify a lane — use a terminal's name or ref instead.":""}`;let m;return m="agent"===u.kind?u.log.map(e=>digestLogEvent(e,PEEK.lineCap)).filter(Boolean).slice(-d).join("\n")||"(no activity yet)":cleanPtyTail(u.buf,d).join("\n")||"(no output yet)",`Terminal ${s(u)} (${u.kind} · ${u.cmd}) · ${o(u)} — last ${d} lines:\n${m}`};export const nativeClaudeProviderAccessFailed=e=>{let t="";try{t="string"==typeof e?e:JSON.stringify(e||"")}catch{t=String(e||"")}return/organization has disabled (?:claude(?: subscription access)?|subscription access)|(?:claude )?subscription access (?:has been |is )?disabled|invalid anthropic (?:api )?key|invalid x-api-key|not logged in to claude|(?:run|use) \/login[^\n]{0,80}claude|no valid anthropic (?:api )?key/i.test(t)};const a=Object.freeze(["nous:anthropic/claude-sonnet-4.6","nous:anthropic/claude-sonnet-4.5","nous:anthropic/claude-sonnet-4"]);export const preferredHermesClaudeReviewModel=(e=[])=>{const t=new Set((Array.isArray(e)?e:[]).map(e=>"string"==typeof e?e:e?.value||e?.slug).filter(Boolean));for(const e of a)if(t.has(e))return e;for(const e of t)if(/^nous:anthropic\/claude-sonnet-/i.test(e))return e;for(const e of t)if(/^nous:anthropic\/claude-haiku-/i.test(e))return e;for(const e of t)if(/^nous:anthropic\/claude-opus-/i.test(e))return e;return null};export const nativeClaudeFallbackHint=({parentRuntime:e,parentModels:t,targetRuntime:r,targetLog:n}={})=>{if("claude"!==r||!nativeClaudeProviderAccessFailed(n))return"";const o="thinkpool provider status: native Claude access failed at the account/provider level. Do not retry Sonnet, Opus, Haiku, or another model alias on the same native Claude provider during this task.",i="hermes"===e?preferredHermesClaudeReviewModel(t):null;return i?`\n\n${o} For a visible manual review fallback, spawn exactly one worker with runtime="hermes", model=${JSON.stringify(i)}, mode="default", and sliceType="review". This Hermes lane is permission-gated, not structurally read-only: instruct it not to edit, deny/stop any write request, and do not treat its review as a Flow safety proof. Never use Hermes delegate_task.`:`\n\n${o} Use a different available runtime/provider once, or report the blocker.`};export const ROOMNOW={laneCap:8,previewLen:70,wtCap:10};export const formatRoomNow=({selfId:e,sessions:t,terms:r,names:n={},worktrees:a=[],now:l=Date.now()}={},c=ROOMNOW)=>{const d=siblingsOf({selfId:e,sessions:t,terms:r,names:n,now:l}),p=[];if(d.length){const e=d.slice(0,c.laneCap),t=e.map(e=>{let t;if("agent"===e.kind){const r=e.log.map(e=>digestLogEvent(e,c.previewLen)).filter(Boolean);t=r[r.length-1]||"(no activity yet)"}else t=cleanPtyTail(e.buf,1)[0]||"(no output yet)";return`- ${s(e)} · ${e.kind} · ${o(e)} — ${i(t,c.previewLen)}`});d.length>e.length&&t.push(`- … +${d.length-e.length} more (read_terminal lists all)`),p.push(`Other lanes in this room right now (this is the roster; use targeted read_terminal only for needed detail):\n${t.join("\n")}`)}const u=Array.isArray(a)?a:[],m=u.slice(0,c.wtCap);if(m.length){const e=m.map(e=>`- ${i(e,c.previewLen+30)}`);u.length>m.length&&e.push(`- … +${u.length-m.length} more (\`git worktree list\` shows all)`),p.push(`Active git worktrees on this host (code edits go in your OWN worktree — never one another lane is on):\n${e.join("\n")}`)}return p.length?`ROOM NOW (live snapshot, this turn):\n${p.join("\n")}`:null};export const CROSSPOST={maxHop:1,perTurnCap:3};export const crossPostDecision=({hop:e=0,postCount:t=0,disabled:r=!1}={},n=CROSSPOST)=>{const o={...CROSSPOST,...n||{}};return r?{ok:!1,reason:"Cross-terminal posting is disabled in this room."}:e>=o.maxHop?{ok:!1,reason:"Cross-terminal hop limit reached — an agent reached via cross-post cannot itself post onward; a person must direct the next cross-terminal action."}:t>=o.perTurnCap?{ok:!1,reason:`Cross-terminal post limit reached for this turn (${o.perTurnCap}).`}:{ok:!0}};export const crossPostNeedsCard=({mode:e="default",spawnedByMe:t=!1}={})=>!("bypassPermissions"===e||!0===t);export const SPAWN={maxHop:1,perWindowCap:6,windowMs:6e5,freeMaxSpawned:3,plusMaxSpawned:6,machineMax:12};export const maxSpawnedFor=(e,t=SPAWN)=>{const r={...SPAWN,...t||{}};return"plus"===e?r.plusMaxSpawned:r.freeMaxSpawned};export const isActiveDispatchedWorker=e=>!(!e?.spawnedBy||"conductor"===e.flowRole||e.flowTaskKey&&e.flowDone);export const countActiveDispatchedWorkers=(e=[])=>[...e].filter(isActiveDispatchedWorker).length;export const machineCapacityDecision=({totalLive:e=0,disabled:t=!1}={},r=SPAWN)=>{const n={...SPAWN,...r||{}};return t?{ok:!1,reason:"Spawning terminals is disabled in this room."}:e>=n.machineMax?{ok:!1,reason:`Room is at the machine cap (${n.machineMax} live lanes) — close one before opening another.`}:{ok:!0}};export const activeWorkerCapacityDecision=({spawnedLive:e=0,totalLive:t=0,plan:r="free",disabled:n=!1}={},o=SPAWN)=>{const i={...SPAWN,...o||{}},s=machineCapacityDecision({totalLive:t,disabled:n},i);if(!s.ok)return s;const a=maxSpawnedFor(r,i);return e>=a?{ok:!1,reason:`Dispatch ceiling reached (${a} lane${1===a?"":"s"} on the ${r} plan)${"plus"!==r?` — Plus raises it to ${i.plusMaxSpawned}.`:"."} Close a dispatched lane to open another.`}:{ok:!0}};export const recentSpawnCount=(e,t,r=SPAWN.windowMs)=>(Array.isArray(e)?e:[]).filter(e=>Number.isFinite(e)&&e>t-r).length;export const spawnDecision=({hop:e=0,spawnTimes:t=[],now:r=0,spawnedLive:n=0,totalLive:o=0,plan:i="free",disabled:s=!1}={},a=SPAWN)=>{const l={...SPAWN,...a||{}};if(s)return{ok:!1,reason:"Spawning terminals is disabled in this room."};if(e>=l.maxHop)return{ok:!1,reason:"Spawn limit reached — a terminal reached via cross-terminal cannot itself open further terminals; a person must open the next lane."};const c=activeWorkerCapacityDecision({spawnedLive:n,totalLive:o,plan:i},l);if(!c.ok)return c;if(recentSpawnCount(t,r,l.windowMs)>=l.perWindowCap){const e=Math.round(l.windowMs/6e4);return{ok:!1,reason:`Spawn burst limit reached (${l.perWindowCap} in ${e} min) — this replenishes as the window slides forward, or instantly when a person types into this lane.`}}return{ok:!0}};const l=Object.freeze(["mode","model","name","provider","runtime","sliceType","task"]),c=new Set(["default","acceptEdits","bypassPermissions","plan","review"]),d=new Set(["claude","codex","hermes"]),p=new Set(["scaffold","feature","fix","review"]),u=/((?<![a-z0-9])sk-[a-z0-9_-]{8,}|(?<![a-z0-9])gsk_[a-z0-9_-]{8,}|(?<![a-z0-9])AIza[a-z0-9_-]{8,}|bearer\s+[a-z0-9._-]{8,})/gi,m=/(?:\/home\/|\/users\/|\/private\/|\/tmp\/|[a-z]:\\|\\\\)/gi,h=e=>Array.isArray(e)?e.map(h):e&&"object"==typeof e?Object.fromEntries(Object.keys(e).sort().map(t=>[t,h(e[t])])):e,f=(e,t)=>null==e?null:String(e).slice(0,t),g=(e,t)=>f(e,t)?.replace(u,"[credential redacted]").replace(m,"[host path redacted]")||"";export function normalizeDispatchArgs(e={},t={}){if(!e||"object"!=typeof e||Array.isArray(e)||Object.keys(e).some(e=>!l.includes(e)))throw new TypeError("Invalid dispatch arguments");const r=e.runtime||t.runtime||"claude",n=e.mode||("plan"===t.mode?"default":t.mode)||"default";if(!d.has(r)||!c.has(n)||e.sliceType&&!p.has(e.sliceType))throw new TypeError("Invalid dispatch arguments");return Object.freeze({name:f(e.name,80),task:f(e.task,12e3),model:f(e.model,160),sliceType:f(e.sliceType,24),runtime:r,provider:f(e.provider,160),mode:n})}export function dispatchCapSnapshot({hop:e=0,spawnTimes:t=[],now:r=0,spawnedLive:n=0,totalLive:o=0,plan:i="free",disabled:s=!1}={},a=SPAWN){const l={...SPAWN,...a||{}},c="plus"===i?"plus":"free",d=maxSpawnedFor(c,l);return Object.freeze({killSwitch:!0===s,hop:Object.freeze({used:Math.max(0,Number(e)||0),limit:l.maxHop}),width:Object.freeze({requested:1,live:Math.max(0,Number(n)||0),limit:d}),machine:Object.freeze({live:Math.max(0,Number(o)||0),limit:l.machineMax}),plan:Object.freeze({name:c,price:"plus"===c?"€5/mo":"€0",used:Math.max(0,Number(n)||0),limit:d}),burst:Object.freeze({used:recentSpawnCount(t,r,l.windowMs),limit:l.perWindowCap,windowMinutes:Math.round(l.windowMs/6e4)})})}export function buildDispatchPreview({args:t,initiatorTerminalId:r,roomCode:n,bridgeAuthorityId:o,localAuthorityId:i,context:s={},limits:a=SPAWN}={}){if(!(r&&n&&o&&i))throw new TypeError("Dispatch authority is incomplete");const l=normalizeDispatchArgs(t,{runtime:s.runtime,mode:s.mode}),c=dispatchCapSnapshot(s,a),d=(p={authority:Object.freeze({initiatorTerminalId:String(r),roomCode:String(n).toUpperCase(),bridgeAuthorityId:String(o),localAuthorityId:String(i)}),exactArgs:l,caps:c},e("sha256").update(JSON.stringify(h(p))).digest("hex"));var p;const u=l.provider||("codex"===l.runtime?"OpenAI / Codex login":"hermes"===l.runtime?"Hermes ACP profile":"Anthropic / host default"),m=l.model||s.resolvedModel||"runtime default",f=g(l.name||l.task?.split(/\r?\n/)[0]||"Open one worker lane",120);return Object.freeze({version:1,fingerprint:d,purpose:f,packages:Object.freeze([{title:g(l.name||"Worker package",80),task:g(l.task||"Open idle for a later hand-off.",600)}]),runtime:Object.freeze({name:l.runtime,provider:g(s.providerName||u,120),model:g(m,160),band:"Start: now–1 min · completion: task-dependent",execution:"Runs locally on the bridge machine; no cloud worker is created.",accountAndSpend:`Uses the host’s ${g(s.providerName||u,100)} account/BYOK. Provider usage is the spend source; thinkpool has no credit meter.`}),permissions:Object.freeze({mode:l.mode,consequence:"bypassPermissions"===l.mode?"Unattended local access within this worker’s sandbox and tool policy.":"review"===l.mode?"Read-only inspection of the pinned parent snapshot; writes and approval escapes are unavailable.":"plan"===l.mode?"Planning only; execution remains gated.":"Protected local actions keep their normal permission gates."}),worktree:"Automatically creates one visible lateral worker lane and an isolated git worktree on this machine.",caps:c})}export function authorizeDispatchApproval({preview:e,approvedFingerprint:t,args:r,initiatorTerminalId:n,roomCode:o,bridgeAuthorityId:i,localAuthorityId:s,context:a={},decision:l="allow",consumed:c=!1,permissionId:d=null,consumedPermissionId:p=null,limits:u=SPAWN}={}){return"allow"!==l?{ok:!1,code:"dispatch_canceled"}:c?{ok:!1,code:d&&d===p?"idempotent_replay":"approval_replayed"}:y({preview:e,approvedFingerprint:t,args:r,initiatorTerminalId:n,roomCode:o,bridgeAuthorityId:i,localAuthorityId:s,context:a,limits:u})}export function authorizeDirectDispatch({preview:e,args:t,initiatorTerminalId:r,roomCode:n,bridgeAuthorityId:o,localAuthorityId:i,context:s={},limits:a=SPAWN}={}){return y({preview:e,approvedFingerprint:e?.fingerprint,args:t,initiatorTerminalId:r,roomCode:n,bridgeAuthorityId:o,localAuthorityId:i,context:s,limits:a})}function y({preview:e,approvedFingerprint:t,args:r,initiatorTerminalId:n,roomCode:o,bridgeAuthorityId:i,localAuthorityId:s,context:a={},limits:l=SPAWN}={}){let c;try{c=buildDispatchPreview({args:r,initiatorTerminalId:n,roomCode:o,bridgeAuthorityId:i,localAuthorityId:s,context:a,limits:l})}catch{return{ok:!1,code:"invalid_dispatch"}}if(!e||e.fingerprint!==t)return{ok:!1,code:"approval_mismatch"};if(c.fingerprint!==e.fingerprint)return{ok:!1,code:"stale_dispatch"};const d=spawnDecision(a,l);return d.ok?{ok:!0,code:"approved",preview:c}:{ok:!1,code:"cap_denied",reason:d.reason}}export function verifyDurableDispatchAuthority({item:e,events:t=[],expected:r={}}={}){const n=e=>({ok:!1,code:e}),o=String(r.fingerprint||"");if(!e||e.id!==r.controlItemId)return n("control_item_mismatch");if(e.session_code!==String(r.roomCode||"").toUpperCase())return n("wrong_room");if("dispatch"!==e.action_kind||"approval"!==e.item_kind)return n("wrong_action");if("resolved"!==e.status||"approved"!==e.resolution_code||!e.resolved_by)return n("not_approved");if("either_member"!==e.resolution_policy||null!=e.required_actor_id)return n("wrong_resolution_policy");if(e.bridge_authority_id!==r.bridgeAuthorityId)return n("wrong_bridge_authority");if(e.local_authority_id!==r.localAuthorityId)return n("wrong_local_authority");if(!/^[0-9a-f]{64}$/.test(o))return n("invalid_fingerprint");if(!String(e.request_context?.action||"").includes(`fp:${o}`))return n("request_fingerprint_mismatch");if(e.resolution_payload?.dispatch_fingerprint!==o)return n("resolution_fingerprint_mismatch");const i=(Array.isArray(t)?t:[]).filter(t=>t?.item_id===e.id);if(1!==i.filter(t=>"resolved"===t.event_type&&t.actor_id===e.resolved_by&&t.payload?.resolution_payload?.dispatch_fingerprint===o&&"approved"===t.payload?.resolution_code).length)return n("resolution_event_mismatch");const s=i.filter(t=>"delivery_attempted"===t.event_type&&t.actor_id===e.resolved_by&&t.payload?.data?.dispatch_fingerprint===o);return 1!==s.length?n("delivery_attempt_mismatch"):i.some(e=>"delivered"===e.event_type||"delivery_failed"===e.event_type)?n("delivery_already_final"):{ok:!0,code:"durable_dispatch_authorized",fingerprint:o,humanActorId:e.resolved_by,attemptKey:s[0].correlation_key}}export const CLOSABLE_HINT_MAX=6;export const closeLaneDecision=({callerId:e,spawnedBy:t,busy:r}={})=>e&&t===e?r?{ok:!1,reason:"busy"}:{ok:!0}:{ok:!1,reason:"not-owner"};export const closableLanes=(e,t=[])=>(Array.isArray(t)?t:[]).filter(t=>t&&closeLaneDecision({callerId:e,spawnedBy:t.spawnedBy,busy:t.busy}).ok);export const formatClosableHint=(e,t=[],r=6)=>{const n=closableLanes(e,t);if(!n.length)return"";const o=n.slice(0,r),i=o.map(e=>`${e.ref}${e.name?` ("${e.name}")`:""}`).join(", "),s=n.length>o.length?` (+${n.length-o.length} more)`:"";return`\n\nYou have ${n.length} finished lane${1===n.length?"":"s"} preserved for review. A person can free a slot by closing one with the X in its Ensemble row: ${i}${s}`};export const CROSSROOM={peekPerTurnCap:5};export const PEER_READ_MCP_TOOLS=Object.freeze(["read_terminal","list_sessions","read_session"]);export const PEER_POST_MCP_TOOLS=Object.freeze(["post_to_terminal","post_to_session"]);export const PEER_MCP_TOOLS=Object.freeze([...PEER_READ_MCP_TOOLS,...PEER_POST_MCP_TOOLS]);export const formatPairRoster=(e,{thisRoom:t,error:r}={})=>{if(r)return String(r);const n=new Set,o=(Array.isArray(e)?e:[]).filter(e=>!(!e||!e.code||e.code===t||n.has(e.code)||(n.add(e.code),0)));return o.length?`Your other thinkpool Code sessions (call read_session with a room code to look inside one):\n${o.map(e=>`- ${e.code}${e.name?` · "${e.name}"`:""}${e.host?` · on ${e.host}`:""}${!1===e.online?" · partner bridge offline":""}`).join("\n")}`:"No other sessions of yours are open right now. (Cross-session reach is limited to rooms this account is running here, plus your partner's rooms in the same pair.)"};export const CROSSROOM_BUS={busTimeoutMs:4e3};export const pairKeyFor=(e,t)=>{const r=String(null==e?"":e).toLowerCase().trim(),n=String(null==t?"":t).toLowerCase().trim();return r&&n&&r!==n?r<n?`${r}.${n}`:`${n}.${r}`:null};export const pairTopic=e=>e?`tppair:${e}`:null;export const CROSSROOM_POST={maxRoomHop:1,crossRoomPostCap:1};export const crossRoomPostDecision=({roomHop:e=0,postCount:t=0,disabled:r=!1}={},n=CROSSROOM_POST)=>{const o={...CROSSROOM_POST,...n||{}};return r?{ok:!1,reason:"Cross-room posting is turned off on this bridge."}:e>=o.maxRoomHop?{ok:!1,reason:"Cross-room hop limit reached — a room reached via a cross-room post cannot itself post into another room; a person must direct the next cross-room action."}:t>=o.crossRoomPostCap?{ok:!1,reason:`Cross-room post limit reached for this turn (${o.crossRoomPostCap}).`}:{ok:!0}};
|
package/lane-work-snapshot.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{execFileSync as e}from"node:child_process";const t=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/,n=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/,r=new Set(["claude","codex","hermes"]),
|
|
1
|
+
import{execFileSync as e}from"node:child_process";const t=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/,n=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/,r=new Set(["claude","codex","hermes"]),o=new Set(["default","acceptEdits","plan","review","bypassPermissions"]),i=new Set(["main","worker","side","flow-conductor","flow-builder","flow-reviewer","scheduled"]),a=new Set(["clean","dirty","unavailable"]),l=/(?:\r|\n|(?:^|[\\/])(?:Users|home|private|tmp|var|workspace)(?:[\\/]|$)|\.thinkpool[\\/]|(?:api[_-]?key|authorization|bearer|password|secret)\b)/i,u=1e5;function d(e){if("string"!=typeof e)return null;const n=e.trim();return t.test(n)?n:null}function s(e){if("string"!=typeof e)return null;const t=e.trim().toLowerCase();return n.test(t)?t:null}function c(e={}){return"conductor"===e.flowRole?"flow-conductor":"reviewer"===e.flowRole||"review"===e.sliceType?"flow-reviewer":e.flowSessionId||e.flowTaskKey||"builder"===e.flowRole?"flow-builder":e.scheduleRunId?"scheduled":e.sideParent?"side":e.spawnedBy?"worker":"main"}function f(e){return new Set(String(e||"").split("\0").filter(Boolean))}export function readLaneWorkGit(t,n=e,r=null){if("string"!=typeof t||!t.trim())return{worktreeState:"unavailable"};let o=null;try{o=s(n("git",["-C",t,"rev-parse","HEAD"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}))}catch{return{worktreeState:"unavailable"}}try{const e=n("git",["-C",t,"status","--porcelain=v1","--untracked-files=all"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}),i={...o?{headSha:o}:{},worktreeState:String(e||"").trim()?"dirty":"clean"},a="clean"===r?.worktreeState?s(r?.headSha):null;if(a){o&&(i.headChanged=o!==a);const e=function(e,t,n){try{const r=n("git",["-C",e,"diff","--name-only","-z","--no-renames",t,"--"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}),o=n("git",["-C",e,"ls-files","--others","--exclude-standard","-z"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}),i=f(r);for(const e of f(o))i.add(e);return Math.min(i.size,u)}catch{return null}}(t,a,n);null!==e&&(i.changedFileCount=e)}return i}catch{return{...o?{headSha:o}:{},worktreeState:"unavailable"}}}export function normalizeLaneWorkSnapshot(e){if(!e||"object"!=typeof e||Array.isArray(e)||![1,2].includes(e.version))return null;const t=d(e.terminalId),n=Number.isSafeInteger(e.turnRev)&&e.turnRev>0?e.turnRev:null,c="string"==typeof e.capturedAt&&Number.isFinite(Date.parse(e.capturedAt))?new Date(e.capturedAt).toISOString():null,f=e.identity,g=r.has(f?.runtime)?f.runtime:null,w=i.has(f?.laneRole)?f.laneRole:null,p=a.has(e.git?.worktreeState)?e.git.worktreeState:null;if(!(t&&n&&c&&g&&w&&p))return null;const h={runtime:g,laneRole:w},m=function(e,t=120){if("string"!=typeof e)return null;const n=e.replace(/\s+/g," ").trim();return!n||n.length>t||l.test(n)?null:n}(f.model),S=o.has(f.mode)?f.mode:null,y=d(f.parentTerminalId),k=d(f.flowId),v=d(f.flowTaskKey);m&&(h.model=m),S&&(h.mode=S),y&&(h.parentTerminalId=y),k&&(h.flowId=k),v&&(h.flowTaskKey=v);const b={worktreeState:p},I=s(e.git?.headSha),C="boolean"==typeof e.git?.headChanged?e.git.headChanged:null,R=Number.isSafeInteger(e.git?.changedFileCount)&&e.git.changedFileCount>=0&&e.git.changedFileCount<=u?e.git.changedFileCount:null;return I&&(b.headSha=I),null!==C&&(b.headChanged=C),null!==R&&(b.changedFileCount=R),{version:e.version,terminalId:t,turnRev:n,capturedAt:c,identity:h,git:b}}export function buildLaneWorkSnapshot(t,{now:n=Date.now(),gitFacts:r}={}){const o=t?.sideParent||("string"!=typeof t?.spawnedBy||t.spawnedBy.startsWith("flow:")?null:t.spawnedBy),i={runtime:t?.runtime,model:t?.model,mode:t?.mode,laneRole:c(t),parentTerminalId:o,flowId:t?.flowSessionId,flowTaskKey:t?.flowTaskKey};return normalizeLaneWorkSnapshot({version:2,terminalId:t?.id,turnRev:Number(t?._turnRev),capturedAt:new Date(n).toISOString(),identity:i,git:r||readLaneWorkGit(t?.cwd,e,t?._turnGitStart)})}
|
package/package.json
CHANGED
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.388",
|
|
5
5
|
"kind": "minified",
|
|
6
6
|
"minifiedModules": 118,
|
|
7
|
-
"sourceModuleBytes":
|
|
8
|
-
"artifactModuleBytes":
|
|
7
|
+
"sourceModuleBytes": 1723427,
|
|
8
|
+
"artifactModuleBytes": 775951,
|
|
9
9
|
"files": {
|
|
10
|
-
"package.json": "
|
|
10
|
+
"package.json": "8a883228c53d6e2ed642f902009192efb1f35a76d8277bcd7a2d8b019a309364",
|
|
11
11
|
"LICENSE": "8a030197ca1cad9669909ca14c9ad15cf48d9fe551da526ccaf1fca993eddb23",
|
|
12
|
-
"bridge.mjs": "
|
|
12
|
+
"bridge.mjs": "9d71cfc27ff670d7a79f3afa015030fa33708167e9b213bb83547f46aba46c6d",
|
|
13
13
|
"bridge-service.sh": "b64f27c473ca8f3a49190fd08c23947ab14ca9958d70b6fa53c7bddc2be91403",
|
|
14
14
|
"command-guidance.mjs": "b9b967b59ff4e77c9613abb0f28858bf3ac5b106a509e471039777b53bec3e29",
|
|
15
15
|
"abort-turn-barrier.mjs": "3734a5b7e2e940ec6d7fa8b5b04935e1429a23d1bd9e92b2ac2a2ecd9f77c75e",
|
|
@@ -24,19 +24,19 @@
|
|
|
24
24
|
"byok-detect.mjs": "f31f2ca426737581a97c391b3cecfc75f0207cfa31f51c6bf4a9148309c9625d",
|
|
25
25
|
"context-contract.mjs": "ffebb435dc5d75c289329bf16ab909df9d634a2b508154c250c6b25906a02a91",
|
|
26
26
|
"context-windows.mjs": "80af664f84d7e95ef2b0a2a3131090ac4ccd522709448ac9a0d96c378bbec0f7",
|
|
27
|
-
"claude-session.mjs": "
|
|
27
|
+
"claude-session.mjs": "41f32dfb89d5b463f4754f3a9c7ad5c73facb959b5b0665da5009966665fca45",
|
|
28
28
|
"terminal-name.mjs": "f39bb8d1e148ab9a74cbb96438d31e524d6597b8035f00d7a906c28c306c0cf8",
|
|
29
29
|
"claude-command-catalog.mjs": "36bd4342b2ae94b43a0072533ef2d1648c7473003964bbad433fdb1a8b2bfec1",
|
|
30
30
|
"codex-session.mjs": "8001b960e20bcffad2e4d23c1f033e81738be6ded9dc2dff36878fac7719f3c8",
|
|
31
31
|
"question-response.mjs": "35a7ba53d3eb117717c18004d2a8441f8f37665b231a3c44f4bd9321ff59dd57",
|
|
32
|
-
"thinkpool-room-prompt.mjs": "
|
|
32
|
+
"thinkpool-room-prompt.mjs": "329f4a34a5342a606966a1ad8536d058a8529b11634cbffca0eb8909de1dd1c6",
|
|
33
33
|
"thinkpool-prompt-contracts.mjs": "051602d7d2fe9b34df92957bd3922c5eeebedbcc60c892adf415243887d8c62f",
|
|
34
|
-
"thinkpool-capabilities.json": "
|
|
34
|
+
"thinkpool-capabilities.json": "803fc6f4af830961b55e43ba1d178c63deebac94ffd8f88250c8a3886b0cf47d",
|
|
35
35
|
"codex-app-server.mjs": "06778825aa3c51595d57cce733235cb07874986351b6fea7adac70ca33f32b11",
|
|
36
36
|
"codex-images.mjs": "31605d6d8b3dd6b73395da63d1b0c513445c95ffa2f4306ee466f201d633ffc0",
|
|
37
37
|
"codex-mcp-http.mjs": "7472543648a9bb575ce20dc3e3270c2da84174c6ea6e9faf87dfaafb95b6212a",
|
|
38
38
|
"lane-worktree.mjs": "37583757ab82843412ba565dfba3d7cab517e94782eb33115decd5438d092d8f",
|
|
39
|
-
"lane-work-snapshot.mjs": "
|
|
39
|
+
"lane-work-snapshot.mjs": "8b6fcc60264879914ed0faf1fa04831435f9e1ad4a1b765dc75f654cd77977a8",
|
|
40
40
|
"codex-event-mapper.mjs": "7e7b878b24cb9208af517a195cc4089de87eda68086355f9e8e3b7e308825dee",
|
|
41
41
|
"edit-diff.mjs": "9a1bef6bb2d853d630ad38aba374cb2a120dd75b9aa08ab42ffc83cb0e1c57b6",
|
|
42
42
|
"cumulative-event-relay.mjs": "cf6e6533e33b3c5bb0b462d15ccc86106f2b56f8b1e66fc1f4867dd8f44d7ae6",
|
|
@@ -81,8 +81,8 @@
|
|
|
81
81
|
"session-search.mjs": "d606fbab5c47357071e4919107aa00ad090f6e7d7e6dc929e0ac5a4d0cb2c538",
|
|
82
82
|
"session-store.mjs": "fa3f7a27a8a7c49bb89364fb28c9c2680f7f487d4b4125329ab4a0ba9362bd8c",
|
|
83
83
|
"side-lane.mjs": "306d451e2d163ecdf40030d886a338770b11bc57952543a107e422f95ca49d45",
|
|
84
|
-
"worker-completion.mjs": "
|
|
85
|
-
"cross-terminal.mjs": "
|
|
84
|
+
"worker-completion.mjs": "86984535a657b558543da2e84a24e453a43e81f08d0ada1caad902bf5c73f541",
|
|
85
|
+
"cross-terminal.mjs": "423920acc5ca0e95fdb86d0da19131eaae0a4ca0f9d20cf701efa5cb4e5fdbc3",
|
|
86
86
|
"cloud-session-transcript.mjs": "1e8b3000d628eac0cff171901d6fed13983528b42e23e277583ef65bf8f9fa2b",
|
|
87
87
|
"pair-bus.mjs": "cbc28cee7f4f06b2213091e0b7b07d61c1d01f0ff207c5c6d808cd616ece221e",
|
|
88
88
|
"direct-pair-room.mjs": "92557b54307da2ca31f0a0d090e44b019a23b1ab32a7dfd6cbcb9d55fd761736",
|
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schemaVersion": 1,
|
|
3
|
-
"bundleVersion":
|
|
3
|
+
"bundleVersion": 32,
|
|
4
4
|
"contracts": [
|
|
5
5
|
{
|
|
6
6
|
"id": "room-coordination",
|
|
7
|
-
"version":
|
|
7
|
+
"version": 8,
|
|
8
8
|
"routes": [
|
|
9
9
|
{
|
|
10
10
|
"id": "room-awareness",
|
|
11
11
|
"tools": ["read_terminal"],
|
|
12
12
|
"trigger": "\\b(other|another|sibling|peer)\\s+(lane|terminal)|\\bread_terminal\\b",
|
|
13
|
-
"prompt": "When the request depends on another lane, a sibling may overlap the work, or a person refers to another terminal, use the current ROOM NOW snapshot as the default roster. Do not repeat it with a no-argument read_terminal call unless the snapshot is missing or truncated; that roster lookup has its own one-call allowance. Read only the relevant terminal by ref or name when its detailed transcript is actually needed. Never poll with read_terminal: wait for the room snapshot or completion signal to show a state change, collect each finished owned worker once
|
|
13
|
+
"prompt": "When the request depends on another lane, a sibling may overlap the work, or a person refers to another terminal, use the current ROOM NOW snapshot as the default roster. Do not repeat it with a no-argument read_terminal call unless the snapshot is missing or truncated; that roster lookup has its own one-call allowance. Read only the relevant terminal by ref or name when its detailed transcript is actually needed. Never poll with read_terminal: wait for the room snapshot or completion signal to show a state change, then collect each finished owned worker once. Leave every finished worker visible for review until a person dismisses it with the Ensemble X. Never call close_terminal merely because work finished. Preserve the bounded targeted-read allowance for worker collection and final review."
|
|
14
14
|
},
|
|
15
15
|
{
|
|
16
16
|
"id": "cross-room-awareness",
|
|
@@ -78,7 +78,7 @@
|
|
|
78
78
|
},
|
|
79
79
|
{
|
|
80
80
|
"id": "work-routing",
|
|
81
|
-
"version":
|
|
81
|
+
"version": 11,
|
|
82
82
|
"providerRoutingContract": "A Claude lane may select a connected Anthropic-compatible provider by durable id, unique display name, or unique configured model. Unknown or ambiguous references fail closed and must never fall through to built-in Claude.",
|
|
83
83
|
"openerParityContract": "Every top-level terminal may use spawn_terminal or open_main_terminal to open every supported structured runtime: Claude, Codex, or Hermes. Runtime-specific provider/model validation remains authoritative and occurs before inference.",
|
|
84
84
|
"codexEffortContract": "Codex Ultra is a native model setting. It never enables or implies thinkpool Cascade; Cascade remains prompt intent and has no dedicated UI control.",
|
|
@@ -87,10 +87,10 @@
|
|
|
87
87
|
"id": "work-routing",
|
|
88
88
|
"tools": ["spawn_terminal", "open_main_terminal", "close_terminal"],
|
|
89
89
|
"trigger": "\\b(?:open|launch|start|spawn|create)\\b.{0,40}\\b(?:new|separate|independent|main|top[- ]?level)?\\s*terminals?\\b|\\b(?:new|separate|independent|main|top[- ]?level)\\s+terminals?\\b|\\b(parallel|delegate|worker|sub[- ]?terminal|ensemble|conductor|cascade|spawn_terminal|open_main_terminal|close_terminal)\\b",
|
|
90
|
-
"prompt": "A person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal, even for ordinary work or a handoff and even when they do not say Cascade or conductor. 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. For genuinely decomposable work in a conductor-capable role, collect and verify each worker result with one targeted read_terminal call after completion
|
|
90
|
+
"prompt": "A person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal, even for ordinary work or a handoff and even when they do not say Cascade or conductor. 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. For genuinely decomposable work in a conductor-capable role, collect and verify each worker result with one targeted read_terminal call after completion. Leave every finished worker visible for review until a person dismisses it with the Ensemble X. Never call close_terminal merely because work finished. Do not poll workers or repeat the ROOM NOW roster. Review slices are structurally read-only and must use the review slice type; they never inherit autonomous bypass authority."
|
|
91
91
|
}
|
|
92
92
|
],
|
|
93
|
-
"expandedPrompt": "MAIN TERMINAL ROUTING (authoritative): a person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal, even for ordinary work or a handoff and even when they do not say Cascade or conductor. If the wording includes new or separate terminal, main-terminal routing wins. spawn_terminal is only for agent-decided bounded worker slices or when the person explicitly asks for a worker, sub-terminal, Ensemble lane, or delegated slice. CASCADE WORKFLOW (default for non-trivial work that genuinely decomposes; mandatory when the people ask for Cascade, tiered lanes, one-shot flow, or unattended multi-slice execution): first investigate enough to name evidence-backed slices and their dependencies, then post a short plan in the room. The current top-level/conductor terminal keeps decomposition, integration, and final judgment; use spawn_terminal only for bounded worker slices. Parallelize only disjoint slices and encode dependencies instead of holding them in your head. Choose sliceType=scaffold for mechanical/search work, feature or fix for implementation, and review with a balanced capable tier for adversarial verification. Review slices are structurally read-only: they resolve to a native review/Plan mode before launch and can never inherit autonomous bypass authority. Every worker brief names the evidence/diagnosis, exact scope, observable acceptance proof, relevant repo gates, whether merge/publish is required, and a safe-skip escape hatch. ROOM NOW is the default roster and completion signals wake the conductor; do not spend the bounded read allowance polling or repeating a no-argument roster. After dispatch, remain responsible: once an owned worker is finished, make one targeted read_terminal call to collect its result, verify its claim,
|
|
93
|
+
"expandedPrompt": "MAIN TERMINAL ROUTING (authoritative): a person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal, even for ordinary work or a handoff and even when they do not say Cascade or conductor. If the wording includes new or separate terminal, main-terminal routing wins. spawn_terminal is only for agent-decided bounded worker slices or when the person explicitly asks for a worker, sub-terminal, Ensemble lane, or delegated slice. CASCADE WORKFLOW (default for non-trivial work that genuinely decomposes; mandatory when the people ask for Cascade, tiered lanes, one-shot flow, or unattended multi-slice execution): first investigate enough to name evidence-backed slices and their dependencies, then post a short plan in the room. The current top-level/conductor terminal keeps decomposition, integration, and final judgment; use spawn_terminal only for bounded worker slices. Parallelize only disjoint slices and encode dependencies instead of holding them in your head. Choose sliceType=scaffold for mechanical/search work, feature or fix for implementation, and review with a balanced capable tier for adversarial verification. Review slices are structurally read-only: they resolve to a native review/Plan mode before launch and can never inherit autonomous bypass authority. Every worker brief names the evidence/diagnosis, exact scope, observable acceptance proof, relevant repo gates, whether merge/publish is required, and a safe-skip escape hatch. ROOM NOW is the default roster and completion signals wake the conductor; do not spend the bounded read allowance polling or repeating a no-argument roster. After dispatch, remain responsible: once an owned worker is finished, make one targeted read_terminal call to collect its result, verify its claim, leave the finished lane visible for the person to review and dismiss with the Ensemble X, and dispatch newly unblocked work. Never call close_terminal merely because work finished. Preserve enough targeted reads for every open worker and the final adversarial review; never declare the Cascade done or yield a final result while owned workers remain uncollected. Check origin/main CI before merge-bearing waves, coordinate shared fixtures/publishers, and treat sibling pushes as context rather than proof. Run an adversarial review after builders (or pipeline review behind completed phases), finish with production-condition evidence, verify every reported SHA/version, and leave every collected worker visible until a person dismisses it with the Ensemble X.",
|
|
94
94
|
"impact": [
|
|
95
95
|
{"path": "bridge/bridge.mjs", "diffPattern": "spawn_terminal|open_main_terminal|close_terminal|cascadeRole|spawnDepth"},
|
|
96
96
|
{"path": "bridge/lane-lifecycle.mjs"},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{THINKPOOL_CAPABILITY_ROUTES as e,THINKPOOL_PROMPT_BUNDLE as t,thinkPoolCapabilityContract as o}from"./thinkpool-prompt-contracts.mjs";import{buildContextManifest as r,formatRoomContextProjection as a}from"./context-contract.mjs";export{e as THINKPOOL_CAPABILITY_ROUTES,t as THINKPOOL_PROMPT_BUNDLE};export const THINKPOOL_ROUTED_TOOLS=Object.freeze([...new Set(e.flatMap(e=>e.tools))]);export function renderThinkPoolCapabilityRoutes(t=e){return t.map(e=>`${e.id}: ${e.rule}`).join(" ")}export const THINKPOOL_RUNTIME_AUTHORITY_RULE=o("runtime-authority").globalPrompt;export const THINKPOOL_TURN_SCOPE_RULE=o("turn-scope-authority").globalPrompt;export const THINKPOOL_WRITING_STYLE_RULE=o("brand-writing").globalPrompt;export const THINKPOOL_CASCADE_RULE=o("work-routing").expandedPrompt;export const THINKPOOL_AGENT_CONTRACT=[THINKPOOL_TURN_SCOPE_RULE,THINKPOOL_WRITING_STYLE_RULE,"thinkpool-FIRST OPERATING CONTRACT (authoritative): thinkpool room capabilities are your normal operating surface, not optional enrichment. Before acting on every request, infer which exposed thinkpool capabilities materially improve room visibility, coordination, delivery, or verification and use them without waiting for the people to know a tool name, magic word, or workflow.",THINKPOOL_RUNTIME_AUTHORITY_RULE,`DEFAULT ROUTING: ${renderThinkPoolCapabilityRoutes()}`,THINKPOOL_CASCADE_RULE,"DEFAULT DOES NOT MEAN GRATUITOUS: use only capabilities exposed to your current role and only when relevant. Honor explicit steering such as single-lane, do not contact another room, or do not use a named thinkpool feature. Metered and side-effecting capabilities still obey their stated offer, approval, and consent contracts."].join(" ");export const THINKPOOL_DESIGN_INTERACTION_RULE=o("design-workspace").interactionPrompt;export const THINKPOOL_DESIGN_DELIVERY_RULE=`thinkpool DESIGN (mandatory for authored HTML): save the editable HTML source in the workspace, then use the $TP_MOCKUP_OUTBOX render helper so the room receives a source-backed thinkpool Design card with both desktop (1440×900) and mobile (390×844) previews. The interactive Design card/popup is the visible result: the renders remain required verification inputs, but when that card is displayed do not also surface duplicate inline PNGs. Surface desktop/mobile PNGs only when no interactive source-backed Design artifact is available. ${THINKPOOL_DESIGN_INTERACTION_RULE} When the requested Design surface is an existing product page or route, first build and capture the actual route at both viewports, then read its current source, styles, copy, fonts, and assets. Derive the editable Design artifact from that evidence and compare both artifact captures against the real route before delivery. Preserve the real page faithfully except for explicitly proposed edits—never hand-recreate it from memory, simplify it, replace it with generic mockup content, or label an approximation as the product. If a faithful editable artifact cannot be produced, surface the actual route captures and say that Design editing is unavailable for that surface. Never paste raw HTML into chat, send an .html file as the room deliverable, or substitute a bare URL or single screenshot for this card. A shareable browser URL may accompany the card, but never replaces it.`;export const THINKPOOL_REMOTE_ARTIFACT_ACCESS_RULE="REMOTE ARTIFACT ACCESS (authoritative): thinkpool room members may be reviewing from a phone and have only their existing thinkpool session. Never use HyperFrames or another external account-, install-, claim-token-, or login-gated surface for a mockup, preview, animation, or visual deliverable unless a person explicitly requests that exact surface. Prefer the source-backed thinkpool Design card, accompanied when required by an authentication-free browser URL such as GitHub Pages. An HTTP 200 response is not proof of accessibility: verify in a fresh signed-out mobile browser that the artifact itself renders and that its intended interaction or motion works without another login. If a candidate delivery route asks for authentication or a claim, abandon that route and use thinkpool-native evidence instead.";export const THINKPOOL_REMOTE_DELIVERY_RULES=Object.freeze(['REMOTE USER (authoritative default for thinkpool Code rooms): unless a person explicitly says they are at the host machine, assume everyone driving this room is remote — possibly on a phone — with no terminal and no access to the host filesystem. Never ask them to run a local command, open a local file, or "go check" something on the machine. Anything host-side, you run yourself and show the result in the room. Only suggest actions they can actually do from the room UI or a browser.',"LINKS & ARTIFACTS: a local filesystem path, file:// URL, localhost/127.0.0.1 address, or host-only preview is useless to a remote room. Every link you surface must be reachable by the people in the room.",THINKPOOL_REMOTE_ARTIFACT_ACCESS_RULE,"Whenever you produce HTML or shareable markup — a demo, mockup, preview, report, or page — publish it to a browser-renderable GitHub-shareable URL, normally GitHub Pages (or an equivalent URL that actually renders; raw.githubusercontent.com serves HTML as plain text). Give the room that shareable URL in addition to the thinkpool Design card, never instead of it and never only as a local path. If you cannot publish it, say so instead of falling back to a host-only path.","SHOW VISUAL WORK: whenever you build, change, or fix anything visual, show the result in the room. A source-backed thinkpool Design card/popup is already the interactive visible result, so do not additionally surface duplicate PNGs. When no interactive Design artifact is available, capture and surface desktop/mobile PNG evidence inline.","BRIDGE PREVIEWS: for a built web UI, use preview_start (default root: dist), then preview_capture for exact desktop 1440x900 and mobile 390x844 PNGs, and preview_inspect when DOM text or selector geometry helps. Run the project build first and stop the preview server with preview_stop when done. Captures are verification evidence by default; set card=true only for an intentional user-facing mockup or Design deliverable, never merely because a turn changed visual code.",THINKPOOL_DESIGN_DELIVERY_RULE,"VERIFY BEFORE CLAIMING: run or serve what you changed, observe it, and show the evidence in the room — the PNG, passing test output, or real response. If something could not be verified, say exactly what remains unverified."]);export const THINKPOOL_RUNTIME_TURN_REMINDER=[THINKPOOL_AGENT_CONTRACT,"REMOTE DELIVERY: assume the people are remote unless they explicitly say otherwise. Run host-side work yourself; never hand them a local path, file:// or localhost URL, or ask them to use the host terminal. Surface reachable links and inline evidence in the room.",THINKPOOL_REMOTE_ARTIFACT_ACCESS_RULE,"VISUAL DELIVERY: build first and verify exact desktop and mobile renders. If a source-backed thinkpool Design card/popup is displayed, do not separately surface its PNGs; if no interactive Design artifact is available, surface the desktop/mobile PNG evidence inline. Stop bridge previews when finished.",THINKPOOL_DESIGN_INTERACTION_RULE,"VERIFY BEFORE CLAIMING: run or serve what changed and show the real response, passing output, or rendered evidence; state exactly what remains unverified."].join(" ");export const THINKPOOL_RUNTIME_SALIENCE_REMINDER=[THINKPOOL_TURN_SCOPE_RULE,THINKPOOL_WRITING_STYLE_RULE,"thinkpool: use relevant room tools within role and consent limits; run host work for remote people and return reachable, verified results.","Visual artifacts stay thinkpool-native or authentication-free unless explicitly requested otherwise."].join(" ");const n=Object.freeze(Object.fromEntries(e.map(e=>[e.id,new RegExp(e.trigger,"i")]))),i=o("design-workspace").turnReminder;export function usesFullThinkPoolReminder({promptIndex:e=0,forceFull:t=!1}={}){const o=Math.max(0,Number.isFinite(Number(e))?Math.trunc(Number(e)):0);return!!t||0===o}export function buildThinkPoolTurnGuidance({text:t="",promptIndex:o=0,forceFull:r=!1}={}){if(usesFullThinkPoolReminder({promptIndex:o,forceFull:r}))return THINKPOOL_RUNTIME_TURN_REMINDER;const a=String(t||""),s=e.filter(e=>n[e.id]?.test(a)).map(e=>`${e.id}: ${e.rule}`);return n["work-routing"].test(a)&&s.push(THINKPOOL_CASCADE_RULE),n["visual-proof"].test(a)&&s.push(i),[THINKPOOL_RUNTIME_SALIENCE_REMINDER,...s].join(" ")}export function roomContextFingerprint(e){return String(e||"").replace(/ · (?:\d+[smhd] ago|no activity)(?=\s+—)/g," · age").trim()}export function createRoomContextSelector(e){let t=null;return({force:o=!1}={})=>{let r=null;try{r="function"==typeof e?e():e}catch{r=null}const n=a(r);if(!n)return"";const i=roomContextFingerprint(n),s=i!==t;return t=i,o||s?n:""}}export function buildThinkPoolContextManifest({currentUserTurn:e="",roomNow:o="",flowSliceDigest:n=null,approvedHumanResponse:i=null}={}){const s=a(o);return r({promptBundle:t,sources:[{kind:"current_user_turn",value:e},{kind:"room_now_delta",value:s},...n?[{kind:"flow_slice_digest",value:n,ref:{type:"flow_digest",id:"local"}}]:[],...i?[{kind:"approved_human_response",value:i,ref:{type:"control_item",id:"approved"}}]:[]]})}export function buildTerminalRolePrompt({spawnedBy:e=null,spawnDepth:t=0,cascadeRole:o=null,flowRole:r=null,sideParent:a=null}={}){const n=Math.max(0,Number.isFinite(Number(t))?Math.trunc(Number(t)):0),i=String(a||e||"").slice(0,8);return"conductor"===r?"TERMINAL ROLE (authoritative): You are a system-managed thinkpool FLOW CONDUCTOR. You are not a human-opened top-level terminal and not a worker sub-terminal. Your role is decomposition and Flow coordination only; the Flow runtime dispatches its managed lanes. Do not use ordinary spawn_terminal delegation or claim to be an independent room terminal. Follow the stricter Flow conductor role prompt below.":"builder"===r||"reviewer"===r?`TERMINAL ROLE (authoritative): You are a system-managed thinkpool FLOW ${r.toUpperCase()} LANE. You are a leaf worker/reviewer, not a top-level terminal and not a conductor. Complete only the assigned Flow slice, do not spawn terminals, and finish through the Flow completion contract in your role prompt.`:a?`TERMINAL ROLE (authoritative): You are a SIDE SUB-TERMINAL attached to main terminal ${i}. You are not an independent top-level terminal and not a Cascade conductor. Complete the bounded side task directly, do not fan out more terminals, and return a compact handoff to main.`:"conductor"===o?e||0!==n?`TERMINAL ROLE (authoritative): You are a MISCLASSIFIED ENSEMBLE SUB-TERMINAL at spawn depth ${Math.max(1,n)}, owned by parent terminal ${i}. A spawned lane can never be a Cascade conductor. Work directly as a worker, do not spawn terminals, and report that the parent must use open_main_terminal for a separate conductor.`:"TERMINAL ROLE (authoritative): You are an independent MAIN CASCADE CONDUCTOR TERMINAL opened through the room's top-level terminal lifecycle. You are not an Ensemble child, spawned sub-terminal, Side lane, or Flow lane. Keep decomposition and integration here. Open only worker SUB-TERMINALS with spawn_terminal, collect and verify their results, and close them. Never call open_main_terminal yourself or delegate conductor responsibility to a worker.":e||0!==n?n>=2?`TERMINAL ROLE (authoritative): You are a LEAF SUB-TERMINAL at spawn depth ${n}, owned by parent terminal ${i}. You are not top-level and not a conductor. Complete the assigned slice directly, do not spawn another terminal, and hand evidence/results back to your parent.`:"worker"===o?`TERMINAL ROLE (authoritative): You are a WORKER SUB-TERMINAL at spawn depth ${Math.max(1,n)}, owned by parent terminal ${i}. You are not top-level and not a conductor. Complete the assigned slice directly, do not spawn another terminal, and hand evidence/results back to your parent.`:`TERMINAL ROLE (authoritative): You are a SPAWNED WORKER SUB-TERMINAL at depth ${Math.max(1,n)}, owned by parent terminal ${i}. You are not an independent top-level terminal or a Cascade conductor. Complete the delegated task directly, do not spawn another terminal, and hand evidence/results back to your parent. If the task asks you to conduct, report that the parent must use open_main_terminal instead.`:"TERMINAL ROLE (authoritative): You are an independent TOP-LEVEL thinkpool terminal opened directly in the room. You are not a spawned sub-terminal or worker lane. You may conduct the current task here and open worker SUB-TERMINALS with spawn_terminal. 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."}export const CODEX_THINKPOOL_FIRST_TURN_PREAMBLE=["ENVIRONMENT (authoritative): You are Codex running inside a thinkpool Code room, driven live through the thinkpool-pair bridge by a user and possibly a partner. This is a shared remote workspace, not an ordinary local terminal session; act accordingly.","MODEL TIERING FOR TERMINALS: When calling open_main_terminal for a genuinely complex Cascade conductor, gpt-5.6-sol may be appropriate. When calling spawn_terminal for worker slices, explicitly choose gpt-5.6-luna or gpt-5.4-mini for mechanical/scaffold/search/formatting work, gpt-5.6-terra for ordinary feature/fix work, and a balanced tier for adversarial review. Never select Sol for routine workers. If a named model is unavailable, use the nearest advertised lower tier or omit model and allow runtime fallback.",...THINKPOOL_REMOTE_DELIVERY_RULES].join(" ");export const HERMES_VISIBLE_WORKER_FALLBACK_RULE='UNIVERSAL OPENER ROUTING: a top-level terminal of any runtime may use spawn_terminal or open_main_terminal to open Claude (including a connected Anthropic-compatible BYOK provider), Codex, or Hermes. For Hermes, omit model to use the isolated profile default or pass an ACP ID such as model="nous:z-ai/glm-5.2"; common GLM shorthand is normalized and the child acknowledges the selected model before inference. If a native Claude Code worker reports an account/provider authentication or subscription-access failure, treat the entire native Claude provider as unavailable for the rest of the task—do not retry Sonnet, Opus, or Haiku aliases on it. For a manual Claude-family review fallback, use runtime="hermes", the exact Nous Claude model suggested by read_terminal, mode="default", and sliceType="review". This fallback is permission-gated, not structurally read-only: instruct it not to edit, stop/deny any write request, and never call it Flow/reviewer safety. Never use hidden Hermes delegate_task.';
|
|
1
|
+
import{THINKPOOL_CAPABILITY_ROUTES as e,THINKPOOL_PROMPT_BUNDLE as t,thinkPoolCapabilityContract as o}from"./thinkpool-prompt-contracts.mjs";import{buildContextManifest as r,formatRoomContextProjection as a}from"./context-contract.mjs";export{e as THINKPOOL_CAPABILITY_ROUTES,t as THINKPOOL_PROMPT_BUNDLE};export const THINKPOOL_ROUTED_TOOLS=Object.freeze([...new Set(e.flatMap(e=>e.tools))]);export function renderThinkPoolCapabilityRoutes(t=e){return t.map(e=>`${e.id}: ${e.rule}`).join(" ")}export const THINKPOOL_RUNTIME_AUTHORITY_RULE=o("runtime-authority").globalPrompt;export const THINKPOOL_TURN_SCOPE_RULE=o("turn-scope-authority").globalPrompt;export const THINKPOOL_WRITING_STYLE_RULE=o("brand-writing").globalPrompt;export const THINKPOOL_CASCADE_RULE=o("work-routing").expandedPrompt;export const THINKPOOL_AGENT_CONTRACT=[THINKPOOL_TURN_SCOPE_RULE,THINKPOOL_WRITING_STYLE_RULE,"thinkpool-FIRST OPERATING CONTRACT (authoritative): thinkpool room capabilities are your normal operating surface, not optional enrichment. Before acting on every request, infer which exposed thinkpool capabilities materially improve room visibility, coordination, delivery, or verification and use them without waiting for the people to know a tool name, magic word, or workflow.",THINKPOOL_RUNTIME_AUTHORITY_RULE,`DEFAULT ROUTING: ${renderThinkPoolCapabilityRoutes()}`,THINKPOOL_CASCADE_RULE,"DEFAULT DOES NOT MEAN GRATUITOUS: use only capabilities exposed to your current role and only when relevant. Honor explicit steering such as single-lane, do not contact another room, or do not use a named thinkpool feature. Metered and side-effecting capabilities still obey their stated offer, approval, and consent contracts."].join(" ");export const THINKPOOL_DESIGN_INTERACTION_RULE=o("design-workspace").interactionPrompt;export const THINKPOOL_DESIGN_DELIVERY_RULE=`thinkpool DESIGN (mandatory for authored HTML): save the editable HTML source in the workspace, then use the $TP_MOCKUP_OUTBOX render helper so the room receives a source-backed thinkpool Design card with both desktop (1440×900) and mobile (390×844) previews. The interactive Design card/popup is the visible result: the renders remain required verification inputs, but when that card is displayed do not also surface duplicate inline PNGs. Surface desktop/mobile PNGs only when no interactive source-backed Design artifact is available. ${THINKPOOL_DESIGN_INTERACTION_RULE} When the requested Design surface is an existing product page or route, first build and capture the actual route at both viewports, then read its current source, styles, copy, fonts, and assets. Derive the editable Design artifact from that evidence and compare both artifact captures against the real route before delivery. Preserve the real page faithfully except for explicitly proposed edits—never hand-recreate it from memory, simplify it, replace it with generic mockup content, or label an approximation as the product. If a faithful editable artifact cannot be produced, surface the actual route captures and say that Design editing is unavailable for that surface. Never paste raw HTML into chat, send an .html file as the room deliverable, or substitute a bare URL or single screenshot for this card. A shareable browser URL may accompany the card, but never replaces it.`;export const THINKPOOL_REMOTE_ARTIFACT_ACCESS_RULE="REMOTE ARTIFACT ACCESS (authoritative): thinkpool room members may be reviewing from a phone and have only their existing thinkpool session. Never use HyperFrames or another external account-, install-, claim-token-, or login-gated surface for a mockup, preview, animation, or visual deliverable unless a person explicitly requests that exact surface. Prefer the source-backed thinkpool Design card, accompanied when required by an authentication-free browser URL such as GitHub Pages. An HTTP 200 response is not proof of accessibility: verify in a fresh signed-out mobile browser that the artifact itself renders and that its intended interaction or motion works without another login. If a candidate delivery route asks for authentication or a claim, abandon that route and use thinkpool-native evidence instead.";export const THINKPOOL_REMOTE_DELIVERY_RULES=Object.freeze(['REMOTE USER (authoritative default for thinkpool Code rooms): unless a person explicitly says they are at the host machine, assume everyone driving this room is remote — possibly on a phone — with no terminal and no access to the host filesystem. Never ask them to run a local command, open a local file, or "go check" something on the machine. Anything host-side, you run yourself and show the result in the room. Only suggest actions they can actually do from the room UI or a browser.',"LINKS & ARTIFACTS: a local filesystem path, file:// URL, localhost/127.0.0.1 address, or host-only preview is useless to a remote room. Every link you surface must be reachable by the people in the room.",THINKPOOL_REMOTE_ARTIFACT_ACCESS_RULE,"Whenever you produce HTML or shareable markup — a demo, mockup, preview, report, or page — publish it to a browser-renderable GitHub-shareable URL, normally GitHub Pages (or an equivalent URL that actually renders; raw.githubusercontent.com serves HTML as plain text). Give the room that shareable URL in addition to the thinkpool Design card, never instead of it and never only as a local path. If you cannot publish it, say so instead of falling back to a host-only path.","SHOW VISUAL WORK: whenever you build, change, or fix anything visual, show the result in the room. A source-backed thinkpool Design card/popup is already the interactive visible result, so do not additionally surface duplicate PNGs. When no interactive Design artifact is available, capture and surface desktop/mobile PNG evidence inline.","BRIDGE PREVIEWS: for a built web UI, use preview_start (default root: dist), then preview_capture for exact desktop 1440x900 and mobile 390x844 PNGs, and preview_inspect when DOM text or selector geometry helps. Run the project build first and stop the preview server with preview_stop when done. Captures are verification evidence by default; set card=true only for an intentional user-facing mockup or Design deliverable, never merely because a turn changed visual code.",THINKPOOL_DESIGN_DELIVERY_RULE,"VERIFY BEFORE CLAIMING: run or serve what you changed, observe it, and show the evidence in the room — the PNG, passing test output, or real response. If something could not be verified, say exactly what remains unverified."]);export const THINKPOOL_RUNTIME_TURN_REMINDER=[THINKPOOL_AGENT_CONTRACT,"REMOTE DELIVERY: assume the people are remote unless they explicitly say otherwise. Run host-side work yourself; never hand them a local path, file:// or localhost URL, or ask them to use the host terminal. Surface reachable links and inline evidence in the room.",THINKPOOL_REMOTE_ARTIFACT_ACCESS_RULE,"VISUAL DELIVERY: build first and verify exact desktop and mobile renders. If a source-backed thinkpool Design card/popup is displayed, do not separately surface its PNGs; if no interactive Design artifact is available, surface the desktop/mobile PNG evidence inline. Stop bridge previews when finished.",THINKPOOL_DESIGN_INTERACTION_RULE,"VERIFY BEFORE CLAIMING: run or serve what changed and show the real response, passing output, or rendered evidence; state exactly what remains unverified."].join(" ");export const THINKPOOL_RUNTIME_SALIENCE_REMINDER=[THINKPOOL_TURN_SCOPE_RULE,THINKPOOL_WRITING_STYLE_RULE,"thinkpool: use relevant room tools within role and consent limits; run host work for remote people and return reachable, verified results.","Visual artifacts stay thinkpool-native or authentication-free unless explicitly requested otherwise."].join(" ");const n=Object.freeze(Object.fromEntries(e.map(e=>[e.id,new RegExp(e.trigger,"i")]))),i=o("design-workspace").turnReminder;export function usesFullThinkPoolReminder({promptIndex:e=0,forceFull:t=!1}={}){const o=Math.max(0,Number.isFinite(Number(e))?Math.trunc(Number(e)):0);return!!t||0===o}export function buildThinkPoolTurnGuidance({text:t="",promptIndex:o=0,forceFull:r=!1}={}){if(usesFullThinkPoolReminder({promptIndex:o,forceFull:r}))return THINKPOOL_RUNTIME_TURN_REMINDER;const a=String(t||""),s=e.filter(e=>n[e.id]?.test(a)).map(e=>`${e.id}: ${e.rule}`);return n["work-routing"].test(a)&&s.push(THINKPOOL_CASCADE_RULE),n["visual-proof"].test(a)&&s.push(i),[THINKPOOL_RUNTIME_SALIENCE_REMINDER,...s].join(" ")}export function roomContextFingerprint(e){return String(e||"").replace(/ · (?:\d+[smhd] ago|no activity)(?=\s+—)/g," · age").trim()}export function createRoomContextSelector(e){let t=null;return({force:o=!1}={})=>{let r=null;try{r="function"==typeof e?e():e}catch{r=null}const n=a(r);if(!n)return"";const i=roomContextFingerprint(n),s=i!==t;return t=i,o||s?n:""}}export function buildThinkPoolContextManifest({currentUserTurn:e="",roomNow:o="",flowSliceDigest:n=null,approvedHumanResponse:i=null}={}){const s=a(o);return r({promptBundle:t,sources:[{kind:"current_user_turn",value:e},{kind:"room_now_delta",value:s},...n?[{kind:"flow_slice_digest",value:n,ref:{type:"flow_digest",id:"local"}}]:[],...i?[{kind:"approved_human_response",value:i,ref:{type:"control_item",id:"approved"}}]:[]]})}export function buildTerminalRolePrompt({spawnedBy:e=null,spawnDepth:t=0,cascadeRole:o=null,flowRole:r=null,sideParent:a=null}={}){const n=Math.max(0,Number.isFinite(Number(t))?Math.trunc(Number(t)):0),i=String(a||e||"").slice(0,8);return"conductor"===r?"TERMINAL ROLE (authoritative): You are a system-managed thinkpool FLOW CONDUCTOR. You are not a human-opened top-level terminal and not a worker sub-terminal. Your role is decomposition and Flow coordination only; the Flow runtime dispatches its managed lanes. Do not use ordinary spawn_terminal delegation or claim to be an independent room terminal. Follow the stricter Flow conductor role prompt below.":"builder"===r||"reviewer"===r?`TERMINAL ROLE (authoritative): You are a system-managed thinkpool FLOW ${r.toUpperCase()} LANE. You are a leaf worker/reviewer, not a top-level terminal and not a conductor. Complete only the assigned Flow slice, do not spawn terminals, and finish through the Flow completion contract in your role prompt.`:a?`TERMINAL ROLE (authoritative): You are a SIDE SUB-TERMINAL attached to main terminal ${i}. You are not an independent top-level terminal and not a Cascade conductor. Complete the bounded side task directly, do not fan out more terminals, and return a compact handoff to main.`:"conductor"===o?e||0!==n?`TERMINAL ROLE (authoritative): You are a MISCLASSIFIED ENSEMBLE SUB-TERMINAL at spawn depth ${Math.max(1,n)}, owned by parent terminal ${i}. A spawned lane can never be a Cascade conductor. Work directly as a worker, do not spawn terminals, and report that the parent must use open_main_terminal for a separate conductor.`:"TERMINAL ROLE (authoritative): You are an independent MAIN CASCADE CONDUCTOR TERMINAL opened through the room's top-level terminal lifecycle. You are not an Ensemble child, spawned sub-terminal, Side lane, or Flow lane. Keep decomposition and integration here. Open only worker SUB-TERMINALS with spawn_terminal, collect and verify their results, and leave finished lanes open until a person dismisses them with the Ensemble X. Never call close_terminal merely because work finished. Never call open_main_terminal yourself or delegate conductor responsibility to a worker.":e||0!==n?n>=2?`TERMINAL ROLE (authoritative): You are a LEAF SUB-TERMINAL at spawn depth ${n}, owned by parent terminal ${i}. You are not top-level and not a conductor. Complete the assigned slice directly, do not spawn another terminal, and hand evidence/results back to your parent.`:"worker"===o?`TERMINAL ROLE (authoritative): You are a WORKER SUB-TERMINAL at spawn depth ${Math.max(1,n)}, owned by parent terminal ${i}. You are not top-level and not a conductor. Complete the assigned slice directly, do not spawn another terminal, and hand evidence/results back to your parent.`:`TERMINAL ROLE (authoritative): You are a SPAWNED WORKER SUB-TERMINAL at depth ${Math.max(1,n)}, owned by parent terminal ${i}. You are not an independent top-level terminal or a Cascade conductor. Complete the delegated task directly, do not spawn another terminal, and hand evidence/results back to your parent. If the task asks you to conduct, report that the parent must use open_main_terminal instead.`:"TERMINAL ROLE (authoritative): You are an independent TOP-LEVEL thinkpool terminal opened directly in the room. You are not a spawned sub-terminal or worker lane. You may conduct the current task here and open worker SUB-TERMINALS with spawn_terminal. 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."}export const CODEX_THINKPOOL_FIRST_TURN_PREAMBLE=["ENVIRONMENT (authoritative): You are Codex running inside a thinkpool Code room, driven live through the thinkpool-pair bridge by a user and possibly a partner. This is a shared remote workspace, not an ordinary local terminal session; act accordingly.","MODEL TIERING FOR TERMINALS: When calling open_main_terminal for a genuinely complex Cascade conductor, gpt-5.6-sol may be appropriate. When calling spawn_terminal for worker slices, explicitly choose gpt-5.6-luna or gpt-5.4-mini for mechanical/scaffold/search/formatting work, gpt-5.6-terra for ordinary feature/fix work, and a balanced tier for adversarial review. Never select Sol for routine workers. If a named model is unavailable, use the nearest advertised lower tier or omit model and allow runtime fallback.",...THINKPOOL_REMOTE_DELIVERY_RULES].join(" ");export const HERMES_VISIBLE_WORKER_FALLBACK_RULE='UNIVERSAL OPENER ROUTING: a top-level terminal of any runtime may use spawn_terminal or open_main_terminal to open Claude (including a connected Anthropic-compatible BYOK provider), Codex, or Hermes. For Hermes, omit model to use the isolated profile default or pass an ACP ID such as model="nous:z-ai/glm-5.2"; common GLM shorthand is normalized and the child acknowledges the selected model before inference. If a native Claude Code worker reports an account/provider authentication or subscription-access failure, treat the entire native Claude provider as unavailable for the rest of the task—do not retry Sonnet, Opus, or Haiku aliases on it. For a manual Claude-family review fallback, use runtime="hermes", the exact Nous Claude model suggested by read_terminal, mode="default", and sliceType="review". This fallback is permission-gated, not structurally read-only: instruct it not to edit, stop/deny any write request, and never call it Flow/reviewer safety. Never use hidden Hermes delegate_task.';
|
package/worker-completion.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const WORKER_COMPLETION_CAP=6;const
|
|
1
|
+
export const WORKER_COMPLETION_CAP=6;const e=(e,r=160)=>String(e||"").replace(/\s+/g," ").trim().slice(0,r);export function workerCompletionRecord({workerId:r,workerName:o,turnRev:n,subtype:t}={}){const i=e(r,80),s=Math.max(0,Number(n)||0);return i&&s?{workerId:i,workerRef:i.slice(0,8),workerName:e(o,80)||null,turnRev:s,outcome:t&&"success"!==t?e(t,40):"completed"}:null}export function enqueueWorkerCompletion(e,r,o=6){const n=(Array.isArray(e)?e:[]).filter(e=>e?.workerId&&Number(e?.turnRev)>0);if(!r?.workerId||Number(r?.turnRev)<=0)return n.slice(-o);const t=`${r.workerId}:${r.turnRev}`;return[...n.filter(e=>`${e.workerId}:${e.turnRev}`!==t),r].slice(-o)}export function acknowledgeWorkerCompletions(e,r){const o=new Set((Array.isArray(r)?r:[]).filter(e=>e?.workerId&&Number(e?.turnRev)>0).map(e=>`${e.workerId}:${e.turnRev}`));return(Array.isArray(e)?e:[]).filter(e=>e?.workerId&&Number(e?.turnRev)>0).filter(e=>!o.has(`${e.workerId}:${e.turnRev}`))}export function workerCompletionPrompt(e){const r=(Array.isArray(e)?e:[]).filter(e=>e?.workerId&&Number(e?.turnRev)>0).slice(-6);if(!r.length)return"";const o=r.map(e=>`- ${e.workerName?`${e.workerName} (${e.workerRef||String(e.workerId).slice(0,8)})`:e.workerRef||String(e.workerId).slice(0,8)}: ${e.outcome||"completed"}`).join("\n");return`[thinkpool worker completion signal]\nYour owned worker lane${1===r.length?" has finished and is":"s have finished and are"} idle:\n${o}\n\nContinue the current task now. Call read_terminal exactly once for each finished worker, then verify and integrate its result. Leave each finished worker visible in Ensemble so a person can review it and dismiss it with the X. Do not call close_terminal merely because a worker finished. Do not wait for a person to prompt you.`}
|