Files
clawdbot/src/commands/sandbox-explain.ts
Peter Steinberger 7acd26a2fc Move provider to a plugin-architecture (#661)
* refactor: introduce provider plugin registry

* refactor: move provider CLI to plugins

* docs: add provider plugin implementation notes

* refactor: shift provider runtime logic into plugins

* refactor: add plugin defaults and summaries

* docs: update provider plugin notes

* feat(commands): add /commands slash list

* Auto-reply: tidy help message

* Auto-reply: fix status command lint

* Tests: align google shared expectations

* Auto-reply: tidy help message

* Auto-reply: fix status command lint

* refactor: move provider routing into plugins

* test: align agent routing expectations

* docs: update provider plugin notes

* refactor: route replies via provider plugins

* docs: note route-reply plugin hooks

* refactor: extend provider plugin contract

* refactor: derive provider status from plugins

* refactor: unify gateway provider control

* refactor: use plugin metadata in auto-reply

* fix: parenthesize cron target selection

* refactor: derive gateway methods from plugins

* refactor: generalize provider logout

* refactor: route provider logout through plugins

* refactor: move WhatsApp web login methods into plugin

* refactor: generalize provider log prefixes

* refactor: centralize default chat provider

* refactor: derive provider lists from registry

* refactor: move provider reload noops into plugins

* refactor: resolve web login provider via alias

* refactor: derive CLI provider options from plugins

* refactor: derive prompt provider list from plugins

* style: apply biome lint fixes

* fix: resolve provider routing edge cases

* docs: update provider plugin refactor notes

* fix(gateway): harden agent provider routing

* refactor: move provider routing into plugins

* refactor: move provider CLI to plugins

* refactor: derive provider lists from registry

* fix: restore slash command parsing

* refactor: align provider ids for schema

* refactor: unify outbound target resolution

* fix: keep outbound labels stable

* feat: add msteams to cron surfaces

* fix: clean up lint build issues

* refactor: localize chat provider alias normalization

* refactor: drive gateway provider lists from plugins

* docs: update provider plugin notes

* style: format message-provider

* fix: avoid provider registry init cycles

* style: sort message-provider imports

* fix: relax provider alias map typing

* refactor: move provider routing into plugins

* refactor: add plugin pairing/config adapters

* refactor: route pairing and provider removal via plugins

* refactor: align auto-reply provider typing

* test: stabilize telegram media mocks

* docs: update provider plugin refactor notes

* refactor: pluginize outbound targets

* refactor: pluginize provider selection

* refactor: generalize text chunk limits

* docs: update provider plugin notes

* refactor: generalize group session/config

* fix: normalize provider id for room detection

* fix: avoid provider init in system prompt

* style: formatting cleanup

* refactor: normalize agent delivery targets

* test: update outbound delivery labels

* chore: fix lint regressions

* refactor: extend provider plugin adapters

* refactor: move elevated/block streaming defaults to plugins

* refactor: defer outbound send deps to plugins

* docs: note plugin-driven streaming/elevated defaults

* refactor: centralize webchat provider constant

* refactor: add provider setup adapters

* refactor: delegate provider add config to plugins

* docs: document plugin-driven provider add

* refactor: add plugin state/binding metadata

* refactor: build agent provider status from plugins

* docs: note plugin-driven agent bindings

* refactor: centralize internal provider constant usage

* fix: normalize WhatsApp targets for groups and E.164 (#631) (thanks @imfing)

* refactor: centralize default chat provider

* refactor: centralize WhatsApp target normalization

* refactor: move provider routing into plugins

* refactor: normalize agent delivery targets

* chore: fix lint regressions

* fix: normalize WhatsApp targets for groups and E.164 (#631) (thanks @imfing)

* feat: expand provider plugin adapters

* refactor: route auto-reply via provider plugins

* fix: align WhatsApp target normalization

* fix: normalize WhatsApp targets for groups and E.164 (#631) (thanks @imfing)

* refactor: centralize WhatsApp target normalization

* feat: add /config chat config updates

* docs: add /config get alias

* feat(commands): add /commands slash list

* refactor: centralize default chat provider

* style: apply biome lint fixes

* chore: fix lint regressions

* fix: clean up whatsapp allowlist typing

* style: format config command helpers

* refactor: pluginize tool threading context

* refactor: normalize session announce targets

* docs: note new plugin threading and announce hooks

* refactor: pluginize message actions

* docs: update provider plugin actions notes

* fix: align provider action adapters

* refactor: centralize webchat checks

* style: format message provider helpers

* refactor: move provider onboarding into adapters

* docs: note onboarding provider adapters

* feat: add msteams onboarding adapter

* style: organize onboarding imports

* fix: normalize msteams allowFrom types

* feat: add plugin text chunk limits

* refactor: use plugin chunk limit fallbacks

* feat: add provider mention stripping hooks

* style: organize provider plugin type imports

* refactor: generalize health snapshots

* refactor: update macOS health snapshot handling

* docs: refresh health snapshot notes

* style: format health snapshot updates

* refactor: drive security warnings via plugins

* docs: note provider security adapter

* style: format provider security adapters

* refactor: centralize provider account defaults

* refactor: type gateway client identity constants

* chore: regen gateway protocol swift

* fix: degrade health on failed provider probe

* refactor: centralize pairing approve hint

* docs: add plugin CLI command references

* refactor: route auth and tool sends through plugins

* docs: expand provider plugin hooks

* refactor: document provider docking touchpoints

* refactor: normalize internal provider defaults

* refactor: streamline outbound delivery wiring

* refactor: make provider onboarding plugin-owned

* refactor: support provider-owned agent tools

* refactor: move telegram draft chunking into telegram module

* refactor: infer provider tool sends via extractToolSend

* fix: repair plugin onboarding imports

* refactor: de-dup outbound target normalization

* style: tidy plugin and agent imports

* refactor: data-drive provider selection line

* fix: satisfy lint after provider plugin rebase

* test: deflake gateway-cli coverage

* style: format gateway-cli coverage test

* refactor(provider-plugins): simplify provider ids

* test(pairing-cli): avoid provider-specific ternary

* style(macos): swiftformat HealthStore

* refactor(sandbox): derive provider tool denylist

* fix(sandbox): avoid plugin init in defaults

* refactor(provider-plugins): centralize provider aliases

* style(test): satisfy biome

* refactor(protocol): v3 providers.status maps

* refactor(ui): adapt to protocol v3

* refactor(macos): adapt to protocol v3

* test: update providers.status v3 fixtures

* refactor(gateway): map provider runtime snapshot

* test(gateway): update reload runtime snapshot

* refactor(whatsapp): normalize heartbeat provider id

* docs(refactor): update provider plugin notes

* style: satisfy biome after rebase

* fix: describe sandboxed elevated in prompt

* feat(gateway): add agent image attachments + live probe

* refactor: derive CLI provider options from plugins

* fix(gateway): harden agent provider routing

* fix(gateway): harden agent provider routing

* refactor: align provider ids for schema

* fix(protocol): keep agent provider string

* fix(gateway): harden agent provider routing

* fix(protocol): keep agent provider string

* refactor: normalize agent delivery targets

* refactor: support provider-owned agent tools

* refactor(config): provider-keyed elevated allowFrom

* style: satisfy biome

* fix(gateway): appease provider narrowing

* style: satisfy biome

* refactor(reply): move group intro hints into plugin

* fix(reply): avoid plugin registry init cycle

* refactor(providers): add lightweight provider dock

* refactor(gateway): use typed client id in connect

* refactor(providers): document docks and avoid init cycles

* refactor(providers): make media limit helper generic

* fix(providers): break plugin registry import cycles

* style: satisfy biome

* refactor(status-all): build providers table from plugins

* refactor(gateway): delegate web login to provider plugin

* refactor(provider): drop web alias

* refactor(provider): lazy-load monitors

* style: satisfy lint/format

* style: format status-all providers table

* style: swiftformat gateway discovery model

* test: make reload plan plugin-driven

* fix: avoid token stringification in status-all

* refactor: make provider IDs explicit in status

* feat: warn on signal/imessage provider runtime errors

* test: cover gateway provider runtime warnings in status

* fix: add runtime kind to provider status issues

* test: cover health degradation on probe failure

* fix: keep routeReply lightweight

* style: organize routeReply imports

* refactor(web): extract auth-store helpers

* refactor(whatsapp): lazy login imports

* refactor(outbound): route replies via plugin outbound

* docs: update provider plugin notes

* style: format provider status issues

* fix: make sandbox scope warning wrap-safe

* refactor: load outbound adapters from provider plugins

* docs: update provider plugin outbound notes

* style(macos): fix swiftformat lint

* docs: changelog for provider plugins

* fix(macos): satisfy swiftformat

* fix(macos): open settings via menu action

* style: format after rebase

* fix(macos): open Settings via menu action

---------

Co-authored-by: LK <luke@kyohere.com>
Co-authored-by: Luke K (pr-0f3t) <2609441+lc0rp@users.noreply.github.com>
Co-authored-by: Xin <xin@imfing.com>
2026-01-11 11:45:25 +00:00

323 lines
10 KiB
TypeScript

import { resolveAgentConfig } from "../agents/agent-scope.js";
import {
resolveSandboxConfigForAgent,
resolveSandboxToolPolicyForAgent,
} from "../agents/sandbox.js";
import type { ClawdbotConfig } from "../config/config.js";
import { loadConfig } from "../config/config.js";
import {
loadSessionStore,
resolveAgentMainSessionKey,
resolveMainSessionKey,
resolveStorePath,
} from "../config/sessions.js";
import { normalizeProviderId } from "../providers/registry.js";
import {
buildAgentMainSessionKey,
normalizeAgentId,
normalizeMainKey,
parseAgentSessionKey,
resolveAgentIdFromSessionKey,
} from "../routing/session-key.js";
import type { RuntimeEnv } from "../runtime.js";
import { formatDocsLink } from "../terminal/links.js";
import { colorize, isRich, theme } from "../terminal/theme.js";
import { INTERNAL_MESSAGE_PROVIDER } from "../utils/message-provider.js";
type SandboxExplainOptions = {
session?: string;
agent?: string;
json: boolean;
};
const SANDBOX_DOCS_URL = "https://docs.clawd.bot/sandbox";
function normalizeExplainSessionKey(params: {
cfg: ClawdbotConfig;
agentId: string;
session?: string;
}): string {
const raw = (params.session ?? "").trim();
if (!raw) {
return resolveAgentMainSessionKey({
cfg: params.cfg,
agentId: params.agentId,
});
}
if (raw.includes(":")) return raw;
if (raw === "global") return "global";
return buildAgentMainSessionKey({
agentId: params.agentId,
mainKey: normalizeMainKey(raw),
});
}
function inferProviderFromSessionKey(params: {
cfg: ClawdbotConfig;
sessionKey: string;
}): string | undefined {
const parsed = parseAgentSessionKey(params.sessionKey);
if (!parsed) return undefined;
const rest = parsed.rest.trim();
if (!rest) return undefined;
const parts = rest.split(":").filter(Boolean);
if (parts.length === 0) return undefined;
const configuredMainKey = normalizeMainKey(params.cfg.session?.mainKey);
if (parts[0] === configuredMainKey) return undefined;
const candidate = parts[0]?.trim().toLowerCase();
if (!candidate) return undefined;
if (candidate === INTERNAL_MESSAGE_PROVIDER) return INTERNAL_MESSAGE_PROVIDER;
return normalizeProviderId(candidate) ?? undefined;
}
function resolveActiveProvider(params: {
cfg: ClawdbotConfig;
agentId: string;
sessionKey: string;
}): string | undefined {
const storePath = resolveStorePath(params.cfg.session?.store, {
agentId: params.agentId,
});
const store = loadSessionStore(storePath);
const entry = store[params.sessionKey];
const candidate = (
entry?.lastProvider ??
entry?.providerOverride ??
entry?.provider ??
""
)
.trim()
.toLowerCase();
if (candidate === INTERNAL_MESSAGE_PROVIDER) return INTERNAL_MESSAGE_PROVIDER;
const normalized = normalizeProviderId(candidate);
if (normalized) return normalized;
return inferProviderFromSessionKey({
cfg: params.cfg,
sessionKey: params.sessionKey,
});
}
export async function sandboxExplainCommand(
opts: SandboxExplainOptions,
runtime: RuntimeEnv,
): Promise<void> {
const cfg = loadConfig();
const defaultAgentId = resolveAgentIdFromSessionKey(
resolveMainSessionKey(cfg),
);
const resolvedAgentId = normalizeAgentId(
opts.agent?.trim()
? opts.agent
: opts.session?.trim()
? resolveAgentIdFromSessionKey(opts.session)
: defaultAgentId,
);
const sessionKey = normalizeExplainSessionKey({
cfg,
agentId: resolvedAgentId,
session: opts.session,
});
const sandboxCfg = resolveSandboxConfigForAgent(cfg, resolvedAgentId);
const toolPolicy = resolveSandboxToolPolicyForAgent(cfg, resolvedAgentId);
const mainSessionKey = resolveAgentMainSessionKey({
cfg,
agentId: resolvedAgentId,
});
const sessionIsSandboxed =
sandboxCfg.mode === "all"
? true
: sandboxCfg.mode === "off"
? false
: sessionKey.trim() !== mainSessionKey.trim();
const provider = resolveActiveProvider({
cfg,
agentId: resolvedAgentId,
sessionKey,
});
const agentConfig = resolveAgentConfig(cfg, resolvedAgentId);
const elevatedGlobal = cfg.tools?.elevated;
const elevatedAgent = agentConfig?.tools?.elevated;
const elevatedGlobalEnabled = elevatedGlobal?.enabled !== false;
const elevatedAgentEnabled = elevatedAgent?.enabled !== false;
const elevatedEnabled = elevatedGlobalEnabled && elevatedAgentEnabled;
const globalAllow = provider
? elevatedGlobal?.allowFrom?.[provider]
: undefined;
const agentAllow = provider
? elevatedAgent?.allowFrom?.[provider]
: undefined;
const allowTokens = (values?: Array<string | number>) =>
(values ?? []).map((v) => String(v).trim()).filter(Boolean);
const globalAllowTokens = allowTokens(globalAllow);
const agentAllowTokens = allowTokens(agentAllow);
const elevatedAllowedByConfig =
elevatedEnabled &&
Boolean(provider) &&
globalAllowTokens.length > 0 &&
(elevatedAgent?.allowFrom ? agentAllowTokens.length > 0 : true);
const elevatedAlwaysAllowedByConfig =
elevatedAllowedByConfig &&
globalAllowTokens.includes("*") &&
(elevatedAgent?.allowFrom ? agentAllowTokens.includes("*") : true);
const elevatedFailures: Array<{ gate: string; key: string }> = [];
if (!elevatedGlobalEnabled) {
elevatedFailures.push({ gate: "enabled", key: "tools.elevated.enabled" });
}
if (!elevatedAgentEnabled) {
elevatedFailures.push({
gate: "enabled",
key: "agents.list[].tools.elevated.enabled",
});
}
if (provider && globalAllowTokens.length === 0) {
elevatedFailures.push({
gate: "allowFrom",
key: `tools.elevated.allowFrom.${provider}`,
});
}
if (provider && elevatedAgent?.allowFrom && agentAllowTokens.length === 0) {
elevatedFailures.push({
gate: "allowFrom",
key: `agents.list[].tools.elevated.allowFrom.${provider}`,
});
}
const fixIt: string[] = [];
if (sandboxCfg.mode !== "off") {
fixIt.push("agents.defaults.sandbox.mode=off");
fixIt.push("agents.list[].sandbox.mode=off");
}
fixIt.push("tools.sandbox.tools.allow");
fixIt.push("tools.sandbox.tools.deny");
fixIt.push("agents.list[].tools.sandbox.tools.allow");
fixIt.push("agents.list[].tools.sandbox.tools.deny");
fixIt.push("tools.elevated.enabled");
if (provider) fixIt.push(`tools.elevated.allowFrom.${provider}`);
const payload = {
docsUrl: SANDBOX_DOCS_URL,
agentId: resolvedAgentId,
sessionKey,
mainSessionKey,
sandbox: {
mode: sandboxCfg.mode,
scope: sandboxCfg.scope,
perSession: sandboxCfg.scope === "session",
workspaceAccess: sandboxCfg.workspaceAccess,
workspaceRoot: sandboxCfg.workspaceRoot,
sessionIsSandboxed,
tools: {
allow: toolPolicy.allow,
deny: toolPolicy.deny,
sources: toolPolicy.sources,
},
},
elevated: {
enabled: elevatedEnabled,
provider,
allowedByConfig: elevatedAllowedByConfig,
alwaysAllowedByConfig: elevatedAlwaysAllowedByConfig,
allowFrom: {
global: provider ? globalAllowTokens : undefined,
agent:
elevatedAgent?.allowFrom && provider ? agentAllowTokens : undefined,
},
failures: elevatedFailures,
},
fixIt,
} as const;
if (opts.json) {
runtime.log(`${JSON.stringify(payload, null, 2)}\n`);
return;
}
const rich = isRich();
const heading = (value: string) => colorize(rich, theme.heading, value);
const key = (value: string) => colorize(rich, theme.muted, value);
const value = (val: string) => colorize(rich, theme.info, val);
const ok = (val: string) => colorize(rich, theme.success, val);
const warn = (val: string) => colorize(rich, theme.warn, val);
const err = (val: string) => colorize(rich, theme.error, val);
const bool = (flag: boolean) => (flag ? ok("true") : err("false"));
const lines: string[] = [];
lines.push(heading("Effective sandbox:"));
lines.push(` ${key("agentId:")} ${value(payload.agentId)}`);
lines.push(` ${key("sessionKey:")} ${value(payload.sessionKey)}`);
lines.push(` ${key("mainSessionKey:")} ${value(payload.mainSessionKey)}`);
lines.push(
` ${key("runtime:")} ${
payload.sandbox.sessionIsSandboxed ? warn("sandboxed") : ok("direct")
}`,
);
lines.push(
` ${key("mode:")} ${value(payload.sandbox.mode)} ${key("scope:")} ${value(
payload.sandbox.scope,
)} ${key("perSession:")} ${bool(payload.sandbox.perSession)}`,
);
lines.push(
` ${key("workspaceAccess:")} ${value(
payload.sandbox.workspaceAccess,
)} ${key("workspaceRoot:")} ${value(payload.sandbox.workspaceRoot)}`,
);
lines.push("");
lines.push(heading("Sandbox tool policy:"));
lines.push(
` ${key(`allow (${payload.sandbox.tools.sources.allow.source}):`)} ${value(
payload.sandbox.tools.allow.join(", ") || "(empty)",
)}`,
);
lines.push(
` ${key(`deny (${payload.sandbox.tools.sources.deny.source}):`)} ${value(
payload.sandbox.tools.deny.join(", ") || "(empty)",
)}`,
);
lines.push("");
lines.push(heading("Elevated:"));
lines.push(` ${key("enabled:")} ${bool(payload.elevated.enabled)}`);
lines.push(
` ${key("provider:")} ${value(payload.elevated.provider ?? "(unknown)")}`,
);
lines.push(
` ${key("allowedByConfig:")} ${bool(payload.elevated.allowedByConfig)}`,
);
if (payload.elevated.failures.length > 0) {
lines.push(
` ${key("failing gates:")} ${warn(
payload.elevated.failures.map((f) => `${f.gate} (${f.key})`).join(", "),
)}`,
);
}
if (
payload.sandbox.mode === "non-main" &&
payload.sandbox.sessionIsSandboxed
) {
lines.push("");
lines.push(
`${warn("Hint:")} sandbox mode is non-main; use main session key to run direct: ${value(
payload.mainSessionKey,
)}`,
);
}
lines.push("");
lines.push(heading("Fix-it:"));
for (const key of payload.fixIt) lines.push(` - ${key}`);
lines.push("");
lines.push(
`${key("Docs:")} ${formatDocsLink("/sandbox", "docs.clawd.bot/sandbox")}`,
);
runtime.log(`${lines.join("\n")}\n`);
}