@tangle-network/sandbox-cli 0.23.191 → 0.23.193

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/README.md CHANGED
@@ -702,6 +702,7 @@ Backend IDs must be unique and use 1 to 128 letters, numbers, dots, underscores,
702
702
  Use `--model provider/model` only when one backend is selected.
703
703
  Each result is identified by both `taskId` and `backendId`.
704
704
  JSON output reports `totalTasks`, `totalBackends`, `totalExecutions`, `totalSuccess`, `totalFailure`, `totalRetries`, and `successRate`.
705
+ Use `--runtime docker|firecracker` to choose the isolation for every batch sandbox; omit it for the platform default. A named runtime never falls back to the other runtime.
705
706
 
706
707
  Use `--request <file.json>` when each backend needs its own model, profile, server, or lifecycle configuration.
707
708
  The file uses the same complete request shape as the TypeScript SDK and cannot be combined with inline task or backend flags.
package/dist/index.mjs CHANGED
@@ -135,7 +135,7 @@ await connect(new StdioServerTransport());`;case`claude-desktop`:return`// Add t
135
135
  <body>
136
136
  <p>${e?`Sandbox CLI login failed: ${Ir(e)}`:`Sandbox CLI login complete. You can close this window.`}</p>
137
137
  </body>
138
- </html>`}const Kr=15*6e4,qr=`sandbox`;function Jr(e){return Number.isFinite(e)&&e>0?e:Kr}async function Yr(e){let t=e.timeoutMs??Kr,n=Date.now(),r=await Xr({baseUrl:e.baseUrl,app:e.app??qr,timeoutMs:t,provider:e.provider});for(e.onInstructions?.({userCode:r.user_code,verificationUrl:r.verification_uri,verificationUrlComplete:r.verification_uri_complete,expiresIn:r.expires_in,intervalSeconds:r.interval});;){if(Date.now()-n>t)throw new me(`Timed out waiting for device authorization to complete`,{timeoutMs:t});let i=await Zr({baseUrl:e.baseUrl,app:e.app??qr,deviceCode:r.device_code,timeoutMs:t});if(i.status===`approved`)return i.data;let a=i.intervalSeconds*1e3;await new Promise(e=>setTimeout(e,a))}}async function Xr(e){let t=Jr(e.timeoutMs),n=e.app!==qr,r=await fetch(`${Qr(e.baseUrl)}${n?`/cross-site/device/start`:`/auth/cli/device/start`}`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify(n?{app:e.app,...e.provider?{provider:e.provider}:{}}:e.provider?{provider:e.provider}:{}),signal:AbortSignal.timeout(t)}).catch(t=>{throw new w(`Failed to reach ${e.baseUrl}`,{cause:t instanceof Error?t:void 0})}),i=await r.json().catch(()=>null);if(!r.ok||!i?.success||!i.data?.device_code)throw Error(i?.error?.message||`Failed to start device login`);return i.data}async function Zr(e){let t=Jr(e.timeoutMs),n=e.app!==qr,r=await fetch(`${Qr(e.baseUrl)}${n?`/cross-site/device/poll`:`/auth/cli/device/poll`}`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify(n?{app:e.app,device_code:e.deviceCode}:{device_code:e.deviceCode}),signal:AbortSignal.timeout(t)}).catch(t=>{throw new w(`Failed to reach ${e.baseUrl}`,{cause:t instanceof Error?t:void 0})}),i=await r.json().catch(()=>null);if(r.status===428&&i?.error?.code===`AUTHORIZATION_PENDING`)return{status:`pending`,intervalSeconds:typeof i.data?.interval==`number`&&i.data.interval>0?i.data.interval:5};if(!r.ok||!i?.success||!i.data?.api_key||!i.data.email)throw Error(i?.error?.message||`Failed to complete device authorization`);return{status:`approved`,data:{apiKey:i.data.api_key,email:i.data.email,name:i.data.name,tier:i.data.tier}}}function Qr(e){return e.replace(/\/$/,``)}async function $r(e){let t=e.apiKey,n=si(e.app??`sandbox`),i=ci(n,e.profile),a=oi(e.provider),o=n===`solve`?_n(e.baseUrl):ln(e.baseUrl,i),c=e.browser!==!1,u=(t,a)=>{ri({profile:i,apiKey:t,baseUrl:(n===`solve`?e.baseUrl:un(e.baseUrl))?o:void 0,platformUrl:hn()??``,activate:n===`sandbox`}),En(),r(`Authenticated`),s({Profile:i,Email:a.email,Tier:a.tier,"Base URL":o}),l(ii),n===`sandbox`&&l(`Next: tangle agent prompt "<task>"`)};if(t&&!Ht(t)){d(`Invalid API key format. Keys should start with 'sk_' or 'sk-tan-'.`),process.exit(1);return}if(g(),!t){let t=c&&n===`sandbox`,r=f(t?`Starting browser login...`:`Starting device login...`);r.start();let i;try{i=t?await Br({baseUrl:o,provider:a,signal:e.signal,onLoginUrl:({loginUrl:e,browserOpened:t})=>{r.stop(),l(t?`Browser login opened.`:`Open this URL to continue browser login:`),console.log(e)}}):await Yr({baseUrl:o,app:n,provider:a,onInstructions:({userCode:e,verificationUrl:t,verificationUrlComplete:i})=>{r.stop(),l(`Complete login in a browser on any device:`),s({"Verification URL":t,"Verification URL (prefilled)":i,"Device Code":e}),n===`solve`&&c&&Wr(i)}})}finally{r.stop()}u(i.apiKey,i);return}let p=f(`Validating credentials...`);p.start();let m=await Nr({apiKey:t,baseUrl:o});p.stop(),u(t,m)}function ei(){let t=new D(`auth`).description(`Manage authentication`);return t.command(`login`).description(`Authenticate with browser login, device code, or an API key`).option(`--no-browser`,`Use device-code login instead of opening a browser`).option(`--profile <name>`,`Profile name`).option(`--provider <provider>`,`Identity provider (github, google, microsoft)`).option(`--app <app>`,`Product to authorize (sandbox or solve)`,`sandbox`).action($r),t.command(`logout`).description(`Remove stored credentials`).option(`--profile <name>`,`Profile name`).option(`--app <app>`,`Product credentials to remove (sandbox or solve)`,`sandbox`).action(e=>{let t=ci(si(e.app),e.profile);$t(t),En(),r(`Logged out successfully.`),l(`Credentials removed for profile '${t}'.`)}),t.command(`status`).description(`Show current authentication status`).option(`--profile <name>`,`Profile name`).option(`--app <app>`,`Product credentials to check (sandbox or solve)`,`sandbox`).action(async t=>{let n=si(t.app),i=ci(n,t.profile),a=n===`solve`?on(t.apiKey,i):nn(t.apiKey,i,t.baseUrl),o=n===`solve`?_n(t.baseUrl):ln(t.baseUrl,i),u=n===`solve`?cn(t.apiKey,i):sn(t.apiKey,i);if(!a){if(t.json){e({authenticated:!1,reason:`missing_credentials`,profile:i,baseUrl:o,credentialSource:null});return}d(`Not authenticated`),l(`Run 'tangle auth login --profile ${i}' to authenticate.`),process.exit(1)}let p=t.json?null:f(`Checking credentials...`);p?.start();try{let d=await Nr({apiKey:a,baseUrl:o}),f=n===`solve`?null:await Xn({...t.apiKey===void 0?{}:{apiKey:t.apiKey},...t.profile===void 0?{}:{profile:t.profile},sandboxBaseUrl:o});p?.stop();let m=f!==null&&!f.reachable&&f.refused,h=!m,g=f!==null&&!f.reachable&&!f.refused;if(t.json){e({authenticated:h,profile:i,baseUrl:o,credentialSource:u,account:d,...f?{sandbox:{authenticated:!0},platform:f}:{}}),h||process.exit(1);return}m?c(`Authenticated for sandbox only`):g?c(`Authenticated — the platform is unreachable right now`):r(`Authenticated`),s({Profile:i,Credentials:`configured`,"Base URL":o,Source:ni(u),Email:d.email,Tier:d.tier,...f?{Platform:f.reachable?`reachable (${f.baseUrl})`:`UNREACHABLE — ${f.reason}`}:{}}),g&&l(`Platform commands (keys, workflows, hub) will not work until the platform answers again. The stored credential is not the cause and does not need replacing.`),h||(l("Platform commands (keys, workflows, hub) will not work until this resolves. Set TANGLE_API_KEY to a key you minted in the console, or run `tangle auth login` again."),process.exit(1))}catch(n){p?.stop(),t.json&&(e({authenticated:!1,profile:i,baseUrl:o,credentialSource:u,error:n instanceof Error?n.message:String(n)}),process.exit(1)),n instanceof C?d(`Stored credentials are invalid.`):c(`Stored credentials found, but validation could not complete.`),s({Profile:i,Credentials:`configured`,"Base URL":o,Source:ni(u),Error:n instanceof Error?n.message:String(n)}),process.exit(1)}}),t.addCommand(ti()),t}function ti(){let t=new D(`profiles`).description(`Manage CLI profiles`);return t.command(`list`).description(`List configured profiles`).action(t=>{let n=Xt();if(t.json){e(n);return}if(n.length===0){l(`No profiles found.`);return}i([`Profile`,`Active`,`Base URL`,`Credentials`,`Source`],n.map(e=>[e.name,e.active?`yes`:`no`,e.baseUrl,e.hasApiKey?`configured`:`none`,e.apiKeySource]))}),t.command(`use <name>`).description(`Set the active profile`).action(e=>{Wt(e);let t=Zt(e);r(`Active profile set to '${t.name}'.`),s({"Base URL":t.baseUrl,Credentials:t.credentialSource===`none`?`missing`:`configured`})}),t.command(`current`).description(`Show the active profile`).action(t=>{let n=Zt();if(t.json){e({name:n.name,active:n.active,baseUrl:n.baseUrl,credentialSource:n.credentialSource});return}s({Profile:n.name,"Base URL":n.baseUrl,Credentials:n.credentialSource===`none`?`missing`:`configured`,Source:ni(n.credentialSource)})}),t}function ni(e){switch(e){case`flag`:return`command flag`;case`env`:return`environment`;case`keychain`:return`OS keychain`;case`file`:return`credentials file`;default:return`unknown`}}function ri(e){let t=Qt(e.profile,{apiKey:e.apiKey,...e.baseUrl?{baseUrl:e.baseUrl}:{},...e.platformUrl===void 0?{}:{platformUrl:e.platformUrl}});e.activate!==!1&&Wt(e.profile),Ut(e.baseUrl&&e.profile===`default`?{baseUrl:e.baseUrl}:{}),ii=ai(e.profile,t)}let ii=`Credentials updated.`;function ai(e,t){return t===`keychain`?e===`default`?`API key saved to the OS keychain for the default profile`:`API key saved to the OS keychain for profile '${e}'`:t===`file`?e===`default`?`API key saved to ~/.tangle/credentials.json for the default profile`:`API key saved to ~/.tangle/credentials.json for profile '${e}'`:`Profile '${e}' updated.`}function oi(e){if(e===void 0||e===`github`||e===`google`||e===`microsoft`)return e;throw Error(`--provider must be one of: github, google, microsoft`)}function si(e){if(e===void 0||e===`sandbox`||e===`solve`)return e??`sandbox`;throw Error(`--app must be one of: sandbox, solve`)}function ci(e,t){return zt(e,t)}function li(e){if(e.status===`stopped`)throw new A(`INVALID_STATE`,`Sandbox ${e.id} is stopped, so its backend is not running`,"The next `tangle agent` or `tangle exec` command resumes it",`tangle sandbox resume ${e.id}`)}function ui(){let n=new D(`backend`).description(`Manage sandbox AI agent backend`);return n.command(`status <sandboxId-or-name>`).description(`Get the harness type the sandbox runs`).action(async(t,n)=>{let{context:r,client:i}=z(n),a=f(`Fetching backend status...`);a.start();let o=await U(i,r,t);li(o);let s=await o.backend.status();a.stop(),n.json?e(s):l(`Backend Type: ${s.type}`)}),n.command(`configure <sandboxId-or-name>`).description(`Update backend configuration; resumes a stopped sandbox`).option(`--model <model>`,`Model id (e.g. provider/model)`).action(async(t,n)=>{let{context:i,client:a}=z(n),o=f(`Updating backend config...`);o.start();let s=await W(await U(a,i,t)),c=n.model?{model:n.model}:{};await s.backend.updateConfig(c),o.stop(),r(`Backend configuration updated`),n.json&&e(c)}),n.command(`mcp-status <sandboxId-or-name>`).description(`Get status of MCP servers`).action(async(n,r)=>{let{context:i,client:a}=z(r),o=f(`Fetching MCP status...`);o.start();let s=await U(a,i,n);li(s);let c=await s.backend.getMcpStatus();if(o.stop(),r.json)e(c);else{let e=Object.entries(c);e.length===0?l(`No MCP servers configured`):t(e.map(([e,t])=>{let n=t;return{name:e,status:n.status,error:n.error??``}}),[{key:`name`,header:`Name`,width:24},{key:`status`,header:`Status`,width:12},{key:`error`,header:`Error`,width:40}])}}),n}function di(e){let t=e.indexOf(`=`);if(t<=0)throw Error(`Invalid --task "${e}": expected format id=message (e.g. t1=summarize README)`);let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();if(!n||!r)throw Error(`Invalid --task "${e}": id and message must be non-empty`);return{id:n,message:r}}function fi(e){let t;try{t=JSON.parse(e)}catch(e){throw Error(`--tasks file is not valid JSON: ${e.message}`)}let n=Array.isArray(t)?t:t?.tasks;if(!Array.isArray(n))throw Error(`--tasks file must contain an array or an object with a "tasks" array`);return n.map((e,t)=>{if(!e||typeof e!=`object`)throw Error(`--tasks[${t}] must be an object`);let n=e,r=typeof n.id==`string`?n.id.trim():``,i=typeof n.message==`string`?n.message:``;if(!r)throw Error(`--tasks[${t}].id must be a non-empty string`);if(!i.trim())throw Error(`--tasks[${t}].message must be a non-empty string`);let a={id:r,message:i};if(n.context!==void 0&&(typeof n.context!=`object`||n.context===null||Array.isArray(n.context)))throw Error(`--tasks[${t}].context must be a JSON object`);if(n.context!==void 0&&(a.context=n.context),n.timeoutMs!==void 0&&(!Number.isInteger(n.timeoutMs)||n.timeoutMs<=0))throw Error(`--tasks[${t}].timeoutMs must be a positive integer`);return n.timeoutMs!==void 0&&(a.timeoutMs=n.timeoutMs),a})}function pi(e){let t=e.readFile??(e=>x(e,`utf8`)),n=[];e.file&&n.push(...fi(t(e.file)));for(let t of e.inline??[])n.push(di(t));if(n.length===0)throw Error(`No tasks provided. Use --tasks <file> and/or --task id=message.`);let r=new Set;for(let e of n){if(r.has(e.id))throw Error(`Duplicate task id: ${e.id}`);r.add(e.id)}return n}const mi=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function hi(e){let t=e.trim(),n=t.indexOf(`/`);if(n<=0||n===t.length-1)throw Error(`--model must be in the form provider/model (got "${e}")`);return{provider:t.slice(0,n),model:t.slice(n+1)}}function gi(e){let t=e.indexOf(`=`);if(t<=0||t===e.length-1)throw Error(`Invalid --backend "${e}": expected format id=type (e.g. primary=opencode)`);let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();if(!mi.test(n))throw Error(`Invalid backend id "${n}": use 1-128 letters, numbers, dots, underscores, or hyphens, starting with a letter or number`);if(!r||r.includes(`=`))throw Error(`Invalid --backend "${e}": type must be a non-empty backend name`);return{id:n,type:r}}function _i(e,t){if(!e||e.length===0)throw Error(`No backends provided. Use --backend id=type or --request <file>.`);let n=e.map(gi),r=new Set;for(let e of n){if(r.has(e.id))throw Error(`Duplicate backend id: ${e.id}`);r.add(e.id)}if(t&&n.length!==1)throw Error(`--model requires exactly one backend; use a profile to configure models for multiple backends`);return t&&(n[0]={...n[0],model:hi(t)}),n}function vi(e){let t;try{t=JSON.parse(e)}catch(e){throw Error(`--request file is not valid JSON: ${e.message}`)}try{return xe(t)}catch(e){throw Error(`--request file is not a valid batch request: ${e.message}`)}}function yi(e,t,n){return n?`${e} [${t}]`:e}function bi(e){let t=new Map;for(let n of e)t.set(n.taskId,(t.get(n.taskId)??0)+1);return new Set([...t.entries()].filter(([,e])=>e>1).map(([e])=>e))}function xi(){let t=new D(`batch`).description(`Run multiple agent tasks in parallel across sandboxes`);return t.command(`run`).description(`Execute a batch of tasks. Provide tasks via --tasks <file.json> and/or repeated --task id=message flags.`).option(`--tasks <file>`,`Path to a JSON file with an array of tasks (or {tasks: [...]})`).option(`--request <file>`,`Path to a complete batch request JSON file`).option(`--task <id=message>`,`Inline task, id=message. Repeatable.`,(e,t=[])=>[...t,e],[]).option(`--stream`,`Stream per-task events as they arrive`).option(`-t, --timeout <ms>`,`Per-task timeout in milliseconds`,`300000`).option(`--persistent`,`Keep sandboxes alive after completion`,!1).option(`--reuse-key <key>`,`Stable workspace identity required by --persistent`).option(`--replay-only`,`Rejoin existing keyed work; refuse missing custody`).option(`--idempotency-key <key>`,`Retry identity; keyed runs continue after disconnect`).option(`--backend <id=type>`,`Backend identity and type. Required and repeatable without --request.`,(e,t=[])=>[...t,e],[]).option(`--model <provider/model>`,`Model override when exactly one backend is selected`).action(async(t,n)=>{let r=new AbortController,i=!1,a=()=>{i||(i=!0,l(`Cancel requested — stopping stream...`),r.abort())};process.on(`SIGINT`,a),process.on(`SIGTERM`,a);try{let i;if(t.request){let e=[`tasks`,`task`,`backend`,`model`,`timeout`,`persistent`,`reuseKey`].filter(e=>n.getOptionValueSource(e)===`cli`);if(e.length>0){let t={reuseKey:`reuse-key`};throw Error(`--request cannot be combined with ${e.map(e=>`--${t[e]??e}`).join(`, `)}`)}i=vi(x(t.request,`utf8`))}else{let e=pi({file:t.tasks,inline:t.task}),n=_i(t.backend,t.model),r=Number(t.timeout);if(!Number.isInteger(r)||r<=0)throw Error(`--timeout must be a positive integer number of milliseconds`);let a=!!t.persistent;if(a&&!t.reuseKey)throw Error(`--persistent requires --reuse-key`);if(!a&&t.reuseKey)throw Error(`--reuse-key requires --persistent`);i=xe({tasks:e,timeoutMs:r,backends:n,...a?{persistent:!0,reuseKey:t.reuseKey}:{persistent:!1}})}let{tasks:a,backends:o}=i,{client:c}=z(t),u={signal:r.signal,replayOnly:!!t.replayOnly,...t.idempotencyKey?{idempotencyKey:t.idempotencyKey}:{}},d;if(t.stream){let e=t.json?console.error:console.log;l(`Streaming batch of ${a.length} task(s)...`),e();let n=c.streamBatch(i,u),r=o.length>1;for(;;){let t=await n.next();if(t.done){d=t.value;break}let i=t.value;switch(i.type){case`batch.started`:{let e=i.data;l(`Batch started (${e.taskCount} tasks, ${e.backendCount} backends)`);break}case`task.started`:{let t=i.data;e(T.dim(`→ ${yi(t.taskId,t.backendId,r)} started`));break}case`task.retry`:{let t=i.data;e(T.yellow(`↻ ${yi(t.taskId,t.backendId,r)} retry ${t.attempt}: ${t.error}`));break}case`task.completed`:{let t=i.data;e(T.green(`✓ ${yi(t.taskId,t.backendId,r)} completed in ${t.durationMs}ms`+(t.retries?` (${t.retries} retries)`:``)));break}case`task.failed`:{let t=i.data;e(T.red(`✗ ${yi(t.taskId,t.backendId,r)} failed: ${t.error}`));break}}}e()}else l(`Running batch of ${a.length} task(s)...`),d=await c.runBatch(i,u),t.json||console.log();if(t.json)e(d);else if(s({"Total tasks":d.totalTasks,"Total backends":d.totalBackends,"Total executions":d.totalExecutions,Succeeded:d.totalSuccess,Failed:d.totalFailure,"Total retries":d.totalRetries,"Success rate":`${d.successRate.toFixed(1)}%`}),!t.stream&&d.results.length>0){let e=bi(d.results);console.log(),console.log(T.bold(`Task Results`)),console.log(T.dim(`─`.repeat(40)));for(let t of d.results){let n=t.success?T.green(`✓`):T.red(`✗`),r=t.success?t.usage.inputTokens+t.usage.outputTokens:0,i=r>0?` • ${r} tokens`:``;console.log(`${n} ${yi(t.taskId,t.backendId,e.has(t.taskId))} ${T.dim(`(${t.durationMs}ms, ${t.retries} retries${i})`)}`),t.success||console.log(T.red(` ${t.error}`))}}d.totalFailure>0&&(process.exitCode=1)}catch(n){let r=n instanceof Error&&`batchCustody`in n?n.batchCustody:void 0;if(r?.acceptance===`accepted`&&!(r.cleanup?.mode===`release`&&r.cleanup.isComplete)&&l(`Batch accepted; retirement receipt unproved.`),i){console.log(),l(`Batch cancelled.`),t.json&&n instanceof Error&&`batchCustody`in n&&e({ok:!1,batchCustody:n.batchCustody}),process.exitCode=130;return}N(n,t.json)}finally{process.off(`SIGINT`,a),process.off(`SIGTERM`,a)}}),t}function Si(){let n=new D(`branch`).description(`Branch a running sandbox into copy-on-write children`);return n.command(`create <sandbox-id-or-name>`).description(`Branch a running sandbox into N copy-on-write children`).option(`--count <n>`,`Number of children to create`,`1`).option(`--idempotency-key <key>`,`Retry identity: the same key and count replays the first fan-out and creates no second one`).action(async(n,i)=>{let a=Number.parseInt(i.count,10);if(!Number.isInteger(a)||a<1)throw Error(`--count must be an integer >= 1 (got ${i.count})`);let{context:o,client:s}=z(i),u=f(`Branching into ${a} child(ren)...`);u.start();let d=await U(s,o,n),p=await d.fork(a,{...i.idempotencyKey?{idempotencyKey:i.idempotencyKey}:{}}),m=p.children;u.stop(),i.json?e({children:m.map(e=>({sandboxId:e.id})),requestedCount:p.requestedCount,materializedCount:p.materializedCount,complete:p.complete,...p.idempotency?{idempotency:p.idempotency}:{}}):(p.complete?r(`Branched ${m.length} child(ren) from ${d.id}`):c(`Branched ${p.materializedCount} of ${p.requestedCount} requested child(ren) from ${d.id}`),p.idempotency?.outcome===`replayed`&&l(`Replayed an earlier fan-out under this key; created none.`),t(m.map(e=>({sandboxId:e.id})),[{key:`sandboxId`,header:`Child Sandbox`,width:28}]))}),n}const Ci=[`codex`,`claude-code`,`nanoclaw`,`kimi-code`,`opencode`,`pi`,`openclaw`,`hermes`],wi=`https://intelligence.tangle.tools/v1/otlp`,Ti=[`codex`,`claude-code`],Ei=[`codex`,`claude-code`,`nanoclaw`],Di=[`SessionStart`,`UserPromptSubmit`,`PreToolUse`,`PostToolUse`,`Stop`],Oi={codex:{kind:`native`,surface:`codex`,label:`Codex`,buildFiles:Vi},"claude-code":{kind:`native`,surface:`claude-code`,label:`Claude Code`,buildFiles:Hi},nanoclaw:{kind:`native`,surface:`nanoclaw`,label:`NanoClaw`,buildFiles:Hi},"kimi-code":{kind:`manual`,surface:`kimi-code`,label:`Kimi Code`,reason:`Kimi Code loads hooks through an explicit config file, so use standard OTLP env wiring until the native config adapter is verified.`},opencode:{kind:`manual`,surface:`opencode`,label:`OpenCode`,reason:`OpenCode hooks run as plugins; use standard OTLP env wiring until the native plugin adapter is verified.`},pi:{kind:`manual`,surface:`pi`,label:`Pi`,reason:`Pi hooks run through TypeScript extensions; use standard OTLP env wiring until the native extension adapter is verified.`},openclaw:{kind:`manual`,surface:`openclaw`,label:`OpenClaw`,reason:`OpenClaw project hooks require user opt-in; use standard OTLP env wiring until the hook toggle and adapter are verified.`},hermes:{kind:`manual`,surface:`hermes`,label:`Hermes`,reason:`Hermes project plugins require explicit enablement; use standard OTLP env wiring until the plugin adapter is verified.`}};function ki(e){let t=e.split(`,`).map(e=>e.trim()).filter(Boolean).flatMap(e=>Bi(e));return t.length===0?[...Ti]:ta(t)}function Ai(e){return Object.hasOwn(Oi,e)}function ji(e=process.cwd()){return Ce(Ee(e))||`agent-workspace`}function Mi(){return E(He(),`.tangle`,`intelligence.json`)}function Ni(e=Mi()){if(!y(e))return null;let t=Qi(e),n=na(t,`apiKey`),r=na(t,`endpoint`),i=na(t,`serviceName`),a=na(t,`environment`);if(!n||!r||!i||!a)throw Error(`${e} is missing apiKey, endpoint, serviceName, or environment`);return{apiKey:n,endpoint:r,serviceName:i,environment:a}}async function Pi(e){let t=Ee(e.workspace),n=Mi(),r=ki(e.selection),i=[],a=[],o=[],s={apiKey:e.apiKey,endpoint:q(e.endpoint),serviceName:e.serviceName,environment:e.environment};e.dryRun||Yi(n,s),o.push(n);for(let n of r){let r=Oi[n];if(r.kind===`manual`){a.push({agent:r.surface,label:r.label,reason:r.reason});continue}i.push(r.surface);let s=t=>Fi(e.hookCommand,r.surface,t);for(let n of r.buildFiles(s)){let r=E(t,n.relPath);if(e.dryRun){o.push(r);continue}Zi(r,JSON.parse(n.content),n.mode),o.push(r)}}return!e.smoke||e.dryRun?{configPath:n,written:o,agents:r,nativeAgents:i,manual:a}:{configPath:n,written:o,agents:r,nativeAgents:i,manual:a,smokeTraceId:await Li({agent:i[0]??r[0]??`codex`,event:`install.smoke`,endpoint:s.endpoint,apiKey:s.apiKey,serviceName:s.serviceName,environment:s.environment,sessionId:`install-smoke-${Date.now()}`,payload:{source:`tangle intelligence connect`}})}}function Fi(e,t,n){return`${e.trim()} --agent ${t} --event ${n} --non-blocking`}function Ii(e){let t=BigInt(Date.now())*1000000n,n=ia(16),r=ia(8),i=e.sessionId??Ui(e.payload),a={"service.name":e.serviceName,"deployment.environment":e.environment,"tangle.agent.surface":e.agent,"tangle.agent.hook.event":e.event,"tangle.agent.hook.source":`local-hook`,...Wi(e.payload)};return i&&(a[`session.id`]=i,a[`gen_ai.conversation.id`]=i,a[`tangle.sessionId`]=i),{body:{resourceSpans:[{resource:{attributes:[aa(`service.name`,e.serviceName),aa(`deployment.environment`,e.environment),aa(`tangle.agent.surface`,e.agent)]},scopeSpans:[{scope:{name:`tangle.intelligence.agent-hook`,version:`1.0.0`},spans:[{traceId:n,spanId:r,name:`agent.${e.agent}.${e.event}`,kind:1,startTimeUnixNano:t.toString(),endTimeUnixNano:(t+1000000n).toString(),attributes:Object.entries(a).map(([e,t])=>aa(e,t)),status:{code:1}}]}]}]},traceId:n}}async function Li(e){let{body:t,traceId:n}=Ii(e),r=await fetch(`${q(e.endpoint)}/v1/traces`,{method:`POST`,headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":`application/json`},body:JSON.stringify(t)});if(!r.ok){let e=await r.text().catch(()=>``);throw Error(`OTLP smoke ingest failed: ${r.status}${e?` ${e}`:``}`)}return n}function Ri(e){return q(e).replace(/\/v1\/otlp$/,``).replace(/\/+$/,``)}async function zi(e){let t=`${Ri(e.endpoint)}/v1/onboarding/status`,n=await fetch(t,{headers:{Authorization:`Bearer ${e.apiKey}`},signal:e.timeoutMs&&e.timeoutMs>0?AbortSignal.timeout(e.timeoutMs):void 0});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`onboarding status request failed: ${n.status}${e?` ${e}`:``}`)}let r=await n.json();return{tracesSeen:!!r.tracesSeen,contentSeen:!!r.contentSeen,lastSeenAt:typeof r.lastSeenAt==`string`?r.lastSeenAt:null,windowDays:typeof r.windowDays==`number`?r.windowDays:7,byAgent:r.byAgent&&typeof r.byAgent==`object`?r.byAgent:{}}}function q(e){let t=e.trim().replace(/\/+$/,``);return t.endsWith(`/v1/traces`)?t.slice(0,-10):t.endsWith(`/v1/logs`)?t.slice(0,-8):t}function Bi(e){switch(e){case`local`:case`both`:return[...Ti];case`all`:return[...Ei];case`claude`:return[`claude-code`];case`kimi`:return[`kimi-code`];default:if(Ai(e))return[e];throw Error(`agent must be one of: local, all, both, ${Ci.join(`, `)}`)}}function Vi(e){let t=Object.fromEntries(Di.map(t=>[t,[{command:e(t),timeoutMs:3e3,blocking:!1,matcher:`*`}]]));return[{relPath:`.codex/hooks.json`,content:JSON.stringify({hooks:t},null,2)}]}function Hi(e){let t=Object.fromEntries(Di.map(t=>[t,[{matcher:`*`,hooks:[{type:`command`,command:e(t),timeout:3}]}]]));return[{relPath:`.claude/settings.json`,content:JSON.stringify({hooks:t},null,2)}]}function Ui(e){return Ki(e,[`session.id`,`sessionId`,`session_id`,`conversationId`,`conversation_id`,`threadId`,`thread_id`,`transcriptId`,`transcript_id`])||process.env.TANGLE_SESSION_ID||process.env.CODEX_THREAD_ID||process.env.CLAUDE_SESSION_ID||process.env.OPENCODE_SESSION_ID}function Wi(e){let t={},n=Gi(e,[`tool.name`,`toolName`,`tool_name`,`tool`]),r=Gi(e,[`command`,`cmd`,`shell_command`,`shellCommand`]),i=Gi(e,[`tool.input`,`toolInput`,`tool_input`,`input`,`arguments`,`args`]),a=Gi(e,[`tool.output`,`toolOutput`,`tool_output`,`output`,`result`]),o=Gi(e,[`tool.exit_code`,`exitCode`,`exit_code`,`status`]),s=Gi(e,[`tool.error.message`,`errorMessage`,`error_message`,`error`]);return n&&(t[`tool.name`]=n),r&&(t[`process.command`]=r),i&&(t[`tool.input.summary`]=i),a&&(t[`tool.output.summary`]=a),o&&(t[`tool.exit_code`]=o),s&&(t[`tool.error.message`]=s),t}function Gi(e,t){let n=qi(e,t);if(n===void 0)return null;if(typeof n==`string`)return Ji(n);if(typeof n==`number`||typeof n==`boolean`||typeof n==`bigint`)return String(n);try{return Ji(JSON.stringify(n))}catch{return null}}function Ki(e,t){let n=qi(e,t);return typeof n==`string`&&n.length>0?n:void 0}function qi(e,t){if(typeof e!=`object`||!e)return;let n=[e],r=new Set;for(;n.length;){let e=n.pop();if(typeof e!=`object`||!e||r.has(e))continue;r.add(e);let i=e;for(let e of t){let t=i[e];if(t!=null&&t!==``)return t}for(let e of Object.values(i))typeof e==`object`&&e&&n.push(e)}}function Ji(e){return e.length>4096?`${e.slice(0,4093)}...`:e}function Yi(e,t){Xi(e,`${JSON.stringify(t,null,2)}\n`)}function Xi(e,t){b(we(e),{mode:448,recursive:!0});let n=`${e}.${process.pid}.tmp`;S(n,t,{mode:384}),re(n,e)}function Zi(e,t,n){b(we(e),{recursive:!0});let r=$i(Qi(e),t);S(e,`${JSON.stringify(r,null,2)}\n`,{mode:n??420})}function Qi(e){if(!y(e))return{};let t=JSON.parse(x(e,`utf8`));if(!ra(t))throw Error(`${e} must contain a JSON object`);return t}function $i(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];ra(t)&&ra(r)?n[e]=$i(t,r):Array.isArray(t)&&Array.isArray(r)?n[e]=ea([...t,...r]):n[e]=r}return n}function ea(e){let t=new Set,n=[];for(let r of e){let e=JSON.stringify(r);t.has(e)||(t.add(e),n.push(r))}return n}function ta(e){return[...new Set(e)]}function na(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function ra(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function ia(e){return je(e).toString(`hex`)}function aa(e,t){return{key:e,value:{stringValue:t}}}const oa=`tangle.opencode-exporter`,sa=16384;function ca(e){return e.length<=sa?e:`${e.slice(0,sa-1)}…`}function J(e,t){return{key:e,value:{stringValue:t}}}function la(e){if(!e||typeof e!=`object`)return null;let t=e,n=k(t.type);return n?{type:n,properties:t.properties&&typeof t.properties==`object`?t.properties:void 0}:null}function ua(e,t){let n=[J(`event.name`,e),J(`gen_ai.system`,`opencode`),J(`service.name`,`opencode`)];return t&&(n.push(J(`session.id`,t)),n.push(J(`gen_ai.conversation.id`,t))),n}function da(e){if(!e)return null;let t=e.part,n=e.info;return k(t?.sessionID)??k(n?.sessionID)??k(e.sessionID)??null}function fa(e,t){let n=k(e.role)??k(e.info?.role);if(n)return n.toLowerCase();let r=k(e.messageID),i=t?.(r)??null;return i?i.toLowerCase():null}function pa(e,t,n){let r=[],i=da(e.properties),a=(n,r)=>({timeUnixNano:t,severityNumber:9,severityText:`INFO`,...n===null?{}:{body:{stringValue:ca(n)}},attributes:[...ua(e.type,i),...r]});if(e.type===`message.part.updated`){let t=e.properties?.part;if(!t)return r;let i=k(t.type);if(i===`text`||i===`reasoning`){let e=k(t.text);if(e){let i=fa(t,n)===`user`?$e:Qe;r.push(a(e,[J(i,ca(e))]))}return r}if(i===`tool`){let e=k(t.tool),n=t.state,i=it(n?.input),o=it(n?.output),s=k(n?.error)??(typeof n?.error==`object`&&n?.error!==null?it(n.error):null);if(e||i){let t=[];e&&t.push(J(tt,e)),i&&t.push(J(et,ca(i))),r.push(a(null,t))}let c=o??s;if(c){let t=[J(nt,ca(c))];e&&t.push(J(tt,e)),r.push(a(c,t))}return r}return r}if(e.type===`session.next.text.delta`||e.type===`session.next.text.ended`){let t=e.properties??{},n=k(t.text)??(e.type===`session.next.text.delta`?k(t.delta):null);return n&&r.push(a(n,[J(Qe,ca(n))])),r}return r}function ma(e=process.env.OTEL_RESOURCE_ATTRIBUTES){if(!e)return null;for(let t of e.split(`,`)){let e=t.indexOf(`=`);if(e===-1||t.slice(0,e).trim()!==rt)continue;let n=t.slice(e+1).trim();if(n.length>0)return n}return null}function ha(e,t){if(e.length===0)return null;let n=[J(`service.name`,`opencode`),J(`gen_ai.system`,`opencode`),J(`telemetry.sdk.name`,oa)];return t&&t.trim().length>0&&n.push(J(rt,t.trim())),{resourceLogs:[{resource:{attributes:n},scopeLogs:[{scope:{name:oa,version:`1.0.0`},logRecords:e}]}]}}function ga(e){return(e??process.env.OPENCODE_BASE_URL??`http://127.0.0.1:4096`).replace(/\/+$/,``)}async function _a(e){let t=q(e.endpoint),n=await(e.fetchImpl??fetch)(`${t}/v1/logs`,{method:`POST`,headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":`application/json`},body:JSON.stringify(e.request),signal:e.timeoutMs&&e.timeoutMs>0?AbortSignal.timeout(e.timeoutMs):void 0});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`OpenCode OTLP logs ingest failed: ${n.status}${e?` ${e}`:``}`)}}var va=class extends Error{partial;constructor(e,t){let n=e instanceof Error?e.message:String(e);super(n),this.name=`OpencodeExporterError`,this.partial=t,e instanceof Error&&(this.cause=e)}};function ya(){return(BigInt(Date.now())*1000000n).toString()}async function ba(e){let t=ga(e.opencodeBaseUrl),n=e.nowUnixNano??ya,r=e.fetchImpl??fetch,i=e.subjectKey===void 0?ma():e.subjectKey,a=await r(`${t}/event`,{headers:{Accept:`text/event-stream`},signal:e.signal});if(!a.ok){let e=await a.text().catch(()=>``);throw Error(`OpenCode event subscribe failed: ${a.status} at ${t}/event${e?` ${e}`:``}. Is OpenCode running with 'opencode serve'?`)}if(!a.body)throw Error(`OpenCode event stream at ${t}/event returned no body — cannot subscribe`);let o={eventsSeen:0,contentEventsExported:0,recordsExported:0},s=new Map,c=e=>e?s.get(e)??null:null;try{for await(let t of be(a.body,{signal:e.signal})){o.eventsSeen++;let a=la(t.data);if(!a)continue;if(a.type===`message.updated`){let e=a.properties?.info,t=k(e?.id),n=k(e?.role);t&&n&&s.set(t,n);continue}let l=pa(a,n(),c),u=ha(l,i);u&&(await _a({endpoint:e.endpoint,apiKey:e.apiKey,request:u,timeoutMs:e.postTimeoutMs,fetchImpl:r}),o.contentEventsExported++,o.recordsExported+=l.length,e.onExport?.({eventType:a.type,records:l.length}))}}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.message.toLowerCase().includes(`abort`)))return o;throw new va(e,o)}return o}const xa=[`claude-code`,`codex`,`opencode`,`openclaw`,`hermes`,`nanoclaw`],Sa={"claude-code":`Claude Code`,codex:`Codex`,opencode:`OpenCode`,openclaw:`OpenClaw`,hermes:`Hermes`,nanoclaw:`NanoClaw`};function Ca(e){return xa.includes(e)}function wa(e){return y(e)?x(e,`utf8`):``}function Ta(e,t){b(we(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;S(n,t,{mode:384}),v(n,384),re(n,e)}const Ea=`# >>> tangle intelligence (claude-code) >>>`,Da=`# <<< tangle intelligence (claude-code) <<<`,Oa={full:[{key:`OTEL_LOG_USER_PROMPTS`,comment:`the user/task prompt text`},{key:`OTEL_LOG_TOOL_DETAILS`,comment:`tool arguments`},{key:`OTEL_LOG_TOOL_CONTENT`,comment:`full tool input+output bodies`},{key:`OTEL_LOG_RAW_API_BODIES`,comment:`full prompt+completion JSON (richest)`}],prompts:[{key:`OTEL_LOG_USER_PROMPTS`,comment:`the user/task prompt text`},{key:`OTEL_LOG_TOOL_DETAILS`,comment:`tool arguments`}],metadata:[]};function ka(e,t){return t===`env`?e:/\s/.test(e)?`"${e}"`:e}function Aa(e,t){let n=t===`shell`?`export `:t===`dockerfile`?`ENV `:``,r=[];for(let i of e){if(i.kind===`blank`){t===`shell`&&r.push(``);continue}if(i.kind===`comment`){t===`shell`&&r.push(`# ${i.text}`);continue}let e=t===`shell`&&i.comment?` # ${i.comment}`:``;r.push(`${n}${i.key}=${ka(i.value,t)}${e}`)}return r.join(`
138
+ </html>`}const Kr=15*6e4,qr=`sandbox`;function Jr(e){return Number.isFinite(e)&&e>0?e:Kr}async function Yr(e){let t=e.timeoutMs??Kr,n=Date.now(),r=await Xr({baseUrl:e.baseUrl,app:e.app??qr,timeoutMs:t,provider:e.provider});for(e.onInstructions?.({userCode:r.user_code,verificationUrl:r.verification_uri,verificationUrlComplete:r.verification_uri_complete,expiresIn:r.expires_in,intervalSeconds:r.interval});;){if(Date.now()-n>t)throw new me(`Timed out waiting for device authorization to complete`,{timeoutMs:t});let i=await Zr({baseUrl:e.baseUrl,app:e.app??qr,deviceCode:r.device_code,timeoutMs:t});if(i.status===`approved`)return i.data;let a=i.intervalSeconds*1e3;await new Promise(e=>setTimeout(e,a))}}async function Xr(e){let t=Jr(e.timeoutMs),n=e.app!==qr,r=await fetch(`${Qr(e.baseUrl)}${n?`/cross-site/device/start`:`/auth/cli/device/start`}`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify(n?{app:e.app,...e.provider?{provider:e.provider}:{}}:e.provider?{provider:e.provider}:{}),signal:AbortSignal.timeout(t)}).catch(t=>{throw new w(`Failed to reach ${e.baseUrl}`,{cause:t instanceof Error?t:void 0})}),i=await r.json().catch(()=>null);if(!r.ok||!i?.success||!i.data?.device_code)throw Error(i?.error?.message||`Failed to start device login`);return i.data}async function Zr(e){let t=Jr(e.timeoutMs),n=e.app!==qr,r=await fetch(`${Qr(e.baseUrl)}${n?`/cross-site/device/poll`:`/auth/cli/device/poll`}`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify(n?{app:e.app,device_code:e.deviceCode}:{device_code:e.deviceCode}),signal:AbortSignal.timeout(t)}).catch(t=>{throw new w(`Failed to reach ${e.baseUrl}`,{cause:t instanceof Error?t:void 0})}),i=await r.json().catch(()=>null);if(r.status===428&&i?.error?.code===`AUTHORIZATION_PENDING`)return{status:`pending`,intervalSeconds:typeof i.data?.interval==`number`&&i.data.interval>0?i.data.interval:5};if(!r.ok||!i?.success||!i.data?.api_key||!i.data.email)throw Error(i?.error?.message||`Failed to complete device authorization`);return{status:`approved`,data:{apiKey:i.data.api_key,email:i.data.email,name:i.data.name,tier:i.data.tier}}}function Qr(e){return e.replace(/\/$/,``)}async function $r(e){let t=e.apiKey,n=si(e.app??`sandbox`),i=ci(n,e.profile),a=oi(e.provider),o=n===`solve`?_n(e.baseUrl):ln(e.baseUrl,i),c=e.browser!==!1,u=(t,a)=>{ri({profile:i,apiKey:t,baseUrl:(n===`solve`?e.baseUrl:un(e.baseUrl))?o:void 0,platformUrl:hn()??``,activate:n===`sandbox`}),En(),r(`Authenticated`),s({Profile:i,Email:a.email,Tier:a.tier,"Base URL":o}),l(ii),n===`sandbox`&&l(`Next: tangle agent prompt "<task>"`)};if(t&&!Ht(t)){d(`Invalid API key format. Keys should start with 'sk_' or 'sk-tan-'.`),process.exit(1);return}if(g(),!t){let t=c&&n===`sandbox`,r=f(t?`Starting browser login...`:`Starting device login...`);r.start();let i;try{i=t?await Br({baseUrl:o,provider:a,signal:e.signal,onLoginUrl:({loginUrl:e,browserOpened:t})=>{r.stop(),l(t?`Browser login opened.`:`Open this URL to continue browser login:`),console.log(e)}}):await Yr({baseUrl:o,app:n,provider:a,onInstructions:({userCode:e,verificationUrl:t,verificationUrlComplete:i})=>{r.stop(),l(`Complete login in a browser on any device:`),s({"Verification URL":t,"Verification URL (prefilled)":i,"Device Code":e}),n===`solve`&&c&&Wr(i)}})}finally{r.stop()}u(i.apiKey,i);return}let p=f(`Validating credentials...`);p.start();let m=await Nr({apiKey:t,baseUrl:o});p.stop(),u(t,m)}function ei(){let t=new D(`auth`).description(`Manage authentication`);return t.command(`login`).description(`Authenticate with browser login, device code, or an API key`).option(`--no-browser`,`Use device-code login instead of opening a browser`).option(`--profile <name>`,`Profile name`).option(`--provider <provider>`,`Identity provider (github, google, microsoft)`).option(`--app <app>`,`Product to authorize (sandbox or solve)`,`sandbox`).action($r),t.command(`logout`).description(`Remove stored credentials`).option(`--profile <name>`,`Profile name`).option(`--app <app>`,`Product credentials to remove (sandbox or solve)`,`sandbox`).action(e=>{let t=ci(si(e.app),e.profile);$t(t),En(),r(`Logged out successfully.`),l(`Credentials removed for profile '${t}'.`)}),t.command(`status`).description(`Show current authentication status`).option(`--profile <name>`,`Profile name`).option(`--app <app>`,`Product credentials to check (sandbox or solve)`,`sandbox`).action(async t=>{let n=si(t.app),i=ci(n,t.profile),a=n===`solve`?on(t.apiKey,i):nn(t.apiKey,i,t.baseUrl),o=n===`solve`?_n(t.baseUrl):ln(t.baseUrl,i),u=n===`solve`?cn(t.apiKey,i):sn(t.apiKey,i);if(!a){if(t.json){e({authenticated:!1,reason:`missing_credentials`,profile:i,baseUrl:o,credentialSource:null});return}d(`Not authenticated`),l(`Run 'tangle auth login --profile ${i}' to authenticate.`),process.exit(1)}let p=t.json?null:f(`Checking credentials...`);p?.start();try{let d=await Nr({apiKey:a,baseUrl:o}),f=n===`solve`?null:await Xn({...t.apiKey===void 0?{}:{apiKey:t.apiKey},...t.profile===void 0?{}:{profile:t.profile},sandboxBaseUrl:o});p?.stop();let m=f!==null&&!f.reachable&&f.refused,h=!m,g=f!==null&&!f.reachable&&!f.refused;if(t.json){e({authenticated:h,profile:i,baseUrl:o,credentialSource:u,account:d,...f?{sandbox:{authenticated:!0},platform:f}:{}}),h||process.exit(1);return}m?c(`Authenticated for sandbox only`):g?c(`Authenticated — the platform is unreachable right now`):r(`Authenticated`),s({Profile:i,Credentials:`configured`,"Base URL":o,Source:ni(u),Email:d.email,Tier:d.tier,...f?{Platform:f.reachable?`reachable (${f.baseUrl})`:`UNREACHABLE — ${f.reason}`}:{}}),g&&l(`Platform commands (keys, workflows, hub) will not work until the platform answers again. The stored credential is not the cause and does not need replacing.`),h||(l("Platform commands (keys, workflows, hub) will not work until this resolves. Set TANGLE_API_KEY to a key you minted in the console, or run `tangle auth login` again."),process.exit(1))}catch(n){p?.stop(),t.json&&(e({authenticated:!1,profile:i,baseUrl:o,credentialSource:u,error:n instanceof Error?n.message:String(n)}),process.exit(1)),n instanceof C?d(`Stored credentials are invalid.`):c(`Stored credentials found, but validation could not complete.`),s({Profile:i,Credentials:`configured`,"Base URL":o,Source:ni(u),Error:n instanceof Error?n.message:String(n)}),process.exit(1)}}),t.addCommand(ti()),t}function ti(){let t=new D(`profiles`).description(`Manage CLI profiles`);return t.command(`list`).description(`List configured profiles`).action(t=>{let n=Xt();if(t.json){e(n);return}if(n.length===0){l(`No profiles found.`);return}i([`Profile`,`Active`,`Base URL`,`Credentials`,`Source`],n.map(e=>[e.name,e.active?`yes`:`no`,e.baseUrl,e.hasApiKey?`configured`:`none`,e.apiKeySource]))}),t.command(`use <name>`).description(`Set the active profile`).action(e=>{Wt(e);let t=Zt(e);r(`Active profile set to '${t.name}'.`),s({"Base URL":t.baseUrl,Credentials:t.credentialSource===`none`?`missing`:`configured`})}),t.command(`current`).description(`Show the active profile`).action(t=>{let n=Zt();if(t.json){e({name:n.name,active:n.active,baseUrl:n.baseUrl,credentialSource:n.credentialSource});return}s({Profile:n.name,"Base URL":n.baseUrl,Credentials:n.credentialSource===`none`?`missing`:`configured`,Source:ni(n.credentialSource)})}),t}function ni(e){switch(e){case`flag`:return`command flag`;case`env`:return`environment`;case`keychain`:return`OS keychain`;case`file`:return`credentials file`;default:return`unknown`}}function ri(e){let t=Qt(e.profile,{apiKey:e.apiKey,...e.baseUrl?{baseUrl:e.baseUrl}:{},...e.platformUrl===void 0?{}:{platformUrl:e.platformUrl}});e.activate!==!1&&Wt(e.profile),Ut(e.baseUrl&&e.profile===`default`?{baseUrl:e.baseUrl}:{}),ii=ai(e.profile,t)}let ii=`Credentials updated.`;function ai(e,t){return t===`keychain`?e===`default`?`API key saved to the OS keychain for the default profile`:`API key saved to the OS keychain for profile '${e}'`:t===`file`?e===`default`?`API key saved to ~/.tangle/credentials.json for the default profile`:`API key saved to ~/.tangle/credentials.json for profile '${e}'`:`Profile '${e}' updated.`}function oi(e){if(e===void 0||e===`github`||e===`google`||e===`microsoft`)return e;throw Error(`--provider must be one of: github, google, microsoft`)}function si(e){if(e===void 0||e===`sandbox`||e===`solve`)return e??`sandbox`;throw Error(`--app must be one of: sandbox, solve`)}function ci(e,t){return zt(e,t)}function li(e){if(e.status===`stopped`)throw new A(`INVALID_STATE`,`Sandbox ${e.id} is stopped, so its backend is not running`,"The next `tangle agent` or `tangle exec` command resumes it",`tangle sandbox resume ${e.id}`)}function ui(){let n=new D(`backend`).description(`Manage sandbox AI agent backend`);return n.command(`status <sandboxId-or-name>`).description(`Get the harness type the sandbox runs`).action(async(t,n)=>{let{context:r,client:i}=z(n),a=f(`Fetching backend status...`);a.start();let o=await U(i,r,t);li(o);let s=await o.backend.status();a.stop(),n.json?e(s):l(`Backend Type: ${s.type}`)}),n.command(`configure <sandboxId-or-name>`).description(`Update backend configuration; resumes a stopped sandbox`).option(`--model <model>`,`Model id (e.g. provider/model)`).action(async(t,n)=>{let{context:i,client:a}=z(n),o=f(`Updating backend config...`);o.start();let s=await W(await U(a,i,t)),c=n.model?{model:n.model}:{};await s.backend.updateConfig(c),o.stop(),r(`Backend configuration updated`),n.json&&e(c)}),n.command(`mcp-status <sandboxId-or-name>`).description(`Get status of MCP servers`).action(async(n,r)=>{let{context:i,client:a}=z(r),o=f(`Fetching MCP status...`);o.start();let s=await U(a,i,n);li(s);let c=await s.backend.getMcpStatus();if(o.stop(),r.json)e(c);else{let e=Object.entries(c);e.length===0?l(`No MCP servers configured`):t(e.map(([e,t])=>{let n=t;return{name:e,status:n.status,error:n.error??``}}),[{key:`name`,header:`Name`,width:24},{key:`status`,header:`Status`,width:12},{key:`error`,header:`Error`,width:40}])}}),n}function di(e){let t=e.indexOf(`=`);if(t<=0)throw Error(`Invalid --task "${e}": expected format id=message (e.g. t1=summarize README)`);let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();if(!n||!r)throw Error(`Invalid --task "${e}": id and message must be non-empty`);return{id:n,message:r}}function fi(e){let t;try{t=JSON.parse(e)}catch(e){throw Error(`--tasks file is not valid JSON: ${e.message}`)}let n=Array.isArray(t)?t:t?.tasks;if(!Array.isArray(n))throw Error(`--tasks file must contain an array or an object with a "tasks" array`);return n.map((e,t)=>{if(!e||typeof e!=`object`)throw Error(`--tasks[${t}] must be an object`);let n=e,r=typeof n.id==`string`?n.id.trim():``,i=typeof n.message==`string`?n.message:``;if(!r)throw Error(`--tasks[${t}].id must be a non-empty string`);if(!i.trim())throw Error(`--tasks[${t}].message must be a non-empty string`);let a={id:r,message:i};if(n.context!==void 0&&(typeof n.context!=`object`||n.context===null||Array.isArray(n.context)))throw Error(`--tasks[${t}].context must be a JSON object`);if(n.context!==void 0&&(a.context=n.context),n.timeoutMs!==void 0&&(!Number.isInteger(n.timeoutMs)||n.timeoutMs<=0))throw Error(`--tasks[${t}].timeoutMs must be a positive integer`);return n.timeoutMs!==void 0&&(a.timeoutMs=n.timeoutMs),a})}function pi(e){let t=e.readFile??(e=>x(e,`utf8`)),n=[];e.file&&n.push(...fi(t(e.file)));for(let t of e.inline??[])n.push(di(t));if(n.length===0)throw Error(`No tasks provided. Use --tasks <file> and/or --task id=message.`);let r=new Set;for(let e of n){if(r.has(e.id))throw Error(`Duplicate task id: ${e.id}`);r.add(e.id)}return n}const mi=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function hi(e){let t=e.trim(),n=t.indexOf(`/`);if(n<=0||n===t.length-1)throw Error(`--model must be in the form provider/model (got "${e}")`);return{provider:t.slice(0,n),model:t.slice(n+1)}}function gi(e){let t=e.indexOf(`=`);if(t<=0||t===e.length-1)throw Error(`Invalid --backend "${e}": expected format id=type (e.g. primary=opencode)`);let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();if(!mi.test(n))throw Error(`Invalid backend id "${n}": use 1-128 letters, numbers, dots, underscores, or hyphens, starting with a letter or number`);if(!r||r.includes(`=`))throw Error(`Invalid --backend "${e}": type must be a non-empty backend name`);return{id:n,type:r}}function _i(e,t){if(!e||e.length===0)throw Error(`No backends provided. Use --backend id=type or --request <file>.`);let n=e.map(gi),r=new Set;for(let e of n){if(r.has(e.id))throw Error(`Duplicate backend id: ${e.id}`);r.add(e.id)}if(t&&n.length!==1)throw Error(`--model requires exactly one backend; use a profile to configure models for multiple backends`);return t&&(n[0]={...n[0],model:hi(t)}),n}function vi(e){let t;try{t=JSON.parse(e)}catch(e){throw Error(`--request file is not valid JSON: ${e.message}`)}try{return xe(t)}catch(e){throw Error(`--request file is not a valid batch request: ${e.message}`)}}function yi(e,t,n){return n?`${e} [${t}]`:e}function bi(e){let t=new Map;for(let n of e)t.set(n.taskId,(t.get(n.taskId)??0)+1);return new Set([...t.entries()].filter(([,e])=>e>1).map(([e])=>e))}function xi(){let t=new D(`batch`).description(`Run multiple agent tasks in parallel across sandboxes`);return t.command(`run`).description(`Execute a batch of tasks. Provide tasks via --tasks <file.json> and/or repeated --task id=message flags.`).option(`--tasks <file>`,`Path to a JSON file with an array of tasks (or {tasks: [...]})`).option(`--request <file>`,`Path to a complete batch request JSON file`).option(`--task <id=message>`,`Inline task, id=message. Repeatable.`,(e,t=[])=>[...t,e],[]).option(`--stream`,`Stream per-task events as they arrive`).option(`-t, --timeout <ms>`,`Per-task timeout in milliseconds`,`300000`).option(`--persistent`,`Keep sandboxes alive after completion`,!1).option(`--reuse-key <key>`,`Stable workspace identity required by --persistent`).option(`--replay-only`,`Rejoin existing keyed work; refuse missing custody`).option(`--idempotency-key <key>`,`Retry identity; keyed runs continue after disconnect`).option(`--backend <id=type>`,`Backend identity and type. Required and repeatable without --request.`,(e,t=[])=>[...t,e],[]).option(`--model <provider/model>`,`Model override when exactly one backend is selected`).option(`--runtime <runtime>`,`Isolation on platform hosts: docker or firecracker`).action(async(t,n)=>{let r=new AbortController,i=!1,a=()=>{i||(i=!0,l(`Cancel requested — stopping stream...`),r.abort())};process.on(`SIGINT`,a),process.on(`SIGTERM`,a);try{let i;if(t.request){let e=[`tasks`,`task`,`backend`,`model`,`runtime`,`timeout`,`persistent`,`reuseKey`].filter(e=>n.getOptionValueSource(e)===`cli`);if(e.length>0){let t={reuseKey:`reuse-key`};throw Error(`--request cannot be combined with ${e.map(e=>`--${t[e]??e}`).join(`, `)}`)}i=vi(x(t.request,`utf8`))}else{let e=pi({file:t.tasks,inline:t.task}),n=_i(t.backend,t.model),r=Number(t.timeout);if(!Number.isInteger(r)||r<=0)throw Error(`--timeout must be a positive integer number of milliseconds`);let a=!!t.persistent;if(a&&!t.reuseKey)throw Error(`--persistent requires --reuse-key`);if(!a&&t.reuseKey)throw Error(`--reuse-key requires --persistent`);i=xe({tasks:e,timeoutMs:r,backends:n,...t.runtime?{runtime:t.runtime}:{},...a?{persistent:!0,reuseKey:t.reuseKey}:{persistent:!1}})}let{tasks:a,backends:o}=i,{client:c}=z(t),u={signal:r.signal,replayOnly:!!t.replayOnly,...t.idempotencyKey?{idempotencyKey:t.idempotencyKey}:{}},d;if(t.stream){let e=t.json?console.error:console.log;l(`Streaming batch of ${a.length} task(s)...`),e();let n=c.streamBatch(i,u),r=o.length>1;for(;;){let t=await n.next();if(t.done){d=t.value;break}let i=t.value;switch(i.type){case`batch.started`:{let e=i.data;l(`Batch started (${e.taskCount} tasks, ${e.backendCount} backends)`);break}case`task.started`:{let t=i.data;e(T.dim(`→ ${yi(t.taskId,t.backendId,r)} started`));break}case`task.retry`:{let t=i.data;e(T.yellow(`↻ ${yi(t.taskId,t.backendId,r)} retry ${t.attempt}: ${t.error}`));break}case`task.completed`:{let t=i.data;e(T.green(`✓ ${yi(t.taskId,t.backendId,r)} completed in ${t.durationMs}ms`+(t.retries?` (${t.retries} retries)`:``)));break}case`task.failed`:{let t=i.data;e(T.red(`✗ ${yi(t.taskId,t.backendId,r)} failed: ${t.error}`));break}}}e()}else l(`Running batch of ${a.length} task(s)...`),d=await c.runBatch(i,u),t.json||console.log();if(t.json)e(d);else if(s({"Total tasks":d.totalTasks,"Total backends":d.totalBackends,"Total executions":d.totalExecutions,Succeeded:d.totalSuccess,Failed:d.totalFailure,"Total retries":d.totalRetries,"Success rate":`${d.successRate.toFixed(1)}%`}),!t.stream&&d.results.length>0){let e=bi(d.results);console.log(),console.log(T.bold(`Task Results`)),console.log(T.dim(`─`.repeat(40)));for(let t of d.results){let n=t.success?T.green(`✓`):T.red(`✗`),r=t.success?t.usage.inputTokens+t.usage.outputTokens:0,i=r>0?` • ${r} tokens`:``;console.log(`${n} ${yi(t.taskId,t.backendId,e.has(t.taskId))} ${T.dim(`(${t.durationMs}ms, ${t.retries} retries${i})`)}`),t.success||console.log(T.red(` ${t.error}`))}}d.totalFailure>0&&(process.exitCode=1)}catch(n){let r=n instanceof Error&&`batchCustody`in n?n.batchCustody:void 0;if(r?.acceptance===`accepted`&&!(r.cleanup?.mode===`release`&&r.cleanup.isComplete)&&l(`Batch accepted; retirement receipt unproved.`),i){console.log(),l(`Batch cancelled.`),t.json&&n instanceof Error&&`batchCustody`in n&&e({ok:!1,batchCustody:n.batchCustody}),process.exitCode=130;return}N(n,t.json)}finally{process.off(`SIGINT`,a),process.off(`SIGTERM`,a)}}),t}function Si(){let n=new D(`branch`).description(`Branch a running sandbox into copy-on-write children`);return n.command(`create <sandbox-id-or-name>`).description(`Branch a running sandbox into N copy-on-write children`).option(`--count <n>`,`Number of children to create`,`1`).option(`--idempotency-key <key>`,`Retry identity: the same key and count replays the first fan-out and creates no second one`).action(async(n,i)=>{let a=Number.parseInt(i.count,10);if(!Number.isInteger(a)||a<1)throw Error(`--count must be an integer >= 1 (got ${i.count})`);let{context:o,client:s}=z(i),u=f(`Branching into ${a} child(ren)...`);u.start();let d=await U(s,o,n),p=await d.fork(a,{...i.idempotencyKey?{idempotencyKey:i.idempotencyKey}:{}}),m=p.children;u.stop(),i.json?e({children:m.map(e=>({sandboxId:e.id})),requestedCount:p.requestedCount,materializedCount:p.materializedCount,complete:p.complete,...p.idempotency?{idempotency:p.idempotency}:{}}):(p.complete?r(`Branched ${m.length} child(ren) from ${d.id}`):c(`Branched ${p.materializedCount} of ${p.requestedCount} requested child(ren) from ${d.id}`),p.idempotency?.outcome===`replayed`&&l(`Replayed an earlier fan-out under this key; created none.`),t(m.map(e=>({sandboxId:e.id})),[{key:`sandboxId`,header:`Child Sandbox`,width:28}]))}),n}const Ci=[`codex`,`claude-code`,`nanoclaw`,`kimi-code`,`opencode`,`pi`,`openclaw`,`hermes`],wi=`https://intelligence.tangle.tools/v1/otlp`,Ti=[`codex`,`claude-code`],Ei=[`codex`,`claude-code`,`nanoclaw`],Di=[`SessionStart`,`UserPromptSubmit`,`PreToolUse`,`PostToolUse`,`Stop`],Oi={codex:{kind:`native`,surface:`codex`,label:`Codex`,buildFiles:Vi},"claude-code":{kind:`native`,surface:`claude-code`,label:`Claude Code`,buildFiles:Hi},nanoclaw:{kind:`native`,surface:`nanoclaw`,label:`NanoClaw`,buildFiles:Hi},"kimi-code":{kind:`manual`,surface:`kimi-code`,label:`Kimi Code`,reason:`Kimi Code loads hooks through an explicit config file, so use standard OTLP env wiring until the native config adapter is verified.`},opencode:{kind:`manual`,surface:`opencode`,label:`OpenCode`,reason:`OpenCode hooks run as plugins; use standard OTLP env wiring until the native plugin adapter is verified.`},pi:{kind:`manual`,surface:`pi`,label:`Pi`,reason:`Pi hooks run through TypeScript extensions; use standard OTLP env wiring until the native extension adapter is verified.`},openclaw:{kind:`manual`,surface:`openclaw`,label:`OpenClaw`,reason:`OpenClaw project hooks require user opt-in; use standard OTLP env wiring until the hook toggle and adapter are verified.`},hermes:{kind:`manual`,surface:`hermes`,label:`Hermes`,reason:`Hermes project plugins require explicit enablement; use standard OTLP env wiring until the plugin adapter is verified.`}};function ki(e){let t=e.split(`,`).map(e=>e.trim()).filter(Boolean).flatMap(e=>Bi(e));return t.length===0?[...Ti]:ta(t)}function Ai(e){return Object.hasOwn(Oi,e)}function ji(e=process.cwd()){return Ce(Ee(e))||`agent-workspace`}function Mi(){return E(He(),`.tangle`,`intelligence.json`)}function Ni(e=Mi()){if(!y(e))return null;let t=Qi(e),n=na(t,`apiKey`),r=na(t,`endpoint`),i=na(t,`serviceName`),a=na(t,`environment`);if(!n||!r||!i||!a)throw Error(`${e} is missing apiKey, endpoint, serviceName, or environment`);return{apiKey:n,endpoint:r,serviceName:i,environment:a}}async function Pi(e){let t=Ee(e.workspace),n=Mi(),r=ki(e.selection),i=[],a=[],o=[],s={apiKey:e.apiKey,endpoint:q(e.endpoint),serviceName:e.serviceName,environment:e.environment};e.dryRun||Yi(n,s),o.push(n);for(let n of r){let r=Oi[n];if(r.kind===`manual`){a.push({agent:r.surface,label:r.label,reason:r.reason});continue}i.push(r.surface);let s=t=>Fi(e.hookCommand,r.surface,t);for(let n of r.buildFiles(s)){let r=E(t,n.relPath);if(e.dryRun){o.push(r);continue}Zi(r,JSON.parse(n.content),n.mode),o.push(r)}}return!e.smoke||e.dryRun?{configPath:n,written:o,agents:r,nativeAgents:i,manual:a}:{configPath:n,written:o,agents:r,nativeAgents:i,manual:a,smokeTraceId:await Li({agent:i[0]??r[0]??`codex`,event:`install.smoke`,endpoint:s.endpoint,apiKey:s.apiKey,serviceName:s.serviceName,environment:s.environment,sessionId:`install-smoke-${Date.now()}`,payload:{source:`tangle intelligence connect`}})}}function Fi(e,t,n){return`${e.trim()} --agent ${t} --event ${n} --non-blocking`}function Ii(e){let t=BigInt(Date.now())*1000000n,n=ia(16),r=ia(8),i=e.sessionId??Ui(e.payload),a={"service.name":e.serviceName,"deployment.environment":e.environment,"tangle.agent.surface":e.agent,"tangle.agent.hook.event":e.event,"tangle.agent.hook.source":`local-hook`,...Wi(e.payload)};return i&&(a[`session.id`]=i,a[`gen_ai.conversation.id`]=i,a[`tangle.sessionId`]=i),{body:{resourceSpans:[{resource:{attributes:[aa(`service.name`,e.serviceName),aa(`deployment.environment`,e.environment),aa(`tangle.agent.surface`,e.agent)]},scopeSpans:[{scope:{name:`tangle.intelligence.agent-hook`,version:`1.0.0`},spans:[{traceId:n,spanId:r,name:`agent.${e.agent}.${e.event}`,kind:1,startTimeUnixNano:t.toString(),endTimeUnixNano:(t+1000000n).toString(),attributes:Object.entries(a).map(([e,t])=>aa(e,t)),status:{code:1}}]}]}]},traceId:n}}async function Li(e){let{body:t,traceId:n}=Ii(e),r=await fetch(`${q(e.endpoint)}/v1/traces`,{method:`POST`,headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":`application/json`},body:JSON.stringify(t)});if(!r.ok){let e=await r.text().catch(()=>``);throw Error(`OTLP smoke ingest failed: ${r.status}${e?` ${e}`:``}`)}return n}function Ri(e){return q(e).replace(/\/v1\/otlp$/,``).replace(/\/+$/,``)}async function zi(e){let t=`${Ri(e.endpoint)}/v1/onboarding/status`,n=await fetch(t,{headers:{Authorization:`Bearer ${e.apiKey}`},signal:e.timeoutMs&&e.timeoutMs>0?AbortSignal.timeout(e.timeoutMs):void 0});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`onboarding status request failed: ${n.status}${e?` ${e}`:``}`)}let r=await n.json();return{tracesSeen:!!r.tracesSeen,contentSeen:!!r.contentSeen,lastSeenAt:typeof r.lastSeenAt==`string`?r.lastSeenAt:null,windowDays:typeof r.windowDays==`number`?r.windowDays:7,byAgent:r.byAgent&&typeof r.byAgent==`object`?r.byAgent:{}}}function q(e){let t=e.trim().replace(/\/+$/,``);return t.endsWith(`/v1/traces`)?t.slice(0,-10):t.endsWith(`/v1/logs`)?t.slice(0,-8):t}function Bi(e){switch(e){case`local`:case`both`:return[...Ti];case`all`:return[...Ei];case`claude`:return[`claude-code`];case`kimi`:return[`kimi-code`];default:if(Ai(e))return[e];throw Error(`agent must be one of: local, all, both, ${Ci.join(`, `)}`)}}function Vi(e){let t=Object.fromEntries(Di.map(t=>[t,[{command:e(t),timeoutMs:3e3,blocking:!1,matcher:`*`}]]));return[{relPath:`.codex/hooks.json`,content:JSON.stringify({hooks:t},null,2)}]}function Hi(e){let t=Object.fromEntries(Di.map(t=>[t,[{matcher:`*`,hooks:[{type:`command`,command:e(t),timeout:3}]}]]));return[{relPath:`.claude/settings.json`,content:JSON.stringify({hooks:t},null,2)}]}function Ui(e){return Ki(e,[`session.id`,`sessionId`,`session_id`,`conversationId`,`conversation_id`,`threadId`,`thread_id`,`transcriptId`,`transcript_id`])||process.env.TANGLE_SESSION_ID||process.env.CODEX_THREAD_ID||process.env.CLAUDE_SESSION_ID||process.env.OPENCODE_SESSION_ID}function Wi(e){let t={},n=Gi(e,[`tool.name`,`toolName`,`tool_name`,`tool`]),r=Gi(e,[`command`,`cmd`,`shell_command`,`shellCommand`]),i=Gi(e,[`tool.input`,`toolInput`,`tool_input`,`input`,`arguments`,`args`]),a=Gi(e,[`tool.output`,`toolOutput`,`tool_output`,`output`,`result`]),o=Gi(e,[`tool.exit_code`,`exitCode`,`exit_code`,`status`]),s=Gi(e,[`tool.error.message`,`errorMessage`,`error_message`,`error`]);return n&&(t[`tool.name`]=n),r&&(t[`process.command`]=r),i&&(t[`tool.input.summary`]=i),a&&(t[`tool.output.summary`]=a),o&&(t[`tool.exit_code`]=o),s&&(t[`tool.error.message`]=s),t}function Gi(e,t){let n=qi(e,t);if(n===void 0)return null;if(typeof n==`string`)return Ji(n);if(typeof n==`number`||typeof n==`boolean`||typeof n==`bigint`)return String(n);try{return Ji(JSON.stringify(n))}catch{return null}}function Ki(e,t){let n=qi(e,t);return typeof n==`string`&&n.length>0?n:void 0}function qi(e,t){if(typeof e!=`object`||!e)return;let n=[e],r=new Set;for(;n.length;){let e=n.pop();if(typeof e!=`object`||!e||r.has(e))continue;r.add(e);let i=e;for(let e of t){let t=i[e];if(t!=null&&t!==``)return t}for(let e of Object.values(i))typeof e==`object`&&e&&n.push(e)}}function Ji(e){return e.length>4096?`${e.slice(0,4093)}...`:e}function Yi(e,t){Xi(e,`${JSON.stringify(t,null,2)}\n`)}function Xi(e,t){b(we(e),{mode:448,recursive:!0});let n=`${e}.${process.pid}.tmp`;S(n,t,{mode:384}),re(n,e)}function Zi(e,t,n){b(we(e),{recursive:!0});let r=$i(Qi(e),t);S(e,`${JSON.stringify(r,null,2)}\n`,{mode:n??420})}function Qi(e){if(!y(e))return{};let t=JSON.parse(x(e,`utf8`));if(!ra(t))throw Error(`${e} must contain a JSON object`);return t}function $i(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];ra(t)&&ra(r)?n[e]=$i(t,r):Array.isArray(t)&&Array.isArray(r)?n[e]=ea([...t,...r]):n[e]=r}return n}function ea(e){let t=new Set,n=[];for(let r of e){let e=JSON.stringify(r);t.has(e)||(t.add(e),n.push(r))}return n}function ta(e){return[...new Set(e)]}function na(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function ra(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function ia(e){return je(e).toString(`hex`)}function aa(e,t){return{key:e,value:{stringValue:t}}}const oa=`tangle.opencode-exporter`,sa=16384;function ca(e){return e.length<=sa?e:`${e.slice(0,sa-1)}…`}function J(e,t){return{key:e,value:{stringValue:t}}}function la(e){if(!e||typeof e!=`object`)return null;let t=e,n=k(t.type);return n?{type:n,properties:t.properties&&typeof t.properties==`object`?t.properties:void 0}:null}function ua(e,t){let n=[J(`event.name`,e),J(`gen_ai.system`,`opencode`),J(`service.name`,`opencode`)];return t&&(n.push(J(`session.id`,t)),n.push(J(`gen_ai.conversation.id`,t))),n}function da(e){if(!e)return null;let t=e.part,n=e.info;return k(t?.sessionID)??k(n?.sessionID)??k(e.sessionID)??null}function fa(e,t){let n=k(e.role)??k(e.info?.role);if(n)return n.toLowerCase();let r=k(e.messageID),i=t?.(r)??null;return i?i.toLowerCase():null}function pa(e,t,n){let r=[],i=da(e.properties),a=(n,r)=>({timeUnixNano:t,severityNumber:9,severityText:`INFO`,...n===null?{}:{body:{stringValue:ca(n)}},attributes:[...ua(e.type,i),...r]});if(e.type===`message.part.updated`){let t=e.properties?.part;if(!t)return r;let i=k(t.type);if(i===`text`||i===`reasoning`){let e=k(t.text);if(e){let i=fa(t,n)===`user`?$e:Qe;r.push(a(e,[J(i,ca(e))]))}return r}if(i===`tool`){let e=k(t.tool),n=t.state,i=it(n?.input),o=it(n?.output),s=k(n?.error)??(typeof n?.error==`object`&&n?.error!==null?it(n.error):null);if(e||i){let t=[];e&&t.push(J(tt,e)),i&&t.push(J(et,ca(i))),r.push(a(null,t))}let c=o??s;if(c){let t=[J(nt,ca(c))];e&&t.push(J(tt,e)),r.push(a(c,t))}return r}return r}if(e.type===`session.next.text.delta`||e.type===`session.next.text.ended`){let t=e.properties??{},n=k(t.text)??(e.type===`session.next.text.delta`?k(t.delta):null);return n&&r.push(a(n,[J(Qe,ca(n))])),r}return r}function ma(e=process.env.OTEL_RESOURCE_ATTRIBUTES){if(!e)return null;for(let t of e.split(`,`)){let e=t.indexOf(`=`);if(e===-1||t.slice(0,e).trim()!==rt)continue;let n=t.slice(e+1).trim();if(n.length>0)return n}return null}function ha(e,t){if(e.length===0)return null;let n=[J(`service.name`,`opencode`),J(`gen_ai.system`,`opencode`),J(`telemetry.sdk.name`,oa)];return t&&t.trim().length>0&&n.push(J(rt,t.trim())),{resourceLogs:[{resource:{attributes:n},scopeLogs:[{scope:{name:oa,version:`1.0.0`},logRecords:e}]}]}}function ga(e){return(e??process.env.OPENCODE_BASE_URL??`http://127.0.0.1:4096`).replace(/\/+$/,``)}async function _a(e){let t=q(e.endpoint),n=await(e.fetchImpl??fetch)(`${t}/v1/logs`,{method:`POST`,headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":`application/json`},body:JSON.stringify(e.request),signal:e.timeoutMs&&e.timeoutMs>0?AbortSignal.timeout(e.timeoutMs):void 0});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`OpenCode OTLP logs ingest failed: ${n.status}${e?` ${e}`:``}`)}}var va=class extends Error{partial;constructor(e,t){let n=e instanceof Error?e.message:String(e);super(n),this.name=`OpencodeExporterError`,this.partial=t,e instanceof Error&&(this.cause=e)}};function ya(){return(BigInt(Date.now())*1000000n).toString()}async function ba(e){let t=ga(e.opencodeBaseUrl),n=e.nowUnixNano??ya,r=e.fetchImpl??fetch,i=e.subjectKey===void 0?ma():e.subjectKey,a=await r(`${t}/event`,{headers:{Accept:`text/event-stream`},signal:e.signal});if(!a.ok){let e=await a.text().catch(()=>``);throw Error(`OpenCode event subscribe failed: ${a.status} at ${t}/event${e?` ${e}`:``}. Is OpenCode running with 'opencode serve'?`)}if(!a.body)throw Error(`OpenCode event stream at ${t}/event returned no body — cannot subscribe`);let o={eventsSeen:0,contentEventsExported:0,recordsExported:0},s=new Map,c=e=>e?s.get(e)??null:null;try{for await(let t of be(a.body,{signal:e.signal})){o.eventsSeen++;let a=la(t.data);if(!a)continue;if(a.type===`message.updated`){let e=a.properties?.info,t=k(e?.id),n=k(e?.role);t&&n&&s.set(t,n);continue}let l=pa(a,n(),c),u=ha(l,i);u&&(await _a({endpoint:e.endpoint,apiKey:e.apiKey,request:u,timeoutMs:e.postTimeoutMs,fetchImpl:r}),o.contentEventsExported++,o.recordsExported+=l.length,e.onExport?.({eventType:a.type,records:l.length}))}}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.message.toLowerCase().includes(`abort`)))return o;throw new va(e,o)}return o}const xa=[`claude-code`,`codex`,`opencode`,`openclaw`,`hermes`,`nanoclaw`],Sa={"claude-code":`Claude Code`,codex:`Codex`,opencode:`OpenCode`,openclaw:`OpenClaw`,hermes:`Hermes`,nanoclaw:`NanoClaw`};function Ca(e){return xa.includes(e)}function wa(e){return y(e)?x(e,`utf8`):``}function Ta(e,t){b(we(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;S(n,t,{mode:384}),v(n,384),re(n,e)}const Ea=`# >>> tangle intelligence (claude-code) >>>`,Da=`# <<< tangle intelligence (claude-code) <<<`,Oa={full:[{key:`OTEL_LOG_USER_PROMPTS`,comment:`the user/task prompt text`},{key:`OTEL_LOG_TOOL_DETAILS`,comment:`tool arguments`},{key:`OTEL_LOG_TOOL_CONTENT`,comment:`full tool input+output bodies`},{key:`OTEL_LOG_RAW_API_BODIES`,comment:`full prompt+completion JSON (richest)`}],prompts:[{key:`OTEL_LOG_USER_PROMPTS`,comment:`the user/task prompt text`},{key:`OTEL_LOG_TOOL_DETAILS`,comment:`tool arguments`}],metadata:[]};function ka(e,t){return t===`env`?e:/\s/.test(e)?`"${e}"`:e}function Aa(e,t){let n=t===`shell`?`export `:t===`dockerfile`?`ENV `:``,r=[];for(let i of e){if(i.kind===`blank`){t===`shell`&&r.push(``);continue}if(i.kind===`comment`){t===`shell`&&r.push(`# ${i.text}`);continue}let e=t===`shell`&&i.comment?` # ${i.comment}`:``;r.push(`${n}${i.key}=${ka(i.value,t)}${e}`)}return r.join(`
139
139
  `)}function ja(e){let t=q(e.endpoint),n=e.apiKey??"${TANGLE_API_KEY}",r=e.content??`full`,i=e.format??`shell`,a=[{kind:`comment`,text:`Enable + point Claude Code at Tangle (JSON protocol — matches our adapter)`},{kind:`set`,key:`CLAUDE_CODE_ENABLE_TELEMETRY`,value:`1`},{kind:`set`,key:`OTEL_EXPORTER_OTLP_PROTOCOL`,value:`http/json`},{kind:`set`,key:`OTEL_EXPORTER_OTLP_ENDPOINT`,value:t},{kind:`set`,key:`OTEL_EXPORTER_OTLP_HEADERS`,value:`Authorization=Bearer ${n}`}];e.projectKey?a.push({kind:`blank`},{kind:`comment`,text:`Groups your runs into a project so Tangle can roll up + automate per-project:`},{kind:`set`,key:`OTEL_RESOURCE_ATTRIBUTES`,value:`tangle.subject.key=${e.projectKey}`}):a.push({kind:`blank`},{kind:`comment`,text:`Label this project so Tangle rolls up + automates per-project (pick your own):`},{kind:`comment`,text:` export OTEL_RESOURCE_ATTRIBUTES=tangle.subject.key=<your project>`}),a.push({kind:`blank`},{kind:`comment`,text:`CONTENT rides LOG EVENTS, so the logs exporter is MANDATORY.`},{kind:`set`,key:`OTEL_LOGS_EXPORTER`,value:`otlp`,comment:`required for prompt/completion/tool content`},{kind:`set`,key:`OTEL_METRICS_EXPORTER`,value:`otlp`,comment:`tokens / cost`},{kind:`set`,key:`OTEL_TRACES_EXPORTER`,value:`otlp`,comment:`spans (beta)`},{kind:`blank`});let o=Oa[r];if(o.length===0)a.push({kind:`comment`,text:`Content gates intentionally OFF (metadata-only: tokens, durations, tool names — no prompt/completion/tool bodies).`});else{a.push({kind:`comment`,text:`THE CONTENT GATES (all default OFF):`});for(let e of o)a.push({kind:`set`,key:e.key,value:`1`,comment:e.comment})}return Aa(a,i)}function Ma(e){return[Ea,ja(e),Da].join(`
