UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

165 lines (164 loc) • 5.81 kB
import { D as parseStrictPositiveInteger, V as timestampMsToIsoString } from "./number-coercion-D6u-4YD8.mjs"; import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs"; import { o as getAsyncWorkSignal } from "./async-work-scope-BXagjUap.mjs"; import { t as captureRuntimeConfigAsyncReader } from "./io.runtime-DsJ2dLCQ.mjs"; import "./io-4QsrsWTJ.mjs"; import { n as resolveSessionTarget, t as callSessionTargetGateway } from "./session-target-Coklf7kJ.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"; //#region 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", "\nExamples:\n openclaw attach Attach Claude Code to the main session\n openclaw attach movies-a1166b81 Attach to a short session reference\n openclaw attach --session agent:main:telegram:123 --ttl 600000\n openclaw attach --print-config Set up the grant + config and print how to launch it yourself\n").action(async (e, t) => { const n = getAsyncWorkSignal(); n?.throwIfAborted(); if (e && t.session) throw new Error("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); }); } //#endregion export { registerAttachCli };