openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
7 lines • 16.5 kB
JavaScript
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{b as uniqueStrings}from"./string-normalization-D_oBUpO3.mjs";import{n as normalizeAgentId}from"./agent-id-cOfqmfln.mjs";import"./session-key-BPgKfU2m.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{Fi as validateExecApprovalGrantsRevokeParams,Ii as validateExecApprovalRequestParams,Li as validateExecApprovalResolveParams,Ni as validateExecApprovalGetParams,Pi as validateExecApprovalGrantsListParams}from"./src-BDZMFmKa.mjs";import{a as normalizeExecSecurity,r as normalizeExecAsk,t as DEFAULT_EXEC_APPROVAL_TIMEOUT_MS}from"./exec-approvals-core-BZ6-zeZE.mjs";import{i as ErrorCodes}from"./missing-scope-error-CkgBgh6d.mjs";import{p as errorShape}from"./error-codes-CQNGhXT-.mjs";import{i as normalizeExecApprovalUnavailableDecisions,s as resolveExecApprovalRequestAllowedDecisions}from"./exec-approvals-policy-DUqwCsoC.mjs";import{t as resolveGrantExpiryDaysConfig}from"./standing-grant-expiry-config-DLLQoEhB.mjs";import{g as analyzeArgvCommand}from"./exec-approvals-allowlist-WcJeUOTK.mjs";import{i as detectCommandCarrierArgv,o as detectInlineEvalInSegments}from"./risks-DuOS52CN.mjs";import"./exec-approvals-BLANskJu.mjs";import{t as resolveExecCommandHighlighting}from"./exec-command-highlighting-DKhOg79F.mjs";import{a as sanitizeExecApprovalWarningText,i as sanitizeExecApprovalDisplayTextWithStatus,r as sanitizeExecApprovalDisplayText,t as boundExecApprovalVisibleText}from"./exec-approval-text-sanitize-h0o6Uj2u.mjs";import{n as defineValidatedGatewayHandler,t as assertValidParams}from"./validation-CM41YclJ.mjs";import{t as sanitizeApprovalScope}from"./approval-scope-BgbNHTF5.mjs";import{n as buildSystemRunApprovalBinding,r as buildSystemRunApprovalEnvBinding}from"./system-run-approval-binding-BW8Wp0Lw.mjs";import{t as resolveExecApprovalCommandDisplay}from"./exec-approval-command-display-Jw_ow0f2.mjs";import{t as lookupCronRunExecSource}from"./cron-run-exec-source-BAvIQVDR.mjs";import{n as parseCronExecOperationBinding,t as buildCronExecOperationBinding}from"./operator-approval-standing-grants-CSJSaiJ_.mjs";import{c as listCronStandingGrants,h as revokeCronStandingGrant}from"./operator-approval-store-3mVTaQpm.mjs";import{n as resolveSystemRunApprovalRequestContext}from"./system-run-approval-context-Clba93A1.mjs";import{a as handleApprovalResolve,c as resolveApprovalDecisionParams,n as bindApprovalReviewerDeviceIds,o as handleApprovalWaitDecision,t as bindApprovalRequesterMetadata}from"./approval-shared-D5K52j8A.mjs";import{c as respondPendingApprovalLookupError,o as resolvePendingApprovalRecord,r as listVisiblePendingApprovalRequests}from"./approval-record-lookup-B95DCWvc.mjs";import{t as handlePendingApprovalRequestWithDelivery}from"./approval-request-delivery-D7M7U3li.mjs";import{t as InvalidApprovalIdError}from"./exec-approval-registration-BAJJt1fr.mjs";import{t as createApprovalRequestAuthority}from"./approval-request-authority-CcHfRvXg.mjs";import{n as registerPendingApprovalRecord,t as captureApprovalWorkerOwner}from"./approval-registration-BFax_YsE.mjs";
//!src/infra/command-analysis/explain.ts
function riskLabel(e){switch(e.kind){case`inline-eval`:return`${e.command} ${e.flag}`;case`shell-wrapper`:return`${e.executable} ${e.flag}`;case`command-carrier`:return e.flag?`${e.command} ${e.flag}`:e.command;case`dynamic-argument`:return`${e.command} dynamic argument`;case`source`:return e.command;case`function-definition`:return e.name;default:return e.kind}}function summarizeCommandSegmentsForDisplay(e){const t=[];const n=[];const r=detectInlineEvalInSegments(e);if(r){t.push(`inline-eval`);n.push(`Contains inline-eval: ${r.normalizedExecutable} ${r.flag}`)}for(const r of e){const e=r.resolution?.effectiveArgv??r.argv;for(const r of detectCommandCarrierArgv(e)){t.push(`command-carrier`);n.push(r.flag?`Contains command-carrier: ${r.command} ${r.flag}`:`Contains command-carrier: ${r.command}`)}}return{commandCount:e.length,nestedCommandCount:0,riskKinds:uniqueStrings(t),warningLines:uniqueStrings(n)}}async function resolveCommandAnalysisSummaryForDisplay(e){let t;if(e.host===`node`){if(!Array.isArray(e.commandArgv)||e.commandArgv.length===0)return null;const n=await analyzeArgvCommand({argv:e.commandArgv,cwd:e.cwd??void 0});if(!n.ok)return null;t=summarizeCommandSegmentsForDisplay(n.segments)}else try{const{explainShellCommand:n}=await import(`./extract-BAHL3D9a.mjs`);const r=await n(e.commandText);t={commandCount:r.topLevelCommands.length,nestedCommandCount:r.nestedCommands.length,riskKinds:uniqueStrings(r.risks.map(e=>e.kind)),warningLines:uniqueStrings(r.risks.map(e=>{const t=riskLabel(e);return t===e.kind?`Contains ${e.kind}`:`Contains ${e.kind}: ${t}`}))}}catch{return null}const n=e.sanitizeText;if(!n)return t;return{commandCount:t.commandCount,nestedCommandCount:t.nestedCommandCount,riskKinds:t.riskKinds.map(e=>n(e)),warningLines:t.warningLines.map(e=>n(e))}}
//!src/shared/exec-approval-command-spans.ts
function normalizeCommandSpans(e,t){if(!e)return;const n=e.filter(e=>Number.isSafeInteger(e.startIndex)&&Number.isSafeInteger(e.endIndex)&&e.startIndex>=0&&e.endIndex>e.startIndex&&e.endIndex<=t).toSorted((e,t)=>e.startIndex-t.startIndex||t.endIndex-e.endIndex);const r=[];let i=0;for(const e of n){if(e.startIndex<i)continue;r.push({startIndex:e.startIndex,endIndex:e.endIndex});i=e.endIndex}return r.length>0?r:void 0}
//!src/gateway/server-methods/exec-approval.ts
const APPROVAL_ALLOW_ALWAYS_UNAVAILABLE_DETAILS={reason:`APPROVAL_ALLOW_ALWAYS_UNAVAILABLE`};const RESERVED_PLUGIN_APPROVAL_ID_PREFIX=`plugin:`;function createExecApprovalHandlers(e,t){return{"exec.approval.get":async t=>{try{var n=_usingCtx();const r=n.u(createApprovalRequestAuthority(t));const{params:i,respond:a,client:o,context:s}=t;if(!assertValidParams(i,validateExecApprovalGetParams,`exec.approval.get`,a))return;const c=await resolvePendingApprovalRecord({authority:r,manager:e,inputId:i.id,client:o,...o?.authenticatedUserProfile?{getCfg:s.getRuntimeConfig}:{},exposeAmbiguousPrefixError:true});r.assertCurrent();if(!c.ok){respondPendingApprovalLookupError({respond:a,response:c.response});return}const{commandText:l,commandPreview:u}=resolveExecApprovalCommandDisplay(c.snapshot.request);a(true,{id:c.approvalId,commandText:l,commandPreview:u,allowedDecisions:resolveExecApprovalRequestAllowedDecisions(c.snapshot.request),host:c.snapshot.request.host??null,nodeId:c.snapshot.request.nodeId??null,agentId:c.snapshot.request.agentId??null,expiresAtMs:c.snapshot.expiresAtMs},void 0)}catch(e){n.e=e}finally{n.d()}},"exec.approval.list":async t=>{try{var n=_usingCtx();const r=n.u(createApprovalRequestAuthority(t));const{respond:i,client:a,context:o}=t;const s=await listVisiblePendingApprovalRequests({authority:r,manager:e,client:a,approvalKind:`exec`,...a?.authenticatedUserProfile?{getCfg:o.getRuntimeConfig}:{}});r.assertCurrent();i(true,s,void 0)}catch(e){n.e=e}finally{n.d()}},"exec.approval.request":defineValidatedGatewayHandler(`exec.approval.request`,validateExecApprovalRequestParams,async({params:n,respond:r,context:i,client:a})=>{const rejectRequest=e=>{r(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,e))};const o=n;const s=o.twoPhase===true;const c=o.timeoutMs??18e5;const l=o.id??null;const u=normalizeOptionalString(o.host)??``;const d=normalizeOptionalString(o.nodeId)??``;const f=a?.internal?.agentRuntimeIdentity;if(f&&i.validateAgentRuntimeApprovalAuthority?.(f)!==true){rejectRequest(`agent runtime approval authority is no longer active`);return}const p=captureApprovalWorkerOwner(f);const m=resolveSystemRunApprovalRequestContext({host:u,command:o.command,commandArgv:o.commandArgv,systemRunPlan:o.systemRunPlan,cwd:o.cwd,agentId:f?.agentId??o.agentId,sessionKey:f?.sessionKey??o.sessionKey});const h=m.commandArgv;const g=m.cwd;const _=m.agentId;const v=m.sessionKey;const y=m.commandText;const b=f?.operationalRunInstance.runId??normalizeOptionalString(o.runId);if(b&&i.chatRunState.hasAbortMarker(b)){r(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,`The approval run was stopped. Start a new turn to request approval again.`,{details:{reason:`EXEC_APPROVAL_RUN_ABORTED`}}));return}if(u===`node`&&!d){rejectRequest(`nodeId is required for host=node`);return}if(u===`node`&&!m.plan){rejectRequest(`systemRunPlan is required for host=node`);return}if(y.trim().length===0){rejectRequest(`command is required`);return}if(l?.startsWith(RESERVED_PLUGIN_APPROVAL_ID_PREFIX)){rejectRequest(`approval ids starting with ${RESERVED_PLUGIN_APPROVAL_ID_PREFIX} are reserved`);return}if(u===`node`&&(!Array.isArray(h)||h.length===0)){rejectRequest(`commandArgv is required for host=node`);return}const x=buildSystemRunApprovalEnvBinding(o.env);const S=normalizeOptionalString(o.warningText);const C=i.getRuntimeConfig();const w=resolveExecCommandHighlighting({config:C,agentId:_});const T=sanitizeExecApprovalDisplayTextWithStatus(y);if(T.truncated||T.oversized){r(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,`command exceeds exec approval display limit`,{details:{reason:`EXEC_APPROVAL_COMMAND_DISPLAY_LIMIT`}}));return}const E=T.text;const D=await resolveCommandAnalysisSummaryForDisplay({host:u,commandText:y,commandArgv:h,cwd:g,sanitizeText:sanitizeExecApprovalWarningText});const O=w&&E===y?normalizeCommandSpans(o.commandSpans,E.length):void 0;const k=u===`node`?buildSystemRunApprovalBinding({argv:h,cwd:g,agentId:_,sessionKey:v,env:o.env}):null;if(l&&await e.getSnapshot(l)){rejectRequest(`approval id already pending`);return}const A=normalizeExecApprovalUnavailableDecisions(o.unavailableDecisions);const j=u===`gateway`&&b?lookupCronRunExecSource(b):void 0;const M=j&&_&&j.agentId===_?{jobId:j.jobId,jobConfigRevision:j.jobConfigRevision}:null;const N=M?resolveGrantExpiryDaysConfig(i.getRuntimeConfig()):null;const P=M&&j&&y?{kind:`standing-grant`,automation:boundExecApprovalVisibleText(j.jobName,128),command:boundExecApprovalVisibleText(y,256),...N!==null?{expiresInDays:N}:{}}:null;const F={command:E,commandPreview:u===`node`||!m.commandPreview?void 0:sanitizeExecApprovalDisplayText(m.commandPreview),commandArgv:u===`node`?void 0:h,envKeys:x.envKeys.length>0?x.envKeys:void 0,systemRunBinding:k?.binding??null,systemRunPlan:m.plan,cwd:g?sanitizeExecApprovalDisplayText(g):null,nodeId:u===`node`?d:null,host:u?sanitizeExecApprovalDisplayText(u):null,security:normalizeExecSecurity(o.security)??null,ask:normalizeExecAsk(o.ask)??null,warningText:S?sanitizeExecApprovalWarningText(S):null,scope:P??(o.scope?sanitizeApprovalScope(o.scope):null),commandAnalysis:D,commandSpans:O,unavailableDecisions:A.length>0?A:void 0,allowedDecisions:resolveExecApprovalRequestAllowedDecisions({ask:o.ask??null,unavailableDecisions:A}),agentId:f?.agentId??_??null,resolvedPath:o.resolvedPath?sanitizeExecApprovalDisplayText(o.resolvedPath):null,sessionKey:f?.sessionKey??v??null,sessionId:f?null:normalizeOptionalString(o.sessionId)??null,runId:b??null,toolCallId:normalizeOptionalString(o.toolCallId)??null,turnSourceChannel:f?f.turnSourceChannel??null:normalizeOptionalString(o.turnSourceChannel)??null,turnSourceTo:f?f.turnSourceTo??null:normalizeOptionalString(o.turnSourceTo)??null,turnSourceAccountId:f?f.turnSourceAccountId??null:normalizeOptionalString(o.turnSourceAccountId)??null,turnSourceThreadId:f?f.turnSourceThreadId??null:o.turnSourceThreadId??null,cronExecutionSource:M,cronOperationBinding:M?buildCronExecOperationBinding({command:y,cwd:g,env:o.env}):null};let I;try{I=e.create(F,c,l)}catch(e){if(e instanceof InvalidApprovalIdError){r(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,e.message,{details:{code:e.code,reason:e.reason}}));return}throw e}bindApprovalRequesterMetadata({record:I,client:a});if(f)I.agentRuntimeDelegatedAuthority=f.delegatedAuthority;const L=f?.executionIdentity;if(L&&b===L.runId)I.executionIdentityToken=L;if(a?.internal?.approvalRuntime===true)bindApprovalReviewerDeviceIds({record:I,deviceIds:o.approvalReviewerDeviceIds});if(!await registerPendingApprovalRecord({manager:e,record:I,timeoutMs:c,respond:r,context:i,workerOwner:p}))return;if(b&&i.chatRunState.hasAbortMarker(b)){await e.forceDenyDetailed(I.id,`run-aborted`,{kind:`system`,id:null},`cancelled`);r(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,`The approval run was stopped. Start a new turn to request approval again.`,{details:{reason:`EXEC_APPROVAL_RUN_ABORTED`}}));return}await handlePendingApprovalRequestWithDelivery({approvalKind:`exec`,manager:e,record:I,respond:r,context:i,clientConnId:a?.connId,twoPhase:s,requireDeliveryRoute:o.requireDeliveryRoute,suppressDelivery:o.suppressDelivery,deliverToApprovalClientsOnly:o.deliverToApprovalClientsOnly===true||M!==null,forwardRequest:t?.forwarder?.handleRequested.bind(t.forwarder),getIosPushDelivery:()=>t?.iosPushDelivery})}),"exec.approval.waitDecision":async t=>{try{var n=_usingCtx();const r=n.u(createApprovalRequestAuthority(t));const{params:i,respond:a,client:o,context:s}=t;await handleApprovalWaitDecision({authority:r,manager:e,inputId:i.id,client:o,...o?.authenticatedUserProfile?{getCfg:s.getRuntimeConfig}:{},respond:a,resolveTerminalReason:e=>{const t=normalizeOptionalString(e.request.runId);return t&&s.chatRunState.hasAbortMarker(t)?`run-aborted`:void 0}})}catch(e){n.e=e}finally{n.d()}},"exec.approval.grants.list":async e=>{try{var t=_usingCtx();const n=t.u(createApprovalRequestAuthority(e));const{params:r,respond:i}=e;if(!assertValidParams(r,validateExecApprovalGrantsListParams,`exec.approval.grants.list`,i))return;const a=await listCronStandingGrants({limit:r.limit,guard:n.guard});n.assertCurrent();i(true,{grants:a.map(e=>{const t=parseCronExecOperationBinding(e.operationBinding);return{grantId:e.grantId,mintedByApprovalId:e.mintedByApprovalId,agentId:e.agentId,cronJobId:e.cronJobId,cronJobName:e.cronJobName,command:boundExecApprovalVisibleText(t?.command??`(unreadable)`,512),cwd:t?.cwd?boundExecApprovalVisibleText(t.cwd,512):null,createdAtMs:e.createdAtMs,expiresAtMs:e.expiresAtMs,revokedAtMs:e.revokedAtMs,revokedBy:e.revokedBy,lastUsedAtMs:e.lastUsedAtMs,useCount:e.useCount}})},void 0)}catch(e){t.e=e}finally{t.d()}},"exec.approval.grants.revoke":async e=>{try{var t=_usingCtx();const n=t.u(createApprovalRequestAuthority(e));const{params:r,respond:i,client:a}=e;if(!assertValidParams(r,validateExecApprovalGrantsRevokeParams,`exec.approval.grants.revoke`,i))return;const o=a?.connect?.client?.displayName??a?.connect?.client?.id??`operator`;const s=await revokeCronStandingGrant({grantId:r.grantId,revokedBy:o,guard:n.guard});n.assertCurrent();i(true,{outcome:s.outcome},void 0)}catch(e){t.e=e}finally{t.d()}},"exec.approval.resolve":async n=>{try{var r=_usingCtx();const i=r.u(createApprovalRequestAuthority(n));const{params:a,respond:o,client:s,context:c}=n;const l=resolveApprovalDecisionParams({rawParams:a,validate:validateExecApprovalResolveParams,methodName:`exec.approval.resolve`,respond:o});if(!l)return;const{inputId:u,decision:d,reviewer:f}=l;const p=a.grantExpiresInDays;const m=d===`allow-always`&&typeof p===`number`?Date.now()+Math.floor(p)*864e5:void 0;let h=false;await handleApprovalResolve({approvalKind:`exec`,authority:i,manager:e,inputId:u,decision:d,respond:o,context:c,client:s,reviewer:f,exposeAmbiguousPrefixError:true,validateDecision:e=>{const t=s?.internal?.approvalRuntime===true?s.internal.agentRuntimeIdentity:void 0;if(t){const n=normalizeAgentId(e.request.agentId??void 0);const r=normalizeOptionalString(e.request.sessionKey);if(d!==`allow-once`||e.request.host!==`node`||n!==t.agentId||r!==t.sessionKey)return{message:`auto-review approval identity does not match request`,details:{reason:`AUTO_REVIEW_APPROVAL_IDENTITY_MISMATCH`}};h=true}return resolveExecApprovalRequestAllowedDecisions(e.request).includes(d)?null:{message:`allow-always is unavailable for this command`,details:APPROVAL_ALLOW_ALWAYS_UNAVAILABLE_DETAILS}},resolveRecord:async({approvalId:t,decision:n,resolvedBy:r,resolver:i,guard:a})=>{if(h)return e.resolveAutoReview(t,r,void 0,a);const o={guard:a,...m!==void 0?{grantExpiresAtMs:m}:{}};return i?(await e.resolveDetailed(t,n,i,r,`operator`,o)).outcome===`resolved`:e.resolve(t,n,r,o)},forwardResolved:e=>t?.forwarder?.handleResolved(e),forwardResolvedErrorLabel:`exec approvals: forward resolve failed`,extraResolvedHandlers:t?.iosPushDelivery?.handleResolved?[{run:e=>t.iosPushDelivery.handleResolved(e),errorLabel:`exec approvals: iOS push resolve failed`}]:void 0})}catch(e){r.e=e}finally{r.d()}}}}export{createExecApprovalHandlers};