@tangle-network/sandbox-cli 0.22.64 → 0.22.66

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.
Files changed (2) hide show
  1. package/dist/index.mjs +2 -2
  2. package/package.json +5 -5
package/dist/index.mjs CHANGED
@@ -123,7 +123,7 @@ await connect(new StdioServerTransport());`;case`claude-desktop`:return`// Add t
123
123
  }
124
124
  }`}}function Zr(e){return{anthropic:`Anthropic Messages API (Claude)`,openai:`OpenAI Chat Completions (function calling)`,"vercel-ai":`Vercel AI SDK (generateText / streamText)`,mastra:`Mastra agent framework`,"mcp-local":`Local MCP server bridge (stdio)`,"claude-desktop":`Claude Desktop config (uses local MCP)`,cursor:`Cursor config (uses local MCP)`,zed:`Zed config (uses local MCP)`}[e]}function Qr(){return new x(`connect`).description(`Print a copy-paste SDK integration snippet for one of: ${Yr.join(`, `)} (to stream a local agent's telemetry to Intelligence, see 'tangle connect')`).argument(`<framework>`,Yr.join(` | `)).option(`-i, --sandbox <id>`,`Sandbox ID to embed in the snippet`,`<SANDBOX_ID>`).option(`-s, --session <id>`,`Session ID to embed in the snippet`,`default`).action((e,t)=>{Yr.includes(e)||(console.error(b.red(`unknown framework: ${e}`),`\nsupported: ${Yr.join(`, `)}`),process.exit(2));let n=e;process.stdout.write(b.cyan(`# ${Zr(n)}\n\n`)),process.stdout.write(`${Xr(n,t.sandbox,t.session)}\n`)})}async function $r(e,t=!1,n){n?.throwIfAborted();let r=t?new Oe({write(e,t,n){n()}}):process.stderr,i=De({input:process.stdin,signal:n,output:r,...t?{terminal:!0}:{}});n&&i.once(`SIGINT`,()=>{process.emit(`SIGINT`),i.close()}),t&&process.stderr.write(e);try{return await new Promise(n=>{i.once(`close`,()=>n(void 0)),i.question(t?``:e,e=>{n(e.trim()),i.close()})})}finally{i.close(),t&&process.stderr.write(`
125
125
  `)}}async function ei(e){let t=await $r(e,!0);if(t===void 0)throw Error(`No answer on stdin.`);return t}async function ti(e,t){let n=await $r(e);if(n===void 0)throw process.stderr.write(`
126
- `),Error(t?`No answer on stdin. Pass ${t} to skip the confirmation.`:`No answer on stdin.`);return[`y`,`yes`].includes(n.toLowerCase())}async function ni(e,t,n){let r=await $r(`${e}${t?` [${t}]`:``}: `,!1,n);if(r===void 0)throw Error(`No answer on stdin.`);return r||t||``}async function ri(e,t=`secret`){if(process.stdin.isTTY)throw Error(e?`${e} reads ${t} from stdin, but stdin is a terminal; pipe it in`:`Cannot read ${t} from stdin when stdin is a TTY`);return(await ke(process.stdin)).toString(`utf8`).replace(/\r?\n$/,``)}function ii(){let e=new x(`profile`).description(`Create, inspect, and validate portable agent profiles`);return e.command(`create [output]`).description(`Create a profile — interactively (a wizard), or fully via flags`).option(`--name <name>`,`Profile name (when set, skips the wizard)`).option(`--description <text>`,`Profile description`).option(`--model <model>`,`Model (provider/model)`).option(`--system-prompt <text>`,`System prompt`).option(`--skills <ref...>`,`Skill refs: local path or github:<owner>/<repo>/<path>[@<ref>]`).option(`--tools <ref...>`,`Tool refs: local path or github:<owner>/<repo>/<path>[@<ref>]`).option(`--harness <name>`,`Harness hint shown in the run command`).action(async(e,t)=>{let n=t.name,r=t.description,i=t.harness,a=t.model,o=t.systemPrompt,s=t.skills??[],c=t.tools??[];if(!n&&process.stdin.isTTY&&(n=await ni(`Profile name`,`my-agent`),r=await ni(`Description (optional)`)||void 0,i=await ni(`Harness`,`claude-code`)||void 0,a=await ni(`Model (optional, provider/model)`)||void 0,o=await ni(`System prompt (optional)`)||void 0,s=await ai(`Skill ref (local path or github:..., blank to finish)`),c=await ai(`Tool ref (blank to finish)`)),!n)throw Error(process.stdin.isTTY?`Profile name is required.`:"`agent profile create` needs at least --name in a non-interactive shell (no TTY to prompt). Pass --name <name> (and optionally --model/--skills/--tools/--system-prompt).");let l=tn({model:a,systemPrompt:o,skills:s,tools:c}),u=rn({...n?{name:n}:{},...r?{description:r}:{},...l??{},...i?{harness:i}:{}},`new profile`);if(t.json){I(u);return}let d=e??`agent-profile.json`;fe(d,`${JSON.stringify(u,null,2)}\n`),R(`Wrote ${d}`),R(`Run it: tangle agent prompt <box> --profile ${d}${i?` --harness ${i}`:``}`)}),e.command(`show <source>`).description(`Load and print a profile (local path, https URL, or github:owner/repo/path[@ref])`).action(async e=>{try{I(await nn(e))}catch(e){U(e,!0)}}),e.command(`validate <source>`).description(`Validate a profile against the canonical AgentProfile schema`).action(async(e,t)=>{let n=await nn(e),r=typeof n.name==`string`?n.name:`(unnamed)`;t.json?I({ok:!0,name:r}):R(`Profile valid: "${r}"`)}),e}async function ai(e){let t=[];for(;;){let n=await ni(e);if(!n)break;t.push(n)}return t}function oi(e){return(process.env.TANGLE_SANDBOX_WEB_URL?.trim()||e).replace(/\/+$/,``)}function si(e,t){if(process.exitCode=1,e.status===`blocked_on_approval`){console.error(b.yellow(`⚠ Blocked on a hub approval.`));let t=e.approval?.approvalId;console.error(t?`Approve it: tangle hub approvals approve ${t}`:"Approve the pending request (`tangle hub approvals`), then re-run.");return}if(e.status===`awaiting_question`){console.error(b.yellow(`⚠ Agent is awaiting an answer to a question.`)),console.error(`Re-run with --interactive to answer it, or answer programmatically via box.session(<id>).answer(<questionId>, { ... }).`);return}if(e.status===`awaiting_interaction`){console.error(b.yellow(`⚠ Agent is awaiting a response.`)),console.error(`Open an interactive session, or answer the canonical interaction through the Sandbox SDK.`);return}if(e.status===`awaiting_plan_decision`){console.error(b.yellow(`⚠ Agent is awaiting a plan decision.`)),console.error(`Approve or reject the pending plan before continuing.`);return}console.error(b.red(`✗ ${e.error&&e.error.length>0?e.error:t}`))}function ci(e){let t=e.part;if(t?.type===`text`)return t.text??t.content??void 0}function li(e){return e.finalText??e.response??e.output??e.content??e.text??void 0}function ui(e){if(!e.result.success){si(e.result,`Agent run failed`);return}let t=Date.now()-e.startedAt,n=e.tokenUsage,r=[`${t}ms`,n?.inputTokens===void 0?void 0:`${n.inputTokens} in`,n?.outputTokens===void 0?void 0:`${n.outputTokens} out`].filter(e=>!!e);console.log(b.green(`✓ Done`),b.dim(`(${r.join(`, `)})`))}async function di(e,t,n=!0){let r=``,i,a=m(),o=e=>{if(e.startsWith(r)){let t=e.slice(r.length);t&&n&&process.stdout.write(t)}else n&&process.stdout.write(e);r=e};try{for await(let t of e)switch(a.observe(t),t.type){case`token`:{let e=t.data?.value;typeof e==`string`&&(n&&process.stdout.write(e),r+=e);break}case`message.part.updated`:{let e=ci(t.data);typeof e==`string`&&e.length>0&&o(e);break}case`raw`:break;case`result`:i=t.data;break}}catch(e){a.observe({type:`error`,data:{message:e instanceof Error?e.message:String(e)}})}if(r.length===0&&i){let e=li(i);typeof e==`string`&&e.length>0&&(n&&process.stdout.write(e),r=e)}return{outcome:{result:a.finish(),startedAt:t,tokenUsage:i?.tokenUsage},resultData:i,printed:r.length,...r.length>0?{response:r}:{}}}function fi(e){let t=kr(e??[]);if(t.length!==0)return{profile:{connections:t}}}function pi(e,t,n,r,i,a){let o={...r??{},harness:n,...i?{model:{...r?.model??{},default:i}}:{}},s={profile:o,requestedProfileDigest:ne(o),initialPrompt:a};return{...s,run:D({provider:`tangle-sandbox`,environmentId:e,sessionId:t,executionId:`interactive-execution-${t}`},s)}}async function mi(e){let t=kr(e.connection??[]);if(t.length===0)throw Error(`--allow-writes needs at least one --connection to grant writes for.`);if(t.some(e=>e.connectionId===`*`))throw Error("--allow-writes needs explicit --connection ids; the `*:*` wildcard can't be bulk-granted. Grant per connection, e.g. --connection conn_x:* --allow-writes.");let n=await q({hubKey:e.hubKey});for(let r of t){let t=await n.permissions.allowWrites(r.connectionId);e.json||R(`Allowed ${t.writeActions} write action${t.writeActions===1?``:`s`} for connection ${r.connectionId} (${t.granted} newly granted).`)}e.json||R(`Revert anytime: ${t.map(e=>`tangle hub permissions revert-writes --connection ${e.connectionId}`).join(` · `)}`)}async function hi(e){!e.connection||e.connection.length===0||(e.connection=await Or(e.connection,()=>q({hubKey:e.hubKey})))}async function gi(e,t){let n=process.stdin,r=process.stdout,i=null,a=!1,o=!1,s,c=new Promise(e=>{s=e}),l=()=>{try{n.setRawMode(!1)}catch{}n.pause()},u=()=>{a||(a=!0,l(),n.off(`data`,p),process.off(`SIGWINCH`,f),process.off(`SIGINT`,d),process.off(`SIGTERM`,d),process.off(`exit`,l),s())},d=e=>{(i?.close()??Promise.resolve()).finally(()=>{u(),process.exit(e===`SIGTERM`?143:130)})},f=()=>{i?.isOpen&&i.resize(r.columns||80,r.rows||24)},p=e=>{if(!i)return;let t=e.indexOf(29);if(t===-1){i.write(e);return}t>0&&i.write(e.subarray(0,t)),i.close().finally(u)};if(i=await e.attach({cols:r.columns||80,rows:r.rows||24,handlers:{onData:e=>{r.write(Buffer.from(e.buffer,e.byteOffset,e.byteLength))},onExit:e=>{o=!0;let t=e.exitCode===void 0?``:` (code ${e.exitCode})`;r.write(`\r\n[interactive session exited${t}]\r\n`),i?.close().finally(u)},onError:e=>{r.write(`\r\n[terminal stream error: ${e.message}]\r\n`)},onClose:()=>u()}}),n.setRawMode(!0),n.resume(),n.on(`data`,p),process.on(`SIGWINCH`,f),process.on(`SIGINT`,d),process.on(`SIGTERM`,d),process.on(`exit`,l),await c,console.log(),o){R(`Interactive session ended.`);return}R(`Detached — the session keeps running.`),B({"Watch & drive":t})}function _i(){let e=new x(`agent`).description(`Interact with AI agent`);return e.command(`prompt <idOrMessage> [message]`).description("Send a single prompt to the agent. With one arg it's the prompt and the box comes from `tangle use` / --box / TANGLE_SANDBOX; with two it's <id> <message>.").option(`--box <id>`,`Target sandbox (overrides the active one)`).option(`--session <id>`,`Continue existing session`).option(`--model <model>`,`Model to use`).option(`-t, --timeout <ms>`,`Timeout in milliseconds`,`300000`).option(`--stream`,`Stream response in real-time`).option(`--interactive`,`Spawn the harness's interactive TUI in the sandbox, inject this prompt, and print a link to watch + drive the live session in the browser (omit for the default headless run)`).option(`--harness <name>`,`Harness that executes this run (claude-code, codex, kimi-code, opencode, pi, amp, hermes). Defaults to the sandbox's configured backend. The box ships all harnesses, so this is a per-run choice.`).option(`--profile <source>`,`Agent profile to run: a local JSON path, an https URL, or github:<owner>/<repo>/<path>[@<ref>]`).option(`--skills <ref...>`,`Attach skills (repeatable): a local file path, or github:<owner>/<repo>/<path>[@<ref>] to pull from a repo`).option(`--tools <ref...>`,`Attach tools (repeatable): a local file path, or github:<owner>/<repo>/<path>[@<ref>]`).option(`--system-prompt <text>`,`Override the agent's system prompt for this run`).option(`--connection <spec>`,"Grant a hub connection to the agent as MCP tools (repeatable). The connection is a connection id or a provider name. Modes: <connection>:<cap1>,<cap2> (least privilege, recommended), <connection>:* (all of one connection), or *:* (all connections). List connections with `tangle hub connections`; paths with `tangle hub tools search <keyword>`.",Dr,[]).option(`--allow-writes`,"Pre-approve every WRITE action of each granted --connection so the agent can write unattended (reads are already allowed; destructive actions still prompt). Revert with `tangle hub permissions revert-writes`.").option(`--no-hub-key`,`Do not auto-mint a platform Hub key for --allow-writes; use the stored credential as-is`).action(async(e,t,n)=>{let r=t===void 0?e:t,i=t===void 0?$n(n.box):e,{context:a,client:o}=K(n),s=await on({profileSource:n.profile,systemPrompt:n.systemPrompt,skills:n.skills,tools:n.tools});await hi(n);let c=fi(n.connection);n.allowWrites&&await mi(n);let l=s||c?{...s,...c?.profile}:void 0,u=n.harness,d=l||u||n.model?{...u?{type:u}:{},...l?{profile:l}:{},...n.model?{model:{model:n.model}}:{}}:void 0,f=await J(o,a,i);if(f=await Y(f),n.interactive){let e=n.session??`int-${w()}`,t=u??(await f.backend.status()).type,o=pi(i,e,t,l,n.model,r),s=f.session(e).interactive(),c=z(`Starting interactive ${t} session...`);c.start();let d;try{d=await s.start(o)}finally{c.stop()}let p=d.ref.preparationReceipt.harness,m=d.state===`running`?d.streamUrl:void 0,h=`${oi(a.baseUrl)}/dashboard/sandbox/${encodeURIComponent(i)}?interactive=${encodeURIComponent(d.ref.run.sessionId)}`;if(n.json){I({state:d.state,sessionId:d.ref.run.sessionId,harness:p,...m?{streamUrl:m}:{},webUrl:h});return}if(R(`Interactive ${p} session ${d.state}.`),console.log(),B({...d.state===`running`?{"Watch & drive":h}:{},Session:d.ref.run.sessionId}),console.log(),d.state===`exited`){R(`The initial prompt completed with reason: ${d.reason}.`);return}R(`Open the link to watch the agent and type to take over.`),process.stdin.isTTY===!0&&process.stdout.isTTY===!0&&(console.log(),R(`Attaching to the live session — press Ctrl-] to detach.`),await gi(s,h));return}if(n.stream){n.json||(R(`Streaming response...`),console.log());let e=Date.now(),t=await di(f.streamPrompt(r,{sessionId:n.session,timeoutMs:Number.parseInt(n.timeout,10),...d?{backend:d}:{}}),e,!n.json);n.json?(I({...t.outcome.result,...t.response?{response:t.response}:{},...t.outcome.tokenUsage?{tokenUsage:t.outcome.tokenUsage}:{},durationMs:Date.now()-e}),t.outcome.result.success||(process.exitCode=1)):(t.printed>0&&console.log(),ui(t.outcome))}else{let e=z(`Processing prompt...`);e.start();let t=await f.prompt(r,{sessionId:n.session,timeoutMs:Number.parseInt(n.timeout,10),...d?{backend:d}:{}});e.stop(),n.json?(I(t),t.success===!1&&(process.exitCode=1)):t.success===!1?si(t,`Agent prompt failed`):(console.log(t.response),console.log(),B({Duration:`${t.durationMs}ms`,"Input Tokens":t.usage?.inputTokens,"Output Tokens":t.usage?.outputTokens}))}}),e.addCommand(Qr()),e.addCommand(ii()),e}async function vi(e){let t=e.timeoutMs??1e4,n=e.baseUrl.replace(/\/$/,``),a=`${n}/v1/account/me`;try{let n=await fetch(a,{headers:{Accept:`application/json`,Authorization:`Bearer ${e.apiKey}`},signal:AbortSignal.timeout(t)});if(!n.ok){let e=await bi(n);throw n.status===401||n.status===403?new r(e||`Invalid API key`):n.status>=500?new u(e||`Sandbox API returned an unexpected error`,{status:n.status}):Error(e||`Credential validation failed with status ${n.status}`)}let i=await n.json();if(!i.success||!i.data)throw Error(`Sandbox API returned an invalid account response`);return{customerId:i.data.customer_id,billingOwnerId:typeof i.data.billing_owner_id==`string`?i.data.billing_owner_id:void 0,apiKeyId:typeof i.data.api_key_id==`string`||i.data.api_key_id===null?i.data.api_key_id:void 0,billingDelegationAuthorized:typeof i.data.billing_delegation_authorized==`boolean`?i.data.billing_delegation_authorized:void 0,email:i.data.email,name:i.data.name,tier:i.data.tier,createdAt:i.data.created_at}}catch(e){throw e instanceof r||e instanceof u||e instanceof f?e:e instanceof Error&&e.name===`AbortError`?new f(`Timed out validating credentials against ${n}`,{timeoutMs:t}):e instanceof Error&&!(e instanceof TypeError)?e:new i(`Failed to reach ${n}`,{cause:yi(e)})}}function yi(e){return e instanceof Error?e:void 0}async function bi(e){let t=await e.text();if(t)try{let e=JSON.parse(t);return e.error?.message??e.message??t}catch{return t}}function xi(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`)}function Si(e){if(!wi(e.hostHeader))return{kind:`host-mismatch`};let t;try{t=new URL(e.requestUrl??`/`,`http://127.0.0.1`)}catch{return{kind:`not-found`}}if(t.pathname!==`/callback`)return{kind:`not-found`};if(t.searchParams.get(`state`)!==e.expectedState)return{kind:`state-mismatch`};let n=t.searchParams.get(`error`);if(n)return{kind:`error`,reason:n};let r=t.searchParams.get(`grant_token`);return r?{kind:`ok`,token:r}:{kind:`missing-token`}}async function Ci(e){e.signal?.throwIfAborted();let t=e.timeoutMs??12e4,n=e.baseUrl.replace(/\/$/,``),r=await import(`node:http`),i=te(32).toString(`hex`),a=null,o=null,s=new Promise((e,t)=>{a=e,o=t}),c=r.createServer((e,t)=>{try{let n=Si({hostHeader:e.headers.host,requestUrl:e.url,expectedState:i});switch(n.kind){case`host-mismatch`:t.writeHead(421,{"content-type":`text/plain; charset=utf-8`}),t.end(`Misdirected request`);return;case`not-found`:t.writeHead(404,{"content-type":`text/plain; charset=utf-8`}),t.end(`Not found`);return;case`state-mismatch`:t.writeHead(400,{"content-type":`text/html; charset=utf-8`}),t.end(Oi(`State mismatch — refusing login`)),o?.(Error(`Browser login state mismatch — refusing potentially hijacked callback`));return;case`error`:t.writeHead(400,{"content-type":`text/html; charset=utf-8`}),t.end(Oi(n.reason)),o?.(Error(`Browser login failed: ${n.reason}`));return;case`missing-token`:t.writeHead(400,{"content-type":`text/html; charset=utf-8`}),t.end(Oi(null)),o?.(Error(`Browser login did not return a grant token`));return;case`ok`:t.writeHead(200,{"content-type":`text/html; charset=utf-8`}),t.end(Oi(null)),a?.(n.token);return}}catch(e){o?.(e instanceof Error?e:Error(`Browser login callback failed`))}});await new Promise((e,t)=>{c.once(`error`,t),c.listen(0,`127.0.0.1`,()=>e())});try{let r=c.address();if(!r||typeof r==`string`)throw Error(`Failed to bind local callback server`);let a=new URL(`http://127.0.0.1:${r.port}/callback`);a.searchParams.set(`state`,i);let o=new URL(`${n}/auth/cli/login`);o.searchParams.set(`callback_url`,a.toString()),e.provider&&o.searchParams.set(`provider`,e.provider);let l=await Di(o.toString());e.onLoginUrl?.({loginUrl:o.toString(),browserOpened:l});let u=await Ei({baseUrl:n,grantToken:await Ti(s,t,e.signal),timeoutMs:t,signal:e.signal});return{apiKey:u.apiKey,email:u.email,name:u.name,tier:u.tier}}finally{e.signal?.aborted&&c.closeAllConnections(),await new Promise((e,t)=>{c.close(n=>{if(n){t(n);return}e()})}).catch(()=>void 0)}}function wi(e){if(!e)return!1;let t=e.toLowerCase().match(/^(\[[^\]]+\]|[^:]+)(?::\d+)?$/);if(!t)return!1;let n=t[1];return n===`127.0.0.1`||n===`localhost`||n===`[::1]`}async function Ti(e,t,n){let r=new AbortController;try{return await Promise.race([e,Ae(t,void 0,{signal:AbortSignal.any([r.signal,...n?[n]:[]])}).then(()=>{throw new f(`Timed out waiting for browser login to complete`,{timeoutMs:t})})])}finally{r.abort()}}async function Ei(e){let t=await fetch(`${e.baseUrl}/auth/cli/exchange`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({grant_token:e.grantToken}),signal:AbortSignal.any([AbortSignal.timeout(e.timeoutMs),...e.signal?[e.signal]:[]])}).catch(t=>{throw new i(`Failed to reach ${e.baseUrl}`,{cause:t instanceof Error?t:void 0})}),n=await t.json().catch(()=>null);if(!t.ok||!n?.success||!n.data?.api_key)throw Error(n?.error?.message||`Failed to exchange browser login grant`);return{apiKey:n.data.api_key,email:n.data.email,name:n.data.name,tier:n.data.tier}}async function Di(e){let{spawn:t}=await import(`node:child_process`),n=process.platform===`darwin`?[`open`,e]:process.platform===`win32`?[`cmd`,`/c`,`start`,``,e]:[`xdg-open`,e];return await new Promise(e=>{let r=t(n[0],n.slice(1),{detached:!0,stdio:`ignore`});r.once(`error`,()=>e(!1)),r.once(`spawn`,()=>{r.unref(),e(!0)})})}function Oi(e){return`<!doctype html>
126
+ `),Error(t?`No answer on stdin. Pass ${t} to skip the confirmation.`:`No answer on stdin.`);return[`y`,`yes`].includes(n.toLowerCase())}async function ni(e,t,n){let r=await $r(`${e}${t?` [${t}]`:``}: `,!1,n);if(r===void 0)throw Error(`No answer on stdin.`);return r||t||``}async function ri(e,t=`secret`){if(process.stdin.isTTY)throw Error(e?`${e} reads ${t} from stdin, but stdin is a terminal; pipe it in`:`Cannot read ${t} from stdin when stdin is a TTY`);return(await ke(process.stdin)).toString(`utf8`).replace(/\r?\n$/,``)}function ii(){let e=new x(`profile`).description(`Create, inspect, and validate portable agent profiles`);return e.command(`create [output]`).description(`Create a profile — interactively (a wizard), or fully via flags`).option(`--name <name>`,`Profile name (when set, skips the wizard)`).option(`--description <text>`,`Profile description`).option(`--model <model>`,`Model (provider/model)`).option(`--system-prompt <text>`,`System prompt`).option(`--skills <ref...>`,`Skill refs: local path or github:<owner>/<repo>/<path>[@<ref>]`).option(`--tools <ref...>`,`Tool refs: local path or github:<owner>/<repo>/<path>[@<ref>]`).option(`--harness <name>`,`Harness hint shown in the run command`).action(async(e,t)=>{let n=t.name,r=t.description,i=t.harness,a=t.model,o=t.systemPrompt,s=t.skills??[],c=t.tools??[];if(!n&&process.stdin.isTTY&&(n=await ni(`Profile name`,`my-agent`),r=await ni(`Description (optional)`)||void 0,i=await ni(`Harness`,`claude-code`)||void 0,a=await ni(`Model (optional, provider/model)`)||void 0,o=await ni(`System prompt (optional)`)||void 0,s=await ai(`Skill ref (local path or github:..., blank to finish)`),c=await ai(`Tool ref (blank to finish)`)),!n)throw Error(process.stdin.isTTY?`Profile name is required.`:"`agent profile create` needs at least --name in a non-interactive shell (no TTY to prompt). Pass --name <name> (and optionally --model/--skills/--tools/--system-prompt).");let l=tn({model:a,systemPrompt:o,skills:s,tools:c}),u=rn({...n?{name:n}:{},...r?{description:r}:{},...l??{},...i?{harness:i}:{}},`new profile`);if(t.json){I(u);return}let d=e??`agent-profile.json`;fe(d,`${JSON.stringify(u,null,2)}\n`),R(`Wrote ${d}`),R(`Run it: tangle agent prompt <box> --profile ${d}${i?` --harness ${i}`:``}`)}),e.command(`show <source>`).description(`Load and print a profile (local path, https URL, or github:owner/repo/path[@ref])`).action(async e=>{try{I(await nn(e))}catch(e){U(e,!0)}}),e.command(`validate <source>`).description(`Validate a profile against the canonical AgentProfile schema`).action(async(e,t)=>{let n=await nn(e),r=typeof n.name==`string`?n.name:`(unnamed)`;t.json?I({ok:!0,name:r}):R(`Profile valid: "${r}"`)}),e}async function ai(e){let t=[];for(;;){let n=await ni(e);if(!n)break;t.push(n)}return t}function oi(e){return(process.env.TANGLE_SANDBOX_WEB_URL?.trim()||e).replace(/\/+$/,``)}function si(e,t){if(process.exitCode=1,e.status===`blocked_on_approval`){console.error(b.yellow(`⚠ Blocked on a hub approval.`));let t=e.approval?.approvalId;console.error(t?`Approve it: tangle hub approvals approve ${t}`:"Approve the pending request (`tangle hub approvals`), then re-run.");return}if(e.status===`awaiting_question`){console.error(b.yellow(`⚠ Agent is awaiting an answer to a question.`)),console.error(`Re-run with --interactive to answer it, or answer programmatically via box.session(<id>).answer(<questionId>, { ... }).`);return}if(e.status===`awaiting_interaction`){console.error(b.yellow(`⚠ Agent is awaiting a response.`)),console.error(`Open an interactive session, or answer the canonical interaction through the Sandbox SDK.`);return}if(e.status===`awaiting_plan_decision`){console.error(b.yellow(`⚠ Agent is awaiting a plan decision.`)),console.error(`Approve or reject the pending plan before continuing.`);return}console.error(b.red(`✗ ${e.error&&e.error.length>0?e.error:t}`))}function ci(e){let t=e.part;if(t?.type===`text`)return t.text??t.content??void 0}function li(e){return e.finalText??e.response??e.output??e.content??e.text??void 0}function ui(e){if(!e.result.success){si(e.result,`Agent run failed`);return}let t=Date.now()-e.startedAt,n=e.tokenUsage,r=[`${t}ms`,n?.inputTokens===void 0?void 0:`${n.inputTokens} in`,n?.outputTokens===void 0?void 0:`${n.outputTokens} out`].filter(e=>!!e);console.log(b.green(`✓ Done`),b.dim(`(${r.join(`, `)})`))}async function di(e,t,n=!0){let r=``,i,a=m(),o=e=>{if(e.startsWith(r)){let t=e.slice(r.length);t&&n&&process.stdout.write(t)}else n&&process.stdout.write(e);r=e};try{for await(let t of e)switch(a.observe(t),t.type){case`token`:{let e=t.data?.value;typeof e==`string`&&(n&&process.stdout.write(e),r+=e);break}case`message.part.updated`:{let e=ci(t.data);typeof e==`string`&&e.length>0&&o(e);break}case`raw`:break;case`result`:i=t.data;break}}catch(e){a.observe({type:`error`,data:{message:e instanceof Error?e.message:String(e)}})}if(r.length===0&&i){let e=li(i);typeof e==`string`&&e.length>0&&(n&&process.stdout.write(e),r=e)}return{outcome:{result:a.finish(),startedAt:t,tokenUsage:i?.tokenUsage},resultData:i,printed:r.length,...r.length>0?{response:r}:{}}}function fi(e){let t=kr(e??[]);if(t.length!==0)return{profile:{connections:t}}}function pi(e,t,n,r,i,a){let o={...r??{},harness:n,...i?{model:{...r?.model??{},default:i}}:{}},s={profile:o,requestedProfileDigest:ne(o),initialPrompt:a};return{...s,run:D({provider:`tangle-sandbox`,environmentId:e,sessionId:t,executionId:`interactive-execution-${t}`},s)}}async function mi(e){let t=kr(e.connection??[]);if(t.length===0)throw Error(`--allow-writes needs at least one --connection to grant writes for.`);if(t.some(e=>e.connectionId===`*`))throw Error("--allow-writes needs explicit --connection ids; the `*:*` wildcard can't be bulk-granted. Grant per connection, e.g. --connection conn_x:* --allow-writes.");let n=await q({hubKey:e.hubKey});for(let r of t){let t=await n.permissions.allowWrites(r.connectionId);e.json||R(`Allowed ${t.writeActions} write action${t.writeActions===1?``:`s`} for connection ${r.connectionId} (${t.granted} newly granted).`)}e.json||R(`Revert anytime: ${t.map(e=>`tangle hub permissions revert-writes --connection ${e.connectionId}`).join(` · `)}`)}async function hi(e){!e.connection||e.connection.length===0||(e.connection=await Or(e.connection,()=>q({hubKey:e.hubKey})))}async function gi(e,t){let n=process.stdin,r=process.stdout,i=null,a=!1,o=!1,s,c=new Promise(e=>{s=e}),l=()=>{try{n.setRawMode(!1)}catch{}n.pause()},u=()=>{a||(a=!0,l(),n.off(`data`,p),process.off(`SIGWINCH`,f),process.off(`SIGINT`,d),process.off(`SIGTERM`,d),process.off(`exit`,l),s())},d=e=>{(i?.close()??Promise.resolve()).finally(()=>{u(),process.exit(e===`SIGTERM`?143:130)})},f=()=>{i?.isOpen&&i.resize(r.columns||80,r.rows||24)},p=e=>{if(!i)return;let t=e.indexOf(29);if(t===-1){i.write(e);return}t>0&&i.write(e.subarray(0,t)),i.close().finally(u)};if(i=await e.attach({cols:r.columns||80,rows:r.rows||24,handlers:{onData:e=>{r.write(Buffer.from(e.buffer,e.byteOffset,e.byteLength))},onExit:e=>{o=!0;let t=e.exitCode===void 0?``:` (code ${e.exitCode})`;r.write(`\r\n[interactive session exited${t}]\r\n`),i?.close().finally(u)},onError:e=>{r.write(`\r\n[terminal stream error: ${e.message}]\r\n`)},onClose:()=>u()}}),n.setRawMode(!0),n.resume(),n.on(`data`,p),process.on(`SIGWINCH`,f),process.on(`SIGINT`,d),process.on(`SIGTERM`,d),process.on(`exit`,l),await c,console.log(),o){R(`Interactive session ended.`);return}R(`Detached — the session keeps running.`),B({"Watch & drive":t})}function _i(){let e=new x(`agent`).description(`Interact with AI agent`);return e.command(`prompt <idOrMessage> [message]`).description("Send a single prompt to the agent. With one arg it's the prompt and the box comes from `tangle use` / --box / TANGLE_SANDBOX; with two it's <id> <message>.").option(`--box <id>`,`Target sandbox (overrides the active one)`).option(`--session <id>`,`Continue existing session`).option(`--model <model>`,`Model to use`).option(`-t, --timeout <ms>`,`Timeout in milliseconds`,`300000`).option(`--stream`,`Stream response in real-time`).option(`--interactive`,`Spawn the harness's interactive TUI in the sandbox, inject this prompt, and print a link to watch + drive the live session in the browser (omit for the default headless run)`).option(`--harness <name>`,`Harness that executes this run (claude-code, codex, kimi-code, opencode, pi, amp, hermes). Defaults to the sandbox's configured backend. The box ships all harnesses, so this is a per-run choice.`).option(`--profile <source>`,`Agent profile to run: a local JSON path, an https URL, or github:<owner>/<repo>/<path>[@<ref>]`).option(`--skills <ref...>`,`Attach skills (repeatable): a local file path, or github:<owner>/<repo>/<path>[@<ref>] to pull from a repo`).option(`--tools <ref...>`,`Attach tools (repeatable): a local file path, or github:<owner>/<repo>/<path>[@<ref>]`).option(`--system-prompt <text>`,`Override the agent's system prompt for this run`).option(`--connection <spec>`,"Grant a hub connection to the agent as MCP tools (repeatable). The connection is a connection id or a provider name. Modes: <connection>:<cap1>,<cap2> (least privilege, recommended), <connection>:* (all of one connection), or *:* (all connections). List connections with `tangle hub connections`; paths with `tangle hub tools search <keyword>`.",Dr,[]).option(`--allow-writes`,"Pre-approve every WRITE action of each granted --connection so the agent can write unattended (reads are already allowed; destructive actions still prompt). Revert with `tangle hub permissions revert-writes`.").option(`--no-hub-key`,`Do not auto-mint a platform Hub key for --allow-writes; use the stored credential as-is`).action(async(e,t,n)=>{let r=t===void 0?e:t,i=t===void 0?$n(n.box):e,{context:a,client:o}=K(n),s=await on({profileSource:n.profile,systemPrompt:n.systemPrompt,skills:n.skills,tools:n.tools});await hi(n);let c=fi(n.connection);n.allowWrites&&await mi(n);let l=s||c?{...s,...c?.profile}:void 0,u=n.harness,d=l||u||n.model?{...u?{type:u}:{},...l?{profile:l}:{},...n.model?{model:{model:n.model}}:{}}:void 0,f=await J(o,a,i);if(f=await Y(f),n.interactive){let e=n.session??`int-${w()}`,t=u??(await f.backend.status()).type,i=pi(f.id,e,t,l,n.model,r),o=f.session(e).interactive(),s=z(`Starting interactive ${t} session...`);s.start();let c;try{c=await o.start(i)}finally{s.stop()}let d=c.ref.preparationReceipt.harness,p=c.state===`running`?c.streamUrl:void 0,m=`${oi(a.baseUrl)}/dashboard/sandbox/${encodeURIComponent(f.id)}?interactive=${encodeURIComponent(c.ref.run.sessionId)}`;if(n.json){I({state:c.state,sessionId:c.ref.run.sessionId,harness:d,...p?{streamUrl:p}:{},webUrl:m});return}if(R(`Interactive ${d} session ${c.state}.`),console.log(),B({...c.state===`running`?{"Watch & drive":m}:{},Session:c.ref.run.sessionId}),console.log(),c.state===`exited`){R(`The initial prompt completed with reason: ${c.reason}.`);return}R(`Open the link to watch the agent and type to take over.`),process.stdin.isTTY===!0&&process.stdout.isTTY===!0&&(console.log(),R(`Attaching to the live session — press Ctrl-] to detach.`),await gi(o,m));return}if(n.stream){n.json||(R(`Streaming response...`),console.log());let e=Date.now(),t=await di(f.streamPrompt(r,{sessionId:n.session,timeoutMs:Number.parseInt(n.timeout,10),...d?{backend:d}:{}}),e,!n.json);n.json?(I({...t.outcome.result,...t.response?{response:t.response}:{},...t.outcome.tokenUsage?{tokenUsage:t.outcome.tokenUsage}:{},durationMs:Date.now()-e}),t.outcome.result.success||(process.exitCode=1)):(t.printed>0&&console.log(),ui(t.outcome))}else{let e=z(`Processing prompt...`);e.start();let t=await f.prompt(r,{sessionId:n.session,timeoutMs:Number.parseInt(n.timeout,10),...d?{backend:d}:{}});e.stop(),n.json?(I(t),t.success===!1&&(process.exitCode=1)):t.success===!1?si(t,`Agent prompt failed`):(console.log(t.response),console.log(),B({Duration:`${t.durationMs}ms`,"Input Tokens":t.usage?.inputTokens,"Output Tokens":t.usage?.outputTokens}))}}),e.addCommand(Qr()),e.addCommand(ii()),e}async function vi(e){let t=e.timeoutMs??1e4,n=e.baseUrl.replace(/\/$/,``),a=`${n}/v1/account/me`;try{let n=await fetch(a,{headers:{Accept:`application/json`,Authorization:`Bearer ${e.apiKey}`},signal:AbortSignal.timeout(t)});if(!n.ok){let e=await bi(n);throw n.status===401||n.status===403?new r(e||`Invalid API key`):n.status>=500?new u(e||`Sandbox API returned an unexpected error`,{status:n.status}):Error(e||`Credential validation failed with status ${n.status}`)}let i=await n.json();if(!i.success||!i.data)throw Error(`Sandbox API returned an invalid account response`);return{customerId:i.data.customer_id,billingOwnerId:typeof i.data.billing_owner_id==`string`?i.data.billing_owner_id:void 0,apiKeyId:typeof i.data.api_key_id==`string`||i.data.api_key_id===null?i.data.api_key_id:void 0,billingDelegationAuthorized:typeof i.data.billing_delegation_authorized==`boolean`?i.data.billing_delegation_authorized:void 0,email:i.data.email,name:i.data.name,tier:i.data.tier,createdAt:i.data.created_at}}catch(e){throw e instanceof r||e instanceof u||e instanceof f?e:e instanceof Error&&e.name===`AbortError`?new f(`Timed out validating credentials against ${n}`,{timeoutMs:t}):e instanceof Error&&!(e instanceof TypeError)?e:new i(`Failed to reach ${n}`,{cause:yi(e)})}}function yi(e){return e instanceof Error?e:void 0}async function bi(e){let t=await e.text();if(t)try{let e=JSON.parse(t);return e.error?.message??e.message??t}catch{return t}}function xi(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`)}function Si(e){if(!wi(e.hostHeader))return{kind:`host-mismatch`};let t;try{t=new URL(e.requestUrl??`/`,`http://127.0.0.1`)}catch{return{kind:`not-found`}}if(t.pathname!==`/callback`)return{kind:`not-found`};if(t.searchParams.get(`state`)!==e.expectedState)return{kind:`state-mismatch`};let n=t.searchParams.get(`error`);if(n)return{kind:`error`,reason:n};let r=t.searchParams.get(`grant_token`);return r?{kind:`ok`,token:r}:{kind:`missing-token`}}async function Ci(e){e.signal?.throwIfAborted();let t=e.timeoutMs??12e4,n=e.baseUrl.replace(/\/$/,``),r=await import(`node:http`),i=te(32).toString(`hex`),a=null,o=null,s=new Promise((e,t)=>{a=e,o=t}),c=r.createServer((e,t)=>{try{let n=Si({hostHeader:e.headers.host,requestUrl:e.url,expectedState:i});switch(n.kind){case`host-mismatch`:t.writeHead(421,{"content-type":`text/plain; charset=utf-8`}),t.end(`Misdirected request`);return;case`not-found`:t.writeHead(404,{"content-type":`text/plain; charset=utf-8`}),t.end(`Not found`);return;case`state-mismatch`:t.writeHead(400,{"content-type":`text/html; charset=utf-8`}),t.end(Oi(`State mismatch — refusing login`)),o?.(Error(`Browser login state mismatch — refusing potentially hijacked callback`));return;case`error`:t.writeHead(400,{"content-type":`text/html; charset=utf-8`}),t.end(Oi(n.reason)),o?.(Error(`Browser login failed: ${n.reason}`));return;case`missing-token`:t.writeHead(400,{"content-type":`text/html; charset=utf-8`}),t.end(Oi(null)),o?.(Error(`Browser login did not return a grant token`));return;case`ok`:t.writeHead(200,{"content-type":`text/html; charset=utf-8`}),t.end(Oi(null)),a?.(n.token);return}}catch(e){o?.(e instanceof Error?e:Error(`Browser login callback failed`))}});await new Promise((e,t)=>{c.once(`error`,t),c.listen(0,`127.0.0.1`,()=>e())});try{let r=c.address();if(!r||typeof r==`string`)throw Error(`Failed to bind local callback server`);let a=new URL(`http://127.0.0.1:${r.port}/callback`);a.searchParams.set(`state`,i);let o=new URL(`${n}/auth/cli/login`);o.searchParams.set(`callback_url`,a.toString()),e.provider&&o.searchParams.set(`provider`,e.provider);let l=await Di(o.toString());e.onLoginUrl?.({loginUrl:o.toString(),browserOpened:l});let u=await Ei({baseUrl:n,grantToken:await Ti(s,t,e.signal),timeoutMs:t,signal:e.signal});return{apiKey:u.apiKey,email:u.email,name:u.name,tier:u.tier}}finally{e.signal?.aborted&&c.closeAllConnections(),await new Promise((e,t)=>{c.close(n=>{if(n){t(n);return}e()})}).catch(()=>void 0)}}function wi(e){if(!e)return!1;let t=e.toLowerCase().match(/^(\[[^\]]+\]|[^:]+)(?::\d+)?$/);if(!t)return!1;let n=t[1];return n===`127.0.0.1`||n===`localhost`||n===`[::1]`}async function Ti(e,t,n){let r=new AbortController;try{return await Promise.race([e,Ae(t,void 0,{signal:AbortSignal.any([r.signal,...n?[n]:[]])}).then(()=>{throw new f(`Timed out waiting for browser login to complete`,{timeoutMs:t})})])}finally{r.abort()}}async function Ei(e){let t=await fetch(`${e.baseUrl}/auth/cli/exchange`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({grant_token:e.grantToken}),signal:AbortSignal.any([AbortSignal.timeout(e.timeoutMs),...e.signal?[e.signal]:[]])}).catch(t=>{throw new i(`Failed to reach ${e.baseUrl}`,{cause:t instanceof Error?t:void 0})}),n=await t.json().catch(()=>null);if(!t.ok||!n?.success||!n.data?.api_key)throw Error(n?.error?.message||`Failed to exchange browser login grant`);return{apiKey:n.data.api_key,email:n.data.email,name:n.data.name,tier:n.data.tier}}async function Di(e){let{spawn:t}=await import(`node:child_process`),n=process.platform===`darwin`?[`open`,e]:process.platform===`win32`?[`cmd`,`/c`,`start`,``,e]:[`xdg-open`,e];return await new Promise(e=>{let r=t(n[0],n.slice(1),{detached:!0,stdio:`ignore`});r.once(`error`,()=>e(!1)),r.once(`spawn`,()=>{r.unref(),e(!0)})})}function Oi(e){return`<!doctype html>
127
127
  <html lang="en">
128
128
  <head>
129
129
  <meta charset="utf-8" />
@@ -167,7 +167,7 @@ c=$(git -c user.name=graph-improve -c user.email=gi@local --git-dir "$g" commit-
167
167
  git init -q --bare -b main "$2.partial" && git --git-dir "$g" push -q "$2.partial" "$c:refs/heads/main"
168
168
  mv "$2.partial" "$2"`,i,a);let l=h(t.id),u=j(ee,`remotes`,`${l.upstream}.git`),{issueTitle:d,issueBodyClean:f}=l,p=`https://github.com/${l.upstream}/issues/${l.issue}`,m=JSON.stringify({title:d,body:f,url:p,state:`OPEN`}),[g,_]=[];try{await Qc(`rm -rf "$2" && git clone -q --bare "$1" "$2" && printf %s "$4" > "$2/tangle-issue-$3.json"`,a,u,`${l.issue}`,m);try{let t={param:v(l,i),json:!0,...n&&{seat:n}},a=await tu(e.file,t,{signal:r});g=`runId`in a?a.runId:void 0;let o=JSON.parse(`text`in a?a.text:`{}`);_=Object.values(o).find(e=>e?.json?.branch)?.json?.branch}catch(e){let n=e;if(n.code!==`GRAPH_RUN_FAILED`)throw e;if(e.runtimeFailures?.some(({failure:e})=>rl(e)))throw new et(t.id,{cause:e});g=n.runId}let o=j(M(),`.tangle`,`runs`,`${g}`),d=(await s(o)).map(e=>e.toolName).find(e=>/web.?(search|fetch)/i.test(e));d&&C.abort(Error(`${g} called ${d}: not offline`)),C.signal.throwIfAborted();let f=_?await Qc(`b=$(git --git-dir "$1" rev-parse main); git --git-dir "$2" diff --binary "$b" "$3"`,a,u,_):``,p=await c(o),h=p&&Kc(p).tokenUsage;return{patch:f,tokens:h?.input!=null&&h.output!=null?{inputTokens:h.input??0,outputTokens:h.output??0}:nl(e.cap),...g&&{runId:g}}}finally{let e=g&&(await uc(g)).cwd;await Ke(u,{recursive:!0,force:!0}),e?.startsWith(`${el}/`)&&await Ke(e,{recursive:!0})}},w=await o.benchmarkScenarios(S,[d]),T=new Set(w.slice(0,n.probe).map(e=>e.id)),E=n.reps??1,D=[...Array(E).keys()],O=[...T].flatMap(e=>D.flatMap(t=>b.map((n,r)=>`${r}|${e}:${t}`))),ne=new Map,re=new Map(O.map(e=>[e,new Promise(t=>ne.set(e,t))])),ie=new Map([...T].map(e=>[e,E*b.length])),ae=b.map(async(e,r)=>{let a=`${e.digest}:${n.seat.join(`,`)}`,s=j($c,`base`,Xl(`${t}:${d}:${a}`));if(d===`holdout`){await Ve(s,{recursive:!0});let e={at:new Date,reason:n.unseal,arms:l};await qe(j(s,`holdout-access.jsonl`),`${JSON.stringify(e)}\n`,{flag:`a`})}return i({scenarios:w,reps:E,runDir:s,resumable:!0,dispatchRef:a,cellFilter:e=>T.has(e.scenario.id),judges:[o.benchmarkJudge(S)],maxConcurrency:3,signal:C.signal,dispatchTimeoutMs:4*36e5,onCellSettled:async(e,{id:t,item:n})=>{e.cached&&ne.get(`${r}|${e.cellId}`)?.(),ie.set(t,(ie.get(t)??1)-1),ie.get(t)||await o.releaseCaseEnvironment(n,{host:x})},dispatch:async(t,i)=>{let a=O.indexOf(`${r}|${i.cellId}`),o=n.seat[a%n.seat.length],s=o??`graph-default`;try{await Promise.all(O.slice(0,a).map(e=>re.get(e)));let n=await i.cost.runPaidCall({actor:e.file,model:s,signal:i.signal,maximumCharge:{model:s,inputTokens:0,outputTokens:e.cap},execute:n=>te(e,t.item,{seat:o,signal:n}),receipt:({tokens:e})=>({model:s,...e}),receiptFromError:()=>({model:s,...nl(e.cap)})});if(!n.succeeded)throw n.error;return n.value}finally{ne.get(`${r}|${i.cellId}`)?.()}}})}),k=await Promise.all(ae);if(C.signal.aborted)throw C.signal.reason;let oe=e=>e.reduce((e,t)=>e+t,0)/e.length,se=k.map((e,t)=>{let n=e.cells.filter(e=>!e.error),r=e=>Object.values(e.judgeScores)[0]?.composite??0,i=n.filter(e=>e.rep===0),o=i.filter(e=>r(e)>=1).length,s=e.cells.filter(e=>e.error),{inputTokens:c,outputTokens:u,usageComplete:d}=e.aggregates.cost;return{graph:l[t],resolved:o,n:i.length,runDir:e.runDir,wilson95:a(o,i.length),unmeasured:s.map(e=>`${e.cellId}: ${e.error}`),tokens:c+u,usageComplete:d,rewards:Object.fromEntries(n.map(e=>[e.cellId,r(e)]))}}),ce=({rewards:e},t)=>D.flatMap(n=>e[`${t}:${n}`]??[]),[le,...ue]=se,de=ue.map((e,t)=>{let n=[...T].filter(t=>ce(le,t).length&&ce(e,t).length),i=[...new Set(n.map(e=>h(e).upstream))],a=i.map(e=>n.filter(t=>h(t).upstream===e)),o=e=>a.map(t=>oe(t.map(t=>oe(ce(e,t))))),[s,c]=[o(le),o(e)],u=r(s,c,{continuous:!0}),{n:d,minimumPairs:f,low:p,threshold:m}=u,g=u.promote?void 0:!u.sufficient&&`insufficient pairs: n ${d} < minimumPairs ${f}`||p<=m&&`interval low ${p} ≤ threshold ${m}`||u.exactTestVetoes&&`McNemar exact test vetoes`||`indeterminate interval`;return{arm:l[t+1],cases:n.length,repos:i.length,rates:[oe(s),oe(c)],delta:u.delta,method:u.method,interval95:[u.low,u.high],sufficient:u.sufficient,decision:u.promote?`promote`:`hold`,why:g}});I({split:n.split,arms:se,paired:de})}async function ol(e,t,n){try{let r=await tu(e,{param:t,json:!0,...n});return`runId`in r?r.runId:void 0}catch(e){if(e.code!==`GRAPH_RUN_FAILED`)throw e;return e.runId}}const sl=async(e,t)=>JSON.parse(await Qc(`cat "$(ls -t "$1"/*/"$2".json | head -1)"`,j(tl,`${e}`,`graph-evidence`),t));async function cl(e,t){let n=await uc(e),r=await We(n.file,`utf8`),i=await Qc(`cd "$1"; jq -c '{kind,reason,nodes:[.tree.nodes[]|select(.status!="done")|{label,status,failure}]}' result.json
169
169
  jq -c 'select(.valid==false)|{node:.nodeName,exit:.exitCode,tail:.output[-3000:]}' command-checks.jsonl 2>/dev/null || :
170
- for f in $(ls -tr graph-evidence/*/*.json 2>/dev/null); do printf '%s ' "$(basename "$f")"; tail -c 2000 "$f"; echo; done | tail -c 24000`,j(tl,e)),a=[`from`,`branch`,`failure`,`approved_head`],o=Object.entries(n.params).filter(([e])=>!a.includes(e)).map(([e,t])=>`${e}=${typeof t==`string`?t:JSON.stringify(t)}`),s=JSON.stringify({records:i,graph:r}),c=[...o,`from=diagnose`,`failure=${s}`],l=await ol(n.file,c,t),u=await sl(l,`diagnose`),d={run:e,diagnoseRun:l,verdict:u};if(u.owner!==`graph`||!u.patch)return I(d);let f=j($c,`repairs`,e);await Ve(f,{recursive:!0});let p=j(f,`graph.yaml`);await qe(p,r),await qe(j(f,`patch.diff`),u.patch),await Qc(`patch -s -p1 -d "$1" -i "$1/patch.diff"`,f);let m=async e=>{let t=await tu(e,{param:o,dryRun:!0});if(!(`graph`in t))throw Error(`${e} did not load locally`);let{nodes:n,deliverable:r,edges:i}=t.graph,a=e=>i.filter(t=>[t.from,t.to].flat().includes(e)),s=n.filter(e=>e.check).map(e=>[e.id,e.check,a(e.id)]);return JSON.stringify([r,s])};if(await m(n.file)!==await m(p))return I({...d,refused:`patch touches a check; not resumed`});let{branch:h,test:g}=(await sl(e,`intake`)).json??{},{from:_=`intake`,failure:v,approved_head:y}=u.resume??{},b=[`from=${_}`];_!==`intake`&&b.push(`branch=${h}`),`test`in n.params||b.push(`test=${g}`),v&&b.push(`failure=${v}`),y&&b.push(`approved_head=${y}`);let ee=await ol(p,[...o,...b],t);I({...d,patched:p,resumed:ee})}function ll(e){e.command(`repair <run>`).description(`Diagnose a failed local graph run; patch and resume it when the graph owns the fix`).option(`--seat-command <program>`,`Executable that prints the account id`).action(cl);let t=(e,t)=>[...t,e];e.command(`improve <graph> [dataset]`).description(`Measure graph arms on js-issues by offline replay`).option(`--arm <graph>`,`Another arm, interleaved; repeatable`,t,[]).option(`--split <split>`,`train, or test (needs --unseal)`,`train`).option(`--unseal <reason>`,`Read the sealed test split, logging why`).option(`--probe <n>`,`Stop after the first n cases`,Number).option(`--reps <n>`,`Reps of every case per arm (default 1)`,Number).option(`--seat <seat>`,`Replay seat; repeatable, one per replay`,t,[]).option(`--docker-host <ssh>`,`Build, verify and grade on this ssh host`).action((e,t,n)=>al(e,t??j($c,`js-issues`),n))}const ul=1e5;function Q(e){throw new V(`GRAPH_INVALID`,`Graph creation failed`,e,`tangle graph new --help`)}function dl(e){return typeof e==`string`&&/^[a-z0-9][a-z0-9-]{0,62}$/i.test(e)}const fl={maxBarren:2,failures:`verbatim`,panel:`off`,bar:`on`,profile:{id:`graph-new-v1`,opening:`The graph has not passed its outside check.`,plan:`Repair the concrete diagnostics with write_graph, run the saved file and submit the actual evidence.`,rules:`Completion requires a successful host run and unchanged YAML. Retain working graph content when blocked.`,headings:{failures:`Failures`,protected:`Passing checks`,changed:`Changes`,findings:`Findings`,bar:`Acceptance`,plan:`Next`,rules:`Rules`}}};var pl=class{owned;lastFailure;pending=Promise.resolve();revision=0;sealed=!1;constructor(e,t,n){this.directory=e,this.options=t,this.cwd=n}async digest(e=this.owned){e||Q(`No graph file was saved`);let t=await Ue(e.file,se.O_RDONLY|se.O_NOFOLLOW);try{let[n,r]=await Promise.all([t.stat(),e.handle.stat()]);return(!n.isFile()||n.dev!==r.dev||n.ino!==r.ino)&&Q(`The owned graph file was replaced`),Xl(await t.readFile())}finally{await t.close()}}enqueue(e){let t=++this.revision,n=this.pending.then(()=>e(t));return this.pending=n.then(()=>void 0,()=>void 0),n}check=()=>this.enqueue(async e=>{let t=this.owned;if(!t?.result)return!1;let{digest:n,result:r}=t,i=await this.digest(t),a=this.revision===e&&this.owned===t&&t.digest===n&&t.result===r&&i===n;return a&&(this.sealed=!0),a});receipt(){this.owned?.result||Q(`No successful graph run was recorded`);let{file:e,digest:t,result:n}=this.owned;return{file:e,digest:t,result:n}}invoke(e,t){return this.sealed&&Q(`The graph is accepted; submit its recorded successful run`),this.enqueue(()=>this.write(e,t)).catch(e=>(this.lastFailure=e,{ok:!1,diagnostic:$t(e)}))}async write(e,t){t.throwIfAborted(),this.lastFailure=void 0;let n=e;(!n||!dl(n.name)||typeof n.source!=`string`||typeof n.run!=`boolean`||Object.keys(n).some(e=>![`name`,`source`,`run`].includes(e)))&&Q(`Expected only name, source and boolean run`),this.options.name!==void 0&&n.name!==this.options.name&&Q(`The graph name must match --name`),this.owned&&(this.owned.result=void 0);let r=j(this.directory,`${n.name}.yaml`);if(this.owned&&this.owned.file!==r&&Q(`This invocation owns one named graph file`),!this.owned)try{this.owned={file:r,handle:await Ue(r,se.O_RDWR|se.O_CREAT|se.O_EXCL|se.O_NOFOLLOW,384),digest:Xl(``)}}catch(e){throw e.code===`EEXIST`&&Q(`Graph already exists: ${r}; choose another --name`),e}let i=this.owned;await this.digest()!==i.digest&&Q(`The owned graph was changed`);let a=Buffer.from(n.source);for(let e=0;e<a.length;){let{bytesWritten:t}=await i.handle.write(a,e,a.length-e,e);if(!t)throw Error(`Graph file write made no progress`);e+=t}await i.handle.truncate(a.length),await i.handle.sync(),i.digest=Xl(a);let o={...this.options,param:[]},s={cwd:this.cwd,signal:t,source:n.source},c=await tu(r,{...o,dryRun:!0},{...s,connectNeeds:!0});`graph`in c||Q(`No canonical graph was returned`),c.graph.deliverable.checkRef===`command`&&Q(`Host command checks need a jailed verifier node`);let{nodes:l,edges:u,budget:d}=c.graph,f=u.reduce((e,t)=>e+(`maxTraversals`in t?(t.maxTraversals??1)-1:0),l.length),p=(f+1)*ul;if(d?.maxTokens!==void 0&&d.maxTokens<p&&Q(`budget.maxTokens ${d.maxTokens} is below ${p}: ${f} agent spawns plus one reservation at ${ul} tokens per native turn`),await this.digest()!==i.digest&&Q(`Graph changed during validation`),!n.run)return{file:r,graphDigest:c.graph.digest,validated:!0};let m=await tu(r,o,{...s,graphDigest:c.graph.digest});return(!(`status`in m)||m.status!==`winner`||m.graphDigest!==c.graph.digest||await this.digest()!==i.digest)&&Q(`The graph must succeed with unchanged YAML`),i.result=m,this.receipt()}async close(){await this.pending,await this.owned?.handle.close()}};async function ml(e,t,n){let{runId:r,runDir:i,cwd:a,bridge:o,signal:s}=e,c=await o(),l=j(await Ge(j(M(),`.tangle`)),`graphs`);(Zl(a,l)||Zl(l,a))&&Q(`The graph store must be outside the agent workspace; choose another working directory`);try{await Ve(l,{mode:448})}catch(e){if(e.code!==`EEXIST`)throw e}await Ge(l)!==l&&Q(`The graph store redirects outside its canonical location`);let u=n.seat??Wn().seat,d=await mc(a,s)(u,{node:`graph-designer`,cwd:a,signal:s,lastCandidate:!0});d||Q(`No authenticated native subscription is available`);let{graphDesignerProfile:f}=await import(`@tangle-network/agent-runtime/profiles`),{supervisePursuit:p}=await import(`@tangle-network/agent-runtime/durable`),m=f({profile:{name:`graph-designer`,harness:d.harness,model:{provider:d.provider,default:d.model,...d.reasoningEffort===void 0?{}:{reasoningEffort:d.reasoningEffort}},prompt:{instructions:[`You are the sole graph designer. Author a canonical YAML graph for the requested intent, then qualify and run it using write_graph. Its nodes are complete AgentProfiles with a real independent verifier and declarative route/data outside check. Command checks execute on the host and are refused here; put executable verification in the verifier node's normal native tools. Read the supplied skills and preserve the user's task and authority.`,`Call write_graph with name, complete YAML source and run:false to validate; repair its concrete diagnostics, then call it with the identical source and run:true. The graph schema and executor are owned by the installed loader. Supply defaults for parameters needed by the first run. Only a real successful host run of the unchanged saved file passes. Submit that evidence using submit_result; explain concrete blockers using report_blocked.`]},tools:{agent_runtime_coordination_write_graph:!0,agent_runtime_coordination_submit_result:!0,agent_runtime_coordination_read_continuation:!0,agent_runtime_coordination_report_blocked:!0}}}),h=ne(m),g=new pl(l,{...n,seat:u},a),_={maxIterations:6,maxTokens:2e6,deadlineMs:9e5};try{let e=await p(m,{intent:t,name:n.name},{pursuitId:r,runId:r,runDir:i,signal:s,backend:{...c,timeoutMs:_.deadlineMs},budget:_,maxDepth:0,coordination:{authentication:!0,requestTimeoutMs:_.deadlineMs},deliverable:{describe:`The saved graph succeeds with unchanged YAML`,check:g.check,checkState:g.check},continuation:fl,resolveSupervisorTools:e=>e.runId!==r||e.nodeId!==r||e.depth!==0||e.identity.profileDigest!==h?[]:[{name:`write_graph`,description:`Save, validate and run this graph.`,inputSchema:{type:`object`,properties:{name:{type:`string`},source:{type:`string`},run:{type:`boolean`}},required:[`name`,`source`,`run`],additionalProperties:!1},handler:(t,n)=>((n.nodeId!==e.nodeId||n.ownerId!==e.ownerId||n.runId!==e.runId)&&Q(`Wrong graph tool owner`),g.invoke(t,n.signal))}]});if(e.result.kind===`no-winner`||!await g.check()){if(g.lastFailure)throw g.lastFailure;let t=e.result.kind===`no-winner`?e.result.error?.message??e.result.reason:`The graph file changed after its successful run`;throw Object.assign(new V(`GRAPH_DESIGN_FAILED`,`Graph design did not finish`,t,`tangle graph new --help`),{runId:r,node:`graph-designer`})}return g.receipt()}finally{await g.close()}}function hl(e){e.command(`new <intent>`).description(`Design, validate and run one portable graph`).option(`--seat <seat>`,`Use harness/model@effort for the designer and graph`).option(`--name <name>`,`Save this graph name`).action(async(e,t)=>{process.env.BRIDGE_JAIL_RW_PATHS?.trim()&&Q(`Remove BRIDGE_JAIL_RW_PATHS before graph new; extra native write roots cannot contain its host store`),t.name!==void 0&&!dl(t.name)&&Q(`Use letters, numbers and hyphens in --name`);let n=await $l({},n=>ml(n,e,t));t.json?I(n):R(`Created ${n.file} · run ${n.result.runId}`)})}const gl=e=>e===void 0?[]:(Array.isArray(e)?e:[e]).map(String),_l=(e=``)=>{let t=e.replace(/\s+/g,` `).trim(),n=t.match(/^.+?[.!?](?=\s|$)/)?.[0]??t;return n.length>90?`${n.slice(0,89)}…`:n},vl=e=>e&&(e.all??[e]).map(e=>{let t=`equals`in e?`= ${JSON.stringify(e.equals)}`:`in`in e?`∈ ${JSON.stringify(e.in)}`:e.exists===!1?`absent`:`exists`;return`${e.node??``}${e.pointer||`/`} ${t}`}).join(` and `);function yl(e,t){try{let n=rt(t,{uniqueKeys:!0,strict:!0}),r=[...n.errors,...n.warnings][0];if(r)throw r;let i=he(e)===`.json`?JSON.parse(t):n.toJS();if(Array.isArray(i?.nodes)&&Array.isArray(i.edges))return i;throw Error(`A graph needs nodes and edges lists`)}catch(t){throw new V(`GRAPH_INVALID`,`Graph file ${e} cannot be read`,t.message,`tangle graph show --help`)}}function bl(e,t){let n=yl(e,t),r=e=>{let t=String(e).match(/^\$\{params\.([\w-]+)\}$/)?.[1];return t?`${n.params?.[t]?.default??`?`} (params.${t})`:e},i=n.nodes.map(e=>{if(e.check){let t=String(e.check.command??``),n=t.match(RegExp(`#\\s*${e.id}:\\s*(.+)`))?.[1],r=t.split(`
170
+ for f in $(ls -tr graph-evidence/*/*.json 2>/dev/null); do printf '%s ' "$(basename "$f")"; tail -c 2000 "$f"; echo; done | tail -c 24000`,j(tl,e)),a=[`from`,`branch`,`failure`,`approved_head`],o=Object.entries(n.params).filter(([e])=>!a.includes(e)).map(([e,t])=>`${e}=${typeof t==`string`?t:JSON.stringify(t)}`),s=JSON.stringify({records:i,graph:r}),c=[...o,`from=diagnose`,`failure=${s}`],l=await ol(n.file,c,t),u=await sl(l,`diagnose`),d={run:e,diagnoseRun:l,verdict:u};if(u.owner!==`graph`||!u.patch)return I(d);let f=j($c,`repairs`,e);await Ve(f,{recursive:!0});let p=j(f,`graph.yaml`);await qe(p,r),await qe(j(f,`patch.diff`),u.patch),await Qc(`patch -s -p1 -d "$1" -i "$1/patch.diff"`,f);let m=async e=>{let t=await tu(e,{param:o,dryRun:!0});if(!(`graph`in t))throw Error(`${e} did not load locally`);let{nodes:n,deliverable:r,edges:i}=t.graph,a=e=>i.filter(t=>[`from`in t&&t.from,t.to].flat().includes(e)),s=n.filter(e=>e.check).map(e=>[e.id,e.check,a(e.id)]);return JSON.stringify([r,s])};if(await m(n.file)!==await m(p))return I({...d,refused:`patch touches a check; not resumed`});let{branch:h,test:g}=(await sl(e,`intake`)).json??{},{from:_=`intake`,failure:v,approved_head:y}=u.resume??{},b=[`from=${_}`];_!==`intake`&&b.push(`branch=${h}`),`test`in n.params||b.push(`test=${g}`),v&&b.push(`failure=${v}`),y&&b.push(`approved_head=${y}`);let ee=await ol(p,[...o,...b],t);I({...d,patched:p,resumed:ee})}function ll(e){e.command(`repair <run>`).description(`Diagnose a failed local graph run; patch and resume it when the graph owns the fix`).option(`--seat-command <program>`,`Executable that prints the account id`).action(cl);let t=(e,t)=>[...t,e];e.command(`improve <graph> [dataset]`).description(`Measure graph arms on js-issues by offline replay`).option(`--arm <graph>`,`Another arm, interleaved; repeatable`,t,[]).option(`--split <split>`,`train, or test (needs --unseal)`,`train`).option(`--unseal <reason>`,`Read the sealed test split, logging why`).option(`--probe <n>`,`Stop after the first n cases`,Number).option(`--reps <n>`,`Reps of every case per arm (default 1)`,Number).option(`--seat <seat>`,`Replay seat; repeatable, one per replay`,t,[]).option(`--docker-host <ssh>`,`Build, verify and grade on this ssh host`).action((e,t,n)=>al(e,t??j($c,`js-issues`),n))}const ul=1e5;function Q(e){throw new V(`GRAPH_INVALID`,`Graph creation failed`,e,`tangle graph new --help`)}function dl(e){return typeof e==`string`&&/^[a-z0-9][a-z0-9-]{0,62}$/i.test(e)}const fl={maxBarren:2,failures:`verbatim`,panel:`off`,bar:`on`,profile:{id:`graph-new-v1`,opening:`The graph has not passed its outside check.`,plan:`Repair the concrete diagnostics with write_graph, run the saved file and submit the actual evidence.`,rules:`Completion requires a successful host run and unchanged YAML. Retain working graph content when blocked.`,headings:{failures:`Failures`,protected:`Passing checks`,changed:`Changes`,findings:`Findings`,bar:`Acceptance`,plan:`Next`,rules:`Rules`}}};var pl=class{owned;lastFailure;pending=Promise.resolve();revision=0;sealed=!1;constructor(e,t,n){this.directory=e,this.options=t,this.cwd=n}async digest(e=this.owned){e||Q(`No graph file was saved`);let t=await Ue(e.file,se.O_RDONLY|se.O_NOFOLLOW);try{let[n,r]=await Promise.all([t.stat(),e.handle.stat()]);return(!n.isFile()||n.dev!==r.dev||n.ino!==r.ino)&&Q(`The owned graph file was replaced`),Xl(await t.readFile())}finally{await t.close()}}enqueue(e){let t=++this.revision,n=this.pending.then(()=>e(t));return this.pending=n.then(()=>void 0,()=>void 0),n}check=()=>this.enqueue(async e=>{let t=this.owned;if(!t?.result)return!1;let{digest:n,result:r}=t,i=await this.digest(t),a=this.revision===e&&this.owned===t&&t.digest===n&&t.result===r&&i===n;return a&&(this.sealed=!0),a});receipt(){this.owned?.result||Q(`No successful graph run was recorded`);let{file:e,digest:t,result:n}=this.owned;return{file:e,digest:t,result:n}}invoke(e,t){return this.sealed&&Q(`The graph is accepted; submit its recorded successful run`),this.enqueue(()=>this.write(e,t)).catch(e=>(this.lastFailure=e,{ok:!1,diagnostic:$t(e)}))}async write(e,t){t.throwIfAborted(),this.lastFailure=void 0;let n=e;(!n||!dl(n.name)||typeof n.source!=`string`||typeof n.run!=`boolean`||Object.keys(n).some(e=>![`name`,`source`,`run`].includes(e)))&&Q(`Expected only name, source and boolean run`),this.options.name!==void 0&&n.name!==this.options.name&&Q(`The graph name must match --name`),this.owned&&(this.owned.result=void 0);let r=j(this.directory,`${n.name}.yaml`);if(this.owned&&this.owned.file!==r&&Q(`This invocation owns one named graph file`),!this.owned)try{this.owned={file:r,handle:await Ue(r,se.O_RDWR|se.O_CREAT|se.O_EXCL|se.O_NOFOLLOW,384),digest:Xl(``)}}catch(e){throw e.code===`EEXIST`&&Q(`Graph already exists: ${r}; choose another --name`),e}let i=this.owned;await this.digest()!==i.digest&&Q(`The owned graph was changed`);let a=Buffer.from(n.source);for(let e=0;e<a.length;){let{bytesWritten:t}=await i.handle.write(a,e,a.length-e,e);if(!t)throw Error(`Graph file write made no progress`);e+=t}await i.handle.truncate(a.length),await i.handle.sync(),i.digest=Xl(a);let o={...this.options,param:[]},s={cwd:this.cwd,signal:t,source:n.source},c=await tu(r,{...o,dryRun:!0},{...s,connectNeeds:!0});`graph`in c||Q(`No canonical graph was returned`),c.graph.deliverable.checkRef===`command`&&Q(`Host command checks need a jailed verifier node`);let{nodes:l,edges:u,budget:d}=c.graph,f=u.reduce((e,t)=>e+(`maxTraversals`in t?(t.maxTraversals??1)-1:0),l.length),p=(f+1)*ul;if(d?.maxTokens!==void 0&&d.maxTokens<p&&Q(`budget.maxTokens ${d.maxTokens} is below ${p}: ${f} agent spawns plus one reservation at ${ul} tokens per native turn`),await this.digest()!==i.digest&&Q(`Graph changed during validation`),!n.run)return{file:r,graphDigest:c.graph.digest,validated:!0};let m=await tu(r,o,{...s,graphDigest:c.graph.digest});return(!(`status`in m)||m.status!==`winner`||m.graphDigest!==c.graph.digest||await this.digest()!==i.digest)&&Q(`The graph must succeed with unchanged YAML`),i.result=m,this.receipt()}async close(){await this.pending,await this.owned?.handle.close()}};async function ml(e,t,n){let{runId:r,runDir:i,cwd:a,bridge:o,signal:s}=e,c=await o(),l=j(await Ge(j(M(),`.tangle`)),`graphs`);(Zl(a,l)||Zl(l,a))&&Q(`The graph store must be outside the agent workspace; choose another working directory`);try{await Ve(l,{mode:448})}catch(e){if(e.code!==`EEXIST`)throw e}await Ge(l)!==l&&Q(`The graph store redirects outside its canonical location`);let u=n.seat??Wn().seat,d=await mc(a,s)(u,{node:`graph-designer`,cwd:a,signal:s,lastCandidate:!0});d||Q(`No authenticated native subscription is available`);let{graphDesignerProfile:f}=await import(`@tangle-network/agent-runtime/profiles`),{supervisePursuit:p}=await import(`@tangle-network/agent-runtime/durable`),m=f({profile:{name:`graph-designer`,harness:d.harness,model:{provider:d.provider,default:d.model,...d.reasoningEffort===void 0?{}:{reasoningEffort:d.reasoningEffort}},prompt:{instructions:[`You are the sole graph designer. Author a canonical YAML graph for the requested intent, then qualify and run it using write_graph. Its nodes are complete AgentProfiles with a real independent verifier and declarative route/data outside check. Command checks execute on the host and are refused here; put executable verification in the verifier node's normal native tools. Read the supplied skills and preserve the user's task and authority.`,`Call write_graph with name, complete YAML source and run:false to validate; repair its concrete diagnostics, then call it with the identical source and run:true. The graph schema and executor are owned by the installed loader. Supply defaults for parameters needed by the first run. Only a real successful host run of the unchanged saved file passes. Submit that evidence using submit_result; explain concrete blockers using report_blocked.`]},tools:{agent_runtime_coordination_write_graph:!0,agent_runtime_coordination_submit_result:!0,agent_runtime_coordination_read_continuation:!0,agent_runtime_coordination_report_blocked:!0}}}),h=ne(m),g=new pl(l,{...n,seat:u},a),_={maxIterations:6,maxTokens:2e6,deadlineMs:9e5};try{let e=await p(m,{intent:t,name:n.name},{pursuitId:r,runId:r,runDir:i,signal:s,backend:{...c,timeoutMs:_.deadlineMs},budget:_,maxDepth:0,coordination:{authentication:!0,requestTimeoutMs:_.deadlineMs},deliverable:{describe:`The saved graph succeeds with unchanged YAML`,check:g.check,checkState:g.check},continuation:fl,resolveSupervisorTools:e=>e.runId!==r||e.nodeId!==r||e.depth!==0||e.identity.profileDigest!==h?[]:[{name:`write_graph`,description:`Save, validate and run this graph.`,inputSchema:{type:`object`,properties:{name:{type:`string`},source:{type:`string`},run:{type:`boolean`}},required:[`name`,`source`,`run`],additionalProperties:!1},handler:(t,n)=>((n.nodeId!==e.nodeId||n.ownerId!==e.ownerId||n.runId!==e.runId)&&Q(`Wrong graph tool owner`),g.invoke(t,n.signal))}]});if(e.result.kind===`no-winner`||!await g.check()){if(g.lastFailure)throw g.lastFailure;let t=e.result.kind===`no-winner`?e.result.error?.message??e.result.reason:`The graph file changed after its successful run`;throw Object.assign(new V(`GRAPH_DESIGN_FAILED`,`Graph design did not finish`,t,`tangle graph new --help`),{runId:r,node:`graph-designer`})}return g.receipt()}finally{await g.close()}}function hl(e){e.command(`new <intent>`).description(`Design, validate and run one portable graph`).option(`--seat <seat>`,`Use harness/model@effort for the designer and graph`).option(`--name <name>`,`Save this graph name`).action(async(e,t)=>{process.env.BRIDGE_JAIL_RW_PATHS?.trim()&&Q(`Remove BRIDGE_JAIL_RW_PATHS before graph new; extra native write roots cannot contain its host store`),t.name!==void 0&&!dl(t.name)&&Q(`Use letters, numbers and hyphens in --name`);let n=await $l({},n=>ml(n,e,t));t.json?I(n):R(`Created ${n.file} · run ${n.result.runId}`)})}const gl=e=>e===void 0?[]:(Array.isArray(e)?e:[e]).map(String),_l=(e=``)=>{let t=e.replace(/\s+/g,` `).trim(),n=t.match(/^.+?[.!?](?=\s|$)/)?.[0]??t;return n.length>90?`${n.slice(0,89)}…`:n},vl=e=>e&&(e.all??[e]).map(e=>{let t=`equals`in e?`= ${JSON.stringify(e.equals)}`:`in`in e?`∈ ${JSON.stringify(e.in)}`:e.exists===!1?`absent`:`exists`;return`${e.node??``}${e.pointer||`/`} ${t}`}).join(` and `);function yl(e,t){try{let n=rt(t,{uniqueKeys:!0,strict:!0}),r=[...n.errors,...n.warnings][0];if(r)throw r;let i=he(e)===`.json`?JSON.parse(t):n.toJS();if(Array.isArray(i?.nodes)&&Array.isArray(i.edges))return i;throw Error(`A graph needs nodes and edges lists`)}catch(t){throw new V(`GRAPH_INVALID`,`Graph file ${e} cannot be read`,t.message,`tangle graph show --help`)}}function bl(e,t){let n=yl(e,t),r=e=>{let t=String(e).match(/^\$\{params\.([\w-]+)\}$/)?.[1];return t?`${n.params?.[t]?.default??`?`} (params.${t})`:e},i=n.nodes.map(e=>{if(e.check){let t=String(e.check.command??``),n=t.match(RegExp(`#\\s*${e.id}:\\s*(.+)`))?.[1],r=t.split(`
171
171
  `).find(e=>e.trim()&&!/^\s*#/.test(e));return{id:e.id,kind:`check`,detail:_l(n??`$ ${r}`)}}let t=[e.profile?.harness,e.profile?.model?.default],n=gl(e.seat).join(` › `)||t.filter(Boolean).join(` · `),r=_l(e.profile?.prompt?.systemPrompt),i=[n||`default seat`,r].filter(Boolean).join(`
172
172
  `);return{id:e.id,kind:`agent`,detail:i}});for(let e of n.gates??[]){let t=gl(e.choices).join(` | `);i.push({id:e.id,kind:`gate`,detail:`${t}\n${e.question}`})}let a=gl(n.entry?.map(e=>e.node??e)),o=[];if(a.length){i.unshift({id:`start`,kind:`start`,detail:``});let e=a.length>1?`fork`:``;o.push({from:[`start`],to:a,label:e,loop:!1})}for(let e of n.edges){let t=e.to?.finish===void 0?`stop`:`finish`,a=e.to?.[t]===void 0?void 0:`${t}:${e.to[t]}`,s=a===void 0?gl(e.to??e.join):[a];a&&!i.some(e=>e.id===a)&&i.push({id:a,kind:t,detail:``});let c=gl(e.kind===`analyzes`?e.over:e.from),l=n.edges.some(t=>!e.when&&t.when&&gl(t.from).join()===c.join()),u=e.maxTraversals!==void 0,d=[vl(e.when)??(l?`otherwise`:e.kind?.replace(`routes`,``)),c.length>1&&`join`,s.length>1&&`fork`,u&&`↺ loop ≤${r(e.maxTraversals)}`];o.push({from:c,to:s,label:d.filter(Boolean).join(` · `),loop:u})}let s=n.check??{},c=[[`params`,Object.entries(n.params??{}).map(([e,t])=>`${e}${`default`in t?`=${JSON.stringify(t.default)}`:` (required)`}`).join(`, `)],[`workspace`,n.workspace],[`done when`,s.command?.command??s.command??vl(s.all||s.pointer?s:void 0)],[``,s.describe]];return{name:n.graph??e.replace(/^.*\/|(\.graph)?\.(ya?ml|json)$/g,``),describe:n.describe?.trim(),facts:c.filter(e=>e[1]),nodes:i,edges:o}}const xl={start:[`▶`,b.green],agent:[`●`,b.cyan.bold],check:[`▣`,b.yellow.bold],gate:[`◇`,b.magenta.bold],finish:[`✓`,b.green.bold],stop:[`■`,b.red.bold]};function Sl(e){let t=t=>e.nodes.find(e=>e.id===t)?.kind??`agent`,n=e=>{let[n,r]=xl[t(e)];return r(`${n} ${e.replace(/^(finish|stop):/,``)}`)},r=Math.max(...e.nodes.map(e=>e.id.length))+4,i=[`${b.bold(`◆ ${e.name}`)}`,...e.describe?[` ${e.describe}`]:[],``];for(let[t,n]of e.facts)i.push(` ${b.dim(t.padEnd(10))} ${n}`);i.push(``,b.bold(`NODES`));for(let t of e.nodes.filter(e=>[`agent`,`check`,`gate`].includes(e.kind))){let[e,...a]=t.detail.split(`
173
173
  `);i.push(` ${n(t.id)}${` `.repeat(Math.max(1,r-t.id.length))}${e}`);for(let e of a)i.push(`${` `.repeat(r+4)}${b.dim(e)}`)}i.push(``,b.bold(`FLOW`));for(let t of e.edges){let e=` ${t.from.map(n).join(b.dim(` + `))} ${b.dim(`─▶`)} ${t.to.map(n).join(b.dim(` ∥ `))}`,r=t.loop?b.magenta(t.label):b.blue(t.label);i.push(...t.label.length+Ze(e).length>100?[e,` ${r}`]:[`${e} ${r}`])}return i.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/sandbox-cli",
3
- "version": "0.22.64",
3
+ "version": "0.22.66",
4
4
  "description": "CLI for Tangle Sandbox operations",
5
5
  "type": "module",
6
6
  "engines": {
@@ -59,8 +59,8 @@
59
59
  "tsx": "^4.23.15",
60
60
  "typescript": "^6.0.3",
61
61
  "vitest": "^4.1.12",
62
- "@tangle-network/runtime-contracts": "0.20.0",
63
- "@repo/shared": "0.0.0"
62
+ "@repo/shared": "0.0.0",
63
+ "@tangle-network/runtime-contracts": "0.20.0"
64
64
  },
65
65
  "publishConfig": {
66
66
  "access": "public",
@@ -80,8 +80,8 @@
80
80
  "author": "Tangle Network",
81
81
  "license": "MIT",
82
82
  "tangleRelease": {
83
- "sourceSha": "81a0c995dde38991bf60d3912d3c465c11ae132d",
84
- "mergedAt": "2026-11-09T08:32:22-08:00"
83
+ "sourceSha": "448896de9dea9fa33bf7b528793ba580b07bbb96",
84
+ "mergedAt": "2026-11-09T08:36:15-08:00"
85
85
  },
86
86
  "scripts": {
87
87
  "build": "tsdown",