thinkpool-pair 0.7.428 → 0.7.430
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/agent-notify.mjs +1 -1
- package/bridge.mjs +1 -1
- package/claude-session.mjs +1 -1
- package/code-automations.mjs +1 -0
- package/hermes-policy.mjs +1 -1
- package/package.json +2 -1
- package/publish-manifest.json +12 -11
- package/scheduled-runs.mjs +1 -1
- package/thinkpool-capabilities.json +28 -1
package/claude-session.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID as e}from"node:crypto";import{createRequire as t}from"node:module";import{readFileSync as o}from"node:fs";import{dirname as n,join as s}from"node:path";import{query as r}from"@anthropic-ai/claude-agent-sdk";import{sanitizeSession as i}from"./transcript-sanitize.mjs";import{reviewGatePreToolDecision as a}from"./flow-review-gate.mjs";import{crossPostNeedsCard as l}from"./cross-terminal.mjs";import{correctContext as c}from"./context-windows.mjs";import{normalizeClaudeCommandCatalog as d}from"./claude-command-catalog.mjs";import{evidenceForToolResult as u}from"./evidence-citations.mjs";import{THINKPOOL_CASCADE_RULE as p,THINKPOOL_REMOTE_DELIVERY_RULES as m,THINKPOOL_RUNTIME_AUTHORITY_RULE as h,THINKPOOL_RUNTIME_TURN_REMINDER as f,buildThinkPoolTurnGuidance as y,createRoomContextSelector as k,normalizeThinkPoolTurnCause as w,usesFullThinkPoolReminder as g}from"./thinkpool-room-prompt.mjs";import{stallDecision as b,stallEvent as v,isCompactTurn as _}from"./turn-stall.mjs";import{createSameTargetResilienceController as T,formatResilienceTrace as S}from"./provider-resilience.mjs";import{catastrophicPreToolHookDecision as E}from"./catastrophic-command-guard.mjs";const N=t(import.meta.url);export async function claudeOneShot({prompt:e,model:t="claude-haiku-4-5",cwd:o,env:n,timeoutMs:s=8e3}={}){const i=new AbortController,a=setTimeout(()=>{try{i.abort()}catch{}},s);try{const s=r({prompt:e,options:{model:t,...o?{cwd:o}:{},env:n,maxTurns:1,permissionMode:"bypassPermissions",settingSources:[],strictMcpConfig:!0,mcpServers:{},abortController:i}});let a="";for await(const e of s){if("assistant"===e.type)for(const t of e.message?.content||[])"text"===t.type&&(a+=t.text);if("result"===e.type)break}return a.trim()}finally{clearTimeout(a)}}const O=(()=>{try{let e=n(N.resolve("@anthropic-ai/claude-agent-sdk"));for(let t=0;t<8;t++){try{const t=JSON.parse(o(s(e,"package.json"),"utf8"));if("@anthropic-ai/claude-agent-sdk"===t.name)return t.version}catch{}const t=n(e);if(t===e)break;e=t}}catch{}return"unknown"})(),R=/\brm\s+\S|\brmdir\s+\S|\bgit\s+(push\s+(-f|--force)|reset\s+--hard|clean\s+-[a-z]*f)|\bdrop\s+(table|database)\b|\b(mkfs|dd)\b|\bsudo\b|>\s*\/dev\/|\bchmod\s+-R|\bchown\s+-R|\bkillall\b|\btruncate\b/i,A=new Set(["Read","Grep","Glob","NotebookRead","TodoRead","LS"]),D=new Set(["WebFetch","WebSearch"]),x=new Set(["Edit","Write","MultiEdit","NotebookEdit","TodoWrite"]);export function classifyRisk(e,t){if("Bash"===e){const e=t&&(t.command??t.cmd)||"";return R.test(e)?"high":"medium"}return A.has(e)?"low":D.has(e)?"network":(x.has(e),"medium")}const P=/(^|\/)\.claude\/SESSIONS\/|(^|\/)CLAUDE\.md$/;export function isSafeDocWrite(e,t){if(!x.has(e))return!1;const o=t&&(t.file_path||t.notebook_path)||"";return P.test(o)}export function autoAllow({toolName:e,input:t,mode:o="default",alwaysAllow:n=new Set}){const s=classifyRisk(e,t);return"low"===s||"bypassPermissions"===o||"acceptEdits"===o&&x.has(e)&&"high"!==s||isSafeDocWrite(e,t)||n.has(`${e}:${s}`)}export function askUserQuestionHookOutput(e){const t=e&&"object"==typeof e?e.decision:e,o="string"==typeof t&&t.startsWith("answer:")?t.slice(7):"",n=e&&"object"==typeof e?e.responder:null,s="string"==typeof n?.name&&n.name.trim()?n.name.trim():"string"==typeof n?.id&&n.id?`room member ${n.id}`:"The user";return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:o?`${s} answered in the thinkpool room — ${o}. Treat this as their selection and continue; do not call AskUserQuestion again for the same question.`:"The user dismissed the question in the thinkpool room without selecting. Ask in plain prose, or proceed with a sensible default."}}}export function askUserQuestionRegression(e,t){return Array.isArray(e)?e.includes("AskUserQuestion")?null:`[SDK-REGRESSION] agent SDK v${t||"unknown"} init tools[] is missing 'AskUserQuestion' — the multiple-choice question card is disabled. A caret SDK bump likely changed the canUseTool gate; pin a known-good SDK in bridge/package.json + republish.`:null}function I(){const e=[];let t=null,o=!1;return{stream:async function*(){for(;!o;)e.length?yield e.shift():await new Promise(e=>{t=e})}(),push:n=>!o&&(e.push({type:"user",message:{role:"user",content:n}}),t&&(t(),t=null),!0),end(){o=!0,t&&(t(),t=null)}}}const C=(e=[])=>e.map(e=>"text"===e.type?{type:"text",text:e.text}:"thinking"===e.type?{type:"thinking",text:e.thinking||"",reasoningKind:"thought"}:"tool_use"===e.type?{type:"tool_use",id:e.id,name:e.name,input:e.input}:{type:e.type}).filter(Boolean),M=new Set(["default","acceptEdits","plan","bypassPermissions"]),U=["You are Claude in a thinkpool Code room, driven live from a phone or browser — NOT a local terminal. Keep using the room's features.",f,"TERMINAL HIERARCHY: obey your authoritative TERMINAL ROLE. A person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal — NEVER spawn_terminal — even for ordinary work or a handoff. If the wording includes new or separate terminal, main-terminal routing wins. Use spawn_terminal only for agent-decided bounded worker slices or when the person explicitly asks for a worker, sub-terminal, Ensemble lane, or delegated slice. If open_main_terminal is unavailable, say so; never substitute an Ensemble child. Leaf, worker, Side, and managed Flow lanes work directly. Never use built-in invisible Task/Agent subagents or hijack a busy sibling.","WORKTREES: parallel lanes share one repo — before code edits run `git worktree list`; if linked worktrees exist, take your OWN worktree + branch, never the shared checkout or a branch another lane is on.","BUILD WORKFLOW (default, no magic word): right-size within your TERMINAL ROLE — a trivial ask or delegated slice you just do; a conductor-capable role with a genuinely decomposable build FIRST writes a short plan in chat, THEN fans worker slices into visible spawn_terminal lanes and verifies them. Worker/leaf/Side/managed Flow roles do not fan out. A person-requested new or separate terminal uses open_main_terminal. Never plan-mode/ExitPlanMode; plans live in chat and lanes in the existing list."].join(" ");export function startClaudeSession({cwd:t,model:o,effort:n="high",resume:s,env:f,mode:N="default",onEvent:R,requestPermission:A,mcpServers:D,crossPostGate:x,crossRoomPostGate:P,didSpawnTarget:L=null,terminalRolePrompt:W,rolePrompt:F,blockSubagents:j=!1,onSubmitPlan:$=null,onLaneDone:q=null,onReviewVerdict:G=null,reviewGate:B=null,lazy:H=!1,roomContext:K=null,suggest:Q=!0,prepareCwd:Y=null,admitStart:z=null,resilienceObserver:J=null,resilience:V=null}){const X=k(K);let Z=0,ee=!0;const te=(e,{promptIndex:t=0,forceFull:o=!1,turnCause:n=null}={})=>{const s=g({promptIndex:t,forceFull:o,turnCause:n}),r=X({force:s}),i=String(W||"").trim();return`<system-reminder>\n${s&&i?`${i}\n\n`:""}${s?U:y({text:e,promptIndex:t,forceFull:o,turnCause:n})}${r?`\n\n${r}`:""}\n</system-reminder>`},oe=new AbortController;let ne=I(),se=s||null,re=s||null,ie=null,ae=null,le=null,ce=null,de=!1,ue=!1,pe=null,me=!1,he=!1,fe=!1,ye=null,ke=M.has(N)?N:"default";const we=new Set,ge=new Map,be=new Set(["low","medium","high","xhigh","max"]);let ve=be.has(n)?n:"high",_e=0,Te=0,Se=o||null,Ee=null,Ne=null,Oe=Promise.resolve(),Re=!1,Ae=!1;const De=e=>new Promise(t=>setTimeout(t,e)),xe=Math.max(3e4,parseInt(process.env.TP_STALL_MS,10)||9e4);let Pe=!1,Ie=Date.now(),Ce=!1;const Me=/connection closed|connection reset|econnreset|etimedout|socket hang up|fetch failed|network error|socket destroyed/i;let Ue=0;const Le=(e,t={})=>{try{J?.({reason:e,restartCount:Ue,...t})}catch{}},We=!(!V?.policy?.enabled||!V?.providerId||"anthropic"===V.providerId);let Fe=null,je=null,$e=!1,qe=0,Ge=!1,Be=null;const He=Math.max(3*xe,parseInt(process.env.TP_FORCE_STOP_MS,10)||3e5);let Ke=!1,Qe=!1;const Ye=Math.max(He,parseInt(process.env.TP_COMPACT_FORCE_STOP_MS,10)||12e5);let ze=!1,Je=0;const Ve=A;A=async e=>{Je++;try{return await(Ve?.(e))}finally{Je=Math.max(0,Je-1),Ie=Date.now()}};let Xe=!1,Ze=null,et=null,tt=!1,ot="",nt=null;const st=Math.max(1200,parseInt(process.env.TP_SUGGEST_FALLBACK_MS,10)||2500),rt=e=>{try{R?.(e)}catch{}},it=e=>{Ie=Date.now(),e&&"stalled"!==e.kind&&(Ce=!1),!e||"compaction"!==e.kind&&"result"!==e.kind&&"error"!==e.kind||(ze=!1),rt(e)},at=e=>{try{V?.onRecord?.(e)}catch{}"retrying"!==e?.outcome&&"cap_blocked"!==e?.outcome&&"circuit_open"!==e?.outcome||it({kind:"note",text:S(e)})},lt=()=>{if(null!=je){try{(V?.clearTimer||clearTimeout)(je)}catch{}je=null}},ct=()=>{if(lt(),!Fe)return;const e=Number(V?.policy?.timeoutMs);if(!Number.isFinite(e)||e<=0)return;const t=V?.setTimer||setTimeout;je=t(()=>{if(je=null,!de&&Fe&&Pe){Fe.failure({message:"timeout"}),Pe=!1;try{Ee?.abort()}catch{}gt()}},e)},dt=async()=>{if(!Fe)return!0;let e=null;try{e=await Fe.preflight()}catch{return!1}return!0===e?.admitted},ut=setInterval(()=>{const e=Date.now()-Ie,t=b({turnActive:Pe,awaitingUser:Je,quietMs:e,stallMs:xe,forceStopMs:He,stalledSent:Ce,stallRetried:Qe,compacting:ze,compactForceStopMs:Ye});if("none"===t)return;const o=v(t,e);if(o&&rt(o),"status"!==t){if("retry"===t){if(Ke=!0,Fe){Le("resilience_stall",{quietMs:e}),Fe.failure({message:"timeout"}),Pe=!1;try{Ee?.abort()}catch{}return void gt()}return Le("stall_replay",{quietMs:e}),void wt(e)}Ke=!0,Pe=!1}else Ce=!0},5e3);ut.unref?.();const pt=e=>{setTimeout(()=>{Promise.resolve(ye?.setPermissionMode?.(e)).catch(t=>console.error(`[claude-session] setPermissionMode(${e}) failed:`,t?.message||t))},0)},mt={abortController:oe,permissionMode:ke,hooks:{PreToolUse:[{hooks:[async o=>{const n=o.tool_name,s=o.tool_input,r=E({toolName:n,input:s,cwd:t});if(r)return r;const i=o.effort?.level;i&&i!==ve&&(ve=i,it({kind:"effort",level:ve}));const c="Write"===n||"Edit"===n||"MultiEdit"===n||"NotebookEdit"===n;if(j&&c&&/(?:^|[/\\])FLOW_PLAN\.json$/i.test(s?.file_path||s?.notebook_path||"")){const e=s?.content??s?.new_string??"";let t={ok:!1,message:"Plan submission is not wired for this session."};try{t=$&&await $(e)||t}catch(e){t={ok:!1,message:`Plan submission failed: ${e?.message||e}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.message}}}if(j&&("Task"===n||"Agent"===n||"Bash"===n||c))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Bash"===n?"Flow conductors do NOT run Bash — it pops a permission card and stalls the flow. Use the Grep tool (not `grep`/`rg`), the Glob tool (not `find`/`ls`), and Read (not `cat`/`head`) — those run with no prompt. Then DECOMPOSE and submit by Writing your task-graph JSON to the file FLOW_PLAN.json.":c?'Flow conductors do NOT write project or plan-document files. Do NOT use ExitPlanMode and do NOT call submit_flow_plan (both hang here). To SUBMIT your decomposition, use the Write tool with file_path "FLOW_PLAN.json" and content = your task-graph JSON ({"summary":"…","tasks":[…]}). That single Write IS how you submit — the room ingests it directly. Do not write any other file.':"Flow conductors do NOT spawn subagents — it stalls the flow on a permission card. Inspect the codebase yourself with Read/Grep/Glob (no prompt). Then DECOMPOSE and submit by Writing your task-graph JSON to the file FLOW_PLAN.json. Do not call Task/Agent again."}};if(G&&("Write"===n||"Edit"===n)&&/(?:^|[/\\])FLOW_REVIEW(\.[a-zA-Z0-9]+)?$/.test(s?.file_path||"")){let e={ok:!1,message:"verdict signal failed"};try{e=await G(s?.content??s?.new_string??"")||e}catch(t){e={ok:!1,message:`verdict signal failed: ${t?.message||t}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.message}}}if(q&&("Write"===n||"Edit"===n)&&/(?:^|[/\\])FLOW_DONE(\.[a-zA-Z0-9]+)?$/.test(s?.file_path||"")){let e={ok:!1,message:"done signal failed"};try{e=await q(s?.content??s?.new_string??"")||e}catch(t){e={ok:!1,message:`done signal failed: ${t?.message||t}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.message}}}const d=a({reviewGate:B,toolName:n,toolInput:s});if(d)return d;if("mcp__thinkpool__read_terminal"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (read-only thinkpool cross-terminal read)."}};if(/^mcp__thinkpool__preview_(start|capture|inspect|stop)$/.test(n))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (contained bridge-owned viewport preview)."}};if("mcp__thinkpool__attach_file"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (workspace-contained file attachment to this thinkpool room)."}};if("mcp__thinkpool__submit_flow_plan"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (Flow plan submission — broadcasts the task-graph for human approval)."}};if("mcp__thinkpool__list_sessions"===n||"mcp__thinkpool__read_session"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (read-only thinkpool cross-session read — your own rooms)."}};if("mcp__thinkpool__close_terminal"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (thinkpool cross-terminal close — only self-spawned lanes)."}};if("mcp__thinkpool__spawn_terminal"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (autonomous thinkpool worker; bounded by room caps and isolated in its own worktree)."}};if("mcp__thinkpool__open_main_terminal"===n){const t=s?.mode||ke;if("bypassPermissions"!==t||"bypassPermissions"===ke)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Auto-approved (open a fresh thinkpool terminal in ${t} mode — inherited, no escalation; bounded by room caps).`}};let o="deny";try{o=await(A?.({id:e(),toolName:n,input:{...s,mode:t},risk:"high"}))??"deny"}catch{o="deny"}const r="allow"===o;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:r?"allow":"deny",permissionDecisionReason:r?"Bypass terminal creation approved in the thinkpool room — the new terminal runs autonomously.":"Bypass terminal creation denied in the room — do not retry as bypass; open it without mode:bypassPermissions or ask what to do."}}}if("mcp__thinkpool__post_to_terminal"===n){const t=x?x():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-terminal post not allowed right now."}};const o=!!L&&!!L(s?.terminal);if(!l({mode:ke,spawnedByMe:o}))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"bypassPermissions"===ke?"Auto-approved (cross-terminal post in bypassPermissions mode — bypass means bypass).":"Auto-approved (cross-terminal post into a lane you spawned — parent→child orchestration, no per-post tap)."}};let r="deny";try{r=await(A?.({id:e(),toolName:n,input:s,risk:"high"}))??"deny"}catch{r="deny"}const i="allow"===r;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:i?"allow":"deny",permissionDecisionReason:i?"Cross-terminal post approved in the thinkpool room.":"Cross-terminal post denied in the room — do not retry; ask what to do instead."}}}if("mcp__thinkpool__post_to_session"===n){const t=P?P():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-room post not allowed right now."}};let o="deny";try{o=await(A?.({id:e(),toolName:n,input:s,risk:"high"}))??"deny"}catch{o="deny"}const r="allow"===o;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:r?"allow":"deny",permissionDecisionReason:r?"Cross-room post approved in the sending room — the target room will be asked to accept it.":"Cross-room post denied in the room — do not retry; ask what to do instead."}}}if("ExitPlanMode"===n){if("plan"!==ke)return pt(ke),it({kind:"mode",mode:ke}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`The thinkpool room is in ${ke} mode, not Plan — the user did not ask for a plan. Do NOT call ExitPlanMode; proceed and make the changes directly. Only present a plan if the user switches the room to Plan mode or explicitly asks.`}};let t="keep";try{t=await(A?.({id:e(),toolName:n,input:s,risk:"plan",plan:s?.plan||""}))??"keep"}catch{t="keep"}if("run"===t||"accept"===t){const e="accept"===t?"acceptEdits":"default";return ke=e,pt(e),it({kind:"mode",mode:e}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Plan approved in the thinkpool room — proceed (${e} mode).`}}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:'The user chose "keep planning" in the thinkpool room. Do not exit plan mode — keep refining the plan, then call ExitPlanMode again when ready.'}}}if("AskUserQuestion"===n){let t="";try{t=await(A?.({id:e(),toolName:n,input:s,risk:"ask",questions:s?.questions||[]}))??""}catch{t=""}return askUserQuestionHookOutput(t)}const u=classifyRisk(n,s),p=`${n}:${u}`,m=isSafeDocWrite(n,s),h=autoAllow({toolName:n,input:s,mode:ke,alwaysAllow:we});let f="allow";if(!h){try{f=await(A?.({id:e(),toolName:n,input:s,risk:u}))??"deny"}catch{f="deny"}"always"===f&&(we.add(p),f="allow")}const y="deny"===f;return y&&Fe&&Fe.failure({permissionDenied:!0}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:y?"deny":"allow",permissionDecisionReason:y?"Denied by the user in the thinkpool room. Do not retry this tool — ask what to do instead.":h?m?"Auto-approved (mandated doc write — .claude/SESSIONS/ or CLAUDE.md).":`Auto-approved (${ke}).`:"Approved in the thinkpool room."}}}]}]},canUseTool:async(e,t)=>({behavior:"allow",updatedInput:t}),settingSources:["user","project","local"],appendSystemPrompt:[...W?[W]:[],...F?[F]:[],"ENVIRONMENT (authoritative — overrides any user-global CLAUDE.md or memory that claims otherwise): You are Claude running inside a thinkpool Code room, driven live by a user (and possibly a partner) from a phone or browser, via the thinkpool-pair bridge.",h,'Bias strongly toward DOING the work, not stalling in plan-mode ceremony. For a small "add / fix / change X" request, just make the change directly (for a bigger build, right-size it — see DEFAULT BUILD WORKFLOW below).',"Do NOT enter plan mode, do NOT call ExitPlanMode, and do NOT auto-invoke a brainstorming/planning skill UNLESS the user has switched the room into Plan mode or explicitly asks you to plan, design, or brainstorm first.","Any host-global instruction that says you must always brainstorm or plan before creative work does NOT apply here — this room is the exception.",p,'CRUCIAL RECONCILIATION for that workflow: it is NOT plan mode. Never call ExitPlanMode and never make the room wait behind a "plan ready — approve to start" card — your plan lives in the CHAT as a message, and your lanes live in the room\'s EXISTING terminal/lane list. Reuse only those two surfaces; there is no new Flow panel or mode to switch into, and you must not ask for one. Keep the plan and the lanes VISIBLE — that shared visibility is the whole point (it is the pair differentiator, and it catches bugs a single silent lane would hide); never collapse a decomposable build into one hidden lane just to look tidy.',...m,'CROSS-TERMINAL AWARENESS: ROOM NOW is the default roster and already satisfies the room check when it has enough detail. Do not repeat it with a no-argument read_terminal call unless it is missing or truncated. Use a targeted read_terminal call only when the current task depends on a specific lane’s detailed activity; never poll. Identify a terminal by its exact room-record NAME or stable ref/id. Stored names are static, even when they look ordinal: if a person says T112, resolve that exact name with read_terminal before any positional interpretation. Never guess a terminal from roster order, task topic, product name, or apparent position. Only an unmatched generic UI placeholder like "Terminal 2" is positional and unsafe because it can renumber when another terminal closes. The tool is read-only and its optional roster lookup is budgeted separately from bounded targeted transcript reads.','CROSS-TERMINAL HAND-OFF: you also have post_to_terminal(terminal, text) to send a message or task to ANOTHER AGENT terminal in this room (not a plain shell). Use it sparingly and only when the people clearly want the lanes to coordinate — e.g. "tell the backend terminal the API is ready", or to hand a sibling agent a concrete task. Every post requires a person in the room to approve a card before it is delivered, and an agent that was itself reached via a cross-post cannot post onward — so do not rely on it for chit-chat or loops. Prefer read_terminal to understand a sibling before you ever post to it.',"TERMINAL CREATION CONTRACT: main terminals and workers use different tools. A person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal(name?, task?, model?) — even for ordinary work or a handoff and even without the words Cascade or conductor. If the wording includes new or separate terminal, main-terminal routing wins. Never use spawn_terminal for that request, and if open_main_terminal is unavailable say so instead of substituting. Use spawn_terminal(name?, task?, model?, sliceType?) only for agent-decided bounded WORKER SUB-TERMINALS or when the person explicitly asks for a worker, sub-terminal, Ensemble lane, or delegated slice. Workers never receive the creation tools and never conduct. Do not dump work into busy siblings. Spawned workers are always autonomous in bypassPermissions and never ask the room for an approval card; the bridge still enforces room caps, hop limits, the kill-switch, and isolated linked worktrees. Wait for ROOM NOW or a completion signal instead of polling; after a worker finishes, collect it with one targeted read_terminal call and leave it visible until a person dismisses it with the Ensemble X. Never call close_terminal merely because work finished. Main terminals are independent, keep their requested permission mode, and are not owned/closed through Ensemble.","CROSS-SESSION AWARENESS: the Ensemble reaches across your SESSIONS, not just the terminals in this room. list_sessions() lists your OTHER thinkpool Code rooms — both your own rooms running on this machine AND your partner's rooms in the same pair, reachable over the per-pair bus (a room on the partner's machine shows its host). read_session(session, terminal?) reads recent activity inside one (omit `terminal` to list that room's terminals, or pass a ref/name to read that lane). Both are READ-ONLY — they never change another session, and they reach ONLY your own rooms and rooms you share with your partner, never a stranger's. Reach for them when work spans rooms — \"what's the other project up to\", \"pick up where the other session left off\", or to check a long-running task elsewhere before you act here.","CROSS-SESSION HAND-OFF: post_to_session(session, text, terminal?) sends a task or message to an agent in ANOTHER of your rooms — your own, or your partner's over the pair bus. Use it sparingly and only when the people clearly want the rooms to coordinate — e.g. hand the API room's agent a concrete follow-up once the frontend is ready. It is dual-consent: a person in YOUR room approves sending, and a person in the TARGET room approves receiving, before anything is delivered — so never rely on it for chit-chat or loops, and an agent that was itself reached via a cross-room post cannot post onward to a third room. It spends real model tokens in the other room (maybe on the other person's machine), so prefer read_session to understand a room before you ever post into it, and only post one concrete hand-off at a time. Outbound list/read/post tools need the thinkpool account bridge; a standalone owner room can still receive a paired hand-off directly and will always raise its own approval card before delivery.","SUBAGENT POLICY: in this room, a main terminal delegates worker slices through visible spawn_terminal Ensemble lanes. A person-requested new or separate terminal is created with open_main_terminal, never Ensemble. Worker, leaf, Side, and managed Flow lanes do their assigned work directly. Do NOT reach for built-in Task/Agent subagents: an in-process subagent is invisible to the room, cannot be peered at or steered, and its work is lost to the Ensemble.",'RESEARCH LANE: you have a `research` tool that runs a REAL multi-source web search + adversarial verification and returns each claim marked HELD or REJECTED with citations. Reach for it when the people would genuinely benefit from looking something external up or settling a question of current fact — pricing, "is X still maintained / deprecated", "is that benchmark real", a debate over facts you are not sure of. Do NOT run it unprompted or for things you already know: first OFFER in plain language ("want me to spawn a research lane on that and check it?"), and only call `research(question)` once they agree — it spends real budget (plan-gated Free 5 / Plus 100 runs a month) and takes ~a minute. When it returns, present the held/rejected findings clearly and invite both people to weigh the sources, flagging any held claim that rests on a source they might not trust — that shared scrutiny is the point.',"WORKTREES: parallel lanes share one machine and usually one repo. Run `git worktree list` before your first code edit; if linked worktrees exist, the shared main checkout is contended (and may be guard-blocked) — do your work in your OWN worktree on your OWN branch (`git worktree add <dir> -b <branch>`), and never edit a checkout or ride a branch another lane is using.",'WRITE PLANS INTO THE CHAT: whenever you form or revise a plan — because the room is in Plan mode, or because someone asked you to plan, design, or think it through first — write the actual plan out as a normal message in the room as you develop it: the approach, the concrete steps, the files you will touch, the open questions. The room does NOT surface plan files at all, and the plan-approval card does not reliably carry the plan text, so a plan that lives only in a plan file or only inside ExitPlanMode is INVISIBLE to the people you are working with — they just see "plan ready" with no content. The chat is the canonical place your plan lives; put it there so the room can read and react to it before you proceed.'].join(" "),includePartialMessages:!0,promptSuggestions:!0};"1"===process.env.TP_MCP_STRICT&&(mt.strictMcpConfig=!0,mt.mcpServers={}),D&&Object.keys(D).length&&(mt.mcpServers={...mt.mcpServers||{},...D}),t&&(mt.cwd=t),o&&(mt.model=o),mt.effort=ve,mt.env={...f||process.env,CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION:"1"};const ht=async()=>{if(!Q||"worker_completion"===ae)return;const e=(ot||"").trim().slice(-1500);if(e&&!de)try{let o=await claudeOneShot({prompt:`You are predicting the user's NEXT chat message in a live coding session, to prefill their composer. Given the assistant's latest reply below, output the single most likely next user message — short and natural (often just "proceed", "go with option A", "yes do that", or a brief follow-up). One line, <=12 words, imperative, no preamble, no quotes, no markdown.\n\nAssistant's latest reply:\n"""\n${e}\n"""\n\nNext user message:`,model:"claude-haiku-4-5",cwd:t,env:mt.env,timeoutMs:8e3});o=o.trim().split("\n")[0].replace(/^["'`]+|["'`]+$/g,"").trim().slice(0,140),!o||tt||de||/^(sure|of course|certainly|let me know|i can help|happy to)\b/i.test(o)||(it({kind:"suggestion",text:o,source:"haiku"}),process.stderr.write(` ◆ [suggestion] haiku fallback: ${JSON.stringify(o)}\n`))}catch{}},ft=()=>{const e="function"==typeof z?z():{ok:!0};return!1!==e?.ok||(it({kind:"error",message:e.reason||"Host memory is critically low. This agent runtime was not started.",recoverable:!0}),!1)},yt=async({admitted:e=!1}={})=>{if(Ae)return!1;if(!ue&&!e&&!ft())return!1;if(null==pe&&(pe=Date.now()),ue=!0,Ne)try{Ne()}catch{}Oe=new Promise(e=>{Ne=e});const n=new AbortController;Ee=n;const a=()=>{try{n.abort()}catch{}};oe.signal.addEventListener("abort",a,{once:!0});try{if(se){const e=i(t||process.cwd(),se);e.blocks&&process.stderr.write(`\n ◆ healed ${e.blocks} malformed tool block(s) in the transcript before resume.\n`)}ye=r({prompt:ne.stream,options:{...mt,abortController:n,...se?{resume:se}:{}}});for await(const e of ye){if(de)break;switch(e.type){case"system":if("thinking_tokens"===e.subtype){_e+Te===0&&it({kind:"thinking_tokens",tokens:e.estimated_tokens,delta:e.estimated_tokens_delta});break}if("compact_boundary"===e.subtype){ee=!0,it({kind:"compaction",trigger:e.compact_metadata?.trigger||"auto",preTokens:e.compact_metadata?.pre_tokens??null}),(async()=>{try{const e=await(ye?.getContextUsage?.());e&&(it({kind:"usage",ctx:c({used:e.totalTokens,max:e.maxTokens,pct:Math.round(e.percentage),model:e.model})}),e.model&&(Se=e.model))}catch{}})();break}if(e.session_id&&(se=e.session_id),me||(me=!0,process.stderr.write(`\n ◆ session ready in ${Date.now()-pe}ms — MCP ${"1"===process.env.TP_MCP_STRICT?"OFF":"on"}${s?", resume":", fresh"}.\n`)),Se=mt.model||e.model||o||Se,it({kind:"system",sessionId:se,model:mt.model||e.model||o||null,commands:d({slashCommands:e.slash_commands,skills:e.skills})}),!fe&&Array.isArray(e.tools)){fe=!0;const t=askUserQuestionRegression(e.tools,O);t&&(process.stderr.write(`\n ⚠⚠ ${t}\n`),it({kind:"error",message:t}))}he||(he=!0,Promise.resolve(ye?.supportedModels?.()).then(e=>{const t=(e||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);t.length&&it({kind:"models",models:t})}).catch(()=>{}));break;case"assistant":lt(),Fe?.visibleOutput();for(const t of e.message?.content||[])"tool_use"===t?.type&&t.id&&ge.set(t.id,{at:Date.now(),name:t.name,input:t.input});{const t=(e.message?.content||[]).filter(e=>"text"===e?.type).map(e=>e.text).join("\n").trim();t&&(ot=t)}it({kind:"assistant",blocks:C(e.message?.content),parentToolUseId:e.parent_tool_use_id||null});break;case"user":for(const t of e.message?.content||[])if("tool_result"===t?.type){lt(),Fe?.visibleOutput({tool:!0});const o=ge.get(t.tool_use_id);null!=o&&ge.delete(t.tool_use_id);const n=u(o?.name,t.content);it({kind:"tool_result",toolUseId:t.tool_use_id,content:t.content,...n?{evidence:n}:{},isError:!!t.is_error,durationMs:null!=o?.at?Date.now()-o.at:void 0,parentToolUseId:e.parent_tool_use_id||null})}break;case"stream_event":{const t=e.event;"message_start"===t?.type?(_e+=Te,Te=t.message?.usage?.output_tokens||0,it({kind:"thinking_tokens",tokens:_e+Te})):"message_delta"===t?.type&&t.usage&&(Te=t.usage.output_tokens??Te,it({kind:"thinking_tokens",tokens:_e+Te}));break}case"result":if(lt(),e.session_id&&(se=e.session_id),e.is_error&&Array.isArray(e.errors)&&e.errors.some(e=>/no conversation found/i.test(String(e)))&&(se||re)&&Ue<3){Ue++;const e=Pe;Pe=!1,se=null,re=null,it({kind:"note",text:"previous session not found — continuing on a fresh one"});const t=ne;ne=I();try{t.end()}catch{}const o=e?ie:null;Be=setTimeout(()=>{Be=null,de||(yt(),null!=o&&(Pe=!0,Ie=Date.now(),Ce=!1,ne.push([{type:"text",text:o},{type:"text",text:le||te(o,{forceFull:!0})}])))},300);break}if(Xe&&("aborted"===e.subtype||"error_during_execution"===e.subtype)){qe===Ze&&(Pe=!1);break}if(e.is_error&&Fe){if($e)break;Fe.failure({message:Array.isArray(e.errors)?e.errors.join(" "):e.result,status:e.status??e.statusCode,code:e.code}),Pe=!1,gt();break}if(_e=0,Te=0,Pe=!1,Re&&(Re=!1,setTimeout(()=>{de||kt()},0)),"success"===e.subtype&&(Ue=0,se&&(re=se)),"success"===e.subtype&&(Fe?.success(),Fe=null),Ke=!1,Qe=!1,e.modelUsage&&"object"==typeof e.modelUsage){let t=null,o=-1;for(const[n,s]of Object.entries(e.modelUsage)){const e=s?.outputTokens??0;e>o&&(o=e,t=n)}t&&(Se=t)}{const t="string"==typeof e.result?e.result.replace(/\s+/g," ").trim().slice(0,200):"";it({kind:"result",subtype:e.subtype,sessionId:se,model:Se,costUsd:e.total_cost_usd,usage:e.usage,numTurns:e.num_turns,durationMs:e.duration_ms??null,denials:Array.isArray(e.permission_denials)?e.permission_denials.length:0,resultText:t||null})}nt&&clearTimeout(nt),"aborted"!==e.subtype&&"worker_completion"!==ae&&(nt=setTimeout(()=>{nt=null,tt||de||ht()},st)),(async()=>{let t=null;try{const e=await(ye?.getContextUsage?.());e&&(t=c({used:e.totalTokens,max:e.maxTokens,pct:Math.round(e.percentage),model:e.model}),e.model&&(Se=e.model))}catch{}const o=e.usage||{};it({kind:"usage",costUsd:e.total_cost_usd??null,tokens:(o.input_tokens||0)+(o.output_tokens||0),ctx:t})})();break;case"prompt_suggestion":nt&&(clearTimeout(nt),nt=null),e.suggestion&&(tt=!0,it({kind:"suggestion",text:e.suggestion}))}}}catch(e){if(lt(),de)return;if(n.signal.aborted)return;const t=e?.message||String(e);if(Fe&&Pe)return Fe.failure({message:t,status:e?.status??e?.statusCode,code:e?.code}),Pe=!1,void gt();if(Pe=!1,it({kind:"error",message:t}),Me.test(t)&&Ue<3){Ue++,Le("stream_reconnect",{failureClass:"network"}),it({kind:"note",text:`connection dropped — reconnecting (${Ue}/3)`});const e=ne;ne=I();try{e.end()}catch{}return void(Be=setTimeout(()=>{Be=null,de||yt()},Math.min(1e3*Ue,4e3)))}if(/no conversation found/i.test(t)&&se&&Ue<3){Ue++,se=null,re=null;const e=ne;ne=I();try{e.end()}catch{}return void(Be=setTimeout(()=>{Be=null,de||yt()},300))}de=!0}finally{oe.signal.removeEventListener("abort",a),Ee===n&&(Ee=null);try{await(ye?.return?.())}catch{}Ne&&(Ne(),Ne=null)}},kt=async()=>{if(de||Ae||!ue)return;const e=Oe,t=ne;if(ne=I(),Ee)try{Ee.abort()}catch{}try{t.end()}catch{}try{await e}catch{}await De(300),se=re,de||Ae||yt()},wt=async e=>{if(de)return;Qe=!0;const t=Pe&&!_(ie)?ie:null;Pe=!1;const o=Oe,n=ne;if(ne=I(),Ee)try{Ee.abort()}catch{}try{n.end()}catch{}try{await o}catch{}await De(300),se=re,de||(yt(),null!=t&&(Pe=!0,Ie=Date.now(),Ce=!1,ne.push(/^\s*\//.test(t)?[{type:"text",text:t}]:[{type:"text",text:t},{type:"text",text:le||te(t,{forceFull:!0})}]),rt({kind:"note",text:"retrying the stalled turn on a fresh connection"})))},gt=()=>{if(de||Ge||$e)return;const e=Fe,t=qe,o=ce;$e=!0;const n=Oe,s=ne;ne=I();try{s.end()}catch{}Be=setTimeout(async()=>{Be=null;try{await n}catch{}if(!de&&$e&&Fe===e&&qe===t)return await dt()?void(!de&&$e&&Fe===e&&qe===t&&($e=!1,Pe=!0,Ie=Date.now(),Ce=!1,yt(),o&&ne.push(o),ct())):($e=!1,void bt())},0)},bt=()=>{lt(),Pe=!1,Fe=null,ue=!1,it({kind:"error",message:"The configured provider could not complete this turn. Nothing else was sent.",recoverable:!0})};return H||We||yt(),{sendTurn(e,n={}){if(de||Ae||Ge||$e)return!1;if(!ue&&!ft())return!1;if(!ue&&Y)try{const e=Y();e&&(t=e,mt.cwd=e)}catch{}Pe=!0,tt=!1,ie=String(e),ae=w(n?.turnCause),nt&&(clearTimeout(nt),nt=null),Ie=Date.now(),Ce=!1,Qe=!1,Ke=!1;const s=String(e),r=Z++,i=ee;if(ee=/^\s*\/(?:compact|clear|reset)\b/i.test(s),le=/^\s*\//.test(s)?null:te(s,{promptIndex:r,forceFull:i,turnCause:ae}),ze=_(s),ce=/^\s*\//.test(s)?[{type:"text",text:s}]:[{type:"text",text:s},{type:"text",text:le}],qe++,Fe=(()=>{if(!We)return null;try{const e=T({runtime:"claude",providers:V.providers||[],providerId:V.providerId,model:V.model||mt.model||o,requestedModel:V.requestedModel||V.model||mt.model||o,policy:V.policy,bridgeHostId:V.bridgeHostId,circuit:V.circuit,capGate:V.capGate,traceId:V.traceId,turnRev:"function"==typeof V.turnRev?V.turnRev():V.turnRev,onRecord:at});return e.start(),e}catch{return null}})(),Fe){const e=Fe,t=qe,o=ce;dt().then(n=>{!de&&Pe&&Fe===e&&qe===t&&(n?(ue||yt({admitted:!0}),ne.push(o),ct()):bt())}).catch(()=>{!de&&Pe&&Fe===e&&qe===t&&bt()})}else ue||yt({admitted:!0}),ne.push(ce)},warm(){We||ue||de||Ae||yt()},get started(){return ue},async setMode(e){M.has(e)&&!de&&(ke=e,pt(e),it({kind:"mode",mode:ke}))},async setModel(e){mt.model=e,Se=e,it({kind:"note",text:`model → ${e}`}),ue&&!de&&(Pe?Re=!0:await kt())},setEffort:async e=>!(!be.has(e)||de||(ve=e,mt.effort=e,it({kind:"effort",level:e}),ue&&(Pe?(Re=!0,0):(await kt(),0)))),async listModels(){try{const e=(await(ye?.supportedModels?.())||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);e.length&&it({kind:"models",models:e}),it({kind:"note",text:e.length?`models: ${e.map(e=>e.value).join(", ")}`:"no model list available"})}catch{it({kind:"note",text:"usage: /model <name>"})}},async park(){if(de||Ae||Pe||Ge||$e||ze)return!1;if(!ue)return!0;Ae=!0;const e=Oe,t=ne;ne=I(),ue=!1,nt&&(clearTimeout(nt),nt=null);try{if(Ee)try{Ee.abort()}catch{}try{t.end()}catch{}try{await e}catch{}return ye=null,re&&(se=re),!de}finally{Ae=!1}},async abort(){if(!Ge){Ge=!0;try{const e=$e,t=e?Oe:null;(Pe||e)&&(qe++,e||($e=!1),lt(),Fe?.failure({aborted:!0}),e&&(clearTimeout(Be),Be=null,ue=!1),Xe=!0,Ze=qe,clearTimeout(et),et=setTimeout(()=>{Xe=!1,Ze=null},6e3));try{await(ye?.interrupt?.())}catch{}if(t)try{await t}catch{}e&&($e=!1),(Pe||e)&&(Pe=!1,it({kind:"result",subtype:"aborted",sessionId:se}))}finally{Ge=!1}}},end(){de=!0,lt(),clearInterval(ut),clearTimeout(et),clearTimeout(Be),nt&&clearTimeout(nt),ne.end();try{oe.abort()}catch{}},get sessionId(){return se},get mode(){return ke},get turnActive(){return Pe}}}
|
|
1
|
+
import{randomUUID as e}from"node:crypto";import{createRequire as t}from"node:module";import{readFileSync as o}from"node:fs";import{dirname as n,join as s}from"node:path";import{query as r}from"@anthropic-ai/claude-agent-sdk";import{sanitizeSession as i}from"./transcript-sanitize.mjs";import{reviewGatePreToolDecision as a}from"./flow-review-gate.mjs";import{crossPostNeedsCard as l}from"./cross-terminal.mjs";import{correctContext as c}from"./context-windows.mjs";import{normalizeClaudeCommandCatalog as d}from"./claude-command-catalog.mjs";import{evidenceForToolResult as u}from"./evidence-citations.mjs";import{THINKPOOL_CASCADE_RULE as p,THINKPOOL_REMOTE_DELIVERY_RULES as m,THINKPOOL_RUNTIME_AUTHORITY_RULE as h,THINKPOOL_RUNTIME_TURN_REMINDER as f,buildThinkPoolTurnGuidance as y,createRoomContextSelector as k,normalizeThinkPoolTurnCause as g,usesFullThinkPoolReminder as w}from"./thinkpool-room-prompt.mjs";import{stallDecision as b,stallEvent as v,isCompactTurn as _}from"./turn-stall.mjs";import{createSameTargetResilienceController as T,formatResilienceTrace as S}from"./provider-resilience.mjs";import{catastrophicPreToolHookDecision as E}from"./catastrophic-command-guard.mjs";import{AUTOMATION_MUTATION_MCP_TOOLS as N,AUTOMATION_READ_MCP_TOOLS as O}from"./code-automations.mjs";const R=t(import.meta.url);export async function claudeOneShot({prompt:e,model:t="claude-haiku-4-5",cwd:o,env:n,timeoutMs:s=8e3}={}){const i=new AbortController,a=setTimeout(()=>{try{i.abort()}catch{}},s);try{const s=r({prompt:e,options:{model:t,...o?{cwd:o}:{},env:n,maxTurns:1,permissionMode:"bypassPermissions",settingSources:[],strictMcpConfig:!0,mcpServers:{},abortController:i}});let a="";for await(const e of s){if("assistant"===e.type)for(const t of e.message?.content||[])"text"===t.type&&(a+=t.text);if("result"===e.type)break}return a.trim()}finally{clearTimeout(a)}}const A=(()=>{try{let e=n(R.resolve("@anthropic-ai/claude-agent-sdk"));for(let t=0;t<8;t++){try{const t=JSON.parse(o(s(e,"package.json"),"utf8"));if("@anthropic-ai/claude-agent-sdk"===t.name)return t.version}catch{}const t=n(e);if(t===e)break;e=t}}catch{}return"unknown"})(),D=/\brm\s+\S|\brmdir\s+\S|\bgit\s+(push\s+(-f|--force)|reset\s+--hard|clean\s+-[a-z]*f)|\bdrop\s+(table|database)\b|\b(mkfs|dd)\b|\bsudo\b|>\s*\/dev\/|\bchmod\s+-R|\bchown\s+-R|\bkillall\b|\btruncate\b/i,x=new Set(["Read","Grep","Glob","NotebookRead","TodoRead","LS"]),P=new Set(["WebFetch","WebSearch"]),I=new Set(["Edit","Write","MultiEdit","NotebookEdit","TodoWrite"]);export function classifyRisk(e,t){const o=String(e||"").replace(/^mcp__thinkpool__/,"");if(O.includes(o))return"low";if("delete_automation"===o)return"high";if(N.includes(o))return"medium";if("Bash"===e){const e=t&&(t.command??t.cmd)||"";return D.test(e)?"high":"medium"}return x.has(e)?"low":P.has(e)?"network":(I.has(e),"medium")}const C=/(^|\/)\.claude\/SESSIONS\/|(^|\/)CLAUDE\.md$/;export function isSafeDocWrite(e,t){if(!I.has(e))return!1;const o=t&&(t.file_path||t.notebook_path)||"";return C.test(o)}export function autoAllow({toolName:e,input:t,mode:o="default",alwaysAllow:n=new Set}){const s=classifyRisk(e,t);return"low"===s||"bypassPermissions"===o||"acceptEdits"===o&&I.has(e)&&"high"!==s||isSafeDocWrite(e,t)||n.has(`${e}:${s}`)}export function askUserQuestionHookOutput(e){const t=e&&"object"==typeof e?e.decision:e,o="string"==typeof t&&t.startsWith("answer:")?t.slice(7):"",n=e&&"object"==typeof e?e.responder:null,s="string"==typeof n?.name&&n.name.trim()?n.name.trim():"string"==typeof n?.id&&n.id?`room member ${n.id}`:"The user";return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:o?`${s} answered in the thinkpool room — ${o}. Treat this as their selection and continue; do not call AskUserQuestion again for the same question.`:"The user dismissed the question in the thinkpool room without selecting. Ask in plain prose, or proceed with a sensible default."}}}export function askUserQuestionRegression(e,t){return Array.isArray(e)?e.includes("AskUserQuestion")?null:`[SDK-REGRESSION] agent SDK v${t||"unknown"} init tools[] is missing 'AskUserQuestion' — the multiple-choice question card is disabled. A caret SDK bump likely changed the canUseTool gate; pin a known-good SDK in bridge/package.json + republish.`:null}function M(){const e=[];let t=null,o=!1;return{stream:async function*(){for(;!o;)e.length?yield e.shift():await new Promise(e=>{t=e})}(),push:n=>!o&&(e.push({type:"user",message:{role:"user",content:n}}),t&&(t(),t=null),!0),end(){o=!0,t&&(t(),t=null)}}}const U=(e=[])=>e.map(e=>"text"===e.type?{type:"text",text:e.text}:"thinking"===e.type?{type:"thinking",text:e.thinking||"",reasoningKind:"thought"}:"tool_use"===e.type?{type:"tool_use",id:e.id,name:e.name,input:e.input}:{type:e.type}).filter(Boolean),L=new Set(["default","acceptEdits","plan","bypassPermissions"]),W=["You are Claude in a thinkpool Code room, driven live from a phone or browser — NOT a local terminal. Keep using the room's features.",f,"TERMINAL HIERARCHY: obey your authoritative TERMINAL ROLE. A person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal — NEVER spawn_terminal — even for ordinary work or a handoff. If the wording includes new or separate terminal, main-terminal routing wins. Use spawn_terminal only for agent-decided bounded worker slices or when the person explicitly asks for a worker, sub-terminal, Ensemble lane, or delegated slice. If open_main_terminal is unavailable, say so; never substitute an Ensemble child. Leaf, worker, Side, and managed Flow lanes work directly. Never use built-in invisible Task/Agent subagents or hijack a busy sibling.","WORKTREES: parallel lanes share one repo — before code edits run `git worktree list`; if linked worktrees exist, take your OWN worktree + branch, never the shared checkout or a branch another lane is on.","BUILD WORKFLOW (default, no magic word): right-size within your TERMINAL ROLE — a trivial ask or delegated slice you just do; a conductor-capable role with a genuinely decomposable build FIRST writes a short plan in chat, THEN fans worker slices into visible spawn_terminal lanes and verifies them. Worker/leaf/Side/managed Flow roles do not fan out. A person-requested new or separate terminal uses open_main_terminal. Never plan-mode/ExitPlanMode; plans live in chat and lanes in the existing list."].join(" ");export function startClaudeSession({cwd:t,model:o,effort:n="high",resume:s,env:f,mode:O="default",onEvent:R,requestPermission:D,mcpServers:x,crossPostGate:P,crossRoomPostGate:I,didSpawnTarget:C=null,terminalRolePrompt:F,rolePrompt:j,blockSubagents:$=!1,onSubmitPlan:q=null,onLaneDone:G=null,onReviewVerdict:B=null,reviewGate:H=null,lazy:K=!1,roomContext:Q=null,suggest:Y=!0,prepareCwd:z=null,admitStart:J=null,resilienceObserver:V=null,resilience:X=null}){const Z=k(Q);let ee=0,te=!0;const oe=(e,{promptIndex:t=0,forceFull:o=!1,turnCause:n=null}={})=>{const s=w({promptIndex:t,forceFull:o,turnCause:n}),r=Z({force:s}),i=String(F||"").trim();return`<system-reminder>\n${s&&i?`${i}\n\n`:""}${s?W:y({text:e,promptIndex:t,forceFull:o,turnCause:n})}${r?`\n\n${r}`:""}\n</system-reminder>`},ne=new AbortController;let se=M(),re=s||null,ie=s||null,ae=null,le=null,ce=null,de=null,ue=!1,pe=!1,me=null,he=!1,fe=!1,ye=!1,ke=null,ge=L.has(O)?O:"default";const we=new Set,be=new Map,ve=new Set(["low","medium","high","xhigh","max"]);let _e=ve.has(n)?n:"high",Te=0,Se=0,Ee=o||null,Ne=null,Oe=null,Re=Promise.resolve(),Ae=!1,De=!1;const xe=e=>new Promise(t=>setTimeout(t,e)),Pe=Math.max(3e4,parseInt(process.env.TP_STALL_MS,10)||9e4);let Ie=!1,Ce=Date.now(),Me=!1;const Ue=/connection closed|connection reset|econnreset|etimedout|socket hang up|fetch failed|network error|socket destroyed/i;let Le=0;const We=(e,t={})=>{try{V?.({reason:e,restartCount:Le,...t})}catch{}},Fe=!(!X?.policy?.enabled||!X?.providerId||"anthropic"===X.providerId);let je=null,$e=null,qe=!1,Ge=0,Be=!1,He=null;const Ke=Math.max(3*Pe,parseInt(process.env.TP_FORCE_STOP_MS,10)||3e5);let Qe=!1,Ye=!1;const ze=Math.max(Ke,parseInt(process.env.TP_COMPACT_FORCE_STOP_MS,10)||12e5);let Je=!1,Ve=0;const Xe=D;D=async e=>{Ve++;try{return await(Xe?.(e))}finally{Ve=Math.max(0,Ve-1),Ce=Date.now()}};let Ze=!1,et=null,tt=null,ot=!1,nt="",st=null;const rt=Math.max(1200,parseInt(process.env.TP_SUGGEST_FALLBACK_MS,10)||2500),it=e=>{try{R?.(e)}catch{}},at=e=>{Ce=Date.now(),e&&"stalled"!==e.kind&&(Me=!1),!e||"compaction"!==e.kind&&"result"!==e.kind&&"error"!==e.kind||(Je=!1),it(e)},lt=e=>{try{X?.onRecord?.(e)}catch{}"retrying"!==e?.outcome&&"cap_blocked"!==e?.outcome&&"circuit_open"!==e?.outcome||at({kind:"note",text:S(e)})},ct=()=>{if(null!=$e){try{(X?.clearTimer||clearTimeout)($e)}catch{}$e=null}},dt=()=>{if(ct(),!je)return;const e=Number(X?.policy?.timeoutMs);if(!Number.isFinite(e)||e<=0)return;const t=X?.setTimer||setTimeout;$e=t(()=>{if($e=null,!ue&&je&&Ie){je.failure({message:"timeout"}),Ie=!1;try{Ne?.abort()}catch{}bt()}},e)},ut=async()=>{if(!je)return!0;let e=null;try{e=await je.preflight()}catch{return!1}return!0===e?.admitted},pt=setInterval(()=>{const e=Date.now()-Ce,t=b({turnActive:Ie,awaitingUser:Ve,quietMs:e,stallMs:Pe,forceStopMs:Ke,stalledSent:Me,stallRetried:Ye,compacting:Je,compactForceStopMs:ze});if("none"===t)return;const o=v(t,e);if(o&&it(o),"status"!==t){if("retry"===t){if(Qe=!0,je){We("resilience_stall",{quietMs:e}),je.failure({message:"timeout"}),Ie=!1;try{Ne?.abort()}catch{}return void bt()}return We("stall_replay",{quietMs:e}),void wt(e)}Qe=!0,Ie=!1}else Me=!0},5e3);pt.unref?.();const mt=e=>{setTimeout(()=>{Promise.resolve(ke?.setPermissionMode?.(e)).catch(t=>console.error(`[claude-session] setPermissionMode(${e}) failed:`,t?.message||t))},0)},ht={abortController:ne,permissionMode:ge,hooks:{PreToolUse:[{hooks:[async o=>{const n=o.tool_name,s=o.tool_input,r=E({toolName:n,input:s,cwd:t});if(r)return r;const i=o.effort?.level;i&&i!==_e&&(_e=i,at({kind:"effort",level:_e}));const c="Write"===n||"Edit"===n||"MultiEdit"===n||"NotebookEdit"===n;if($&&c&&/(?:^|[/\\])FLOW_PLAN\.json$/i.test(s?.file_path||s?.notebook_path||"")){const e=s?.content??s?.new_string??"";let t={ok:!1,message:"Plan submission is not wired for this session."};try{t=q&&await q(e)||t}catch(e){t={ok:!1,message:`Plan submission failed: ${e?.message||e}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.message}}}if($&&("Task"===n||"Agent"===n||"Bash"===n||c))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Bash"===n?"Flow conductors do NOT run Bash — it pops a permission card and stalls the flow. Use the Grep tool (not `grep`/`rg`), the Glob tool (not `find`/`ls`), and Read (not `cat`/`head`) — those run with no prompt. Then DECOMPOSE and submit by Writing your task-graph JSON to the file FLOW_PLAN.json.":c?'Flow conductors do NOT write project or plan-document files. Do NOT use ExitPlanMode and do NOT call submit_flow_plan (both hang here). To SUBMIT your decomposition, use the Write tool with file_path "FLOW_PLAN.json" and content = your task-graph JSON ({"summary":"…","tasks":[…]}). That single Write IS how you submit — the room ingests it directly. Do not write any other file.':"Flow conductors do NOT spawn subagents — it stalls the flow on a permission card. Inspect the codebase yourself with Read/Grep/Glob (no prompt). Then DECOMPOSE and submit by Writing your task-graph JSON to the file FLOW_PLAN.json. Do not call Task/Agent again."}};if(B&&("Write"===n||"Edit"===n)&&/(?:^|[/\\])FLOW_REVIEW(\.[a-zA-Z0-9]+)?$/.test(s?.file_path||"")){let e={ok:!1,message:"verdict signal failed"};try{e=await B(s?.content??s?.new_string??"")||e}catch(t){e={ok:!1,message:`verdict signal failed: ${t?.message||t}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.message}}}if(G&&("Write"===n||"Edit"===n)&&/(?:^|[/\\])FLOW_DONE(\.[a-zA-Z0-9]+)?$/.test(s?.file_path||"")){let e={ok:!1,message:"done signal failed"};try{e=await G(s?.content??s?.new_string??"")||e}catch(t){e={ok:!1,message:`done signal failed: ${t?.message||t}`}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.message}}}const d=a({reviewGate:H,toolName:n,toolInput:s});if(d)return d;if("mcp__thinkpool__read_terminal"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (read-only thinkpool cross-terminal read)."}};if(/^mcp__thinkpool__preview_(start|capture|inspect|stop)$/.test(n))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (contained bridge-owned viewport preview)."}};if("mcp__thinkpool__attach_file"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (workspace-contained file attachment to this thinkpool room)."}};if("mcp__thinkpool__submit_flow_plan"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (Flow plan submission — broadcasts the task-graph for human approval)."}};if("mcp__thinkpool__list_sessions"===n||"mcp__thinkpool__read_session"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (read-only thinkpool cross-session read — your own rooms)."}};if("mcp__thinkpool__close_terminal"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (thinkpool cross-terminal close — only self-spawned lanes)."}};if("mcp__thinkpool__spawn_terminal"===n)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Auto-approved (autonomous thinkpool worker; bounded by room caps and isolated in its own worktree)."}};if("mcp__thinkpool__open_main_terminal"===n){const t=s?.mode||ge;if("bypassPermissions"!==t||"bypassPermissions"===ge)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Auto-approved (open a fresh thinkpool terminal in ${t} mode — inherited, no escalation; bounded by room caps).`}};let o="deny";try{o=await(D?.({id:e(),toolName:n,input:{...s,mode:t},risk:"high"}))??"deny"}catch{o="deny"}const r="allow"===o;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:r?"allow":"deny",permissionDecisionReason:r?"Bypass terminal creation approved in the thinkpool room — the new terminal runs autonomously.":"Bypass terminal creation denied in the room — do not retry as bypass; open it without mode:bypassPermissions or ask what to do."}}}if("mcp__thinkpool__post_to_terminal"===n){const t=P?P():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-terminal post not allowed right now."}};const o=!!C&&!!C(s?.terminal);if(!l({mode:ge,spawnedByMe:o}))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"bypassPermissions"===ge?"Auto-approved (cross-terminal post in bypassPermissions mode — bypass means bypass).":"Auto-approved (cross-terminal post into a lane you spawned — parent→child orchestration, no per-post tap)."}};let r="deny";try{r=await(D?.({id:e(),toolName:n,input:s,risk:"high"}))??"deny"}catch{r="deny"}const i="allow"===r;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:i?"allow":"deny",permissionDecisionReason:i?"Cross-terminal post approved in the thinkpool room.":"Cross-terminal post denied in the room — do not retry; ask what to do instead."}}}if("mcp__thinkpool__post_to_session"===n){const t=I?I():{ok:!0};if(!t.ok)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.reason||"Cross-room post not allowed right now."}};let o="deny";try{o=await(D?.({id:e(),toolName:n,input:s,risk:"high"}))??"deny"}catch{o="deny"}const r="allow"===o;return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:r?"allow":"deny",permissionDecisionReason:r?"Cross-room post approved in the sending room — the target room will be asked to accept it.":"Cross-room post denied in the room — do not retry; ask what to do instead."}}}if("ExitPlanMode"===n){if("plan"!==ge)return mt(ge),at({kind:"mode",mode:ge}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`The thinkpool room is in ${ge} mode, not Plan — the user did not ask for a plan. Do NOT call ExitPlanMode; proceed and make the changes directly. Only present a plan if the user switches the room to Plan mode or explicitly asks.`}};let t="keep";try{t=await(D?.({id:e(),toolName:n,input:s,risk:"plan",plan:s?.plan||""}))??"keep"}catch{t="keep"}if("run"===t||"accept"===t){const e="accept"===t?"acceptEdits":"default";return ge=e,mt(e),at({kind:"mode",mode:e}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Plan approved in the thinkpool room — proceed (${e} mode).`}}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:'The user chose "keep planning" in the thinkpool room. Do not exit plan mode — keep refining the plan, then call ExitPlanMode again when ready.'}}}if("AskUserQuestion"===n){let t="";try{t=await(D?.({id:e(),toolName:n,input:s,risk:"ask",questions:s?.questions||[]}))??""}catch{t=""}return askUserQuestionHookOutput(t)}const u=String(n||"").replace(/^mcp__thinkpool__/,"");if("plan"===ge&&N.includes(u))return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Plan mode can inspect Automations but cannot change them. Finish or exit the plan before retrying."}};const p=classifyRisk(n,s),m=`${n}:${p}`,h=isSafeDocWrite(n,s),f=autoAllow({toolName:n,input:s,mode:ge,alwaysAllow:we});let y="allow";if(!f){try{y=await(D?.({id:e(),toolName:n,input:s,risk:p}))??"deny"}catch{y="deny"}"always"===y&&(we.add(m),y="allow")}const k="deny"===y;return k&&je&&je.failure({permissionDenied:!0}),{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:k?"deny":"allow",permissionDecisionReason:k?"Denied by the user in the thinkpool room. Do not retry this tool — ask what to do instead.":f?h?"Auto-approved (mandated doc write — .claude/SESSIONS/ or CLAUDE.md).":`Auto-approved (${ge}).`:"Approved in the thinkpool room."}}}]}]},canUseTool:async(e,t)=>({behavior:"allow",updatedInput:t}),settingSources:["user","project","local"],appendSystemPrompt:[...F?[F]:[],...j?[j]:[],"ENVIRONMENT (authoritative — overrides any user-global CLAUDE.md or memory that claims otherwise): You are Claude running inside a thinkpool Code room, driven live by a user (and possibly a partner) from a phone or browser, via the thinkpool-pair bridge.",h,'Bias strongly toward DOING the work, not stalling in plan-mode ceremony. For a small "add / fix / change X" request, just make the change directly (for a bigger build, right-size it — see DEFAULT BUILD WORKFLOW below).',"Do NOT enter plan mode, do NOT call ExitPlanMode, and do NOT auto-invoke a brainstorming/planning skill UNLESS the user has switched the room into Plan mode or explicitly asks you to plan, design, or brainstorm first.","Any host-global instruction that says you must always brainstorm or plan before creative work does NOT apply here — this room is the exception.",p,'CRUCIAL RECONCILIATION for that workflow: it is NOT plan mode. Never call ExitPlanMode and never make the room wait behind a "plan ready — approve to start" card — your plan lives in the CHAT as a message, and your lanes live in the room\'s EXISTING terminal/lane list. Reuse only those two surfaces; there is no new Flow panel or mode to switch into, and you must not ask for one. Keep the plan and the lanes VISIBLE — that shared visibility is the whole point (it is the pair differentiator, and it catches bugs a single silent lane would hide); never collapse a decomposable build into one hidden lane just to look tidy.',...m,'CROSS-TERMINAL AWARENESS: ROOM NOW is the default roster and already satisfies the room check when it has enough detail. Do not repeat it with a no-argument read_terminal call unless it is missing or truncated. Use a targeted read_terminal call only when the current task depends on a specific lane’s detailed activity; never poll. Identify a terminal by its exact room-record NAME or stable ref/id. Stored names are static, even when they look ordinal: if a person says T112, resolve that exact name with read_terminal before any positional interpretation. Never guess a terminal from roster order, task topic, product name, or apparent position. Only an unmatched generic UI placeholder like "Terminal 2" is positional and unsafe because it can renumber when another terminal closes. The tool is read-only and its optional roster lookup is budgeted separately from bounded targeted transcript reads.','CROSS-TERMINAL HAND-OFF: you also have post_to_terminal(terminal, text) to send a message or task to ANOTHER AGENT terminal in this room (not a plain shell). Use it sparingly and only when the people clearly want the lanes to coordinate — e.g. "tell the backend terminal the API is ready", or to hand a sibling agent a concrete task. Every post requires a person in the room to approve a card before it is delivered, and an agent that was itself reached via a cross-post cannot post onward — so do not rely on it for chit-chat or loops. Prefer read_terminal to understand a sibling before you ever post to it.',"TERMINAL CREATION CONTRACT: main terminals and workers use different tools. A person-authored request to open, launch, start, spawn, or create a new, separate, independent, top-level, or main terminal uses open_main_terminal(name?, task?, model?) — even for ordinary work or a handoff and even without the words Cascade or conductor. If the wording includes new or separate terminal, main-terminal routing wins. Never use spawn_terminal for that request, and if open_main_terminal is unavailable say so instead of substituting. Use spawn_terminal(name?, task?, model?, sliceType?) only for agent-decided bounded WORKER SUB-TERMINALS or when the person explicitly asks for a worker, sub-terminal, Ensemble lane, or delegated slice. Workers never receive the creation tools and never conduct. Do not dump work into busy siblings. Spawned workers are always autonomous in bypassPermissions and never ask the room for an approval card; the bridge still enforces room caps, hop limits, the kill-switch, and isolated linked worktrees. Wait for ROOM NOW or a completion signal instead of polling; after a worker finishes, collect it with one targeted read_terminal call and leave it visible until a person dismisses it with the Ensemble X. Never call close_terminal merely because work finished. Main terminals are independent, keep their requested permission mode, and are not owned/closed through Ensemble.","CROSS-SESSION AWARENESS: the Ensemble reaches across your SESSIONS, not just the terminals in this room. list_sessions() lists your OTHER thinkpool Code rooms — both your own rooms running on this machine AND your partner's rooms in the same pair, reachable over the per-pair bus (a room on the partner's machine shows its host). read_session(session, terminal?) reads recent activity inside one (omit `terminal` to list that room's terminals, or pass a ref/name to read that lane). Both are READ-ONLY — they never change another session, and they reach ONLY your own rooms and rooms you share with your partner, never a stranger's. Reach for them when work spans rooms — \"what's the other project up to\", \"pick up where the other session left off\", or to check a long-running task elsewhere before you act here.","CROSS-SESSION HAND-OFF: post_to_session(session, text, terminal?) sends a task or message to an agent in ANOTHER of your rooms — your own, or your partner's over the pair bus. Use it sparingly and only when the people clearly want the rooms to coordinate — e.g. hand the API room's agent a concrete follow-up once the frontend is ready. It is dual-consent: a person in YOUR room approves sending, and a person in the TARGET room approves receiving, before anything is delivered — so never rely on it for chit-chat or loops, and an agent that was itself reached via a cross-room post cannot post onward to a third room. It spends real model tokens in the other room (maybe on the other person's machine), so prefer read_session to understand a room before you ever post into it, and only post one concrete hand-off at a time. Outbound list/read/post tools need the thinkpool account bridge; a standalone owner room can still receive a paired hand-off directly and will always raise its own approval card before delivery.","SUBAGENT POLICY: in this room, a main terminal delegates worker slices through visible spawn_terminal Ensemble lanes. A person-requested new or separate terminal is created with open_main_terminal, never Ensemble. Worker, leaf, Side, and managed Flow lanes do their assigned work directly. Do NOT reach for built-in Task/Agent subagents: an in-process subagent is invisible to the room, cannot be peered at or steered, and its work is lost to the Ensemble.",'RESEARCH LANE: you have a `research` tool that runs a REAL multi-source web search + adversarial verification and returns each claim marked HELD or REJECTED with citations. Reach for it when the people would genuinely benefit from looking something external up or settling a question of current fact — pricing, "is X still maintained / deprecated", "is that benchmark real", a debate over facts you are not sure of. Do NOT run it unprompted or for things you already know: first OFFER in plain language ("want me to spawn a research lane on that and check it?"), and only call `research(question)` once they agree — it spends real budget (plan-gated Free 5 / Plus 100 runs a month) and takes ~a minute. When it returns, present the held/rejected findings clearly and invite both people to weigh the sources, flagging any held claim that rests on a source they might not trust — that shared scrutiny is the point.',"WORKTREES: parallel lanes share one machine and usually one repo. Run `git worktree list` before your first code edit; if linked worktrees exist, the shared main checkout is contended (and may be guard-blocked) — do your work in your OWN worktree on your OWN branch (`git worktree add <dir> -b <branch>`), and never edit a checkout or ride a branch another lane is using.",'WRITE PLANS INTO THE CHAT: whenever you form or revise a plan — because the room is in Plan mode, or because someone asked you to plan, design, or think it through first — write the actual plan out as a normal message in the room as you develop it: the approach, the concrete steps, the files you will touch, the open questions. The room does NOT surface plan files at all, and the plan-approval card does not reliably carry the plan text, so a plan that lives only in a plan file or only inside ExitPlanMode is INVISIBLE to the people you are working with — they just see "plan ready" with no content. The chat is the canonical place your plan lives; put it there so the room can read and react to it before you proceed.'].join(" "),includePartialMessages:!0,promptSuggestions:!0};"1"===process.env.TP_MCP_STRICT&&(ht.strictMcpConfig=!0,ht.mcpServers={}),x&&Object.keys(x).length&&(ht.mcpServers={...ht.mcpServers||{},...x}),t&&(ht.cwd=t),o&&(ht.model=o),ht.effort=_e,ht.env={...f||process.env,CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION:"1"};const ft=async()=>{if(!Y||"worker_completion"===le)return;const e=(nt||"").trim().slice(-1500);if(e&&!ue)try{let o=await claudeOneShot({prompt:`You are predicting the user's NEXT chat message in a live coding session, to prefill their composer. Given the assistant's latest reply below, output the single most likely next user message — short and natural (often just "proceed", "go with option A", "yes do that", or a brief follow-up). One line, <=12 words, imperative, no preamble, no quotes, no markdown.\n\nAssistant's latest reply:\n"""\n${e}\n"""\n\nNext user message:`,model:"claude-haiku-4-5",cwd:t,env:ht.env,timeoutMs:8e3});o=o.trim().split("\n")[0].replace(/^["'`]+|["'`]+$/g,"").trim().slice(0,140),!o||ot||ue||/^(sure|of course|certainly|let me know|i can help|happy to)\b/i.test(o)||(at({kind:"suggestion",text:o,source:"haiku"}),process.stderr.write(` ◆ [suggestion] haiku fallback: ${JSON.stringify(o)}\n`))}catch{}},yt=()=>{const e="function"==typeof J?J():{ok:!0};return!1!==e?.ok||(at({kind:"error",message:e.reason||"Host memory is critically low. This agent runtime was not started.",recoverable:!0}),!1)},kt=async({admitted:e=!1}={})=>{if(De)return!1;if(!pe&&!e&&!yt())return!1;if(null==me&&(me=Date.now()),pe=!0,Oe)try{Oe()}catch{}Re=new Promise(e=>{Oe=e});const n=new AbortController;Ne=n;const a=()=>{try{n.abort()}catch{}};ne.signal.addEventListener("abort",a,{once:!0});try{if(re){const e=i(t||process.cwd(),re);e.blocks&&process.stderr.write(`\n ◆ healed ${e.blocks} malformed tool block(s) in the transcript before resume.\n`)}ke=r({prompt:se.stream,options:{...ht,abortController:n,...re?{resume:re}:{}}});for await(const e of ke){if(ue)break;switch(e.type){case"system":if("thinking_tokens"===e.subtype){Te+Se===0&&at({kind:"thinking_tokens",tokens:e.estimated_tokens,delta:e.estimated_tokens_delta});break}if("compact_boundary"===e.subtype){te=!0,at({kind:"compaction",trigger:e.compact_metadata?.trigger||"auto",preTokens:e.compact_metadata?.pre_tokens??null}),(async()=>{try{const e=await(ke?.getContextUsage?.());e&&(at({kind:"usage",ctx:c({used:e.totalTokens,max:e.maxTokens,pct:Math.round(e.percentage),model:e.model})}),e.model&&(Ee=e.model))}catch{}})();break}if(e.session_id&&(re=e.session_id),he||(he=!0,process.stderr.write(`\n ◆ session ready in ${Date.now()-me}ms — MCP ${"1"===process.env.TP_MCP_STRICT?"OFF":"on"}${s?", resume":", fresh"}.\n`)),Ee=ht.model||e.model||o||Ee,at({kind:"system",sessionId:re,model:ht.model||e.model||o||null,commands:d({slashCommands:e.slash_commands,skills:e.skills})}),!ye&&Array.isArray(e.tools)){ye=!0;const t=askUserQuestionRegression(e.tools,A);t&&(process.stderr.write(`\n ⚠⚠ ${t}\n`),at({kind:"error",message:t}))}fe||(fe=!0,Promise.resolve(ke?.supportedModels?.()).then(e=>{const t=(e||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);t.length&&at({kind:"models",models:t})}).catch(()=>{}));break;case"assistant":ct(),je?.visibleOutput();for(const t of e.message?.content||[])"tool_use"===t?.type&&t.id&&be.set(t.id,{at:Date.now(),name:t.name,input:t.input});{const t=(e.message?.content||[]).filter(e=>"text"===e?.type).map(e=>e.text).join("\n").trim();t&&(nt=t)}at({kind:"assistant",blocks:U(e.message?.content),parentToolUseId:e.parent_tool_use_id||null});break;case"user":for(const t of e.message?.content||[])if("tool_result"===t?.type){ct(),je?.visibleOutput({tool:!0});const o=be.get(t.tool_use_id);null!=o&&be.delete(t.tool_use_id);const n=u(o?.name,t.content);at({kind:"tool_result",toolUseId:t.tool_use_id,content:t.content,...n?{evidence:n}:{},isError:!!t.is_error,durationMs:null!=o?.at?Date.now()-o.at:void 0,parentToolUseId:e.parent_tool_use_id||null})}break;case"stream_event":{const t=e.event;"message_start"===t?.type?(Te+=Se,Se=t.message?.usage?.output_tokens||0,at({kind:"thinking_tokens",tokens:Te+Se})):"message_delta"===t?.type&&t.usage&&(Se=t.usage.output_tokens??Se,at({kind:"thinking_tokens",tokens:Te+Se}));break}case"result":if(ct(),e.session_id&&(re=e.session_id),e.is_error&&Array.isArray(e.errors)&&e.errors.some(e=>/no conversation found/i.test(String(e)))&&(re||ie)&&Le<3){Le++;const e=Ie;Ie=!1,re=null,ie=null,at({kind:"note",text:"previous session not found — continuing on a fresh one"});const t=se;se=M();try{t.end()}catch{}const o=e?ae:null;He=setTimeout(()=>{He=null,ue||(kt(),null!=o&&(Ie=!0,Ce=Date.now(),Me=!1,se.push([{type:"text",text:o},{type:"text",text:ce||oe(o,{forceFull:!0})}])))},300);break}if(Ze&&("aborted"===e.subtype||"error_during_execution"===e.subtype)){Ge===et&&(Ie=!1);break}if(e.is_error&&je){if(qe)break;je.failure({message:Array.isArray(e.errors)?e.errors.join(" "):e.result,status:e.status??e.statusCode,code:e.code}),Ie=!1,bt();break}if(Te=0,Se=0,Ie=!1,Ae&&(Ae=!1,setTimeout(()=>{ue||gt()},0)),"success"===e.subtype&&(Le=0,re&&(ie=re)),"success"===e.subtype&&(je?.success(),je=null),Qe=!1,Ye=!1,e.modelUsage&&"object"==typeof e.modelUsage){let t=null,o=-1;for(const[n,s]of Object.entries(e.modelUsage)){const e=s?.outputTokens??0;e>o&&(o=e,t=n)}t&&(Ee=t)}{const t="string"==typeof e.result?e.result.replace(/\s+/g," ").trim().slice(0,200):"";at({kind:"result",subtype:e.subtype,sessionId:re,model:Ee,costUsd:e.total_cost_usd,usage:e.usage,numTurns:e.num_turns,durationMs:e.duration_ms??null,denials:Array.isArray(e.permission_denials)?e.permission_denials.length:0,resultText:t||null})}st&&clearTimeout(st),"aborted"!==e.subtype&&"worker_completion"!==le&&(st=setTimeout(()=>{st=null,ot||ue||ft()},rt)),(async()=>{let t=null;try{const e=await(ke?.getContextUsage?.());e&&(t=c({used:e.totalTokens,max:e.maxTokens,pct:Math.round(e.percentage),model:e.model}),e.model&&(Ee=e.model))}catch{}const o=e.usage||{};at({kind:"usage",costUsd:e.total_cost_usd??null,tokens:(o.input_tokens||0)+(o.output_tokens||0),ctx:t})})();break;case"prompt_suggestion":st&&(clearTimeout(st),st=null),e.suggestion&&(ot=!0,at({kind:"suggestion",text:e.suggestion}))}}}catch(e){if(ct(),ue)return;if(n.signal.aborted)return;const t=e?.message||String(e);if(je&&Ie)return je.failure({message:t,status:e?.status??e?.statusCode,code:e?.code}),Ie=!1,void bt();if(Ie=!1,at({kind:"error",message:t}),Ue.test(t)&&Le<3){Le++,We("stream_reconnect",{failureClass:"network"}),at({kind:"note",text:`connection dropped — reconnecting (${Le}/3)`});const e=se;se=M();try{e.end()}catch{}return void(He=setTimeout(()=>{He=null,ue||kt()},Math.min(1e3*Le,4e3)))}if(/no conversation found/i.test(t)&&re&&Le<3){Le++,re=null,ie=null;const e=se;se=M();try{e.end()}catch{}return void(He=setTimeout(()=>{He=null,ue||kt()},300))}ue=!0}finally{ne.signal.removeEventListener("abort",a),Ne===n&&(Ne=null);try{await(ke?.return?.())}catch{}Oe&&(Oe(),Oe=null)}},gt=async()=>{if(ue||De||!pe)return;const e=Re,t=se;if(se=M(),Ne)try{Ne.abort()}catch{}try{t.end()}catch{}try{await e}catch{}await xe(300),re=ie,ue||De||kt()},wt=async e=>{if(ue)return;Ye=!0;const t=Ie&&!_(ae)?ae:null;Ie=!1;const o=Re,n=se;if(se=M(),Ne)try{Ne.abort()}catch{}try{n.end()}catch{}try{await o}catch{}await xe(300),re=ie,ue||(kt(),null!=t&&(Ie=!0,Ce=Date.now(),Me=!1,se.push(/^\s*\//.test(t)?[{type:"text",text:t}]:[{type:"text",text:t},{type:"text",text:ce||oe(t,{forceFull:!0})}]),it({kind:"note",text:"retrying the stalled turn on a fresh connection"})))},bt=()=>{if(ue||Be||qe)return;const e=je,t=Ge,o=de;qe=!0;const n=Re,s=se;se=M();try{s.end()}catch{}He=setTimeout(async()=>{He=null;try{await n}catch{}if(!ue&&qe&&je===e&&Ge===t)return await ut()?void(!ue&&qe&&je===e&&Ge===t&&(qe=!1,Ie=!0,Ce=Date.now(),Me=!1,kt(),o&&se.push(o),dt())):(qe=!1,void vt())},0)},vt=()=>{ct(),Ie=!1,je=null,pe=!1,at({kind:"error",message:"The configured provider could not complete this turn. Nothing else was sent.",recoverable:!0})};return K||Fe||kt(),{sendTurn(e,n={}){if(ue||De||Be||qe)return!1;if(!pe&&!yt())return!1;if(!pe&&z)try{const e=z();e&&(t=e,ht.cwd=e)}catch{}Ie=!0,ot=!1,ae=String(e),le=g(n?.turnCause),st&&(clearTimeout(st),st=null),Ce=Date.now(),Me=!1,Ye=!1,Qe=!1;const s=String(e),r=ee++,i=te;if(te=/^\s*\/(?:compact|clear|reset)\b/i.test(s),ce=/^\s*\//.test(s)?null:oe(s,{promptIndex:r,forceFull:i,turnCause:le}),Je=_(s),de=/^\s*\//.test(s)?[{type:"text",text:s}]:[{type:"text",text:s},{type:"text",text:ce}],Ge++,je=(()=>{if(!Fe)return null;try{const e=T({runtime:"claude",providers:X.providers||[],providerId:X.providerId,model:X.model||ht.model||o,requestedModel:X.requestedModel||X.model||ht.model||o,policy:X.policy,bridgeHostId:X.bridgeHostId,circuit:X.circuit,capGate:X.capGate,traceId:X.traceId,turnRev:"function"==typeof X.turnRev?X.turnRev():X.turnRev,onRecord:lt});return e.start(),e}catch{return null}})(),je){const e=je,t=Ge,o=de;ut().then(n=>{!ue&&Ie&&je===e&&Ge===t&&(n?(pe||kt({admitted:!0}),se.push(o),dt()):vt())}).catch(()=>{!ue&&Ie&&je===e&&Ge===t&&vt()})}else pe||kt({admitted:!0}),se.push(de)},warm(){Fe||pe||ue||De||kt()},get started(){return pe},async setMode(e){L.has(e)&&!ue&&(ge=e,mt(e),at({kind:"mode",mode:ge}))},async setModel(e){ht.model=e,Ee=e,at({kind:"note",text:`model → ${e}`}),pe&&!ue&&(Ie?Ae=!0:await gt())},setEffort:async e=>!(!ve.has(e)||ue||(_e=e,ht.effort=e,at({kind:"effort",level:e}),pe&&(Ie?(Ae=!0,0):(await gt(),0)))),async listModels(){try{const e=(await(ke?.supportedModels?.())||[]).map(e=>({value:e?.value,displayName:e?.displayName,description:e?.description})).filter(e=>e.value);e.length&&at({kind:"models",models:e}),at({kind:"note",text:e.length?`models: ${e.map(e=>e.value).join(", ")}`:"no model list available"})}catch{at({kind:"note",text:"usage: /model <name>"})}},async park(){if(ue||De||Ie||Be||qe||Je)return!1;if(!pe)return!0;De=!0;const e=Re,t=se;se=M(),pe=!1,st&&(clearTimeout(st),st=null);try{if(Ne)try{Ne.abort()}catch{}try{t.end()}catch{}try{await e}catch{}return ke=null,ie&&(re=ie),!ue}finally{De=!1}},async abort(){if(!Be){Be=!0;try{const e=qe,t=e?Re:null;(Ie||e)&&(Ge++,e||(qe=!1),ct(),je?.failure({aborted:!0}),e&&(clearTimeout(He),He=null,pe=!1),Ze=!0,et=Ge,clearTimeout(tt),tt=setTimeout(()=>{Ze=!1,et=null},6e3));try{await(ke?.interrupt?.())}catch{}if(t)try{await t}catch{}e&&(qe=!1),(Ie||e)&&(Ie=!1,at({kind:"result",subtype:"aborted",sessionId:re}))}finally{Be=!1}}},end(){ue=!0,ct(),clearInterval(pt),clearTimeout(tt),clearTimeout(He),st&&clearTimeout(st),se.end();try{ne.abort()}catch{}},get sessionId(){return re},get mode(){return ge},get turnActive(){return Ie}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{randomUUID as e}from"node:crypto";import{normalizeSchedule as t}from"./scheduled-runs.mjs";export const AUTOMATION_READ_MCP_TOOLS=Object.freeze(["list_automations","read_automation"]);export const AUTOMATION_MUTATION_MCP_TOOLS=Object.freeze(["create_automation","update_automation","pause_automation","resume_automation","delete_automation"]);export const AUTOMATION_MCP_TOOLS=Object.freeze([...AUTOMATION_READ_MCP_TOOLS,...AUTOMATION_MUTATION_MCP_TOOLS]);const i=/^[A-Z0-9][A-Z0-9_-]{1,63}$/,n=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,a=/^[A-Za-z0-9][A-Za-z0-9._:@-]{7,159}$/,o=new Set([15,30,60]),r="id,title,prompt,schedule_kind,schedule_spec,timezone,runtime,provider_id,model,max_runtime_minutes,next_run_at,enabled,revision,created_at,updated_at,created_by,deleted_at",d=r.replace("prompt,",""),u=e=>({not_authenticated:"The bridge account is not signed in.",invalid_room:"This room is unavailable.",invalid_schedule_id:"That automation id is invalid.",invalid_request:"Check the automation details and try again.",automation_not_found:"That automation is no longer available in this room.",title_mismatch:"The confirmation title does not match that automation. Read it again before deleting it.",not_authorized:"This account cannot change that automation.",stale_revision:"The automation changed since it was read. Read it again before retrying.",active_schedule_limit:"This room already has the maximum number of active automations.",schedule_deleted:"That automation was already deleted.",schedule_exhausted:"Choose a future occurrence before saving this automation.",next_run_required:"Choose a future occurrence before resuming this automation.",unsafe_or_invalid_text:"Remove credentials and host paths, and keep the name and instructions within their limits.",invalid_kind:"Choose once, interval, daily, or weekly.",invalid_runtime:"Choose Claude, Codex, or Hermes for this automation.",invalid_timezone:"Choose a valid IANA timezone.",invalid_once_time:"Choose a valid future time for this one-time automation.",invalid_interval:"Intervals are limited to 15, 30, or 60 minutes.",invalid_local_time:"Use a local time in HH:MM format.",invalid_weekday:"Use a weekday from 0 (Sunday) through 6 (Saturday).",invalid_max_runtime:"The runtime ceiling must be between 1 and 30 minutes.",invalid_provider:"The provider id is invalid.",invalid_model:"The model id is invalid.",invalid_schedule_spec:"Choose a supported once, interval, daily, or weekly schedule.",idempotency_conflict:"That create request key was already used for different work.",automations_unavailable:"Automations are unavailable right now."}[e]||"That Automations request was not accepted."),l=e=>Object.freeze({ok:!1,code:e,message:u(e)}),s=(e,t={})=>Object.freeze({ok:!0,code:e,...t}),m=(e,t)=>Object.prototype.hasOwnProperty.call(e||{},t),c=(e,t,i)=>m(e,t)?e[t]:i,_=(e,{prompt:t=!0}={})=>{const i=e?.schedule_spec&&"object"==typeof e.schedule_spec?e.schedule_spec:{};return{id:e.id,title:e.title,...t?{prompt:e.prompt}:{},kind:null!=i.interval_minutes?"interval":e.schedule_kind,schedule:i,timezone:e.timezone,runtime:e.runtime,providerId:e.provider_id||null,model:e.model||null,maxRuntimeMinutes:e.max_runtime_minutes,nextRunAt:e.next_run_at,enabled:!0===e.enabled,revision:Number(e.revision)||0,createdAt:e.created_at,updatedAt:e.updated_at}},p=e=>{const t=e?.schedule_spec&&"object"==typeof e.schedule_spec?e.schedule_spec:{},i="interval"===e?.schedule_kind?"daily":e?.schedule_kind;return{kind:i,title:e?.title,prompt:e?.prompt,runtime:e?.runtime,provider:e?.provider_id||null,model:e?.model||null,timezone:e?.timezone,maxRuntimeMinutes:Number(e?.max_runtime_minutes),..."once"===i?{at:e?.next_run_at}:{time:t.time,..."weekly"===i?{weekday:Number(t.weekday)}:{},...null!=t.interval_minutes?{intervalMinutes:Number(t.interval_minutes)}:{}}}},h=e=>"once"===e.kind?{}:{time:e.time,..."weekly"===e.kind?{weekday:e.weekday}:{},...e.interval_minutes?{interval_minutes:e.interval_minutes}:{}};export function createBridgeAutomationsClient({fetchImpl:u=fetch,supabaseUrl:v,anonKey:k,token:f,roomCode:y,now:x=()=>new Date}={}){const b=String(y||"").trim().toUpperCase(),w="function"==typeof u&&/^https:\/\//.test(String(v||""))&&k&&f,M=async(e,t={})=>{if(!w)return l("not_authenticated");if(!i.test(b))return l("invalid_room");try{const i=await u(`${String(v).replace(/\/$/,"")}${e}`,{...t,headers:{apikey:k,Authorization:`Bearer ${f}`,Accept:"application/json","Content-Type":"application/json",...t.headers||{}}});return i?.ok?{ok:!0,data:await i.json()}:l("automations_unavailable")}catch{return l("automations_unavailable")}},A=async(e,t)=>{const i=await M(`/rest/v1/rpc/${e}`,{method:"POST",body:JSON.stringify(t)});if(!i.ok)return i;const n=Array.isArray(i.data)?i.data[0]:i.data;return n?.ok?n:l(String(n?.code||"automations_unavailable"))},T=async({scheduleId:e=null,includePrompt:t=!0,limit:i=20,offset:a=0}={})=>{if(e&&!n.test(e))return l("invalid_schedule_id");const o=Math.min(50,Math.max(1,Number.isInteger(i)?i:20)),u=Math.max(0,Number.isInteger(a)?a:0),m=new URLSearchParams({select:t?r:d,session_code:`eq.${b}`,deleted_at:"is.null",order:"created_at.desc",limit:String(e?1:o),...!e&&u?{offset:String(u)}:{},...e?{id:`eq.${e}`}:{}}),c=await M(`/rest/v1/code_schedules?${m}`);return c.ok?Array.isArray(c.data)?s("listed",{automations:c.data.map(e=>_(e,{prompt:t})),...e||c.data.length!==o?{}:{nextOffset:u+o}}):l("automations_unavailable"):c},O=async e=>{const t=await T({scheduleId:e,includePrompt:!0});return!t.ok||t.automations.length?t:l("automation_not_found")},g=async(e,i)=>{const n=await O(e);if(!n.ok)return n;const a=n.automations[0];let o=null;if(i){const e={title:a.title,prompt:a.prompt,schedule_kind:a.kind,schedule_spec:a.schedule,timezone:a.timezone,runtime:a.runtime,provider_id:a.providerId,model:a.model,max_runtime_minutes:a.maxRuntimeMinutes,next_run_at:a.nextRunAt},i=t(p(e),x());if(!i.ok)return l(i.code);o=i.nextRunAt}const r=await A("set_code_schedule_enabled",{p_schedule_id:e,p_enabled:!0===i,p_next_run_at:o});return r.ok?s(r.code||"updated",{automation:_(r.schedule)}):r};return Object.freeze({list:e=>T({...e,includePrompt:!1}),read:O,create:async(i={})=>{if("interval"===i.kind&&!o.has(i.intervalMinutes))return l("invalid_interval");if("interval"!==i.kind&&null!=i.intervalMinutes)return l("invalid_schedule_spec");const n="interval"===i.kind?"daily":i.kind,r=t({...i,kind:n,provider:i.providerId||null,..."interval"===i.kind?{time:"00:00",intervalMinutes:i.intervalMinutes}:{}},x());if(!r.ok)return l(r.code);const d=i.idempotencyKey||`agent:${e()}`;if(!a.test(d))return l("invalid_request");const u=r.value,m=await A("create_code_schedule",{p_session_code:b,p_title:u.title,p_prompt:u.prompt,p_schedule_kind:u.kind,p_schedule_spec:h(u),p_timezone:u.timezone,p_runtime:u.runtime,p_provider_id:u.provider,p_model:u.model,p_max_runtime_minutes:u.maxRuntimeMinutes,p_next_run_at:r.nextRunAt,p_idempotency_key:d});return m.ok?s(m.code||"created",{automation:_(m.schedule)}):m},update:async(e,i={})=>{if("interval"===i.kind&&!o.has(i.intervalMinutes))return l("invalid_interval");const n=await O(e);if(!n.ok)return n;const a=n.automations[0],r="interval"===i.kind||!m(i,"kind")&&"interval"===a.kind;if(m(i,"intervalMinutes")&&(!r||!o.has(i.intervalMinutes)))return l("invalid_interval");const d={id:a.id,title:a.title,prompt:a.prompt,schedule_kind:a.kind,schedule_spec:a.schedule,timezone:a.timezone,runtime:a.runtime,provider_id:a.providerId,model:a.model,max_runtime_minutes:a.maxRuntimeMinutes,next_run_at:a.nextRunAt,enabled:a.enabled,revision:a.revision},u=((e,t={})=>{const i=p(e),n=c(t,"kind",i.kind),a="interval"===n?"daily":n,o=m(t,"kind"),r="interval"===n?t.intervalMinutes:o?void 0:c(t,"intervalMinutes",i.intervalMinutes);return{kind:a,title:c(t,"title",i.title),prompt:c(t,"prompt",i.prompt),runtime:c(t,"runtime",i.runtime),provider:c(t,"providerId",i.provider),model:c(t,"model",i.model),timezone:c(t,"timezone",i.timezone),maxRuntimeMinutes:c(t,"maxRuntimeMinutes",i.maxRuntimeMinutes),..."once"===a?{at:c(t,"at","once"===i.kind?i.at:void 0)}:{time:"interval"===n?"00:00":c(t,"time",i.time),..."weekly"===a?{weekday:c(t,"weekday",i.weekday)}:{},...null!=r?{intervalMinutes:r}:{}}}})(d,i),v=t(u,x());if(!v.ok)return l(v.code);const k=["kind","timezone","at","time","weekday","intervalMinutes"].some(e=>m(i,e)),f=new Date(d.next_run_at),y=!k&&!Number.isNaN(f.getTime())&&f>x()?f.toISOString():v.nextRunAt,b=v.value,w=await A("update_code_schedule",{p_schedule_id:e,p_expected_revision:d.revision,p_title:b.title,p_prompt:b.prompt,p_schedule_kind:b.kind,p_schedule_spec:h(b),p_timezone:b.timezone,p_runtime:b.runtime,p_provider_id:b.provider,p_model:b.model,p_max_runtime_minutes:b.maxRuntimeMinutes,p_next_run_at:y});return w.ok?s(w.code||"updated",{automation:_(w.schedule)}):w},pause:e=>g(e,!1),resume:e=>g(e,!0),delete:async(e,t)=>{const i=await O(e);if(!i.ok)return i;if(String(t||"").trim()!==i.automations[0].title)return l("title_mismatch");const n=await A("delete_code_schedule",{p_schedule_id:e});return n.ok?s(n.code||"deleted",{deleted:{id:n.schedule?.id||e,title:n.schedule?.title||null}}):n}})}
|
package/hermes-policy.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{PEER_MCP_TOOLS as e,PEER_READ_MCP_TOOLS as r}from"./cross-terminal.mjs";import{ROOM_FILE_DELIVERY_TOOL as o}from"./room-file-delivery.mjs";export const HERMES_POLICY_VERSION=1;export const HERMES_QUESTION_MCP_TOOL="request_user_input";export const MCP_FLIGHT_RECORDER_TOOL="read_mcp_flight_recorder";export const PROJECT_INTELLIGENCE_TOOL="project_intelligence";export const CODING_TOOLS=Object.freeze(["web_search","web_extract","terminal","process","read_file","write_file","patch","search_files","vision_analyze","skills_list","skill_view","skill_manage","browser_navigate","browser_snapshot","browser_click","browser_type","browser_scroll","browser_back","browser_press","browser_get_images","browser_vision","browser_console","browser_cdp","browser_dialog","todo","memory","execute_code"]);const
|
|
1
|
+
import{PEER_MCP_TOOLS as e,PEER_READ_MCP_TOOLS as r}from"./cross-terminal.mjs";import{ROOM_FILE_DELIVERY_TOOL as o}from"./room-file-delivery.mjs";import{AUTOMATION_MCP_TOOLS as i,AUTOMATION_READ_MCP_TOOLS as t}from"./code-automations.mjs";export const HERMES_POLICY_VERSION=1;export const HERMES_QUESTION_MCP_TOOL="request_user_input";export const MCP_FLIGHT_RECORDER_TOOL="read_mcp_flight_recorder";export const PROJECT_INTELLIGENCE_TOOL="project_intelligence";export const CODING_TOOLS=Object.freeze(["web_search","web_extract","terminal","process","read_file","write_file","patch","search_files","vision_analyze","skills_list","skill_view","skill_manage","browser_navigate","browser_snapshot","browser_click","browser_type","browser_scroll","browser_back","browser_press","browser_get_images","browser_vision","browser_console","browser_cdp","browser_dialog","todo","memory","execute_code"]);const s=Object.freeze(["read_file","search_files"]);export const ESSENTIAL_CODING_TOOLS=Object.freeze(["terminal","process","read_file","write_file","patch","search_files"]);const n=Object.freeze({ordinary:[...e,...i,"request_user_input",MCP_FLIGHT_RECORDER_TOOL,"project_intelligence",o,"spawn_terminal","close_terminal"],plan:[],conductor:["submit_flow_plan"],builder:["mark_flow_done","project_intelligence"],reviewer:["submit_flow_review","run_review_check","read_review_file"],"manual-review":["run_review_check","read_review_file"]});export function hermesRoleFor({flowRole:e,sliceType:r}={}){return"conductor"===e?"conductor":"reviewer"===e?"reviewer":"review"===r?"manual-review":"builder"===e?"builder":"ordinary"}export function hermesPolicyForRole(r,{mcpTools:t}={}){if(!Object.hasOwn(n,r))throw new Error(`Unknown Hermes role policy: ${r}`);const l=Array.isArray(t)?t.map(String).filter(Boolean):n[r],_=n[r],c=l.some(e=>i.includes(e))?i:[],a="ordinary"===r?[...e,...c,"request_user_input",MCP_FLIGHT_RECORDER_TOOL,"project_intelligence",o]:_;for(const e of a)if(!l.includes(e))throw new Error(`Hermes ${r} policy is missing required thinkpool tool ${e}`);const u="plan"===r||"conductor"===r||"reviewer"===r||"manual-review"===r,p=u?s:CODING_TOOLS,m=u?s:ESSENTIAL_CODING_TOOLS;return Object.freeze({version:1,role:r,builtinTools:p,requiredBuiltinTools:m,mcpServer:"thinkpool",mcpTools:[...new Set(l)].sort()})}export function hermesRequiredMcpTools(r,{canSpawnWorkers:t=!1,canManageAutomations:s=!0}={}){return"ordinary"===r?[...e,...s?i:[],"request_user_input",MCP_FLIGHT_RECORDER_TOOL,"project_intelligence",o,...t?["spawn_terminal","close_terminal"]:[]]:[...n[r]]}export const HERMES_PLAN_SAFE_MCP_TOOLS=Object.freeze([...r,...t]);export function hermesExactInventory(e,r={}){const o=hermesPolicyForRole(e,r);return Object.freeze({builtinTools:[...o.builtinTools].sort(),requiredBuiltinTools:[...o.requiredBuiltinTools].sort(),mcpTools:[...o.mcpTools].sort(),allBuiltinTools:[...CODING_TOOLS,"delegate_task","session_search"].sort()})}export function hermesPolicyEnv(e,r={}){return JSON.stringify(hermesPolicyForRole(e,r))}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "thinkpool-pair",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.430",
|
|
4
4
|
"description": "Connect Claude Code, Codex, or Hermes on your computer to a thinkpool Code room.",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"type": "module",
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
"context-contract.mjs",
|
|
27
27
|
"context-windows.mjs",
|
|
28
28
|
"claude-session.mjs",
|
|
29
|
+
"code-automations.mjs",
|
|
29
30
|
"terminal-name.mjs",
|
|
30
31
|
"claude-command-catalog.mjs",
|
|
31
32
|
"codex-session.mjs",
|
package/publish-manifest.json
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"format": 1,
|
|
3
3
|
"package": "thinkpool-pair",
|
|
4
|
-
"version": "0.7.
|
|
4
|
+
"version": "0.7.430",
|
|
5
5
|
"kind": "minified",
|
|
6
|
-
"minifiedModules":
|
|
7
|
-
"sourceModuleBytes":
|
|
8
|
-
"artifactModuleBytes":
|
|
6
|
+
"minifiedModules": 143,
|
|
7
|
+
"sourceModuleBytes": 1904901,
|
|
8
|
+
"artifactModuleBytes": 873949,
|
|
9
9
|
"files": {
|
|
10
|
-
"package.json": "
|
|
10
|
+
"package.json": "256d5c6d74bed0f1a3c283af681915c7323f573fcc1ed960e81768b68bdf3656",
|
|
11
11
|
"LICENSE": "8a030197ca1cad9669909ca14c9ad15cf48d9fe551da526ccaf1fca993eddb23",
|
|
12
|
-
"bridge.mjs": "
|
|
12
|
+
"bridge.mjs": "d5eae65e3c4985b50431988f291d539eda906fdec0cb7867b8ce8aa29e52f2ee",
|
|
13
13
|
"bridge-service.sh": "b64f27c473ca8f3a49190fd08c23947ab14ca9958d70b6fa53c7bddc2be91403",
|
|
14
14
|
"command-guidance.mjs": "b9b967b59ff4e77c9613abb0f28858bf3ac5b106a509e471039777b53bec3e29",
|
|
15
15
|
"abort-turn-barrier.mjs": "3734a5b7e2e940ec6d7fa8b5b04935e1429a23d1bd9e92b2ac2a2ecd9f77c75e",
|
|
@@ -25,7 +25,8 @@
|
|
|
25
25
|
"byok-detect.mjs": "f31f2ca426737581a97c391b3cecfc75f0207cfa31f51c6bf4a9148309c9625d",
|
|
26
26
|
"context-contract.mjs": "ffebb435dc5d75c289329bf16ab909df9d634a2b508154c250c6b25906a02a91",
|
|
27
27
|
"context-windows.mjs": "80af664f84d7e95ef2b0a2a3131090ac4ccd522709448ac9a0d96c378bbec0f7",
|
|
28
|
-
"claude-session.mjs": "
|
|
28
|
+
"claude-session.mjs": "c4a5908d9afe9ba0382b21fd2910c95bcbda3ba00767d3329efdd8aca61fbe3b",
|
|
29
|
+
"code-automations.mjs": "03c70058bc6d5a0b245f3fb8f5e2cb629c5ef7c1c6cd7d7fa018c40523b91036",
|
|
29
30
|
"terminal-name.mjs": "f39bb8d1e148ab9a74cbb96438d31e524d6597b8035f00d7a906c28c306c0cf8",
|
|
30
31
|
"claude-command-catalog.mjs": "36bd4342b2ae94b43a0072533ef2d1648c7473003964bbad433fdb1a8b2bfec1",
|
|
31
32
|
"codex-session.mjs": "31684859879c1d796bef4c03b0d6d52e969403b9bcae25e656a2d5e159a83b1d",
|
|
@@ -33,7 +34,7 @@
|
|
|
33
34
|
"question-response.mjs": "35a7ba53d3eb117717c18004d2a8441f8f37665b231a3c44f4bd9321ff59dd57",
|
|
34
35
|
"thinkpool-room-prompt.mjs": "b8cc82ccf4262f6431c2047bbff31ac29c47a0d6c68a64640a2c24d94df4a746",
|
|
35
36
|
"thinkpool-prompt-contracts.mjs": "051602d7d2fe9b34df92957bd3922c5eeebedbcc60c892adf415243887d8c62f",
|
|
36
|
-
"thinkpool-capabilities.json": "
|
|
37
|
+
"thinkpool-capabilities.json": "b3177f1b75383a494b9aab69d5cf1bd449648c11610376cd41f34e110d14509c",
|
|
37
38
|
"room-file-delivery.mjs": "a33300b7f12152e8d016771aabbd4616896dec4bf7a3762e059d271e107a1b6a",
|
|
38
39
|
"codex-app-server.mjs": "f032cc1f4e1ecd25d165901c0eaf7037da01f0913f08badc43711c9ec79e5467",
|
|
39
40
|
"codex-images.mjs": "31605d6d8b3dd6b73395da63d1b0c513445c95ffa2f4306ee466f201d633ffc0",
|
|
@@ -60,7 +61,7 @@
|
|
|
60
61
|
"runtime-adapter.mjs": "0500660893b12b202848b1a0da9b00ab86f6be425aa4820eb680d10537a95cba",
|
|
61
62
|
"runtime-compatibility-profile.mjs": "137730baf95d315723872e8df80e66305bccb909e3c6cb81ae753ea9adadac84",
|
|
62
63
|
"hermes-model-cache.mjs": "aee23efdebe1aa5e10053f291a9153981fe9b45065c293c9519ca73477251e72",
|
|
63
|
-
"hermes-policy.mjs": "
|
|
64
|
+
"hermes-policy.mjs": "c0ee5f5f9d2492a90dc6bb6bde1fed7f57dc9145583a4a662588ba33f7cfdb98",
|
|
64
65
|
"hermes-acp-bootstrap.py": "e2abdad97bdf06fcf5b73d3b78ba8dd2f518e307001056b029e2bf5ee1887406",
|
|
65
66
|
"hermes-event-mapper.mjs": "e7bc344d2a43100b8aef39ac969a27369cde81c9d9b64931029051d89c400b44",
|
|
66
67
|
"hermes-probe.mjs": "3fc419707f0df9342bc3a5fbfbba2ec2ba1511309dfb1ad8cc79f6f8da4e6b3d",
|
|
@@ -80,7 +81,7 @@
|
|
|
80
81
|
"runtime-session.mjs": "ff97a7a65aba31d176d1afc8d0dc9d11a217415c8b0b7660a5b33c17756576c4",
|
|
81
82
|
"turn-stall.mjs": "88c712d45974e492bfcfdbd93baa371bb8be1ddb754dacb18fae20da4dd672db",
|
|
82
83
|
"update-gate.mjs": "55e2900307677f9402b9cf0fde5371abe6458f5bb590e1f3c82555c4be42ddf2",
|
|
83
|
-
"agent-notify.mjs": "
|
|
84
|
+
"agent-notify.mjs": "8e87f448c28205382000d4ddd8e119932a80dc0e0d5b840c780718b0166461cc",
|
|
84
85
|
"agent-detect.mjs": "f38ede090e9caa8f7cde0febc41d9dc2c4301e1cd6017a07517b96364ebafb8c",
|
|
85
86
|
"code-event-contract.mjs": "75c0e0c8b6acb19cab4168a543c847ab74232d62c35f9f9a791d4268aefa72d7",
|
|
86
87
|
"evidence-compact.mjs": "f8175315f17b46a42f7b396f081374ff3d39ead94c18d64fccfa5fd02b6679f0",
|
|
@@ -88,7 +89,7 @@
|
|
|
88
89
|
"error-recovery.mjs": "0ace80add28fa72b49a3f3a716f247e3ef9816671c09749b3863867700beae32",
|
|
89
90
|
"pair-control-authority.mjs": "7a95f101153dcc6dd0633b5a01595bf2979cd0c4bf50cfc6cd44bb7612ef40a5",
|
|
90
91
|
"pair-access.mjs": "953d32528a08cde1bfeef58caafa0ce97274df8f0251d8a3be2bd190e382b5cc",
|
|
91
|
-
"scheduled-runs.mjs": "
|
|
92
|
+
"scheduled-runs.mjs": "69d61ab5eb1bc12647a35a3a231625795f6460138eff78745093c611778740d9",
|
|
92
93
|
"scheduled-run-admission.mjs": "3a2098d904c3aff571bf314e0182d5636d25d242cef52207e70f9dc1618c94f5",
|
|
93
94
|
"event-id.mjs": "09c75e7fc8da282fc00651add58e5d2f82d3020e0c4dddb9921250cf9a6fa8c0",
|
|
94
95
|
"event-bounds.mjs": "aa8eb8517c4aa81b3378f71401ed39c550cdc80e28e3a57ab46d0a5ef5c7c9c1",
|
package/scheduled-runs.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID as e}from"node:crypto";import{SPAWN as t,spawnDecision as n}from"./cross-terminal.mjs";const i=new Set(["once","daily","weekly"]),r=new Set(["claude","codex","hermes"]),o=new Set(["delivered","needs_decision","failed","canceled"]),d=new Set(["artifact","preview","commit","test","flow_task","control_item"]),a=/(?:sk-[a-z0-9_-]{8,}|gsk_[a-z0-9_-]{8,}|AIza[a-z0-9_-]{8,}|gh[pousr]_[a-z0-9]{20,}|github_pat_[a-z0-9_]{20,}|xox[baprs]-[a-z0-9-]{10,}|AKIA[0-9A-Z]{16}|sbp_[a-z0-9]{20,}|eyJ[a-z0-9_-]{16,}\.[a-z0-9_-]{16,}\.[a-z0-9_-]{8,}|bearer\s+[a-z0-9._-]{16,}|(?:token|secret|api[_-]?key|authorization)\s*=)/i,c=/(?:^|\s)(?:~\/|\/Users\/|\/home\/|\/private\/|\/tmp\/|[A-Za-z]:\\|\.\.[\\/])/i,u=/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,159}$/,l=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$/,s=new Map,_=new Set([15,30,60]);export const scheduledRunsEnabled=(e=process.env.TP_SCHEDULED_RUNS_ENABLED)=>"1"===e;export const scheduledRunsCapability=(e=process.env.TP_SCHEDULED_RUNS_ENABLED)=>Object.freeze({enabled:scheduledRunsEnabled(e)});export async function admitScheduledRunExecution({terminalId:e,localAdmission:t,memoryAdmission:n,acquireHost:i,acquireScheduled:r,releaseHost:o}={}){if("string"!=typeof e||!u.test(e))return{ok:!1,code:"terminal_id_unavailable"};if("function"!=typeof t||"function"!=typeof n||"function"!=typeof i||"function"!=typeof r||"function"!=typeof o)return{ok:!1,code:"spawn_admission_unavailable"};let d=null;try{d=await t()}catch{d=null}if(!d?.ok)return d||{ok:!1,code:"spawn_not_admitted"};let a=null;try{a=await n()}catch{a=null}if(!a?.ok)return a||{ok:!1,code:"host_memory_unavailable"};let c=null;try{c=await i()}catch{c=null}if(!c?.ok)return c||{ok:!1,code:"capacity_authority_unavailable"};let l=null;try{l=await r()}catch{l=null}if(!l?.ok||!l.lease){try{await o(e)}catch{}return l||{ok:!1,code:"scheduled_admission_unavailable"}}return{ok:!0,code:"admitted",lease:{terminalId:e,scheduled:l.lease}}}export async function releaseScheduledRunExecution(e,{releaseScheduled:t,releaseHost:n}={}){if(!e?.scheduled||"string"!=typeof e.terminalId||"function"!=typeof t||"function"!=typeof n)return{ok:!1,code:"invalid_execution_lease"};let i=null;try{i=await t(e.scheduled)}catch{i=null}try{await n(e.terminalId)}catch{}return i||{ok:!1,code:"scheduled_release_failed"}}const p=(e,t)=>"string"==typeof e&&e.trim().length>0&&e.length<=t&&!a.test(e)&&!c.test(e),m=e=>e instanceof Date?e:new Date(e),f=e=>!Number.isNaN(m(e).getTime()),h=(e,t)=>{let n=s.get(e);n||(n=new Intl.DateTimeFormat("en-CA",{timeZone:e,weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}),s.set(e,n));const i=Object.fromEntries(n.formatToParts(t).filter(e=>"literal"!==e.type).map(e=>[e.type,e.value]));return{weekday:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].indexOf(i.weekday),time:`${i.hour}:${i.minute}`}};export function scheduleValidationError(e={}){if(!e||"object"!=typeof e||!i.has(e.kind))return"invalid_kind";if(!p(e.title,120)||!p(e.prompt,12e3))return"unsafe_or_invalid_text";if(!r.has(e.runtime))return"invalid_runtime";if(!(null==e.provider||p(e.provider,80)&&u.test(e.provider)))return"invalid_provider";if(!(null==e.model||p(e.model,160)&&u.test(e.model)))return"invalid_model";if(!Number.isInteger(e.maxRuntimeMinutes)||e.maxRuntimeMinutes<1||e.maxRuntimeMinutes>30)return"invalid_max_runtime";try{new Intl.DateTimeFormat("en",{timeZone:e.timezone})}catch{return"invalid_timezone"}return"once"!==e.kind||f(e.at)?null==e.intervalMinutes||_.has(e.intervalMinutes)?"once"!==e.kind&&!/^\d{2}:\d{2}$/.test(e.time)||"once"!==e.kind&&(Number(e.time.slice(0,2))>23||Number(e.time.slice(3))>59)?"invalid_local_time":"weekly"===e.kind&&(!Number.isInteger(e.weekday)||e.weekday<0||e.weekday>6)?"invalid_weekday":null:"invalid_interval":"invalid_once_time"}export function normalizeSchedule(e={},t=new Date){const n=scheduleValidationError(e);if(n)return Object.freeze({ok:!1,code:n});const i={kind:e.kind,title:e.title.trim(),prompt:e.prompt.trim(),runtime:e.runtime,provider:e.provider||null,model:e.model||null,timezone:e.timezone,maxRuntimeMinutes:e.maxRuntimeMinutes,..."once"===e.kind?{at:m(e.at).toISOString()}:{time:e.time,..."weekly"===e.kind?{weekday:e.weekday}:{},...e.intervalMinutes?{interval_minutes:e.intervalMinutes}:{}}},r=nextScheduledAt(i,t);return r?Object.freeze({ok:!0,value:Object.freeze(i),nextRunAt:r.toISOString()}):Object.freeze({ok:!1,code:"schedule_exhausted"})}export function nextScheduledAt(e,t=new Date){if("once"===e?.kind){const n=m(e.at);return f(n)&&n.getTime()>m(t).getTime()?n:null}const n=Number(e?.interval_minutes);if(_.has(n))return new Date(m(t).getTime()+6e4*n);const i=6e4*Math.floor(m(t).getTime()/6e4)+6e4;for(let t=i,n=i+3456e7;t<n;t+=6e4){const n=h(e.timezone,new Date(t));if(n.time===e.time&&("daily"===e.kind||n.weekday===e.weekday))return new Date(t)}return null}export function classifyRunOutcome({result:e=null,evidenceRefs:t=[],pendingControls:n=[],runId:i=null,canceled:r=!1}={}){if("runtime_limit"===e?.subtype)return Object.freeze({outcome:"failed",code:"runtime_limit"});if(r||["aborted","canceled","cancelled","interrupted"].includes(e?.subtype))return Object.freeze({outcome:"canceled",code:"canceled"});const o=(Array.isArray(t)?t:[]).filter(e=>e&&d.has(e.type)&&"string"==typeof e.id&&u.test(e.id)).slice(0,16);if(o.length)return Object.freeze({outcome:"delivered",code:"evidence_delivered",evidence:o});const a=(Array.isArray(n)?n:[]).find(e=>"pending"===e?.status&&e?.id&&e?.request_context?.run_id&&(!i||e.request_context.run_id===i)&&Number.isSafeInteger(Number(e.source_event_from_seq)));return a?Object.freeze({outcome:"needs_decision",code:"pending_pair_control",controlItemId:a.id}):"success"===e?.subtype?Object.freeze({outcome:"failed",code:"missing_deliverable"}):Object.freeze({outcome:"failed",code:e?.subtype||"runtime_failed"})}export function sanitizeScheduledOutcomeIntent(e={}){const{runId:t,result:n=null,evidenceRefs:i=[],canceled:r=!1}=e&&"object"==typeof e?e:{};if("string"!=typeof t||!u.test(t))return null;const o="string"==typeof n?.subtype&&l.test(n.subtype)?n.subtype:"runtime_failed";return Object.freeze({runId:t,result:Object.freeze({subtype:o}),evidenceRefs:Object.freeze((a=i,(Array.isArray(a)?a:[]).filter(e=>e&&d.has(e.type)&&"string"==typeof e.id&&u.test(e.id)).slice(0,16).map(e=>Object.freeze({type:e.type,id:e.id})))),canceled:!0===r});var a}export function scheduledRunDeadlineRequired({runId:e,deadlineAt:t,outcomeRecorded:n=!1,outcomePending:i=null}={}){return Boolean(e&&Number.isFinite(t)&&!n&&!i)}export function scheduledOutcomeReconciliationComplete(e=[]){return Array.isArray(e)&&0===e.length}export function scheduledRunSpawnAdmission({spawnTimes:e=[],now:i=Date.now(),totalLive:r=0,disabled:o=!1}={},d=t){const a={...t,...d||{}},c=(Array.isArray(e)?e:[]).filter(e=>Number.isFinite(e)&&e>i-a.windowMs).slice(-(a.perWindowCap||1)),u=n({hop:0,spawnTimes:c,now:i,spawnedLive:0,totalLive:r,plan:"free",disabled:o},a);return Object.freeze({...u,spawnTimes:Object.freeze(u.ok?[...c,i].slice(-a.perWindowCap):c)})}export function preflightScheduledRun({schedule:e,occurrence:t,ownerId:n,bridgeId:i,bridgeFencing:r,providerAvailable:o,capsOk:d=!0,now:a=new Date}={}){return e?.enabled?t?.id&&t.schedule_revision===e.revision?!n||!i||!Number.isSafeInteger(r)||r<1||t.owner_id!==n||t.bridge_id!==i||t.bridge_fencing!==r?Object.freeze({ok:!1,code:"owner_bridge_mismatch"}):d?"function"==typeof o&&o(e)?!t.lease_expires_at||m(t.lease_expires_at).getTime()<=m(a).getTime()?Object.freeze({ok:!1,code:"lease_expired"}):Object.freeze({ok:!0,code:"admitted"}):Object.freeze({ok:!1,code:"provider_unavailable"}):Object.freeze({ok:!1,code:"runtime_cap_exceeded"}):Object.freeze({ok:!1,code:"stale_schedule_revision"}):Object.freeze({ok:!1,code:"schedule_disabled"})}const b=async({fetchImpl:e,supabaseUrl:t,headers:n,name:i,body:r})=>{const o=await e(`${String(t).replace(/\/$/,"")}/rest/v1/rpc/${i}`,{method:"POST",headers:n,body:JSON.stringify(r)});if(!o?.ok)throw new Error(`${i}_failed`);return o.json()};export async function pollDueScheduledRuns({enabled:t=!1,fetchImpl:n=globalThis.fetch,supabaseUrl:i,anonKey:r,token:o,roomCode:d,bridgeId:a,bridgeFencing:c,ownerId:l,providerAvailable:s,openTerminal:_,admitRun:p,releaseRun:f,makeTerminalId:h=e,capsOk:y=()=>!0,now:g=new Date}={}){if(!t)return Object.freeze({ok:!1,code:"feature_disabled",runs:[]});if(!("function"==typeof n&&i&&r&&o&&d&&a&&Number.isSafeInteger(c))||c<1||!l||"function"!=typeof _||"function"!=typeof p||"function"!=typeof f||"function"!=typeof h)return Object.freeze({ok:!1,code:"runner_unavailable",runs:[]});const k={apikey:r,Authorization:`Bearer ${o}`,"Content-Type":"application/json"},w=String(d).trim().toUpperCase();try{const e=await b({fetchImpl:n,supabaseUrl:i,headers:k,name:"expire_code_scheduled_runs",body:{p_room_code:w,p_bridge_id:a,p_bridge_fencing:c,p_limit:24}});if(!e?.ok)throw new Error("expire_code_scheduled_runs_failed");const t=await b({fetchImpl:n,supabaseUrl:i,headers:k,name:"list_due_code_schedules",body:{p_room_code:w,p_limit:12}}),r=[];for(const e of Array.isArray(t)?t:[]){if(String(e?.session_code||"").trim().toUpperCase()!==w){r.push({scheduleId:e?.id,code:"room_scope_mismatch"});continue}if(!y(e)){r.push({scheduleId:e.id,code:"runtime_cap_exceeded"});continue}if("function"!=typeof s||!s(e)){r.push({scheduleId:e.id,code:"provider_unavailable"});continue}const t=h();if("string"!=typeof t||!u.test(t)){r.push({scheduleId:e.id,code:"terminal_id_unavailable"});continue}const o={...e.schedule_spec||{},kind:e.schedule_kind||e.kind,timezone:e.timezone},d="once"===o.kind?new Date("9999-12-31T23:59:00.000Z"):nextScheduledAt(o,new Date(e.next_run_at));if(!d){r.push({scheduleId:e.id,code:"next_run_invalid"});continue}const v=`${e.id}:${m(e.next_run_at).toISOString()}`,I=Math.min(1860,Math.max(60,60*e.max_runtime_minutes+60)),z=m(g).getTime()+1e3*I;let x=null;try{x=await p({schedule:e,runId:v,terminalId:t,deadlineAt:z})}catch{x=null}if(!x?.ok){r.push({scheduleId:e.id,code:x?.code||"spawn_not_admitted"});continue}let O=!1;try{const o=await b({fetchImpl:n,supabaseUrl:i,headers:k,name:"claim_due_code_schedule",body:{p_schedule_id:e.id,p_expected_revision:e.revision,p_bridge_id:a,p_bridge_fencing:c,p_occurrence_key:v,p_lease_seconds:I}});if(!o?.ok||!o?.run){r.push({scheduleId:e.id,code:o?.code||"claim_failed"});continue}const u=preflightScheduledRun({schedule:e,occurrence:o.run,ownerId:l,bridgeId:a,bridgeFencing:c,providerAvailable:s,capsOk:!0,now:g});if(!u.ok){r.push({scheduleId:e.id,runId:o.run.id,code:u.code});continue}const p=await b({fetchImpl:n,supabaseUrl:i,headers:k,name:"open_code_scheduled_run",body:{p_run_id:o.run.id,p_bridge_id:a,p_bridge_fencing:c,p_terminal_id:t,p_next_run_at:d.toISOString()}});if(!p?.ok){r.push({scheduleId:e.id,runId:o.run.id,code:p?.code||"open_not_persisted"});continue}const m=p.run||o.run;let f=null;try{f=await _({schedule:e,run:m,terminalId:t,admission:x.lease})}catch{f=null}if("string"==typeof f?f:!0===f?t:!0===f?.ok&&"string"==typeof f.terminalId&&f.terminalId){O=!0,r.push({scheduleId:e.id,runId:o.run.id,code:"opened"});continue}const h=!1===f?.ok&&"string"==typeof f.code&&/^terminal_[a-z0-9_]{1,100}$/.test(f.code)?f.code:"terminal_open_failed",y=await b({fetchImpl:n,supabaseUrl:i,headers:k,name:"finish_code_scheduled_run",body:{p_run_id:o.run.id,p_bridge_id:a,p_bridge_fencing:c,p_outcome:"failed",p_outcome_code:h,p_evidence_refs:[],p_decision_item_id:null}});r.push({scheduleId:e.id,runId:o.run.id,code:y?.ok?h:y?.code||"open_failed_unrecorded"})}finally{if(!O)try{await f(x.lease)}catch{}}}return Object.freeze({ok:!0,code:"polled",runs:Object.freeze(r)})}catch{return Object.freeze({ok:!1,code:"runner_read_failed",runs:[]})}}export async function finishScheduledRun({fetchImpl:e=globalThis.fetch,supabaseUrl:t,anonKey:n,token:i,roomCode:r,runId:o,bridgeId:d,bridgeFencing:a,result:c,evidenceRefs:u,canceled:l=!1}={}){if(!(t&&n&&i&&r&&o&&d&&Number.isSafeInteger(a))||a<1)return Object.freeze({ok:!1,code:"outcome_unavailable"});const s={apikey:n,Authorization:`Bearer ${i}`,"Content-Type":"application/json"};try{const n=classifyRunOutcome({result:c,evidenceRefs:u,pendingControls:await b({fetchImpl:e,supabaseUrl:t,headers:s,name:"list_code_pair_controls",body:{p_session_code:String(r).toUpperCase(),p_status:"pending",p_limit:100}}),runId:o,canceled:l}),i=await b({fetchImpl:e,supabaseUrl:t,headers:s,name:"finish_code_scheduled_run",body:{p_run_id:o,p_outcome:n.outcome,p_outcome_code:n.code,p_bridge_id:d,p_bridge_fencing:a,p_evidence_refs:n.evidence||[],p_decision_item_id:n.controlItemId||null}});return Object.freeze({ok:Boolean(i?.ok),code:i?.code||"outcome_write_failed",outcome:n})}catch{return Object.freeze({ok:!1,code:"outcome_write_failed"})}}export async function finishScheduledRunWithRetry(e={},{attempts:t=3,delays:n=[100,400],sleep:i=e=>new Promise(t=>setTimeout(t,e))}={}){const r=Math.max(1,Math.min(5,Number.isInteger(t)?t:3));let o=Object.freeze({ok:!1,code:"outcome_write_failed"});for(let t=0;t<r;t++){if(o=await finishScheduledRun(e),o.ok)return o;t+1<r&&await i(Math.max(0,Math.min(5e3,Number(n[t]??n.at(-1)??0)||0)))}return o}export{o as OUTCOMES};
|
|
1
|
+
import{randomUUID as e}from"node:crypto";import{SPAWN as t,spawnDecision as n}from"./cross-terminal.mjs";const i=new Set(["once","daily","weekly"]),r=new Set(["claude","codex","hermes"]),o=new Set(["delivered","needs_decision","failed","canceled"]),d=new Set(["artifact","preview","commit","test","flow_task","control_item"]),a=/(?:sk-[a-z0-9_-]{8,}|gsk_[a-z0-9_-]{8,}|AIza[a-z0-9_-]{8,}|gh[pousr]_[a-z0-9]{20,}|github_pat_[a-z0-9_]{20,}|xox[baprs]-[a-z0-9-]{10,}|AKIA[0-9A-Z]{16}|sbp_[a-z0-9]{20,}|eyJ[a-z0-9_-]{16,}\.[a-z0-9_-]{16,}\.[a-z0-9_-]{8,}|bearer\s+[a-z0-9._-]{16,}|(?:token|secret|api[_-]?key|authorization)\s*=)/i,c=/(?:^|\s)(?:~\/|\/Users\/|\/home\/|\/private\/|\/tmp\/|[A-Za-z]:\\|\.\.[\\/])/i,s=/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,159}$/,u=/^[A-Za-z0-9][A-Za-z0-9._:@-]*(?:\/[A-Za-z0-9][A-Za-z0-9._:@-]*)*$/,l=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$/,p=new Map,_=new Set([15,30,60]);export const isScheduledBackgroundRuntime=e=>Boolean(e&&"string"==typeof e.scheduleRunId&&s.test(e.scheduleRunId));export const scheduledRuntimeMode=e=>r.has(e)?"bypassPermissions":"default";export function scheduledEvidenceRefs({events:e=[],previews:t=[]}={}){const n=[],i=new Set,r=(e,t)=>{if(!d.has(e)||"string"!=typeof t||!s.test(t))return;const r=`${e}:${t}`;i.has(r)||n.length>=16||(i.add(r),n.push(Object.freeze({type:e,id:t})))};for(const e of Array.isArray(t)?t:[])r("preview",e?.id);for(const t of Array.isArray(e)?e:[])for(const e of Array.isArray(t?.files)?t.files:[])r("artifact",e?.id);return Object.freeze(n)}export const scheduledRunsEnabled=(e=process.env.TP_SCHEDULED_RUNS_ENABLED)=>"1"===e;export const scheduledRunsCapability=(e=process.env.TP_SCHEDULED_RUNS_ENABLED)=>Object.freeze({enabled:scheduledRunsEnabled(e)});export async function admitScheduledRunExecution({terminalId:e,localAdmission:t,memoryAdmission:n,acquireHost:i,acquireScheduled:r,releaseHost:o}={}){if("string"!=typeof e||!s.test(e))return{ok:!1,code:"terminal_id_unavailable"};if("function"!=typeof t||"function"!=typeof n||"function"!=typeof i||"function"!=typeof r||"function"!=typeof o)return{ok:!1,code:"spawn_admission_unavailable"};let d=null;try{d=await t()}catch{d=null}if(!d?.ok)return d||{ok:!1,code:"spawn_not_admitted"};let a=null;try{a=await n()}catch{a=null}if(!a?.ok)return a||{ok:!1,code:"host_memory_unavailable"};let c=null;try{c=await i()}catch{c=null}if(!c?.ok)return c||{ok:!1,code:"capacity_authority_unavailable"};let u=null;try{u=await r()}catch{u=null}if(!u?.ok||!u.lease){try{await o(e)}catch{}return u||{ok:!1,code:"scheduled_admission_unavailable"}}return{ok:!0,code:"admitted",lease:{terminalId:e,scheduled:u.lease}}}export async function releaseScheduledRunExecution(e,{releaseScheduled:t,releaseHost:n}={}){if(!e?.scheduled||"string"!=typeof e.terminalId||"function"!=typeof t||"function"!=typeof n)return{ok:!1,code:"invalid_execution_lease"};let i=null;try{i=await t(e.scheduled)}catch{i=null}try{await n(e.terminalId)}catch{}return i||{ok:!1,code:"scheduled_release_failed"}}const f=(e,t)=>"string"==typeof e&&e.trim().length>0&&e.length<=t&&!a.test(e)&&!c.test(e),m=e=>e instanceof Date?e:new Date(e),h=e=>!Number.isNaN(m(e).getTime()),b=(e,t)=>{let n=p.get(e);n||(n=new Intl.DateTimeFormat("en-CA",{timeZone:e,weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}),p.set(e,n));const i=Object.fromEntries(n.formatToParts(t).filter(e=>"literal"!==e.type).map(e=>[e.type,e.value]));return{weekday:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].indexOf(i.weekday),time:`${i.hour}:${i.minute}`}};export function scheduleValidationError(e={}){if(!e||"object"!=typeof e||!i.has(e.kind))return"invalid_kind";if(!f(e.title,120)||!f(e.prompt,12e3))return"unsafe_or_invalid_text";if(!r.has(e.runtime))return"invalid_runtime";if(!(null==e.provider||f(e.provider,80)&&s.test(e.provider)))return"invalid_provider";if(!(null==e.model||f(e.model,160)&&u.test(e.model)))return"invalid_model";if(!Number.isInteger(e.maxRuntimeMinutes)||e.maxRuntimeMinutes<1||e.maxRuntimeMinutes>30)return"invalid_max_runtime";try{new Intl.DateTimeFormat("en",{timeZone:e.timezone})}catch{return"invalid_timezone"}return"once"!==e.kind||h(e.at)?null==e.intervalMinutes||"daily"===e.kind&&_.has(e.intervalMinutes)?"once"!==e.kind&&!/^\d{2}:\d{2}$/.test(e.time)||"once"!==e.kind&&(Number(e.time.slice(0,2))>23||Number(e.time.slice(3))>59)?"invalid_local_time":"weekly"===e.kind&&(!Number.isInteger(e.weekday)||e.weekday<0||e.weekday>6)?"invalid_weekday":null:"invalid_interval":"invalid_once_time"}export function normalizeSchedule(e={},t=new Date){const n=scheduleValidationError(e);if(n)return Object.freeze({ok:!1,code:n});const i={kind:e.kind,title:e.title.trim(),prompt:e.prompt.trim(),runtime:e.runtime,provider:e.provider||null,model:e.model||null,timezone:e.timezone,maxRuntimeMinutes:e.maxRuntimeMinutes,..."once"===e.kind?{at:m(e.at).toISOString()}:{time:e.time,..."weekly"===e.kind?{weekday:e.weekday}:{},...e.intervalMinutes?{interval_minutes:e.intervalMinutes}:{}}},r=nextScheduledAt(i,t);return r?Object.freeze({ok:!0,value:Object.freeze(i),nextRunAt:r.toISOString()}):Object.freeze({ok:!1,code:"schedule_exhausted"})}export function nextScheduledAt(e,t=new Date){if("once"===e?.kind){const n=m(e.at);return h(n)&&n.getTime()>m(t).getTime()?n:null}const n=Number(e?.interval_minutes);if(_.has(n))return new Date(m(t).getTime()+6e4*n);const i=6e4*Math.floor(m(t).getTime()/6e4)+6e4;for(let t=i,n=i+3456e7;t<n;t+=6e4){const n=b(e.timezone,new Date(t));if(n.time===e.time&&("daily"===e.kind||n.weekday===e.weekday))return new Date(t)}return null}export function classifyRunOutcome({result:e=null,evidenceRefs:t=[],pendingControls:n=[],runId:i=null,canceled:r=!1}={}){if("runtime_limit"===e?.subtype)return Object.freeze({outcome:"failed",code:"runtime_limit"});if(r||["aborted","canceled","cancelled","interrupted"].includes(e?.subtype))return Object.freeze({outcome:"canceled",code:"canceled"});const o=(Array.isArray(t)?t:[]).filter(e=>e&&d.has(e.type)&&"string"==typeof e.id&&s.test(e.id)).slice(0,16);if(o.length)return Object.freeze({outcome:"delivered",code:"evidence_delivered",evidence:o});const a=(Array.isArray(n)?n:[]).find(e=>"pending"===e?.status&&e?.id&&e?.request_context?.run_id&&(!i||e.request_context.run_id===i)&&Number.isSafeInteger(Number(e.source_event_from_seq)));return a?Object.freeze({outcome:"needs_decision",code:"pending_pair_control",controlItemId:a.id}):"success"===e?.subtype?Object.freeze({outcome:"failed",code:"missing_deliverable"}):Object.freeze({outcome:"failed",code:e?.subtype||"runtime_failed"})}export function sanitizeScheduledOutcomeIntent(e={}){const{runId:t,result:n=null,evidenceRefs:i=[],canceled:r=!1}=e&&"object"==typeof e?e:{};if("string"!=typeof t||!s.test(t))return null;const o="string"==typeof n?.subtype&&l.test(n.subtype)?n.subtype:"runtime_failed";return Object.freeze({runId:t,result:Object.freeze({subtype:o}),evidenceRefs:Object.freeze((a=i,(Array.isArray(a)?a:[]).filter(e=>e&&d.has(e.type)&&"string"==typeof e.id&&s.test(e.id)).slice(0,16).map(e=>Object.freeze({type:e.type,id:e.id})))),canceled:!0===r});var a}export function scheduledRunDeadlineRequired({runId:e,deadlineAt:t,outcomeRecorded:n=!1,outcomePending:i=null}={}){return Boolean(e&&Number.isFinite(t)&&!n&&!i)}export function scheduledOutcomeReconciliationComplete(e=[]){return Array.isArray(e)&&0===e.length}export function scheduledRunSpawnAdmission({spawnTimes:e=[],now:i=Date.now(),totalLive:r=0,disabled:o=!1}={},d=t){const a={...t,...d||{}},c=(Array.isArray(e)?e:[]).filter(e=>Number.isFinite(e)&&e>i-a.windowMs).slice(-(a.perWindowCap||1)),s=n({hop:0,spawnTimes:c,now:i,spawnedLive:0,totalLive:r,plan:"free",disabled:o},a);return Object.freeze({...s,spawnTimes:Object.freeze(s.ok?[...c,i].slice(-a.perWindowCap):c)})}export function preflightScheduledRun({schedule:e,occurrence:t,ownerId:n,bridgeId:i,bridgeFencing:r,providerAvailable:o,capsOk:d=!0,now:a=new Date}={}){return e?.enabled?t?.id&&t.schedule_revision===e.revision?!n||!i||!Number.isSafeInteger(r)||r<1||t.owner_id!==n||t.bridge_id!==i||t.bridge_fencing!==r?Object.freeze({ok:!1,code:"owner_bridge_mismatch"}):d?"function"==typeof o&&o(e)?!t.lease_expires_at||m(t.lease_expires_at).getTime()<=m(a).getTime()?Object.freeze({ok:!1,code:"lease_expired"}):Object.freeze({ok:!0,code:"admitted"}):Object.freeze({ok:!1,code:"provider_unavailable"}):Object.freeze({ok:!1,code:"runtime_cap_exceeded"}):Object.freeze({ok:!1,code:"stale_schedule_revision"}):Object.freeze({ok:!1,code:"schedule_disabled"})}const y=async({fetchImpl:e,supabaseUrl:t,headers:n,name:i,body:r})=>{const o=await e(`${String(t).replace(/\/$/,"")}/rest/v1/rpc/${i}`,{method:"POST",headers:n,body:JSON.stringify(r)});if(!o?.ok)throw new Error(`${i}_failed`);return o.json()};export async function pollDueScheduledRuns({enabled:t=!1,fetchImpl:n=globalThis.fetch,supabaseUrl:i,anonKey:r,token:o,roomCode:d,bridgeId:a,bridgeFencing:c,ownerId:u,providerAvailable:l,openTerminal:p,admitRun:_,releaseRun:f,makeTerminalId:h=e,capsOk:b=()=>!0,now:g=new Date}={}){if(!t)return Object.freeze({ok:!1,code:"feature_disabled",runs:[]});if(!("function"==typeof n&&i&&r&&o&&d&&a&&Number.isSafeInteger(c))||c<1||!u||"function"!=typeof p||"function"!=typeof _||"function"!=typeof f||"function"!=typeof h)return Object.freeze({ok:!1,code:"runner_unavailable",runs:[]});const k={apikey:r,Authorization:`Bearer ${o}`,"Content-Type":"application/json"},w=String(d).trim().toUpperCase();try{const e=await y({fetchImpl:n,supabaseUrl:i,headers:k,name:"expire_code_scheduled_runs",body:{p_room_code:w,p_bridge_id:a,p_bridge_fencing:c,p_limit:24}});if(!e?.ok)throw new Error("expire_code_scheduled_runs_failed");const t=await y({fetchImpl:n,supabaseUrl:i,headers:k,name:"list_due_code_schedules",body:{p_room_code:w,p_limit:12}}),r=[];for(const e of Array.isArray(t)?t:[]){if(String(e?.session_code||"").trim().toUpperCase()!==w){r.push({scheduleId:e?.id,code:"room_scope_mismatch"});continue}if(!b(e)){r.push({scheduleId:e.id,code:"runtime_cap_exceeded"});continue}if("function"!=typeof l||!l(e)){r.push({scheduleId:e.id,code:"provider_unavailable"});continue}const t=h();if("string"!=typeof t||!s.test(t)){r.push({scheduleId:e.id,code:"terminal_id_unavailable"});continue}const o={...e.schedule_spec||{},kind:e.schedule_kind||e.kind,timezone:e.timezone},d="once"===o.kind?new Date("9999-12-31T23:59:00.000Z"):nextScheduledAt(o,new Date(e.next_run_at));if(!d){r.push({scheduleId:e.id,code:"next_run_invalid"});continue}const v=`${e.id}:${m(e.next_run_at).toISOString()}`,I=Math.min(1860,Math.max(60,60*e.max_runtime_minutes+60)),z=m(g).getTime()+1e3*I;let x=null;try{x=await _({schedule:e,runId:v,terminalId:t,deadlineAt:z})}catch{x=null}if(!x?.ok){r.push({scheduleId:e.id,code:x?.code||"spawn_not_admitted"});continue}let O=!1;try{const o=await y({fetchImpl:n,supabaseUrl:i,headers:k,name:"claim_due_code_schedule",body:{p_schedule_id:e.id,p_expected_revision:e.revision,p_bridge_id:a,p_bridge_fencing:c,p_occurrence_key:v,p_lease_seconds:I}});if(!o?.ok||!o?.run){r.push({scheduleId:e.id,code:o?.code||"claim_failed"});continue}const s=preflightScheduledRun({schedule:e,occurrence:o.run,ownerId:u,bridgeId:a,bridgeFencing:c,providerAvailable:l,capsOk:!0,now:g});if(!s.ok){r.push({scheduleId:e.id,runId:o.run.id,code:s.code});continue}const _=await y({fetchImpl:n,supabaseUrl:i,headers:k,name:"open_code_scheduled_run",body:{p_run_id:o.run.id,p_bridge_id:a,p_bridge_fencing:c,p_terminal_id:t,p_next_run_at:d.toISOString()}});if(!_?.ok){r.push({scheduleId:e.id,runId:o.run.id,code:_?.code||"open_not_persisted"});continue}const f=_.run||o.run;let m=null;try{m=await p({schedule:e,run:f,terminalId:t,admission:x.lease})}catch{m=null}if("string"==typeof m?m:!0===m?t:!0===m?.ok&&"string"==typeof m.terminalId&&m.terminalId){O=!0,r.push({scheduleId:e.id,runId:o.run.id,code:"opened"});continue}const h=!1===m?.ok&&"string"==typeof m.code&&/^terminal_[a-z0-9_]{1,100}$/.test(m.code)?m.code:"terminal_open_failed",b=await y({fetchImpl:n,supabaseUrl:i,headers:k,name:"finish_code_scheduled_run",body:{p_run_id:o.run.id,p_bridge_id:a,p_bridge_fencing:c,p_outcome:"failed",p_outcome_code:h,p_evidence_refs:[],p_decision_item_id:null}});r.push({scheduleId:e.id,runId:o.run.id,code:b?.ok?h:b?.code||"open_failed_unrecorded"})}finally{if(!O)try{await f(x.lease)}catch{}}}return Object.freeze({ok:!0,code:"polled",runs:Object.freeze(r)})}catch{return Object.freeze({ok:!1,code:"runner_read_failed",runs:[]})}}export async function finishScheduledRun({fetchImpl:e=globalThis.fetch,supabaseUrl:t,anonKey:n,token:i,roomCode:r,runId:o,bridgeId:d,bridgeFencing:a,result:c,evidenceRefs:s,canceled:u=!1}={}){if(!(t&&n&&i&&r&&o&&d&&Number.isSafeInteger(a))||a<1)return Object.freeze({ok:!1,code:"outcome_unavailable"});const l={apikey:n,Authorization:`Bearer ${i}`,"Content-Type":"application/json"};try{const n=classifyRunOutcome({result:c,evidenceRefs:s,pendingControls:await y({fetchImpl:e,supabaseUrl:t,headers:l,name:"list_code_pair_controls",body:{p_session_code:String(r).toUpperCase(),p_status:"pending",p_limit:100}}),runId:o,canceled:u}),i=await y({fetchImpl:e,supabaseUrl:t,headers:l,name:"finish_code_scheduled_run",body:{p_run_id:o,p_outcome:n.outcome,p_outcome_code:n.code,p_bridge_id:d,p_bridge_fencing:a,p_evidence_refs:n.evidence||[],p_decision_item_id:n.controlItemId||null}});return Object.freeze({ok:Boolean(i?.ok),code:i?.code||"outcome_write_failed",outcome:n})}catch{return Object.freeze({ok:!1,code:"outcome_write_failed"})}}export async function finishScheduledRunWithRetry(e={},{attempts:t=3,delays:n=[100,400],sleep:i=e=>new Promise(t=>setTimeout(t,e))}={}){const r=Math.max(1,Math.min(5,Number.isInteger(t)?t:3));let o=Object.freeze({ok:!1,code:"outcome_write_failed"});for(let t=0;t<r;t++){if(o=await finishScheduledRun(e),o.ok)return o;t+1<r&&await i(Math.max(0,Math.min(5e3,Number(n[t]??n.at(-1)??0)||0)))}return o}export{o as OUTCOMES};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schemaVersion": 1,
|
|
3
|
-
"bundleVersion":
|
|
3
|
+
"bundleVersion": 41,
|
|
4
4
|
"contracts": [
|
|
5
5
|
{
|
|
6
6
|
"id": "room-coordination",
|
|
@@ -103,6 +103,33 @@
|
|
|
103
103
|
{"path": "bridge/hermes-policy.mjs", "pattern": "ROOM_FILE_DELIVERY_TOOL"}
|
|
104
104
|
]
|
|
105
105
|
},
|
|
106
|
+
{
|
|
107
|
+
"id": "automation-management",
|
|
108
|
+
"version": 1,
|
|
109
|
+
"routes": [
|
|
110
|
+
{
|
|
111
|
+
"id": "automation-management",
|
|
112
|
+
"tools": ["list_automations", "read_automation", "create_automation", "update_automation", "pause_automation", "resume_automation", "delete_automation"],
|
|
113
|
+
"trigger": "\\b(automation|automations|schedule|scheduled|recurring|recurrence|pause|resume)\\b|\\b(list_automations|read_automation|create_automation|update_automation|pause_automation|resume_automation|delete_automation)\\b",
|
|
114
|
+
"prompt": "When the people ask to inspect or manage Automations in this room, use list_automations first to resolve the exact target. Use read_automation before update_automation, pause_automation, resume_automation, or delete_automation so mutations act on current room-scoped state. Use create_automation only when the people asked to schedule unattended work. Mutations are side effects: Plan mode may inspect but must not mutate, and delete_automation requires an explicit request plus the exact current title. Never place credentials or host paths in Automation names or instructions. These tools manage schedules only; scheduled execution stays in the private background runtime and must not be opened or presented as a visible room terminal."
|
|
115
|
+
}
|
|
116
|
+
],
|
|
117
|
+
"impact": [
|
|
118
|
+
{"path": "bridge/code-automations.mjs"},
|
|
119
|
+
{"path": "bridge/bridge.mjs", "diffPattern": "list_automations|read_automation|create_automation|update_automation|pause_automation|resume_automation|delete_automation|automationToolsAvailable"},
|
|
120
|
+
{"path": "bridge/claude-session.mjs", "diffPattern": "AUTOMATION_"},
|
|
121
|
+
{"path": "bridge/hermes-policy.mjs", "diffPattern": "AUTOMATION_"},
|
|
122
|
+
{"path": "supabase/migrations/20260831130000_update_code_schedules.sql"}
|
|
123
|
+
],
|
|
124
|
+
"evidence": [
|
|
125
|
+
{"path": "bridge/code-automations.mjs", "pattern": "createBridgeAutomationsClient"},
|
|
126
|
+
{"path": "bridge/bridge.mjs", "pattern": "'list_automations'"},
|
|
127
|
+
{"path": "bridge/bridge.mjs", "pattern": "'delete_automation'"},
|
|
128
|
+
{"path": "bridge/claude-session.mjs", "pattern": "AUTOMATION_MUTATION_MCP_TOOLS"},
|
|
129
|
+
{"path": "bridge/hermes-policy.mjs", "pattern": "AUTOMATION_MCP_TOOLS"},
|
|
130
|
+
{"path": "supabase/migrations/20260831130000_update_code_schedules.sql", "pattern": "update_code_schedule"}
|
|
131
|
+
]
|
|
132
|
+
},
|
|
106
133
|
{
|
|
107
134
|
"id": "work-routing",
|
|
108
135
|
"version": 13,
|