140
140
  `)}function Na(e,t){let n=e.indexOf(Ea);if(n!==-1){let r=e.indexOf(Da,n);if(r===-1)throw Error(`shell rc has a '${Ea}' marker without its closing '${Da}' — fix it by hand and re-run`);let i=r+43,a=`${e.slice(0,n)}${t}${e.slice(i)}`;return{contents:a,changed:a!==e}}return{contents:`${e.length===0?``:Pa(e)}${t}\n`,changed:!0}}function Pa(e){return e.endsWith(`
141
141
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/sandbox-cli",
3
- "version": "0.23.191",
3
+ "version": "0.23.193",
4
4
  "description": "CLI for Tangle Sandbox operations",
5
5
  "type": "module",
6
6
  "engines": {
@@ -26,7 +26,7 @@
26
26
  "@tangle-network/agent-runtime": "^10.0.12",
27
27
  "@tangle-network/harness-sessions": "^1.0.13",
28
28
  "@tangle-network/hub-sdk": "1.0.35",
29
- "@tangle-network/sandbox": "^1.0.619",
29
+ "@tangle-network/sandbox": "^1.0.622",
30
30
  "@tangle-network/sdk-cli-runner": "^0.3.18",
31
31
  "chalk": "^5.6.2",
32
32
  "cli-bridge": "https://codeload.github.com/drewstone/cli-bridge/tar.gz/57fe9a06cdf4b649b05caa01fa242736d5e0ffd5",
@@ -61,8 +61,8 @@
61
61
  "typescript": "^6.0.3",
62
62
  "vitest": "^4.1.12",
63
63
  "@repo/shared": "0.0.0",
64
- "@tangle-network/runtime-contracts": "0.20.0",
65
64
  "@tangle-network/sdk-session-persistence": "0.7.0",
65
+ "@tangle-network/runtime-contracts": "0.20.0",
66
66
  "@repo/knowledge-host": "0.0.0"
67
67
  },
68
68
  "publishConfig": {
@@ -87,8 +87,8 @@
87
87
  "author": "Tangle Network",
88
88
  "license": "MIT",
89
89
  "tangleRelease": {
90
- "sourceSha": "834c0a75e51ca8855687f8ea6cf9ea0b54a4f17d",
91
- "mergedAt": "2026-11-27T04:29:42-08:00"
90
+ "sourceSha": "4eefe96acd84a12f05283daae49a04206ee8af5e",
91
+ "mergedAt": "2026-11-27T06:24:27-08:00"
92
92
  },
93
93
  "scripts": {
94
94
  "build": "tsdown",