UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

9 lines • 4.92 kB
import{D as parseStrictPositiveInteger,V as timestampMsToIsoString}from"./number-coercion-B3CfI447.mjs";import{r as defaultRuntime}from"./runtime-DIcLIHcp.mjs";import{o as getAsyncWorkSignal}from"./async-work-scope-DBcxYU4O.mjs";import{t as captureRuntimeConfigAsyncReader}from"./io.runtime-BvSeVFIY.mjs";import"./io-Di_yuX3t.mjs";import{n as throwExpectedCliError}from"./expected-cli-error-oDVmXYil.mjs";import{n as resolveSessionTarget,t as callSessionTargetGateway}from"./session-target-TPW_U_r7.mjs";import{mkdtempSync,rmSync,writeFileSync}from"node:fs";import{join}from"node:path";import{constants as constants$1,tmpdir}from"node:os";import{spawn}from"node:child_process"; //!src/cli/attach-cli.ts function writeClaudeMcpConfig(e){const t=mkdtempSync(join(tmpdir(),`openclaw-attach-`));const n=join(t,`.mcp.json`);try{writeFileSync(n,JSON.stringify(e,null,2),{encoding:`utf8`,mode:384})}catch(e){rmSync(t,{recursive:true,force:true});throw e}return{path:n,cleanup:()=>rmSync(t,{recursive:true,force:true})}}async function registerAttachCli(e){e.command(`attach`).description(`Attach Claude Code to a gateway session with scoped MCP tools`).argument(`[target]`,`Control UI URL, host/agent/ref, short ref, or agent:... key`).option(`--session <key>`,`Gateway session key to bind (default: main session)`).option(`--url <url>`,`Gateway WebSocket URL`).option(`--token <token>`,`Gateway token (if required)`).option(`--password <password>`,`Gateway password (if required)`).option(`--tls-fingerprint <sha256>`,`Expected Gateway TLS certificate fingerprint`).option(`--ttl <ms>`,`Grant TTL in positive base-10 integer milliseconds (default: gateway policy)`).option(`--bin <path>`,`Claude Code binary to spawn`,`claude`).option(`--print-config`,`Mint the grant + write the .mcp.json, print how to launch it, and exit without spawning`,false).addHelpText(`after`,` Examples: openclaw attach Attach Claude Code to the main session openclaw attach movies-a1166b81 Attach to a short session reference openclaw attach --session agent:main:telegram:123 --ttl 600000 openclaw attach --print-config Set up the grant + config and print how to launch it yourself `).action(async(e,t)=>{const n=getAsyncWorkSignal();n?.throwIfAborted();if(e&&t.session)throwExpectedCliError(`pass one session target: use either the positional target or --session`);let r;if(t.ttl!==void 0){r=parseStrictPositiveInteger(t.ttl);if(r===void 0){defaultRuntime.error(`--ttl must be a positive integer of milliseconds. Got: ${JSON.stringify(t.ttl)}`);defaultRuntime.exit(1);return}}const i={config:await captureRuntimeConfigAsyncReader()(),url:t.url,token:t.token,password:t.password,tlsFingerprint:t.tlsFingerprint};const a=e?await resolveSessionTarget({raw:e,gateway:i}):void 0;const o=a?.gateway??i;n?.throwIfAborted();const s=await callSessionTargetGateway({gateway:o,method:`attach.grant`,request:{sessionKey:a?.sessionKey??t.session,...a?{agentId:a.agentId}:{},ttlMs:r},requiredScope:`operator.admin`});let c=false;let l;let detachChild;const u=timestampMsToIsoString(s?.expiresAtMs);let d=0;try{if(!s||typeof s.token!==`string`||typeof s.sessionKey!==`string`||u===void 0||!s.mcpConfig?.mcpServers||typeof s.env!==`object`||s.env===null){defaultRuntime.error(`attach.grant returned an unexpected response from the gateway.`);defaultRuntime.exit(1);return}n?.throwIfAborted();const e=writeClaudeMcpConfig(s.mcpConfig);l=e.cleanup;const r=[`--strict-mcp-config`,`--mcp-config`,e.path];if(t.printConfig){defaultRuntime.log(JSON.stringify({sessionKey:s.sessionKey,expiresAt:u,env:s.env,configPath:e.path,launch:[t.bin,...r]},null,2));defaultRuntime.log(`Grant is live until ${u} and auto-expires; it is not revoked here. Launch with the env above, then delete ${e.path} when done.`);c=true;return}defaultRuntime.log(`Attaching Claude Code to session ${s.sessionKey} (grant expires ${u})…`);n?.throwIfAborted();const i=spawn(t.bin,r,{stdio:`inherit`,env:{...process.env,...s.env}});let a=false;let o;const onError=e=>{o??=e};const onSigint=()=>{};const onSigterm=()=>{if(!a)i.kill(`SIGTERM`)};i.on(`error`,onError);process.on(`SIGINT`,onSigint);process.on(`SIGTERM`,onSigterm);detachChild=()=>{i.off(`error`,onError);process.off(`SIGINT`,onSigint);process.off(`SIGTERM`,onSigterm)};const f=await new Promise(e=>{i.once(`close`,(t,n)=>{a=true;e({code:t,signal:n})})});if(o){defaultRuntime.error(`Failed to launch '${t.bin}': ${String(o)}`);d=1}else d=f.signal?128+(constants$1.signals[f.signal]??0):f.code??0}finally{try{if(!c&&typeof s?.token===`string`)try{await callSessionTargetGateway({gateway:o,method:`attach.revoke`,request:{token:s.token},requiredScope:`operator.admin`})}catch(e){defaultRuntime.error(`Warning: failed to revoke attach grant; it remains live until ${u??String(s.expiresAtMs)}. ${String(e)}`)}finally{l?.()}}finally{detachChild?.()}}defaultRuntime.exit(d)})}export{registerAttachCli};