@gguf/claw
Version:
WhatsApp gateway CLI (Baileys web) with Pi RPC agent
996 lines (987 loc) • 630 kB
JavaScript
import { $ as DEFAULT_CHAT_CHANNEL, A as getChildLogger, B as resolveConfigPath, C as setVerbose, D as colorize, F as CONFIG_PATH, L as STATE_DIR, M as getResolvedLoggerSettings, O as isRich, R as isNixMode, U as resolveGatewayLockDir, W as resolveGatewayPort, X as resolveStateDir, Z as CHANNEL_IDS, j as getLogger, k as theme, l as setConsoleSubsystemFilter, n as isTruthyEnvValue, o as createSubsystemLogger, p as defaultRuntime, r as logAcceptedEnvOption, s as runtimeForLogger, st as getActivePluginRegistry, u as setConsoleTimestampPrefix } from "./entry.js";
import { D as isCliProvider, E as getModelRefStatus, F as resolveHooksGmailModel, L as resolveThinkingDefault, N as resolveConfiguredModelRef, P as resolveDefaultModelForAgent, _t as DEFAULT_PROVIDER, gt as DEFAULT_MODEL, ht as DEFAULT_CONTEXT_TOKENS, j as resolveAllowedModelRef } from "./auth-profiles-CYBuGiBb.js";
import { t as formatCliCommand } from "./command-format-ayFsmwwz.js";
import { _ as parseAgentSessionKey, c as normalizeAgentId, g as isSubagentSessionKey, i as buildAgentMainSessionKey, l as normalizeMainKey, p as toAgentRequestSessionKey, t as DEFAULT_ACCOUNT_ID, u as resolveAgentIdFromSessionKey } from "./session-key-CZkcvAtx.js";
import { b as truncateUtf16Safe, g as shortenHomePath, m as resolveUserPath, o as ensureDir, t as CONFIG_DIR } from "./utils-DX85MiPR.js";
import { a as logDebug, c as logWarn, n as runExec, t as runCommandWithTimeout } from "./exec-B8JKbXKW.js";
import { t as resolveOpenClawPackageRoot } from "./openclaw-root-9ILYSmJ9.js";
import { T as resolveWorkspaceTemplateDir, _ as DEFAULT_MEMORY_FILENAME, b as DEFAULT_USER_FILENAME, c as resolveDefaultAgentId, d as DEFAULT_AGENTS_FILENAME, g as DEFAULT_MEMORY_ALT_FILENAME, h as DEFAULT_IDENTITY_FILENAME, i as resolveAgentModelFallbacksOverride, l as resolveSessionAgentId, m as DEFAULT_HEARTBEAT_FILENAME, n as resolveAgentConfig, p as DEFAULT_BOOTSTRAP_FILENAME, r as resolveAgentDir, s as resolveAgentWorkspaceDir, t as listAgentIds, v as DEFAULT_SOUL_FILENAME, w as resolveDefaultAgentWorkspaceDir, x as ensureAgentWorkspace, y as DEFAULT_TOOLS_FILENAME } from "./agent-scope-C9VjJXEK.js";
import "./github-copilot-token-SLWintYd.js";
import "./pi-model-discovery-DzEIEgHL.js";
import { A as resolveSubagentMaxConcurrent, T as applyLegacyMigrations, a as parseConfigJson5, c as writeConfigFile, i as loadConfig, j as VERSION, k as resolveAgentMaxConcurrent, l as validateConfigObjectWithPlugins, n as migrateLegacyConfig, o as readConfigFileSnapshot, r as createConfigIO, s as resolveConfigSnapshotHash, u as OpenClawSchema } from "./config-CKLedg5Y.js";
import { o as isTestDefaultMemorySlotDisabled } from "./manifest-registry-C69Z-I4v.js";
import "./server-context-yKyxyxOJ.js";
import { d as ensurePortAvailable, f as inspectPortUsage, m as formatPortDiagnostics, n as formatErrorMessage } from "./errors-CZ9opC6L.js";
import { t as rawDataToString } from "./ws-D091yo4M.js";
import { n as createBrowserControlContext, r as startBrowserControlServiceFromConfig } from "./control-service-D2E9NKqQ.js";
import { t as ensureOpenClawCliOnPath } from "./path-env-h3xp5PqO.js";
import { i as enableTailscaleServe, n as disableTailscaleServe, o as getTailnetHostname, r as enableTailscaleFunnel, t as disableTailscaleFunnel } from "./tailscale-9MusRvOi.js";
import { n as pickPrimaryTailnetIPv6, t as pickPrimaryTailnetIPv4 } from "./tailnet-Byp3obcc.js";
import { a as resolveGatewayBindHost, n as isLoopbackHost$2, o as resolveGatewayClientIp, r as isTrustedProxyAddress, s as resolveGatewayListenHosts, t as isLoopbackAddress } from "./net-CWMMy37F.js";
import { i as resolveGatewayAuth, n as authorizeGatewayConnect, r as isLocalDirectRequest, t as assertGatewayAuthConfigured } from "./auth-DksjO6WG.js";
import { $ as validatePollParams, A as validateDevicePairListParams, At as deriveDeviceIdFromPublicKey, B as validateLogsTailParams, C as validateCronListParams, Ct as PROTOCOL_VERSION, D as validateCronStatusParams, Dt as parseSessionLabel, E as validateCronRunsParams, F as validateExecApprovalResolveParams, G as validateNodeInvokeResultParams, H as validateNodeDescribeParams, I as validateExecApprovalsGetParams, J as validateNodePairListParams, K as validateNodeListParams, L as validateExecApprovalsNodeGetParams, M as validateDeviceTokenRevokeParams, Mt as normalizeDevicePublicKeyBase64Url, N as validateDeviceTokenRotateParams, Nt as verifyDeviceSignature, O as validateCronUpdateParams, Ot as buildDeviceAuthPayload, P as validateExecApprovalRequestParams, Q as validateNodeRenameParams, R as validateExecApprovalsNodeSetParams, S as validateCronAddParams, St as validateWizardStatusParams, T as validateCronRunParams, Tt as errorShape, U as validateNodeEventParams, V as validateModelsListParams, W as validateNodeInvokeParams, X as validateNodePairRequestParams, Y as validateNodePairRejectParams, Z as validateNodePairVerifyParams, _ as validateConfigGetParams, _t as validateWebLoginStartParams, a as validateAgentWaitParams, at as validateSessionsPatchParams, b as validateConfigSetParams, bt as validateWizardNextParams, c as validateAgentsFilesSetParams, ct as validateSessionsResolveParams, d as validateChannelsStatusParams, dt as validateSkillsInstallParams, et as validateRequestFrame, f as validateChatAbortParams, ft as validateSkillsStatusParams, g as validateConfigApplyParams, gt as validateWakeParams, h as validateChatSendParams, ht as validateUpdateRunParams, i as validateAgentParams, it as validateSessionsListParams, j as validateDevicePairRejectParams, k as validateDevicePairApproveParams, l as validateAgentsListParams, lt as validateSessionsUsageParams, m as validateChatInjectParams, mt as validateTalkModeParams, n as formatValidationErrors, nt as validateSessionsCompactParams, o as validateAgentsFilesGetParams, ot as validateSessionsPreviewParams, p as validateChatHistoryParams, pt as validateSkillsUpdateParams, q as validateNodePairApproveParams, r as validateAgentIdentityParams, rt as validateSessionsDeleteParams, s as validateAgentsFilesListParams, st as validateSessionsResetParams, tt as validateSendParams, u as validateChannelsLogoutParams, ut as validateSkillsBinsParams, v as validateConfigPatchParams, vt as validateWebLoginWaitParams, w as validateCronRemoveParams, wt as ErrorCodes, x as validateConnectParams, xt as validateWizardStartParams, y as validateConfigSchemaParams, yt as validateWizardCancelParams, z as validateExecApprovalsSetParams } from "./client-CxbkcEZ7.js";
import { n as callGateway, o as loadGatewayTlsRuntime$1 } from "./call-90HgQQ8o.js";
import { f as GATEWAY_CLIENT_CAPS, g as hasGatewayClientCap, h as GATEWAY_CLIENT_NAMES, i as isGatewayMessageChannel, l as normalizeMessageChannel, m as GATEWAY_CLIENT_MODES, n as isDeliverableMessageChannel, p as GATEWAY_CLIENT_IDS, r as isGatewayCliClient, s as isWebchatClient, t as INTERNAL_MESSAGE_CHANNEL } from "./message-channel-BlgPSDAh.js";
import { t as formatDocsLink } from "./links-D0uzJbi6.js";
import { r as buildChannelUiCatalog, t as applyPluginAutoEnable } from "./plugin-auto-enable-DyW8lHTT.js";
import { n as listChannelPlugins, r as normalizeChannelId, t as getChannelPlugin } from "./plugins-BUPpq5aS.js";
import "./logging-CfEk_PnX.js";
import "./accounts-Dto4p9zB.js";
import { $ as approveNodePairing, $n as isTtsEnabled, $t as listSessionsFromStore, A as resolveHeartbeatVisibility, An as scheduleGatewaySigusr1Restart, Ar as clearInternalHooks, B as createReplyDispatcher, Bn as normalizeCronJobPatch, Bt as emitAgentEvent, C as buildControlUiAvatarUrl, Cn as resetDirectoryCache, Cr as resolveUserTimeFormat, Ct as normalizeMimeList, Dn as authorizeGatewaySigusr1Restart, Dt as runEmbeddedPiAgent, Et as stopSubagentsForRequester, Ft as getHookType, G as normalizeSendPolicy, Gn as isSystemEventContextChanged, H as getCliSessionId, Ht as onAgentEvent, In as summarizeRestartSentinel, It as isExternalHookSession, J as primeRemoteSkillsCache, Jt as loadProviderUsageSummary, K as resolveSendPolicy, Kt as loadModelCatalog, L as getChannelActivity, Lt as initSubagentRegistry, M as getLastHeartbeatEvent, Mn as consumeRestartSentinel, Mr as registerInternalHook, Mt as createOpenClawTools, N as onHeartbeatEvent, Nn as formatDoctorNonInteractiveHint, Nr as triggerInternalHook, Nt as buildSafeExternalPrompt, O as createReplyPrefixOptions, On as consumeGatewaySigusr1RestartAuthorization, Or as resolveAgentIdentity, Ot as abortEmbeddedPiRun, Pn as formatRestartSentinelMessage, Pt as detectSuspiciousPatterns, Q as setSkillsRemoteRegistry, Qn as getTtsProvider, Qt as listAgentsForGateway, Rn as writeRestartSentinel, Rt as resolveAgentTimeoutMs, S as CONTROL_UI_AVATAR_PREFIX, Sr as formatUserTime, St as extractImageContentFromSource, T as resolveAssistantAvatarUrl, Tn as runWithModelFallback, Tt as isAbortTrigger, U as setCliSessionId, Ut as registerAgentRunContext, Vn as migrateLegacyCronPayload, Vt as getAgentRunContext, W as runCliAgent, Wn as enqueueSystemEvent, Wt as resolveAnnounceTargetFromKey, X as refreshRemoteBinsForConnectedNodes, Xn as OPENAI_TTS_MODELS, Y as recordRemoteNodeInfo, Yn as getPluginToolMeta, Z as refreshRemoteNodeBins, Zn as OPENAI_TTS_VOICES, _t as DEFAULT_INPUT_PDF_MAX_PAGES, an as capArrayByJsonBytes, ar as resolveTtsProviderOrder, at as verifyNodeToken, bn as resolveOutboundTarget, bt as DEFAULT_INPUT_TIMEOUT_MS, cn as resolveSessionTranscriptCandidates, cr as textToSpeech, d as handleReset, dn as lookupContextTokens, dr as CommandLane, dt as DEFAULT_INPUT_FILE_MAX_BYTES, en as loadCombinedSessionStoreForGateway, er as isTtsProviderConfigured, et as listNodePairing, fn as clearSessionQueues, fr as startDiagnosticHeartbeat, ft as DEFAULT_INPUT_FILE_MAX_CHARS, gn as resolveOutboundSessionRoute, gt as DEFAULT_INPUT_MAX_REDIRECTS, hn as ensureOutboundSessionEntry, hr as DEFAULT_HEARTBEAT_ACK_MAX_CHARS, ht as DEFAULT_INPUT_IMAGE_MIMES, in as archiveFileOnDisk, ir as resolveTtsPrefsPath, it as updatePairedNodeMetadata, jn as setGatewaySigusr1RestartPolicy, jr as createInternalHookEvent, jt as registerUnhandledRejectionHandler, k as buildHistoryContextFromEntries, kn as isGatewaySigusr1RestartExternallyAllowed, kt as waitForEmbeddedPiRunEnd, ln as stripEnvelopeFromMessages, lt as applyVerboseOverride, mr as isDiagnosticsEnabled, mt as DEFAULT_INPUT_IMAGE_MAX_BYTES, n as handleSlackHttpRequest, nn as resolveGatewaySessionStoreTarget, nr as resolveTtsAutoMode, nt as renamePairedNode, on as readSessionMessages, or as setTtsEnabled, ot as getSkillsSnapshotVersion, pn as normalizeGroupActivation, pr as stopDiagnosticHeartbeat, pt as DEFAULT_INPUT_FILE_MIMES, q as getRemoteSkillEligibility, qn as requestHeartbeatNow, qt as applyModelOverrideToSessionEntry, rn as resolveSessionModelRef, rr as resolveTtsConfig, rt as requestNodePairing, sn as readSessionPreviewItemsFromTranscript, sr as setTtsProvider, st as registerSkillsChangeListener, t as loadOpenClawPlugins, tn as loadSessionEntry, tr as resolveTtsApiKey, tt as rejectNodePairing, ur as setCommandLaneConcurrency, ut as parseVerboseOverride, vt as DEFAULT_INPUT_PDF_MAX_PIXELS, w as normalizeControlUiBasePath, wr as resolveUserTimezone, wt as formatZonedTimestamp, xn as resolveSessionDeliveryTarget, xr as normalizePollInput, xt as extractFileContentFromSource, yr as stripHeartbeatToken, yt as DEFAULT_INPUT_PDF_MIN_TEXT_CHARS, z as dispatchInboundMessage, zn as normalizeCronJobCreate, zt as clearAgentRunContext } from "./loader-_Pj-TZS2.js";
import { n as withProgress } from "./progress-Da1ehW-x.js";
import "./prompt-style-Dc0C5HC9.js";
import "./note-Ci08TSbV.js";
import { t as WizardCancelledError } from "./prompts-CXLLIBwP.js";
import { t as resolveChannelDefaultAccountId } from "./helpers-D66_XoIz.js";
import "./onboard-channels-D-ZQTy5V.js";
import "./archive-D0z3LZDK.js";
import "./skill-scanner-Bp1D9gra.js";
import "./installs-DsJkyWfL.js";
import "./manager-BXiIQku7.js";
import { n as resolveSessionFilePath, o as resolveStorePath, r as resolveSessionTranscriptPath } from "./paths-CTg8F3AE.js";
import "./sqlite-DqUEZnjO.js";
import { m as detectMime, r as saveMediaBuffer } from "./routes-BSfXf8a5.js";
import { B as normalizeThinkLevel, F as formatXHighModelHint, H as normalizeVerboseLevel, P as formatThinkingLevels, R as normalizeElevatedLevel, V as normalizeUsageDisplay, W as supportsXHighThinking, z as normalizeReasoningLevel } from "./pi-embedded-helpers-DF8SAHU-.js";
import { o as normalizeReplyPayloadsForDelivery, t as deliverOutboundPayloads } from "./deliver-Cau4HL7W.js";
import { $ as stripPluginOnlyAllowlist, F as resolveExplicitAgentSessionKey, I as resolveMainSessionKey, J as collectExplicitAllowlist, L as resolveMainSessionKeyFromConfig, P as resolveAgentMainSessionKey, Q as resolveToolProfilePolicy, S as mergeDeliveryContext, Y as expandPolicyWithPluginGroups, Z as normalizeToolName, b as deliveryContextFromSession, d as loadSessionStore, g as updateSessionStore, q as buildPluginToolGroups, w as normalizeSessionDeliveryFields, z as snapshotSessionOrigin } from "./sandbox-DuqLKN5J.js";
import "./channel-summary-D9nzC5WB.js";
import { i as getMachineDisplayName, r as createBrowserRouteDispatcher } from "./wsl-ATjkMwMA.js";
import { d as hasBinary, i as loadWorkspaceSkillEntries, r as buildWorkspaceSkillSnapshot } from "./skills-CmU0Q92f.js";
import "./image-nRwqkmtf.js";
import { c as normalizeExecApprovals, g as saveExecApprovals, l as readExecApprovalsSnapshot, m as resolveExecApprovalsSocketPath, r as ensureExecApprovals } from "./exec-approvals-BCEFzcbC.js";
import "./redact-B8YiFlwn.js";
import "./tool-display-DmgKs6-V.js";
import { t as parseAbsoluteTimeMs } from "./parse-gTOGQPH6.js";
import { n as resolveMessageChannelSelection } from "./channel-selection-PZuuCvrp.js";
import { i as loadSessionUsageTimeSeries, l as hasNonzeroUsage, n as loadCostUsageSummary, r as loadSessionCostSummary, t as discoverAllSessions } from "./session-cost-usage-BTXosU1k.js";
import { n as formatTokenCount, r as formatUsd } from "./usage-format-E3bMcUMV.js";
import { c as resolveSubagentToolPolicy, i as filterToolsByPolicy, o as resolveEffectiveToolPolicy, s as resolveGroupToolPolicy } from "./commands-DAC7XMAT.js";
import "./pairing-store-DTfv_FGA.js";
import "./login-qr-Cmsf7BGt.js";
import { r as runCommandWithRuntime } from "./cli-utils-ByANh4Sp.js";
import "./pairing-labels-BbydDT7w.js";
import { t as buildChannelAccountSnapshot } from "./status-CRIEi8Mc.js";
import "./channels-status-issues-CJ8PJgDc.js";
import "./register.subclis-BpIR6Iqi.js";
import "./completion-cli-BbhA_JbG.js";
import { n as createOutboundSendDeps, t as createDefaultDeps } from "./deps-ytXmI88x.js";
import "./daemon-runtime-BCn_QIHK.js";
import "./service-_JwSmGSn.js";
import "./systemd-8sIc6isV.js";
import "./shared-fnGLWyZ6.js";
import { a as runDaemonStop, i as runDaemonStart, n as runDaemonStatus, o as runDaemonUninstall, r as runDaemonRestart, s as runDaemonInstall } from "./daemon-cli-CMKd_D6h.js";
import "./service-audit-DDX1kO3k.js";
import "./table-CJSx0YID.js";
import { n as resolveWideAreaDiscoveryDomain, r as writeWideAreaGatewayZone } from "./widearea-dns-CsSylzXH.js";
import { a as toOptionString, i as parsePort$1, n as extractGatewayMiskeys, r as maybeExplainGatewayServiceStop, t as describeUnknownError } from "./shared-C1XLEyB0.js";
import { i as probeGateway } from "./audit-BWbjQmyv.js";
import { g as discoverGatewayBeacons, n as installSkill } from "./onboard-skills-YobctE-R.js";
import { a as resolveControlUiRootOverrideSync, c as getHealthSnapshot, d as runHeartbeatOnce, f as setHeartbeatsEnabled, n as ensureControlUiAssetsBuilt, o as resolveControlUiRootSync, p as startHeartbeatRunner, s as formatHealthChannelLines } from "./health-format-ND2rUbQO.js";
import { S as normalizeUpdateChannel, _ as resolveNpmChannelTag, h as compareSemverStrings, m as checkUpdateStatus, t as runGatewayUpdate, y as DEFAULT_PACKAGE_CHANNEL } from "./update-runner-2i8_mIG5.js";
import "./github-copilot-auth-B_lK1g__.js";
import "./logging-Cc7m6PTv.js";
import { i as shouldIncludeHook, n as loadWorkspaceHookEntries, r as resolveHookConfig } from "./hooks-status-CKmUPU-M.js";
import { f as runOnboardingWizard, n as getStatusSummary, s as loadAgentIdentity, u as loadAgentIdentityFromWorkspace } from "./status-BRXuHUsK.js";
import { t as buildWorkspaceSkillStatus } from "./skills-status-DtXrj3fy.js";
import "./tui-DPorsF4z.js";
import { i as setGatewayWsLogStyle, n as logWs, r as summarizeAgentEventForWsLog, t as formatForLog } from "./ws-log-DJIXahf0.js";
import { T as resolveGmailHookRuntimeConfig, _ as buildGogWatchServeArgs, i as ensureTailscaleEndpoint, v as buildGogWatchStartArgs } from "./gmail-setup-utils-Bi6W14MK.js";
import { a as createOutboundSendDeps$1, i as resolveAgentOutboundTarget, r as resolveAgentDeliveryPlan, t as agentCommand } from "./agent-DztWhVCH.js";
import "./node-service-Lc1LlnFH.js";
import { n as forceFreePortAndWait } from "./ports-0V-Mu4ch.js";
import { spawn, spawnSync } from "node:child_process";
import path from "node:path";
import os from "node:os";
import chalk from "chalk";
import * as fsSync from "node:fs";
import fs, { constants } from "node:fs";
import JSON5 from "json5";
import fs$1 from "node:fs/promises";
import { fileURLToPath, pathToFileURL } from "node:url";
import crypto, { createHash, randomUUID } from "node:crypto";
import { CURRENT_SESSION_VERSION } from "@mariozechner/pi-coding-agent";
import { z } from "zod";
import { createServer } from "node:http";
import { WebSocketServer } from "ws";
import { Buffer as Buffer$1 } from "node:buffer";
import net from "node:net";
import chokidar from "chokidar";
import { createServer as createServer$1 } from "node:https";
import { Cron } from "croner";
//#region src/infra/ssh-config.ts
function parsePort(value) {
if (!value) return;
const parsed = Number.parseInt(value, 10);
if (!Number.isFinite(parsed) || parsed <= 0) return;
return parsed;
}
function parseSshConfigOutput(output) {
const result = { identityFiles: [] };
const lines = output.split("\n");
for (const raw of lines) {
const line = raw.trim();
if (!line) continue;
const [key, ...rest] = line.split(/\s+/);
const value = rest.join(" ").trim();
if (!key || !value) continue;
switch (key) {
case "user":
result.user = value;
break;
case "hostname":
result.host = value;
break;
case "port":
result.port = parsePort(value);
break;
case "identityfile":
if (value !== "none") result.identityFiles.push(value);
break;
default: break;
}
}
return result;
}
async function resolveSshConfig(target, opts = {}) {
const sshPath = "/usr/bin/ssh";
const args = ["-G"];
if (target.port > 0 && target.port !== 22) args.push("-p", String(target.port));
if (opts.identity?.trim()) args.push("-i", opts.identity.trim());
const userHost = target.user ? `${target.user}@${target.host}` : target.host;
args.push("--", userHost);
return await new Promise((resolve) => {
const child = spawn(sshPath, args, { stdio: [
"ignore",
"pipe",
"ignore"
] });
let stdout = "";
child.stdout?.setEncoding("utf8");
child.stdout?.on("data", (chunk) => {
stdout += String(chunk);
});
const timeoutMs = Math.max(200, opts.timeoutMs ?? 800);
const timer = setTimeout(() => {
try {
child.kill("SIGKILL");
} finally {
resolve(null);
}
}, timeoutMs);
child.once("error", () => {
clearTimeout(timer);
resolve(null);
});
child.once("exit", (code) => {
clearTimeout(timer);
if (code !== 0 || !stdout.trim()) {
resolve(null);
return;
}
resolve(parseSshConfigOutput(stdout));
});
});
}
//#endregion
//#region src/infra/ssh-tunnel.ts
function isErrno(err) {
return Boolean(err && typeof err === "object" && "code" in err);
}
function parseSshTarget(raw) {
const trimmed = raw.trim().replace(/^ssh\s+/, "");
if (!trimmed) return null;
const [userPart, hostPart] = trimmed.includes("@") ? (() => {
const idx = trimmed.indexOf("@");
const user = trimmed.slice(0, idx).trim();
const host = trimmed.slice(idx + 1).trim();
return [user || void 0, host];
})() : [void 0, trimmed];
const colonIdx = hostPart.lastIndexOf(":");
if (colonIdx > 0 && colonIdx < hostPart.length - 1) {
const host = hostPart.slice(0, colonIdx).trim();
const portRaw = hostPart.slice(colonIdx + 1).trim();
const port = Number.parseInt(portRaw, 10);
if (!host || !Number.isFinite(port) || port <= 0) return null;
if (host.startsWith("-")) return null;
return {
user: userPart,
host,
port
};
}
if (!hostPart) return null;
if (hostPart.startsWith("-")) return null;
return {
user: userPart,
host: hostPart,
port: 22
};
}
async function pickEphemeralPort() {
return await new Promise((resolve, reject) => {
const server = net.createServer();
server.once("error", reject);
server.listen(0, "127.0.0.1", () => {
const addr = server.address();
server.close(() => {
if (!addr || typeof addr === "string") {
reject(/* @__PURE__ */ new Error("failed to allocate a local port"));
return;
}
resolve(addr.port);
});
});
});
}
async function canConnectLocal(port) {
return await new Promise((resolve) => {
const socket = net.connect({
host: "127.0.0.1",
port
});
const done = (ok) => {
socket.removeAllListeners();
socket.destroy();
resolve(ok);
};
socket.once("connect", () => done(true));
socket.once("error", () => done(false));
socket.setTimeout(250, () => done(false));
});
}
async function waitForLocalListener(port, timeoutMs) {
const startedAt = Date.now();
while (Date.now() - startedAt < timeoutMs) {
if (await canConnectLocal(port)) return;
await new Promise((r) => setTimeout(r, 50));
}
throw new Error(`ssh tunnel did not start listening on localhost:${port}`);
}
async function startSshPortForward(opts) {
const parsed = parseSshTarget(opts.target);
if (!parsed) throw new Error(`invalid SSH target: ${opts.target}`);
let localPort = opts.localPortPreferred;
try {
await ensurePortAvailable(localPort);
} catch (err) {
if (isErrno(err) && err.code === "EADDRINUSE") localPort = await pickEphemeralPort();
else throw err;
}
const userHost = parsed.user ? `${parsed.user}@${parsed.host}` : parsed.host;
const args = [
"-N",
"-L",
`${localPort}:127.0.0.1:${opts.remotePort}`,
"-p",
String(parsed.port),
"-o",
"ExitOnForwardFailure=yes",
"-o",
"BatchMode=yes",
"-o",
"StrictHostKeyChecking=accept-new",
"-o",
"UpdateHostKeys=yes",
"-o",
"ConnectTimeout=5",
"-o",
"ServerAliveInterval=15",
"-o",
"ServerAliveCountMax=3"
];
if (opts.identity?.trim()) args.push("-i", opts.identity.trim());
args.push("--", userHost);
const stderr = [];
const child = spawn("/usr/bin/ssh", args, { stdio: [
"ignore",
"ignore",
"pipe"
] });
child.stderr?.setEncoding("utf8");
child.stderr?.on("data", (chunk) => {
const lines = String(chunk).split("\n").map((l) => l.trim()).filter(Boolean);
stderr.push(...lines);
});
const stop = async () => {
if (child.killed) return;
child.kill("SIGTERM");
await new Promise((resolve) => {
const t = setTimeout(() => {
try {
child.kill("SIGKILL");
} finally {
resolve();
}
}, 1500);
child.once("exit", () => {
clearTimeout(t);
resolve();
});
});
};
try {
await Promise.race([waitForLocalListener(localPort, Math.max(250, opts.timeoutMs)), new Promise((_, reject) => {
child.once("exit", (code, signal) => {
reject(/* @__PURE__ */ new Error(`ssh exited (${code ?? "null"}${signal ? `/${signal}` : ""})`));
});
})]);
} catch (err) {
await stop();
const suffix = stderr.length > 0 ? `\n${stderr.join("\n")}` : "";
throw new Error(`${err instanceof Error ? err.message : String(err)}${suffix}`, { cause: err });
}
return {
parsedTarget: parsed,
localPort,
remotePort: opts.remotePort,
pid: typeof child.pid === "number" ? child.pid : null,
stderr,
stop
};
}
//#endregion
//#region src/commands/gateway-status/helpers.ts
function parseIntOrNull(value) {
const s = typeof value === "string" ? value.trim() : typeof value === "number" || typeof value === "bigint" ? String(value) : "";
if (!s) return null;
const n = Number.parseInt(s, 10);
return Number.isFinite(n) ? n : null;
}
function parseTimeoutMs(raw, fallbackMs) {
const value = typeof raw === "string" ? raw.trim() : typeof raw === "number" || typeof raw === "bigint" ? String(raw) : "";
if (!value) return fallbackMs;
const parsed = Number.parseInt(value, 10);
if (!Number.isFinite(parsed) || parsed <= 0) throw new Error(`invalid --timeout: ${value}`);
return parsed;
}
function normalizeWsUrl(value) {
const trimmed = value.trim();
if (!trimmed) return null;
if (!trimmed.startsWith("ws://") && !trimmed.startsWith("wss://")) return null;
return trimmed;
}
function resolveTargets(cfg, explicitUrl) {
const targets = [];
const add = (t) => {
if (!targets.some((x) => x.url === t.url)) targets.push(t);
};
const explicit = typeof explicitUrl === "string" ? normalizeWsUrl(explicitUrl) : null;
if (explicit) add({
id: "explicit",
kind: "explicit",
url: explicit,
active: true
});
const remoteUrl = typeof cfg.gateway?.remote?.url === "string" ? normalizeWsUrl(cfg.gateway.remote.url) : null;
if (remoteUrl) add({
id: "configRemote",
kind: "configRemote",
url: remoteUrl,
active: cfg.gateway?.mode === "remote"
});
add({
id: "localLoopback",
kind: "localLoopback",
url: `ws://127.0.0.1:${resolveGatewayPort(cfg)}`,
active: cfg.gateway?.mode !== "remote"
});
return targets;
}
function resolveProbeBudgetMs(overallMs, kind) {
if (kind === "localLoopback") return Math.min(800, overallMs);
if (kind === "sshTunnel") return Math.min(2e3, overallMs);
return Math.min(1500, overallMs);
}
function sanitizeSshTarget(value) {
if (typeof value !== "string") return null;
const trimmed = value.trim();
if (!trimmed) return null;
return trimmed.replace(/^ssh\\s+/, "");
}
function resolveAuthForTarget(cfg, target, overrides) {
const tokenOverride = overrides.token?.trim() ? overrides.token.trim() : void 0;
const passwordOverride = overrides.password?.trim() ? overrides.password.trim() : void 0;
if (tokenOverride || passwordOverride) return {
token: tokenOverride,
password: passwordOverride
};
if (target.kind === "configRemote" || target.kind === "sshTunnel") {
const token = typeof cfg.gateway?.remote?.token === "string" ? cfg.gateway.remote.token.trim() : "";
const remotePassword = (cfg.gateway?.remote)?.password;
const password = typeof remotePassword === "string" ? remotePassword.trim() : "";
return {
token: token.length > 0 ? token : void 0,
password: password.length > 0 ? password : void 0
};
}
const envToken = process.env.OPENCLAW_GATEWAY_TOKEN?.trim() || "";
const envPassword = process.env.OPENCLAW_GATEWAY_PASSWORD?.trim() || "";
const cfgToken = typeof cfg.gateway?.auth?.token === "string" ? cfg.gateway.auth.token.trim() : "";
const cfgPassword = typeof cfg.gateway?.auth?.password === "string" ? cfg.gateway.auth.password.trim() : "";
return {
token: envToken || cfgToken || void 0,
password: envPassword || cfgPassword || void 0
};
}
function pickGatewaySelfPresence(presence) {
if (!Array.isArray(presence)) return null;
const entries = presence;
const self = entries.find((e) => e.mode === "gateway" && e.reason === "self") ?? entries.find((e) => typeof e.text === "string" && String(e.text).startsWith("Gateway:")) ?? null;
if (!self) return null;
return {
host: typeof self.host === "string" ? self.host : void 0,
ip: typeof self.ip === "string" ? self.ip : void 0,
version: typeof self.version === "string" ? self.version : void 0,
platform: typeof self.platform === "string" ? self.platform : void 0
};
}
function extractConfigSummary(snapshotUnknown) {
const snap = snapshotUnknown;
const path = typeof snap?.path === "string" ? snap.path : null;
const exists = Boolean(snap?.exists);
const valid = Boolean(snap?.valid);
const issuesRaw = Array.isArray(snap?.issues) ? snap.issues : [];
const legacyRaw = Array.isArray(snap?.legacyIssues) ? snap.legacyIssues : [];
const cfg = snap?.config ?? {};
const gateway = cfg.gateway ?? {};
const wideArea = (cfg.discovery ?? {}).wideArea ?? {};
const remote = gateway.remote ?? {};
const auth = gateway.auth ?? {};
const controlUi = gateway.controlUi ?? {};
const tailscale = gateway.tailscale ?? {};
const authMode = typeof auth.mode === "string" ? auth.mode : null;
const authTokenConfigured = typeof auth.token === "string" ? auth.token.trim().length > 0 : false;
const authPasswordConfigured = typeof auth.password === "string" ? auth.password.trim().length > 0 : false;
const remoteUrl = typeof remote.url === "string" ? normalizeWsUrl(remote.url) : null;
const remoteTokenConfigured = typeof remote.token === "string" ? remote.token.trim().length > 0 : false;
const remotePasswordConfigured = typeof remote.password === "string" ? String(remote.password).trim().length > 0 : false;
const wideAreaEnabled = typeof wideArea.enabled === "boolean" ? wideArea.enabled : null;
return {
path,
exists,
valid,
issues: issuesRaw.filter((i) => Boolean(i && typeof i.path === "string" && typeof i.message === "string")).map((i) => ({
path: i.path,
message: i.message
})),
legacyIssues: legacyRaw.filter((i) => Boolean(i && typeof i.path === "string" && typeof i.message === "string")).map((i) => ({
path: i.path,
message: i.message
})),
gateway: {
mode: typeof gateway.mode === "string" ? gateway.mode : null,
bind: typeof gateway.bind === "string" ? gateway.bind : null,
port: parseIntOrNull(gateway.port),
controlUiEnabled: typeof controlUi.enabled === "boolean" ? controlUi.enabled : null,
controlUiBasePath: typeof controlUi.basePath === "string" ? controlUi.basePath : null,
authMode,
authTokenConfigured,
authPasswordConfigured,
remoteUrl,
remoteTokenConfigured,
remotePasswordConfigured,
tailscaleMode: typeof tailscale.mode === "string" ? tailscale.mode : null
},
discovery: { wideAreaEnabled }
};
}
function buildNetworkHints(cfg) {
const tailnetIPv4 = pickPrimaryTailnetIPv4();
const port = resolveGatewayPort(cfg);
return {
localLoopbackUrl: `ws://127.0.0.1:${port}`,
localTailnetUrl: tailnetIPv4 ? `ws://${tailnetIPv4}:${port}` : null,
tailnetIPv4: tailnetIPv4 ?? null
};
}
function renderTargetHeader(target, rich) {
const kindLabel = target.kind === "localLoopback" ? "Local loopback" : target.kind === "sshTunnel" ? "Remote over SSH" : target.kind === "configRemote" ? target.active ? "Remote (configured)" : "Remote (configured, inactive)" : "URL (explicit)";
return `${colorize(rich, theme.heading, kindLabel)} ${colorize(rich, theme.muted, target.url)}`;
}
function renderProbeSummaryLine(probe, rich) {
if (probe.ok) {
const latency = typeof probe.connectLatencyMs === "number" ? `${probe.connectLatencyMs}ms` : "unknown";
return `${colorize(rich, theme.success, "Connect: ok")} (${latency}) · ${colorize(rich, theme.success, "RPC: ok")}`;
}
const detail = probe.error ? ` - ${probe.error}` : "";
if (probe.connectLatencyMs != null) {
const latency = typeof probe.connectLatencyMs === "number" ? `${probe.connectLatencyMs}ms` : "unknown";
return `${colorize(rich, theme.success, "Connect: ok")} (${latency}) · ${colorize(rich, theme.error, "RPC: failed")}${detail}`;
}
return `${colorize(rich, theme.error, "Connect: failed")}${detail}`;
}
//#endregion
//#region src/commands/gateway-status.ts
async function gatewayStatusCommand(opts, runtime) {
const startedAt = Date.now();
const cfg = loadConfig();
const rich = isRich() && opts.json !== true;
const overallTimeoutMs = parseTimeoutMs(opts.timeout, 3e3);
const wideAreaDomain = resolveWideAreaDiscoveryDomain({ configDomain: cfg.discovery?.wideArea?.domain });
const baseTargets = resolveTargets(cfg, opts.url);
const network = buildNetworkHints(cfg);
const discoveryTimeoutMs = Math.min(1200, overallTimeoutMs);
const discoveryPromise = discoverGatewayBeacons({
timeoutMs: discoveryTimeoutMs,
wideAreaDomain
});
let sshTarget = sanitizeSshTarget(opts.ssh) ?? sanitizeSshTarget(cfg.gateway?.remote?.sshTarget);
let sshIdentity = sanitizeSshTarget(opts.sshIdentity) ?? sanitizeSshTarget(cfg.gateway?.remote?.sshIdentity);
const remotePort = resolveGatewayPort(cfg);
let sshTunnelError = null;
let sshTunnelStarted = false;
if (!sshTarget) sshTarget = inferSshTargetFromRemoteUrl(cfg.gateway?.remote?.url);
if (sshTarget) {
const resolved = await resolveSshTarget(sshTarget, sshIdentity, overallTimeoutMs);
if (resolved) {
sshTarget = resolved.target;
if (!sshIdentity && resolved.identity) sshIdentity = resolved.identity;
}
}
const { discovery, probed } = await withProgress({
label: "Inspecting gateways…",
indeterminate: true,
enabled: opts.json !== true
}, async () => {
const tryStartTunnel = async () => {
if (!sshTarget) return null;
try {
const tunnel = await startSshPortForward({
target: sshTarget,
identity: sshIdentity ?? void 0,
localPortPreferred: remotePort,
remotePort,
timeoutMs: Math.min(1500, overallTimeoutMs)
});
sshTunnelStarted = true;
return tunnel;
} catch (err) {
sshTunnelError = err instanceof Error ? err.message : String(err);
return null;
}
};
const discoveryTask = discoveryPromise.catch(() => []);
const tunnelTask = sshTarget ? tryStartTunnel() : Promise.resolve(null);
const [discovery, tunnelFirst] = await Promise.all([discoveryTask, tunnelTask]);
if (!sshTarget && opts.sshAuto) {
const user = process.env.USER?.trim() || "";
const candidates = discovery.map((b) => {
const host = b.tailnetDns || b.lanHost || b.host;
if (!host?.trim()) return null;
const sshPort = typeof b.sshPort === "number" && b.sshPort > 0 ? b.sshPort : 22;
const base = user ? `${user}@${host.trim()}` : host.trim();
return sshPort !== 22 ? `${base}:${sshPort}` : base;
}).filter((candidate) => Boolean(candidate && parseSshTarget(candidate)));
if (candidates.length > 0) sshTarget = candidates[0] ?? null;
}
const tunnel = tunnelFirst || (sshTarget && !sshTunnelStarted && !sshTunnelError ? await tryStartTunnel() : null);
const tunnelTarget = tunnel ? {
id: "sshTunnel",
kind: "sshTunnel",
url: `ws://127.0.0.1:${tunnel.localPort}`,
active: true,
tunnel: {
kind: "ssh",
target: sshTarget ?? "",
localPort: tunnel.localPort,
remotePort,
pid: tunnel.pid
}
} : null;
const targets = tunnelTarget ? [tunnelTarget, ...baseTargets.filter((t) => t.url !== tunnelTarget.url)] : baseTargets;
try {
return {
discovery,
probed: await Promise.all(targets.map(async (target) => {
const auth = resolveAuthForTarget(cfg, target, {
token: typeof opts.token === "string" ? opts.token : void 0,
password: typeof opts.password === "string" ? opts.password : void 0
});
const timeoutMs = resolveProbeBudgetMs(overallTimeoutMs, target.kind);
const probe = await probeGateway({
url: target.url,
auth,
timeoutMs
});
return {
target,
probe,
configSummary: probe.configSnapshot ? extractConfigSummary(probe.configSnapshot) : null,
self: pickGatewaySelfPresence(probe.presence)
};
}))
};
} finally {
if (tunnel) try {
await tunnel.stop();
} catch {}
}
});
const reachable = probed.filter((p) => p.probe.ok);
const ok = reachable.length > 0;
const multipleGateways = reachable.length > 1;
const primary = reachable.find((p) => p.target.kind === "explicit") ?? reachable.find((p) => p.target.kind === "sshTunnel") ?? reachable.find((p) => p.target.kind === "configRemote") ?? reachable.find((p) => p.target.kind === "localLoopback") ?? null;
const warnings = [];
if (sshTarget && !sshTunnelStarted) warnings.push({
code: "ssh_tunnel_failed",
message: sshTunnelError ? `SSH tunnel failed: ${String(sshTunnelError)}` : "SSH tunnel failed to start; falling back to direct probes."
});
if (multipleGateways) warnings.push({
code: "multiple_gateways",
message: "Unconventional setup: multiple reachable gateways detected. Usually one gateway per network is recommended unless you intentionally run isolated profiles, like a rescue bot (see docs: /gateway#multiple-gateways-same-host).",
targetIds: reachable.map((p) => p.target.id)
});
if (opts.json) {
runtime.log(JSON.stringify({
ok,
ts: Date.now(),
durationMs: Date.now() - startedAt,
timeoutMs: overallTimeoutMs,
primaryTargetId: primary?.target.id ?? null,
warnings,
network,
discovery: {
timeoutMs: discoveryTimeoutMs,
count: discovery.length,
beacons: discovery.map((b) => ({
instanceName: b.instanceName,
displayName: b.displayName ?? null,
domain: b.domain ?? null,
host: b.host ?? null,
lanHost: b.lanHost ?? null,
tailnetDns: b.tailnetDns ?? null,
gatewayPort: b.gatewayPort ?? null,
sshPort: b.sshPort ?? null,
wsUrl: (() => {
const host = b.tailnetDns || b.lanHost || b.host;
const port = b.gatewayPort ?? 18789;
return host ? `ws://${host}:${port}` : null;
})()
}))
},
targets: probed.map((p) => ({
id: p.target.id,
kind: p.target.kind,
url: p.target.url,
active: p.target.active,
tunnel: p.target.tunnel ?? null,
connect: {
ok: p.probe.ok,
latencyMs: p.probe.connectLatencyMs,
error: p.probe.error,
close: p.probe.close
},
self: p.self,
config: p.configSummary,
health: p.probe.health,
summary: p.probe.status,
presence: p.probe.presence
}))
}, null, 2));
if (!ok) runtime.exit(1);
return;
}
runtime.log(colorize(rich, theme.heading, "Gateway Status"));
runtime.log(ok ? `${colorize(rich, theme.success, "Reachable")}: yes` : `${colorize(rich, theme.error, "Reachable")}: no`);
runtime.log(colorize(rich, theme.muted, `Probe budget: ${overallTimeoutMs}ms`));
if (warnings.length > 0) {
runtime.log("");
runtime.log(colorize(rich, theme.warn, "Warning:"));
for (const w of warnings) runtime.log(`- ${w.message}`);
}
runtime.log("");
runtime.log(colorize(rich, theme.heading, "Discovery (this machine)"));
const discoveryDomains = wideAreaDomain ? `local. + ${wideAreaDomain}` : "local.";
runtime.log(discovery.length > 0 ? `Found ${discovery.length} gateway(s) via Bonjour (${discoveryDomains})` : `Found 0 gateways via Bonjour (${discoveryDomains})`);
if (discovery.length === 0) runtime.log(colorize(rich, theme.muted, "Tip: if the gateway is remote, mDNS won’t cross networks; use Wide-Area Bonjour (split DNS) or SSH tunnels."));
runtime.log("");
runtime.log(colorize(rich, theme.heading, "Targets"));
for (const p of probed) {
runtime.log(renderTargetHeader(p.target, rich));
runtime.log(` ${renderProbeSummaryLine(p.probe, rich)}`);
if (p.target.tunnel?.kind === "ssh") runtime.log(` ${colorize(rich, theme.muted, "ssh")}: ${colorize(rich, theme.command, p.target.tunnel.target)}`);
if (p.probe.ok && p.self) {
const host = p.self.host ?? "unknown";
const ip = p.self.ip ? ` (${p.self.ip})` : "";
const platform = p.self.platform ? ` · ${p.self.platform}` : "";
const version = p.self.version ? ` · app ${p.self.version}` : "";
runtime.log(` ${colorize(rich, theme.info, "Gateway")}: ${host}${ip}${platform}${version}`);
}
if (p.configSummary) {
const c = p.configSummary;
const wideArea = c.discovery.wideAreaEnabled === true ? "enabled" : c.discovery.wideAreaEnabled === false ? "disabled" : "unknown";
runtime.log(` ${colorize(rich, theme.info, "Wide-area discovery")}: ${wideArea}`);
}
runtime.log("");
}
if (!ok) runtime.exit(1);
}
function inferSshTargetFromRemoteUrl(rawUrl) {
if (typeof rawUrl !== "string") return null;
const trimmed = rawUrl.trim();
if (!trimmed) return null;
let host = null;
try {
host = new URL(trimmed).hostname || null;
} catch {
return null;
}
if (!host) return null;
const user = process.env.USER?.trim() || "";
return user ? `${user}@${host}` : host;
}
function buildSshTarget(input) {
const host = input.host?.trim() ?? "";
if (!host) return null;
const user = input.user?.trim() ?? "";
const base = user ? `${user}@${host}` : host;
const port = input.port ?? 22;
if (port && port !== 22) return `${base}:${port}`;
return base;
}
async function resolveSshTarget(rawTarget, identity, overallTimeoutMs) {
const parsed = parseSshTarget(rawTarget);
if (!parsed) return null;
const config = await resolveSshConfig(parsed, {
identity: identity ?? void 0,
timeoutMs: Math.min(800, overallTimeoutMs)
});
if (!config) return {
target: rawTarget,
identity: identity ?? void 0
};
const target = buildSshTarget({
user: config.user ?? parsed.user,
host: config.host ?? parsed.host,
port: config.port ?? parsed.port
});
if (!target) return {
target: rawTarget,
identity: identity ?? void 0
};
return {
target,
identity: identity ?? config.identityFiles.find((entry) => entry.trim().length > 0)?.trim() ?? void 0
};
}
//#endregion
//#region src/cli/gateway-cli/call.ts
const gatewayCallOpts = (cmd) => cmd.option("--url <url>", "Gateway WebSocket URL (defaults to gateway.remote.url when configured)").option("--token <token>", "Gateway token (if required)").option("--password <password>", "Gateway password (password auth)").option("--timeout <ms>", "Timeout in ms", "10000").option("--expect-final", "Wait for final response (agent)", false).option("--json", "Output JSON", false);
const callGatewayCli = async (method, opts, params) => withProgress({
label: `Gateway ${method}`,
indeterminate: true,
enabled: opts.json !== true
}, async () => await callGateway({
url: opts.url,
token: opts.token,
password: opts.password,
method,
params,
expectFinal: Boolean(opts.expectFinal),
timeoutMs: Number(opts.timeout ?? 1e4),
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI
}));
//#endregion
//#region src/cli/gateway-cli/discover.ts
function parseDiscoverTimeoutMs(raw, fallbackMs) {
if (raw === void 0 || raw === null) return fallbackMs;
const value = typeof raw === "string" ? raw.trim() : typeof raw === "number" || typeof raw === "bigint" ? String(raw) : null;
if (value === null) throw new Error("invalid --timeout");
if (!value) return fallbackMs;
const parsed = Number.parseInt(value, 10);
if (!Number.isFinite(parsed) || parsed <= 0) throw new Error(`invalid --timeout: ${value}`);
return parsed;
}
function pickBeaconHost(beacon) {
const host = beacon.tailnetDns || beacon.lanHost || beacon.host;
return host?.trim() ? host.trim() : null;
}
function pickGatewayPort(beacon) {
const port = beacon.gatewayPort ?? 18789;
return port > 0 ? port : 18789;
}
function dedupeBeacons(beacons) {
const out = [];
const seen = /* @__PURE__ */ new Set();
for (const b of beacons) {
const host = pickBeaconHost(b) ?? "";
const key = [
b.domain ?? "",
b.instanceName ?? "",
b.displayName ?? "",
host,
String(b.port ?? ""),
String(b.gatewayPort ?? "")
].join("|");
if (seen.has(key)) continue;
seen.add(key);
out.push(b);
}
return out;
}
function renderBeaconLines(beacon, rich) {
const nameRaw = (beacon.displayName || beacon.instanceName || "Gateway").trim();
const domainRaw = (beacon.domain || "local.").trim();
const title = colorize(rich, theme.accentBright, nameRaw);
const domain = colorize(rich, theme.muted, domainRaw);
const host = pickBeaconHost(beacon);
const gatewayPort = pickGatewayPort(beacon);
const scheme = beacon.gatewayTls ? "wss" : "ws";
const wsUrl = host ? `${scheme}://${host}:${gatewayPort}` : null;
const lines = [`- ${title} ${domain}`];
if (beacon.tailnetDns) lines.push(` ${colorize(rich, theme.info, "tailnet")}: ${beacon.tailnetDns}`);
if (beacon.lanHost) lines.push(` ${colorize(rich, theme.info, "lan")}: ${beacon.lanHost}`);
if (beacon.host) lines.push(` ${colorize(rich, theme.info, "host")}: ${beacon.host}`);
if (wsUrl) lines.push(` ${colorize(rich, theme.muted, "ws")}: ${colorize(rich, theme.command, wsUrl)}`);
if (beacon.role) lines.push(` ${colorize(rich, theme.muted, "role")}: ${beacon.role}`);
if (beacon.transport) lines.push(` ${colorize(rich, theme.muted, "transport")}: ${beacon.transport}`);
if (beacon.gatewayTls) {
const fingerprint = beacon.gatewayTlsFingerprintSha256 ? `sha256 ${beacon.gatewayTlsFingerprintSha256}` : "enabled";
lines.push(` ${colorize(rich, theme.muted, "tls")}: ${fingerprint}`);
}
if (typeof beacon.sshPort === "number" && beacon.sshPort > 0 && host) {
const ssh = `ssh -N -L 18789:127.0.0.1:18789 <user>@${host} -p ${beacon.sshPort}`;
lines.push(` ${colorize(rich, theme.muted, "ssh")}: ${colorize(rich, theme.command, ssh)}`);
}
return lines;
}
//#endregion
//#region src/gateway/server/close-reason.ts
const CLOSE_REASON_MAX_BYTES = 120;
function truncateCloseReason(reason, maxBytes = CLOSE_REASON_MAX_BYTES) {
if (!reason) return "invalid handshake";
const buf = Buffer$1.from(reason);
if (buf.length <= maxBytes) return reason;
return buf.subarray(0, maxBytes).toString();
}
//#endregion
//#region src/infra/exec-approval-forwarder.ts
const log$3 = createSubsystemLogger("gateway/exec-approvals");
const DEFAULT_MODE = "session";
function normalizeMode(mode) {
return mode ?? DEFAULT_MODE;
}
function matchSessionFilter(sessionKey, patterns) {
return patterns.some((pattern) => {
try {
return sessionKey.includes(pattern) || new RegExp(pattern).test(sessionKey);
} catch {
return sessionKey.includes(pattern);
}
});
}
function shouldForward(params) {
const config = params.config;
if (!config?.enabled) return false;
if (config.agentFilter?.length) {
const agentId = params.request.request.agentId ?? parseAgentSessionKey(params.request.request.sessionKey)?.agentId;
if (!agentId) return false;
if (!config.agentFilter.includes(agentId)) return false;
}
if (config.sessionFilter?.length) {
const sessionKey = params.request.request.sessionKey;
if (!sessionKey) return false;
if (!matchSessionFilter(sessionKey, config.sessionFilter)) return false;
}
return true;
}
function buildTargetKey(target) {
const channel = normalizeMessageChannel(target.channel) ?? target.channel;
const accountId = target.accountId ?? "";
const threadId = target.threadId ?? "";
return [
channel,
target.to,
accountId,
threadId
].join(":");
}
function buildRequestMessage(request, nowMs) {
const lines = ["🔒 Exec approval required", `ID: ${request.id}`];
lines.push(`Command: ${request.request.command}`);
if (request.request.cwd) lines.push(`CWD: ${request.request.cwd}`);
if (request.request.host) lines.push(`Host: ${request.request.host}`);
if (request.request.agentId) lines.push(`Agent: ${request.request.agentId}`);
if (request.request.security) lines.push(`Security: ${request.request.security}`);
if (request.request.ask) lines.push(`Ask: ${request.request.ask}`);
const expiresIn = Math.max(0, Math.round((request.expiresAtMs - nowMs) / 1e3));
lines.push(`Expires in: ${expiresIn}s`);
lines.push("Reply with: /approve <id> allow-once|allow-always|deny");
return lines.join("\n");
}
function decisionLabel(decision) {
if (decision === "allow-once") return "allowed once";
if (decision === "allow-always") return "allowed always";
return "denied";
}
function buildResolvedMessage(resolved) {
return `${`✅ Exec approval ${decisionLabel(resolved.decision)}.`}${resolved.resolvedBy ? ` Resolved by ${resolved.resolvedBy}.` : ""} ID: ${resolved.id}`;
}
function buildExpiredMessage(request) {
return `⏱️ Exec approval expired. ID: ${request.id}`;
}
function defaultResolveSessionTarget(params) {
const sessionKey = params.request.request.sessionKey?.trim();
if (!sessionKey) return null;
const agentId = parseAgentSessionKey(sessionKey)?.agentId ?? params.request.request.agentId ?? "main";
const entry = loadSessionStore(resolveStorePath(params.cfg.session?.store, { agentId }))[sessionKey];
if (!entry) return null;
const target = resolveSessionDeliveryTarget({
entry,
requestedChannel: "last"
});
if (!target.channel || !target.to) return null;
if (!isDeliverableMessageChannel(target.channel)) return null;
return {
channel: target.channel,
to: target.to,
accountId: target.accountId,
threadId: target.threadId
};
}
async function deliverToTargets(params) {
const deliveries = params.targets.map(async (target) => {
if (params.shouldSend && !params.shouldSend()) return;
const channel = normalizeMessageChannel(target.channel) ?? target.channel;
if (!isDeliverableMessageChannel(channel)) return;
try {
await params.deliver({
cfg: params.cfg,
channel,
to: target.to,
accountId: target.accountId,
threadId: target.threadId,
payloads: [{ text: params.text }]
});
} catch (err) {
log$3.error(`exec approvals: failed to deliver to ${channel}:${target.to}: ${String(err)}`);
}
});
await Promise.allSettled(deliveries);
}
function createExecApprovalForwarder(deps = {}) {
const getConfig = deps.getConfig ?? loadConfig;
const deliver = deps.deliver ?? deliverOutboundPayloads;
const nowMs = deps.nowMs ?? Date.now;
const resolveSessionTarget = deps.resolveSessionTarget ?? defaultResolveSessionTarget;
const pending = /* @__PURE__ */ new Map();
const handleRequested = async (request) => {
const cfg = getConfig();
const config = cfg.approvals?.exec;
if (!shouldForward({
config,
request
})) return;
const mode = normalizeMode(config?.mode);
const targets = [];
const seen = /* @__PURE__ */ new Set();
if (mode === "session" || mode === "both") {
const sessionTarget = resolveSessionTarget({
cfg,
request
});
if (sessionTarget) {
const key = buildTargetKey(sessionTarget);
if (!seen.has(key)) {
seen.add(key);