@gguf/claw
Version:
Multi-channel AI gateway with extensible messaging integrations
309 lines (305 loc) • 14.8 kB
JavaScript
import { Dt as theme, _ as defaultRuntime, w as DEFAULT_CHAT_CHANNEL, xt as setVerbose } from "./entry.js";
import "./auth-profiles-DFa1zzNy.js";
import { t as formatCliCommand } from "./command-format-D3syQOZg.js";
import { l as normalizeAgentId } from "./session-key-BGiG_JcT.js";
import "./exec-CBKBIMpA.js";
import { n as listAgentIds } from "./agent-scope-RzK9Zcks.js";
import "./github-copilot-token-DuFIqfeC.js";
import "./model-DY9t1aT6.js";
import "./pi-model-discovery-Do3xMEtM.js";
import "./frontmatter-D-YR-Ghi.js";
import "./skills-DJmGZazd.js";
import "./manifest-registry-DS2iK5AZ.js";
import { i as loadConfig } from "./config-B2kL1ciP.js";
import "./client-CDjZdZtI.js";
import { a as randomIdempotencyKey, n as callGateway } from "./call-DXhJGwEy.js";
import { h as GATEWAY_CLIENT_NAMES, l as normalizeMessageChannel, m as GATEWAY_CLIENT_MODES } from "./message-channel-CVHJDItx.js";
import "./pairing-token-Byh6drgn.js";
import { C as agentCommand, O as createDefaultDeps, w as resolveSessionKeyForRequest } from "./subagent-registry-C7Edpn23.js";
import "./sessions-BD5dyLxb.js";
import "./tokens-D5RzuaYP.js";
import "./normalize-Db7Xtx2v.js";
import "./accounts-BpzwDfBB.js";
import "./bindings-KqaGKS1E.js";
import "./logging-CFvkxgcX.js";
import "./send-BFiRlO6V.js";
import "./plugins-RqhjLCb6.js";
import "./send-CWDtU8Gi.js";
import "./with-timeout-nVWy7PWz.js";
import "./deliver-CeVE1Jh-.js";
import "./diagnostic-774btyou.js";
import "./diagnostic-session-state-HO94DMou.js";
import "./accounts-B3D4iWUP.js";
import "./send-DCCBUsNn.js";
import "./image-ops-lDlFpoR2.js";
import "./pi-embedded-helpers-NVEtaJwl.js";
import "./sandbox-CO-R8v6J.js";
import "./common-DcSh1hZE.js";
import "./chrome-52ZF7gmE.js";
import "./tailscale-BzRVNhMW.js";
import "./auth-Dq2pFnjj.js";
import "./server-context-C1f7cijA.js";
import "./routes-BJmh1Ify.js";
import "./redact-C2s6sr73.js";
import "./errors-CFEPAPWc.js";
import "./fs-safe-3YwsxSr5.js";
import "./paths-CXKNzNjU.js";
import "./ssrf-Cv2DiHsm.js";
import "./store-e6fIrP17.js";
import "./ports-59j-bA53.js";
import "./trash-DVLJ0k6q.js";
import "./dock-BZuwgj1O.js";
import "./accounts-Jg3_1Y-r.js";
import "./paths-CXpciDEv.js";
import "./thinking-CJPPUYWd.js";
import "./models-config-5zJ39mUb.js";
import "./reply-prefix-DJOqzjBt.js";
import "./memory-cli-C3uas9sI.js";
import "./manager-D3ZmOwqt.js";
import "./gemini-auth-CdgAkz2K.js";
import "./sqlite-1-TCahE6.js";
import "./retry-BcjnIuo-.js";
import "./chunk-Z2NYDchs.js";
import "./markdown-tables-GCHx-nGT.js";
import "./fetch-guard-B5BAqVyD.js";
import "./local-roots-SkDT1Wv8.js";
import "./ir-DAwVi0a7.js";
import "./render-e7fENCYH.js";
import "./commands-registry-CRmMPJQ9.js";
import "./image-QGUQCdGh.js";
import "./tool-display-Cs1uRaRV.js";
import "./runner-D81xREgc.js";
import "./model-catalog-DLoDxnxL.js";
import "./session-utils-C3Oi9cXA.js";
import "./skill-commands-D2rmj6w8.js";
import "./workspace-dirs-BXftTDSV.js";
import "./pairing-store-CruPwgBw.js";
import "./fetch-vg2oFVIH.js";
import "./exec-approvals-BZA6z4HM.js";
import "./nodes-screen-x7YKy8Ay.js";
import "./session-cost-usage-CpxG9Mup.js";
import "./pi-tools.policy-DeRwGLEO.js";
import "./control-service-DGleRjGJ.js";
import "./stagger-CArN2YVJ.js";
import "./channel-selection-DoXlsBhe.js";
import "./send-C3RIrBTr.js";
import "./outbound-attachment-CdFWGHgJ.js";
import "./delivery-queue-DKdWlR61.js";
import "./send-0Nz3O9Jc.js";
import "./resolve-route-BONxzeyg.js";
import "./channel-activity-BYGpAtHP.js";
import "./tables-BrqD0SUa.js";
import "./proxy-DL3MD6-P.js";
import { t as formatDocsLink } from "./links-CW8Bx7rK.js";
import { n as runCommandWithRuntime } from "./cli-utils-CCaEbxAz.js";
import { t as formatHelpExamples } from "./help-format-B0pWGnZs.js";
import { n as withProgress } from "./progress-BAHiAaDW.js";
import "./replies-CuUAAFF2.js";
import "./onboard-helpers-CEx2tGVB.js";
import "./prompt-style-DwCXob2h.js";
import "./pairing-labels-DtxjElSq.js";
import { t as hasExplicitOptions } from "./command-options-CRqZtG5w.js";
import "./catalog-vmrRUSxJ.js";
import "./note-D3Xn5qjj.js";
import "./clack-prompter-DOOcFy2t.js";
import "./plugin-auto-enable-DR5UZ2Ky.js";
import "./install-safe-path-CnPOnUC0.js";
import "./npm-registry-spec-Dx1jSlNK.js";
import "./skill-scanner-BlmeBzA8.js";
import "./installs-Bfs-7l-S.js";
import "./onboard-channels-CBn2fwj1.js";
import "./config-validation-CBZ_NgG2.js";
import { t as collectOption } from "./helpers-B7ilMWgy.js";
import "./agents.config-CUoqlGqW.js";
import "./shared-DpLvAirU.js";
import "./auth-token-B5F1NkdJ.js";
import "./logging-BGewRZy0.js";
import "./provider-auth-helpers-CSWFmrj3.js";
import { a as agentsAddCommand, i as agentsDeleteCommand, n as agentsListCommand, r as agentsSetIdentityCommand } from "./agents-Dm5MQsPx.js";
import "./auth-choice-fTuBDh_7.js";
import "./openai-model-default-DYWb04WS.js";
import "./vllm-setup-DYvSzA2g.js";
//#region src/commands/agent-via-gateway.ts
const NO_GATEWAY_TIMEOUT_MS = 2147e6;
function parseTimeoutSeconds(opts) {
const raw = opts.timeout !== void 0 ? Number.parseInt(String(opts.timeout), 10) : opts.cfg.agents?.defaults?.timeoutSeconds ?? 600;
if (Number.isNaN(raw) || raw < 0) throw new Error("--timeout must be a non-negative integer (seconds; 0 means no timeout)");
return raw;
}
function formatPayloadForLog(payload) {
const lines = [];
if (payload.text) lines.push(payload.text.trimEnd());
const mediaUrl = typeof payload.mediaUrl === "string" && payload.mediaUrl.trim() ? payload.mediaUrl.trim() : void 0;
const media = payload.mediaUrls ?? (mediaUrl ? [mediaUrl] : []);
for (const url of media) lines.push(`MEDIA:${url}`);
return lines.join("\n").trimEnd();
}
async function agentViaGatewayCommand(opts, runtime) {
const body = (opts.message ?? "").trim();
if (!body) throw new Error("Message (--message) is required");
if (!opts.to && !opts.sessionId && !opts.agent) throw new Error("Pass --to <E.164>, --session-id, or --agent to choose a session");
const cfg = loadConfig();
const agentIdRaw = opts.agent?.trim();
const agentId = agentIdRaw ? normalizeAgentId(agentIdRaw) : void 0;
if (agentId) {
if (!listAgentIds(cfg).includes(agentId)) throw new Error(`Unknown agent id "${agentIdRaw}". Use "${formatCliCommand("openclaw agents list")}" to see configured agents.`);
}
const timeoutSeconds = parseTimeoutSeconds({
cfg,
timeout: opts.timeout
});
const gatewayTimeoutMs = timeoutSeconds === 0 ? NO_GATEWAY_TIMEOUT_MS : Math.max(1e4, (timeoutSeconds + 30) * 1e3);
const sessionKey = resolveSessionKeyForRequest({
cfg,
agentId,
to: opts.to,
sessionId: opts.sessionId
}).sessionKey;
const channel = normalizeMessageChannel(opts.channel) ?? DEFAULT_CHAT_CHANNEL;
const idempotencyKey = opts.runId?.trim() || randomIdempotencyKey();
const response = await withProgress({
label: "Waiting for agent reply…",
indeterminate: true,
enabled: opts.json !== true
}, async () => await callGateway({
method: "agent",
params: {
message: body,
agentId,
to: opts.to,
replyTo: opts.replyTo,
sessionId: opts.sessionId,
sessionKey,
thinking: opts.thinking,
deliver: Boolean(opts.deliver),
channel,
replyChannel: opts.replyChannel,
replyAccountId: opts.replyAccount,
timeout: timeoutSeconds,
lane: opts.lane,
extraSystemPrompt: opts.extraSystemPrompt,
idempotencyKey
},
expectFinal: true,
timeoutMs: gatewayTimeoutMs,
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI
}));
if (opts.json) {
runtime.log(JSON.stringify(response, null, 2));
return response;
}
const payloads = (response?.result)?.payloads ?? [];
if (payloads.length === 0) {
runtime.log(response?.summary ? String(response.summary) : "No reply from agent.");
return response;
}
for (const payload of payloads) {
const out = formatPayloadForLog(payload);
if (out) runtime.log(out);
}
return response;
}
async function agentCliCommand(opts, runtime, deps) {
const localOpts = {
...opts,
agentId: opts.agent,
replyAccountId: opts.replyAccount
};
if (opts.local === true) return await agentCommand(localOpts, runtime, deps);
try {
return await agentViaGatewayCommand(opts, runtime);
} catch (err) {
runtime.error?.(`Gateway agent failed; falling back to embedded: ${String(err)}`);
return await agentCommand(localOpts, runtime, deps);
}
}
//#endregion
//#region src/cli/program/register.agent.ts
function registerAgentCommands(program, args) {
program.command("agent").description("Run an agent turn via the Gateway (use --local for embedded)").requiredOption("-m, --message <text>", "Message body for the agent").option("-t, --to <number>", "Recipient number in E.164 used to derive the session key").option("--session-id <id>", "Use an explicit session id").option("--agent <id>", "Agent id (overrides routing bindings)").option("--thinking <level>", "Thinking level: off | minimal | low | medium | high").option("--verbose <on|off>", "Persist agent verbose level for the session").option("--channel <channel>", `Delivery channel: ${args.agentChannelOptions} (default: ${DEFAULT_CHAT_CHANNEL})`).option("--reply-to <target>", "Delivery target override (separate from session routing)").option("--reply-channel <channel>", "Delivery channel override (separate from routing)").option("--reply-account <id>", "Delivery account id override").option("--local", "Run the embedded agent locally (requires model provider API keys in your shell)", false).option("--deliver", "Send the agent's reply back to the selected channel", false).option("--json", "Output result as JSON", false).option("--timeout <seconds>", "Override agent command timeout (seconds, default 600 or config value)").addHelpText("after", () => `
${theme.heading("Examples:")}
${formatHelpExamples([
["openclaw agent --to +15555550123 --message \"status update\"", "Start a new session."],
["openclaw agent --agent ops --message \"Summarize logs\"", "Use a specific agent."],
["openclaw agent --session-id 1234 --message \"Summarize inbox\" --thinking medium", "Target a session with explicit thinking level."],
["openclaw agent --to +15555550123 --message \"Trace logs\" --verbose on --json", "Enable verbose logging and JSON output."],
["openclaw agent --to +15555550123 --message \"Summon reply\" --deliver", "Deliver reply."],
["openclaw agent --agent ops --message \"Generate report\" --deliver --reply-channel slack --reply-to \"#reports\"", "Send reply to a different channel/target."]
])}
${theme.muted("Docs:")} ${formatDocsLink("/cli/agent", "docs.openclaw.ai/cli/agent")}`).action(async (opts) => {
setVerbose((typeof opts.verbose === "string" ? opts.verbose.toLowerCase() : "") === "on");
const deps = createDefaultDeps();
await runCommandWithRuntime(defaultRuntime, async () => {
await agentCliCommand(opts, defaultRuntime, deps);
});
});
const agents = program.command("agents").description("Manage isolated agents (workspaces + auth + routing)").addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/agents", "docs.openclaw.ai/cli/agents")}\n`);
agents.command("list").description("List configured agents").option("--json", "Output JSON instead of text", false).option("--bindings", "Include routing bindings", false).action(async (opts) => {
await runCommandWithRuntime(defaultRuntime, async () => {
await agentsListCommand({
json: Boolean(opts.json),
bindings: Boolean(opts.bindings)
}, defaultRuntime);
});
});
agents.command("add [name]").description("Add a new isolated agent").option("--workspace <dir>", "Workspace directory for the new agent").option("--model <id>", "Model id for this agent").option("--agent-dir <dir>", "Agent state directory for this agent").option("--bind <channel[:accountId]>", "Route channel binding (repeatable)", collectOption, []).option("--non-interactive", "Disable prompts; requires --workspace", false).option("--json", "Output JSON summary", false).action(async (name, opts, command) => {
await runCommandWithRuntime(defaultRuntime, async () => {
const hasFlags = hasExplicitOptions(command, [
"workspace",
"model",
"agentDir",
"bind",
"nonInteractive"
]);
await agentsAddCommand({
name: typeof name === "string" ? name : void 0,
workspace: opts.workspace,
model: opts.model,
agentDir: opts.agentDir,
bind: Array.isArray(opts.bind) ? opts.bind : void 0,
nonInteractive: Boolean(opts.nonInteractive),
json: Boolean(opts.json)
}, defaultRuntime, { hasFlags });
});
});
agents.command("set-identity").description("Update an agent identity (name/theme/emoji/avatar)").option("--agent <id>", "Agent id to update").option("--workspace <dir>", "Workspace directory used to locate the agent + IDENTITY.md").option("--identity-file <path>", "Explicit IDENTITY.md path to read").option("--from-identity", "Read values from IDENTITY.md", false).option("--name <name>", "Identity name").option("--theme <theme>", "Identity theme").option("--emoji <emoji>", "Identity emoji").option("--avatar <value>", "Identity avatar (workspace path, http(s) URL, or data URI)").option("--json", "Output JSON summary", false).addHelpText("after", () => `
${theme.heading("Examples:")}
${formatHelpExamples([
["openclaw agents set-identity --agent main --name \"OpenClaw\" --emoji \"🦞\"", "Set name + emoji."],
["openclaw agents set-identity --agent main --avatar avatars/openclaw.png", "Set avatar path."],
["openclaw agents set-identity --workspace ~/.openclaw/workspace --from-identity", "Load from IDENTITY.md."],
["openclaw agents set-identity --identity-file ~/.openclaw/workspace/IDENTITY.md --agent main", "Use a specific IDENTITY.md."]
])}
`).action(async (opts) => {
await runCommandWithRuntime(defaultRuntime, async () => {
await agentsSetIdentityCommand({
agent: opts.agent,
workspace: opts.workspace,
identityFile: opts.identityFile,
fromIdentity: Boolean(opts.fromIdentity),
name: opts.name,
theme: opts.theme,
emoji: opts.emoji,
avatar: opts.avatar,
json: Boolean(opts.json)
}, defaultRuntime);
});
});
agents.command("delete <id>").description("Delete an agent and prune workspace/state").option("--force", "Skip confirmation", false).option("--json", "Output JSON summary", false).action(async (id, opts) => {
await runCommandWithRuntime(defaultRuntime, async () => {
await agentsDeleteCommand({
id: String(id),
force: Boolean(opts.force),
json: Boolean(opts.json)
}, defaultRuntime);
});
});
agents.action(async () => {
await runCommandWithRuntime(defaultRuntime, async () => {
await agentsListCommand({}, defaultRuntime);
});
});
}
//#endregion
export { registerAgentCommands };