openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
8 lines • 18.4 kB
JavaScript
import{r as defaultRuntime}from"./runtime-DIcLIHcp.mjs";import{o as getAsyncWorkSignal}from"./async-work-scope-DBcxYU4O.mjs";import{n as sanitizeTerminalText}from"./safe-text-B_QTgn0s.mjs";import{n as normalizeAgentId}from"./agent-id-cOfqmfln.mjs";import{N as parseAgentSessionKey}from"./session-key-BPgKfU2m.mjs";import{i as listAgentIds}from"./agent-roster-4XrgUgPK.mjs";import{T as resolveSoleAgentId,h as resolveConfiguredAgentId,t as AgentSelectionRequiredError}from"./agent-scope-config-CG9CFpGX.mjs";import{r as captureOpenClawStateWorkerContext}from"./openclaw-state-worker-context-Dx8YjqO2.mjs";import{a as normalizeExecSecurity,c as resolveExactExecModeFromPolicy,i as normalizeExecMode,o as normalizeExecTarget,r as normalizeExecAsk,u as resolveExecModePolicy}from"./exec-approvals-core-BZ6-zeZE.mjs";import{s as readConfigFileSnapshot}from"./io.runtime-BvSeVFIY.mjs";import{r as replaceConfigFile}from"./mutate-DcH8aT_4.mjs";import"./config-DkZ8y8Gv.mjs";import{r as theme}from"./theme-DS2CtI9X.mjs";import{d as updateExecApprovals,l as readExecApprovalsSnapshotAsync,u as restoreExecApprovalsSnapshotLocked}from"./exec-approvals-store-CKqFK0Id.mjs";import"./exec-approvals-BLANskJu.mjs";import{r as sanitizeExecApprovalDisplayText}from"./exec-approval-text-sanitize-h0o6Uj2u.mjs";import{t as ExpectedCliError}from"./expected-cli-error-oDVmXYil.mjs";import{d as rethrowExpectedCliError}from"./failure-output-Gn9zHEk3.mjs";import{r as callGatewayFromCliWithTransport,s as resolveGatewayRpcOptionsWithLocalPort,t as addGatewayClientOptions}from"./gateway-rpc-17pTfL8i.mjs";import{t as runWithLocalStateOwner}from"./local-state-owner-fjzTarAw.mjs";import{n as renderTable,t as getTerminalTableWidth}from"./table-TWLemnkw.mjs";import{n as resolveConfiguredToolAccess}from"./tool-access-diagnostics-CVUQKdC6.mjs";import{t as formatDocsHelp}from"./help-format-DLfgiheF.mjs";import{n as collectExecPolicyScopeSnapshots,t as SESSION_EXEC_OVERRIDES_NOTE}from"./exec-approvals-effective-DfCfd3qR.mjs";
//!src/cli/exec-policy-diagnostics.ts
const TERMINAL_TOOLS=[`exec`,`process`];async function buildExecPolicyToolAccess(e,t,n){const r=t.agent?.trim();const i=t.session?.trim();if(t.agent!==void 0&&!r)throw new Error(`--agent must not be blank.`);if(t.session!==void 0&&!i)throw new Error(`--session must not be blank.`);const a=i?parseAgentSessionKey(i)?.agentId:void 0;const o=r?normalizeAgentId(r):void 0;if(o&&a&&o!==a)throw new Error(`Agent "${o}" does not match session agent "${a}".`);const s=i?o??a:resolveConfiguredAgentId(e,o??resolveSoleAgentId(e,{surface:`exec-policy show`,hint:`Pass --agent <id> or --session <agent session key>.`}));const c={...s?{agentId:s}:{},...i?{sessionKey:i}:{}};if(i)try{const e=await callGatewayFromCliWithTransport(`tools.effective`,t,{...s?{agentId:s}:{},sessionKey:i},{progress:false,sharedStateMode:`read-only`,signal:n});if(s&&e.agentId!==s)throw new Error(`The Gateway returned tool access for a different agent.`);c.agentId=e.agentId;c.live={status:`verified`,diagnostics:e.toolAccess??describeLegacySessionPreview(e)}}catch(e){c.live={status:`unverified`,error:e instanceof Error?e.message:String(e)}}if(c.agentId&&listAgentIds(e).includes(c.agentId))c.local=resolveConfiguredToolAccess({config:e,agentId:c.agentId,toolNames:TERMINAL_TOOLS});return c}function describeLegacySessionPreview(e){const t=e.groups.flatMap(e=>e.tools);return{checked:`live-session`,profiles:[],tools:TERMINAL_TOOLS.map(e=>{const n=t.find(t=>t.id===e);return{id:e,status:n?.deniedBySession?`excluded`:n?`available`:`unavailable`,reasons:n?.deniedBySession?[{kind:`session`,label:`Denied by this session's tool restrictions`}]:n?[]:[{kind:`runtime`,label:`Not included in the session preview`}]}})}}function display(e){return sanitizeExecApprovalDisplayText(sanitizeTerminalText(e))}function terminalTools(e){return e.tools.filter(e=>TERMINAL_TOOLS.some(t=>t===e.id))}function formatExecPolicyCommandApprovals(e){const t=e.scopes.map(t=>{const n=t.ask.effective===`on-miss`?`ask on miss`:t.ask.effective===`always`?`always ask`:t.ask.effective===`off`?`no approval prompts`:`approval mode unknown`;return display(`${e.showScopeLabels&&t.scopeLabel?`${t.scopeLabel}: `:``}${t.host.requested} · ${t.security.effective} · ${n} · fallback ${t.askFallback.effective}`)});if(!e.approvalsExists)t.push(`Approvals State: defaults (no stored overrides)`);t.push(`Command approvals do not grant tool access.`,SESSION_EXEC_OVERRIDES_NOTE);return t}function renderExecPolicyToolAccess(e){const{access:t}=e;const n=t.live?.status===`verified`?t.live.diagnostics:void 0;const r=n??t.local;const i=r?terminalTools(r):[];const a=i.filter(e=>e.status===`excluded`);const o=i.some(e=>e.status===`unavailable`);const s=t.live?.status===`unverified`?`UNVERIFIED`:a.length===TERMINAL_TOOLS.length?n?`BLOCKED`:`OFF`:a.length>0?`PARTIAL`:n?`PREVIEW`:`UNVERIFIED`;const c=[theme.heading(`TERMINAL ACCESS · ${display(t.agentId??`unknown agent`)} — ${s}`)];if(t.sessionKey)c.push(`Session: ${display(t.sessionKey)}`);const section=e=>{c.push(``,theme.heading(`── ${e} ${`─`.repeat(Math.max(1,43-e.length))}`),``)};if(r&&r.profiles.length>0){section(n?`PROFILE (GATEWAY CONFIGURATION)`:`PROFILE`);const e=r.profiles.find(e=>e.source===`tools.profile`);const t=r.profiles.find(e=>e.source.startsWith(`agents.`)&&e.source.endsWith(`.tools.profile`));const profileText=e=>`${display(e.profile)}${e.active?` ← active`:``}`;if(e)c.push(`Global: ${profileText(e)}`);if(t)c.push(`${e?`└─ `:``}Agent: ${profileText(t)}`);for(const n of r.profiles.filter(n=>n!==e&&n!==t))c.push(`${display(n.source)}: ${profileText(n)}`)}section(`CHECK RESULTS`);if(!t.local)c.push(`Local tool policy: unavailable — no matching local agent.`);if(t.live?.status===`unverified`){if(t.local){const e=terminalTools(t.local).filter(e=>e.status===`excluded`);c.push(e.length>0?`Local configuration excludes: ${e.map(e=>e.id).join(`, `)}`:`Local configuration allows terminal tools; execution unverified`)}c.push(`Session preview: could not retrieve — ${display(t.live.error)}`)}for(const e of i){const t=e.status===`available`?`Included in session preview`:e.status===`allowed`?`Allowed by configuration; execution unverified`:e.status===`excluded`?`Excluded by policy`:`Not included in session preview; execution unverified`;c.push(`${display(e.id)}: ${t}`);for(const t of e.reasons)c.push(` ${display(t.label)}${t.source?` (${display(t.source)})`:``}`)}if(r)c.push(``,`Based on: ${n?`session preview (saved settings)`:`local configuration`}`);if(n)c.push(`Session preview uses saved settings; active runs may differ.`);section(`COMMAND APPROVALS (LOCAL)`);c.push(...formatExecPolicyCommandApprovals({scopes:e.approvals?[e.approvals]:[],approvalsExists:e.approvalsExists}));section(`NEXT STEP`);if(t.live?.status===`unverified`)c.push(`Check the Gateway connection and session key, then retry.`);else if(a.length>0){const e=/* @__PURE__ */ new Map;if(!o&&a.every(e=>e.alsoAllowPath)){for(const t of a){const n=t.alsoAllowPath;e.set(n,[...e.get(n)??[],t.id])}c.push(`If terminal access is intended, append:`);for(const[t,n]of e)c.push(` ${n.join(`, `)}`,`to:`,` ${display(t)}`);c.push(``,`Preserve existing entries and command approvals.`,`Inspect the session preview, then verify execution in a run.`)}else c.push(`Review the policy exclusions listed above before enabling terminal access.`)}else if(n)c.push(o?`Missing preview tools are not necessarily disabled.`:`Preview inclusion does not guarantee execution.`,`Verify execution in a run; command approvals still apply.`);else{c.push(`Inspect an existing session's tool preview:`);c.push(` openclaw exec-policy show --session <session-key>`);c.push(`Verify execution in a run; command approvals still apply.`)}if(n&&o&&a.length>0)c.push(`Missing preview tools are not necessarily disabled; verify execution in a run.`);if(e.verbose){section(`TOOL POLICY SOURCES`);for(const e of r?.profiles??[])c.push(`${display(e.source)} = ${display(e.profile)}`)}else c.push(``,`Use --verbose for policy sources and all command approval scopes.`);defaultRuntime.log(c.join(`
`))}
//!src/cli/exec-policy-cli.ts
const EXEC_POLICY_PRESETS={yolo:{host:`gateway`,security:`full`,ask:`off`,askFallback:`full`},cautious:{host:`gateway`,security:`allowlist`,ask:`on-miss`,askFallback:`deny`},"deny-all":{host:`gateway`,security:`deny`,ask:`off`,askFallback:`deny`}};function formatExecPolicyError(e){return sanitizeExecPolicyMessage(e instanceof Error?e.message:String(e))}async function runExecPolicyAction(e,t){try{await t()}catch(t){const n=formatExecPolicyError(t);if(e.json){rethrowExpectedCliError(t);const e=new ExpectedCliError({message:n,humanOutput:n,machineOutput:n});e.cause=t;throw e}defaultRuntime.error(n);defaultRuntime.exit(1)}}function sanitizeExecPolicyTableCell(e){return sanitizeExecApprovalDisplayText(sanitizeTerminalText(e))}function formatExecPolicyTableLines(...e){return e.map(sanitizeExecPolicyTableCell).join(`
`)}function sanitizeExecPolicyMessage(e){return sanitizeTerminalText(String(e))}async function buildLocalExecPolicyShowPayload(e,t){const n=await readConfigFileSnapshot();const r=await readExecApprovalsSnapshotAsync();const i=n.config??{};const a=collectExecPolicyScopeSnapshots({cfg:i,approvals:r.file,hostPath:r.path}).map(buildExecPolicyShowScope);const o=a.some(e=>e.runtimeApprovalsSource===`node-runtime`)?`Scopes requesting host=node are node-managed at runtime. Local approvals are shown only for local/gateway scopes.`:`Effective exec policy is the host approvals policy intersected with requested tools.exec policy.`;const s={configPath:n.path,approvalsPath:r.path,approvalsExists:r.exists,effectivePolicy:{note:`${o} ${SESSION_EXEC_OVERRIDES_NOTE}`,scopes:a}};if(!e)return s;const c=e.agent!==void 0||e.session!==void 0;if(!c&&listAgentIds(i).length===0){s.toolAccessSelectionRequired={agentIds:[],hint:`Configure an agent with openclaw agents add to inspect terminal tool access.`};return s}try{s.toolAccess=await buildExecPolicyToolAccess(i,e,t)}catch(e){if(c||!(e instanceof AgentSelectionRequiredError))throw e;s.toolAccessSelectionRequired={agentIds:e.agentIds,hint:e.hint}}return s}function buildExecPolicyShowScope(e){const{allowedDecisions:t,...n}=e;if(e.host.requested!==`node`)return{...n,runtimeApprovalsSource:`local-file`};const nodeManagedPolicy=t=>({requested:e[t].requested,requestedSource:e[t].requestedSource,host:`unknown`,hostSource:`node runtime approvals`,effective:`unknown`,note:`runtime policy resolved by node approvals`});return{...n,runtimeApprovalsSource:`node-runtime`,security:nodeManagedPolicy(`security`),ask:nodeManagedPolicy(`ask`),askFallback:{effective:`unknown`,source:`node runtime approvals`}}}function renderExecPolicyShow(e){defaultRuntime.log(theme.heading(`Exec Policy`));defaultRuntime.log(renderTable({width:getTerminalTableWidth(),columns:[{key:`Field`,header:`Field`,minWidth:14},{key:`Value`,header:`Value`,minWidth:24,flex:true}],rows:[{Field:`Config`,Value:sanitizeExecPolicyTableCell(e.configPath)},{Field:`Approvals`,Value:sanitizeExecPolicyTableCell(e.approvalsPath)},{Field:`Approvals State`,Value:sanitizeExecPolicyTableCell(e.approvalsExists?`stored`:`defaults (no stored overrides)`)}]}).trimEnd());defaultRuntime.log(``);defaultRuntime.log(theme.heading(`Effective Policy`));defaultRuntime.log(renderTable({width:getTerminalTableWidth(),columns:[{key:`Scope`,header:`Scope`,minWidth:12},{key:`Requested`,header:`Requested`,minWidth:24,flex:true},{key:`Host`,header:`Host`,minWidth:24,flex:true},{key:`Effective`,header:`Effective`,minWidth:16}],rows:e.effectivePolicy.scopes.map(e=>({Scope:sanitizeExecPolicyTableCell(e.scopeLabel),Requested:formatExecPolicyTableLines(`host=${e.host.requested} (${e.host.requestedSource})`,`security=${e.security.requested} (${e.security.requestedSource})`,`ask=${e.ask.requested} (${e.ask.requestedSource})`),Host:formatExecPolicyTableLines(`security=${e.security.host} (${e.security.hostSource})`,`ask=${e.ask.host} (${e.ask.hostSource})`,`askFallback=${e.askFallback.effective} (${e.askFallback.source})`),Effective:formatExecPolicyTableLines(`security=${e.security.effective}`,`ask=${e.ask.effective}`)}))}).trimEnd());defaultRuntime.log(``);defaultRuntime.log(theme.muted(e.effectivePolicy.note))}function applyLocalExecPolicy(e){return runWithLocalStateOwner({method:`exec-policy.set`,params:{...e},target:`local exec policy and approvals`,onForeignOwner:`refuse`,runLocal:async({assertCurrent:t})=>{const n=captureOpenClawStateWorkerContext();const r=await readConfigFileSnapshot();t();const i=structuredClone(r.config??{});i.tools??={};i.tools.exec??={};if(e.host!==void 0)i.tools.exec.host=e.host;if(e.security!==void 0||e.ask!==void 0){const t=resolveExecModePolicy({mode:normalizeExecMode(i.tools.exec.mode),security:i.tools.exec.security??`full`,ask:i.tools.exec.ask??`off`});const n=e.security??t.security;const r=e.ask??t.ask;const a=t.mode===`auto`&&n===t.security&&r===t.ask?`auto`:resolveExactExecModeFromPolicy({security:n,ask:r});if(a){i.tools.exec.mode=a;delete i.tools.exec.security;delete i.tools.exec.ask}else{delete i.tools.exec.mode;i.tools.exec.security=n;i.tools.exec.ask=r}}if(i.tools?.exec?.host===`node`)throw new Error(`Local exec-policy cannot synchronize host=node. Node approvals are fetched from the node at runtime.`);const a=await readExecApprovalsSnapshotAsync(n);t();const o=structuredClone(a.file);o.defaults??={};if(e.security!==void 0)o.defaults.security=e.security;if(e.ask!==void 0)o.defaults.ask=e.ask;if(e.askFallback!==void 0)o.defaults.askFallback=e.askFallback;const s=await updateExecApprovals({baseHash:a.hash,assertCurrent:t,update:{kind:`replace`,file:o}},n);if(!s)throw new Error(`Exec approvals changed; reload and retry.`);try{t();await replaceConfigFile({baseHash:r.hash,nextConfig:i,writeOptions:{assertCurrent:t}})}catch(r){try{t();if(!await restoreExecApprovalsSnapshotLocked(a,s.hash,n,t))await updateExecApprovals({assertCurrent:t,update:{kind:`rollback-defaults`,original:a.file,written:s.file,policy:e}},n)}catch(e){throw new Error(`Config update failed: ${formatExecPolicyError(r)}; exec approvals rollback failed: ${formatExecPolicyError(e)}`,{cause:e})}throw r}return await buildLocalExecPolicyShowPayload()}})}function registerExecPolicyCli(e){const t=e.command(`exec-policy`).description(`Show or synchronize requested exec policy with host approvals`).addHelpText(`after`,()=>formatDocsHelp(`/cli/approvals`));addGatewayClientOptions(t.command(`show`).description(`Explain terminal tool access and command approvals (offline unless --session)`).option(`--agent <id>`,`Agent whose terminal tools to inspect (automatic for one agent)`).option(`--session <key>`,`Fetch an existing session's tool preview from saved settings`).option(`--verbose`,`Include policy sources and all command approval scopes`,false).option(`--json`,`Output as JSON`,false)).action(async(e,t)=>{await runExecPolicyAction(e,async()=>{const n=getAsyncWorkSignal();const r=await buildLocalExecPolicyShowPayload(resolveGatewayRpcOptionsWithLocalPort(e,t),n);if(n?.aborted)return;if(e.json){defaultRuntime.writeJson(r,0);return}if(r.toolAccess){const t=r.effectivePolicy.scopes.find(e=>e.scopeLabel===`agent:${r.toolAccess?.agentId}`)??r.effectivePolicy.scopes.find(e=>e.agentId===r.toolAccess?.agentId)??r.effectivePolicy.scopes[0];renderExecPolicyToolAccess({access:r.toolAccess,approvals:t,approvalsExists:r.approvalsExists,verbose:e.verbose})}else if(r.toolAccessSelectionRequired){const{agentIds:t,hint:n}=r.toolAccessSelectionRequired;const i=`TERMINAL ACCESS — ${t.length?`SELECT AGENT`:`NO AGENT CONFIGURED`}`;defaultRuntime.log(theme.heading(i));if(t.length>0)defaultRuntime.log(`Configured agents: ${t.map(sanitizeExecPolicyTableCell).join(`, `)}`);defaultRuntime.log(``);defaultRuntime.log(theme.heading(`── COMMAND APPROVALS (LOCAL) ──────────────────`));defaultRuntime.log(``);defaultRuntime.log(formatExecPolicyCommandApprovals({scopes:r.effectivePolicy.scopes,approvalsExists:r.approvalsExists,showScopeLabels:true}).join(`
`));defaultRuntime.log(``);defaultRuntime.log(theme.heading(`── NEXT STEP ─────────────────────────────────`));defaultRuntime.log(``);defaultRuntime.log(sanitizeExecPolicyTableCell(n));if(!e.verbose)defaultRuntime.log(`Use --verbose for policy sources and detailed command approval scopes.`)}if(e.verbose){defaultRuntime.log(``);renderExecPolicyShow(r)}})});t.command(`preset <name>`).description(`Apply a synchronized preset: "yolo", "cautious", or "deny-all"`).option(`--json`,`Output as JSON`,false).action(async(e,t)=>{await runExecPolicyAction(t,async()=>{if(!Object.hasOwn(EXEC_POLICY_PRESETS,e))throw new Error(`Unknown exec-policy preset: ${sanitizeExecPolicyMessage(e)}`);const n=EXEC_POLICY_PRESETS[e];const r=await applyLocalExecPolicy(n);if(t.json){defaultRuntime.writeJson({preset:e,...r},0);return}defaultRuntime.log(`Applied exec-policy preset: ${sanitizeExecPolicyMessage(e)}`);defaultRuntime.log(``);renderExecPolicyShow(r)})});t.command(`set`).description(`Synchronize local config and host approvals using explicit values`).option(`--host <host>`,`Exec host target: auto|sandbox|gateway|node`).option(`--security <mode>`,`Exec security: deny|allowlist|full`).option(`--ask <mode>`,`Exec ask mode: off|on-miss|always`).option(`--ask-fallback <mode>`,`Host approvals fallback: deny|allowlist|full`).option(`--json`,`Output as JSON`,false).action(async e=>{await runExecPolicyAction(e,async()=>{const t={};const parse=(e,t,n)=>{const r=t(e);if(!r)throw new Error(`Invalid exec ${n}: ${sanitizeExecPolicyMessage(e)}`);return r};if(e.host!==void 0)t.host=parse(e.host,normalizeExecTarget,`host`);if(e.security!==void 0)t.security=parse(e.security,normalizeExecSecurity,`security`);if(e.ask!==void 0)t.ask=parse(e.ask,normalizeExecAsk,`ask mode`);if(e.askFallback!==void 0)t.askFallback=parse(e.askFallback,normalizeExecSecurity,`askFallback`);if(Object.keys(t).length===0)throw new Error(`Provide at least one of --host, --security, --ask, or --ask-fallback.`);const n=await applyLocalExecPolicy(t);if(e.json){defaultRuntime.writeJson({applied:t,...n},0);return}defaultRuntime.log(`Synchronized local exec policy.`);defaultRuntime.log(``);renderExecPolicyShow(n)})})}export{registerExecPolicyCli};