@x-otto/guard 0.1.0-alpha.9 → 0.3.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,4219 @@
1
- import{createLogger as e}from"@x-otto/shared";import{resolve as t}from"node:path";import{defineHook as n}from"@x-otto/hooks";import{realpathSync as r}from"node:fs";function i(e){let t=[],n=``,r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a],s=e[a+1];if(r){o===`'`&&(r=!1),n+=o;continue}if(i){o===`"`&&(i=!1),n+=o;continue}if(o===`'`){r=!0,n+=o;continue}if(o===`"`){i=!0,n+=o;continue}if(o===`&`&&s===`&`||o===`|`&&s===`|`){t.push(n),n=``,a++;continue}if(o===`;`||o===`|`||o===`
2
- `||o===`&`){t.push(n),n=``;continue}n+=o}return t.push(n),t.map(e=>e.trim()).filter(Boolean)}function a(e){let t=e.trim();return t.length>=2&&(t[0]===`"`&&t[t.length-1]===`"`||t[0]===`'`&&t[t.length-1]===`'`)?t.slice(1,-1):t}function o(e){let t=e.match(/^(?:\S*\/)?(?:bash|sh|zsh|dash|ksh|ash|python[0-9.]*|node|nodejs|perl|ruby|php|deno|bun)\b[\s\S]*?\s-[a-z]*[cer]\b\s*([\s\S]+)$/i);return t?a(t[1]):null}function s(e){let t=e.trim();for(let e=0;e<10;e++){let e=t;if(t=t.replace(/^[A-Za-z_][A-Za-z0-9_]*=(?:"[^"]*"|'[^']*'|\S*)\s+/,``),t=t.replace(/^(?:sudo|env|nohup|setsid|ionice)\b(?:\s+-\S+|\s+[A-Za-z_][A-Za-z0-9_]*=\S+)*\s+/i,``),t=t.replace(/^(?:nice|stdbuf)\b(?:\s+-\S+)*\s+/i,``),t=t.replace(/^timeout\b(?:\s+-\S+)*\s+\S+\s+/i,``),t===e)break}return t}function c(e){let t=[];for(let n=0;n<e.length;n++)if(e[n]===`$`&&e[n+1]===`(`){let r=1,i=n+2,a=i;for(;i<e.length&&r>0;)e[i]===`(`?r++:e[i]===`)`&&r--,i++;r===0&&t.push(e.slice(a,i-1))}let n=e.match(/`([^`]+)`/g);if(n)for(let e of n)t.push(e.slice(1,-1));return t}const l={n:`
3
- `,t:` `,r:`\r`,a:`\x07`,b:`\b`,f:`\f`,v:`\v`,e:`\x1B`,E:`\x1B`,"\\":`\\`,"'":`'`,'"':`"`,"?":`?`};function u(e){return/[0-9a-fA-F]/.test(e)}function d(e){let t=``,n=0;for(;n<e.length;){if(e[n]!==`\\`){t+=e[n],n++;continue}let r=e[n+1];if(r===void 0){t+=`\\`;break}if(r===`x`){let r=``;for(;r.length<2&&u(e[n+2+r.length]??``);)r+=e[n+2+r.length];if(r){t+=String.fromCharCode(parseInt(r,16)),n+=2+r.length;continue}}if(r===`u`||r===`U`){let i=r===`u`?4:8,a=``;for(;a.length<i&&u(e[n+2+a.length]??``);)a+=e[n+2+a.length];if(a){t+=String.fromCodePoint(parseInt(a,16)),n+=2+a.length;continue}}if(r>=`0`&&r<=`7`){let r=``;for(;r.length<3;){let t=e[n+1+r.length]??``;if(t<`0`||t>`7`)break;r+=t}t+=String.fromCharCode(parseInt(r,8)&255),n+=1+r.length;continue}t+=l[r]??r,n+=2}return t}function f(e){return e.replace(/\$'((?:\\.|[^'\\])*)'/g,(e,t)=>d(t))}function p(e){return e.replace(/\$\{IFS[^}]*\}/g,` `).replace(/\$IFS\b(?:\$[0-9@*])?/g,` `)}function ee(e){return p(f(e))}function m(e){let t=new Set,n=[],r=(e,l)=>{let u=e.trim();if(!u||l>12||t.has(u))return;t.add(u),n.push(u);let d=ee(u);d!==u&&r(d,l+1);let f=u.match(/<<<\s*('[^']*'|"[^"]*"|[^\s|;&]+)/)?.[1];f&&r(a(f),l+1);for(let e of c(u))r(e,l+1);let p=i(u);if(p.length>1){for(let e of p)r(e,l+1);return}let m=o(u);m&&r(m,l+1);let h=s(u);h!==u&&r(h,l+1)};return r(e,0),n}function h(e){return e.length>=2&&(e[0]===`"`&&e.endsWith(`"`)||e[0]===`'`&&e.endsWith(`'`))?e.slice(1,-1):e}function g(e){let t=[],n=``,r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(r){o===`'`?r=!1:n+=o;continue}if(i){o===`"`?i=!1:n+=o;continue}if(o===`'`){r=!0;continue}if(o===`"`){i=!0;continue}if(o===` `||o===` `){n&&=(t.push(n),``);continue}n+=o}return n&&t.push(n),t}const _=/(?:^|[^0-9&>])(?:[0-9]*&?>>?|>\|)\s*('[^']*'|"[^"]*"|[^\s;|&<>]+)/g;function v(e,t){let n;for(_.lastIndex=0;(n=_.exec(e))!==null;)t(n[1]);let r=g(e);if(r.length===0)return;let i=r[0].replace(/^.*\//,``),a=r.slice(1),o=a.filter(e=>!e.startsWith(`-`));if(i===`tee`)for(let e of o)t(e);else if(i===`cp`||i===`mv`||i===`install`||i===`ln`)o.length>=1&&t(o[o.length-1]);else if(i===`touch`||i===`rm`||i===`rmdir`||i===`mkdir`)for(let e of o)t(e);else if(i===`dd`)for(let e of a)e.startsWith(`of=`)&&t(e.slice(3))}function te(e){let t=g(e.trim());if(t.length<2||t[0]!==`cd`)return null;let n=t.find((e,t)=>t>0&&!e.startsWith(`-`));return!n||n.includes(`$`)?null:n}function ne(e,t){let n=null;for(let r of i(e)){let e=te(r);if(e){n=e.startsWith(`/`)||e.startsWith(`~`)||!n?e:`${n}/${e}`;continue}if(!n)continue;let i=[];v(r,e=>{e&&i.push(e)});for(let e of i){let r=h(e.trim());r&&!r.startsWith(`/`)&&!r.startsWith(`~`)&&t(`${n}/${r}`)}}}function re(e){let t=new Set,n=e=>{if(!e)return;let n=h(e.trim());n&&!n.startsWith(`-`)&&!n.includes(`$`)&&n!==`/dev/null`&&n!==`/dev/stdout`&&n!==`/dev/stderr`&&t.add(n)};for(let t of m(e))v(t,n);return ne(e,n),[...t]}function y(e){return{readonlyTools:new Set(e?.readonlyTools??[]),writeTools:new Set(e?.writeTools??[]),fileWriteTools:new Set(e?.fileWriteTools??[])}}function ie(e){let t=new Set,n=new Set,r=new Set;for(let i of e)if(i.name){if(i.readonly===!0){t.add(i.name);continue}if(i.name===`bash`){n.add(i.name);continue}if(i.metadata?.category===`fs`){n.add(i.name),r.add(i.name);continue}i.name.startsWith(`mcp__`)&&n.add(i.name)}return{readonlyTools:t,writeTools:n,fileWriteTools:r}}function b(e,t){return e?m(e).some(e=>t.some(t=>t.test(e))):!1}function x(e,t,n){if(!e.startsWith(`mcp__`))return!1;for(let e of Object.values(t))if(typeof e==`string`&&b(e,n))return!0;return!1}const S=[/^\/etc\//,/^\/usr\//,/^\/sys\//,/^\/proc\//,/node_modules\//,/\.git\//,/\.env$/,/\.env\.local$/,/\/\.ssh\//,/\/\.aws\//,/\/\.(bash|zsh)rc$/,/\/\.(bash_profile|zprofile|profile)$/];function C(e){let{fileWriteTools:t}=y(e);return{name:`builtin::file-guard`,priority:10,enabled:!0,safety:!0,scope:{agents:[`*`]},rules:[{name:`protect-system-paths`,effect:`deny`,match:{tools:[...t],paths:S},denyReason:`Write to protected system path is not allowed`}]}}const ae=/\b(rmdir\b|drop\s+table|git\s+push\s+(?:\S+\s+)*(?:--force\b|-f\b)|git\s+reset\s+--hard|git\s+clean\s+-[a-z]*f|truncate\s+table|dd\s+if=|mkfs\b|>\s*\/dev\/(?:sd|nvme|disk|hd))/i;function w(e){let t=g(e);return t.length===0||t[0].replace(/^.*\//,``)!==`rm`?!1:t.slice(1).some(e=>e===`--recursive`||e===`--force`?!0:/^-[a-z]*[rf]/i.test(e))}const T=/(\beval\s|(?:curl|wget)\b[^|;&]*\|\s*(?:sudo\s+)?(?:ba|z|d)?sh\b|:\s*\(\s*\)\s*\{[^}]*:\s*\|\s*:|base64\s+(?:-d|--decode)\b[^|]*\|)/i,oe=/\b(?:python[0-9.]*|pythonw|pypy[0-9]*|node|nodejs|deno|bun|perl|ruby|php|osascript|Rscript|pwsh|powershell(?:\.exe)?)\b[^|;&\n]*?(?:\s-{1,2}(?:c|e|r|E|p|eval|Command|EncodedCommand)\b|\s*<<)/i;function E(e){return e?m(e).some(e=>ae.test(e)||w(e)||T.test(e)||oe.test(e)):!1}function se(e,t){return e.startsWith(`mcp__`)?Object.values(t).some(e=>typeof e==`string`&&E(e)):!1}const D={name:`builtin::destructive-guard`,priority:15,enabled:!0,safety:!0,scope:{agents:[`*`]},rules:[{name:`ask-destructive-bash`,effect:`ask`,match:{condition:e=>E(String(e.args.command??``))},askPrompt:`This command may be destructive or runs code that cannot be statically checked. Continue?`},{name:`ask-destructive-mcp-args`,effect:`ask`,match:{condition:e=>se(e.toolName,e.args)},askPrompt:`This MCP tool argument may run a destructive or unverifiable command. Continue?`}]},ce=[/\/\.ssh(\/|$)/,/\/\.aws(\/|$)/,/\/\.gnupg(\/|$)/,/\/otto\/auth\.json$/],le=[/\/\.env(\.[\w.-]+)?$/],O=[/\.ssh(\/|\s|$)/,/\.aws(\/|\s|$)/,/\.gnupg(\/|\s|$)/,/otto\/auth\.json/],k=[/\.env(\b|\.[\w-]+)/],A={name:`builtin::credential-guard`,priority:16,enabled:!0,safety:!0,scope:{agents:[`*`]},rules:[{name:`deny-credential-paths`,effect:`deny`,match:{paths:ce},denyReason:`Reading credential/secret files (~/.ssh, ~/.aws, ~/.gnupg, auth store) is not allowed`},{name:`deny-credential-command`,effect:`deny`,match:{condition:e=>b(String(e.args.command??``),O)},denyReason:`Command references credential/secret paths (~/.ssh, ~/.aws, ~/.gnupg, auth store)`},{name:`ask-dotenv-paths`,effect:`ask`,match:{paths:le},askPrompt:`This reads a .env file which may contain secrets. Continue?`},{name:`ask-dotenv-command`,effect:`ask`,match:{condition:e=>b(String(e.args.command??``),k)},askPrompt:`This command references a .env file which may contain secrets. Continue?`},{name:`deny-mcp-credential-args`,effect:`deny`,match:{condition:e=>x(e.toolName,e.args,O)},denyReason:`MCP tool argument references credential/secret paths (~/.ssh, ~/.aws, ~/.gnupg, auth store)`},{name:`ask-mcp-dotenv-args`,effect:`ask`,match:{condition:e=>x(e.toolName,e.args,k)},askPrompt:`This MCP tool reads a .env file which may contain secrets. Continue?`}]},ue=[/\.otto\/plugin-trust\.json$/,/\.otto\/claude-trust\.json$/,/\.otto\/config\.json$/,/\.otto\/schedules\//,/\.otto\/plugins\//,/\.otto\/timers\//],de=[/\.otto\/sessions\//,/\.otto\/.*\.lock$/],fe=[/\.otto\/AGENTS\.md$/,/\.otto\/MEMORY\.md$/,/\.otto\/memory\//,/\.otto\/local\/MEMORY\.md$/,/\.otto\/local\/memory\//,/\.otto\/lessons\.json$/,/\.otto\/local\/lessons\.json$/],pe=[/\.otto\/(plugin-trust|claude-trust|config)\.json/,/\.otto\/(schedules|plugins|timers|sessions)\//,/\.otto\/.*\.lock\b/,/\.otto\/AGENTS\.md/,/\.otto\/(local\/)?MEMORY\.md/,/\.otto\/(local\/)?memory\//,/\.otto\/(local\/)?lessons\.json/];function j(e){let{fileWriteTools:t}=y(e),n=[...t];return{name:`builtin::otto-state-domain-guard`,priority:17,enabled:!0,safety:!0,scope:{agents:[`*`]},rules:[{name:`deny-otto-trust-and-execution-state`,effect:`deny`,match:{tools:n,paths:ue},denyReason:`Writing to otto trust/config/schedule/plugin state is not allowed via file tools — use the dedicated command (/extension, schedule_create, settings) instead`},{name:`deny-otto-runtime-state`,effect:`deny`,match:{tools:n,paths:de},denyReason:`otto runtime state (sessions/locks) must not be modified directly`},{name:`deny-otto-memory-state`,effect:`deny`,match:{tools:n,paths:fe},denyReason:`Cross-session memory must be written via the memory_record tool (not edit/write) — use scope: "workspace" | "local" | "project-shared"`},{name:`deny-otto-state-command-reference`,effect:`deny`,match:{condition:e=>b(String(e.args.command??``),pe)},denyReason:`Command references otto trust/config/schedule/plugin/session state — not allowed via bash`}]}}function me(e){try{return new URL(e).hostname.toLowerCase()}catch{return null}}function he(e,t){return t.some(t=>{let n=t.trim().toLowerCase().replace(/^\*?\./,``);return n.length>0&&(e===n||e.endsWith(`.${n}`))})}function ge(e){let t=e.map(e=>e.trim().toLowerCase()).filter(Boolean);return{name:`setting::egress-allowlist`,priority:8,enabled:!0,safety:!0,scope:{agents:[`*`]},rules:[{name:`ask-egress-offlist`,effect:`ask`,match:{condition:e=>{let n=e.args.url;if(typeof n!=`string`)return!1;let r=me(n);return r?!he(r,t):!1}},askPrompt:`This requests a host not in the egress allowlist. Continue?`}]}}function M(e){return{name:`setting::disabled-tools`,priority:2,enabled:!0,scope:{agents:[`*`]},rules:[{name:`deny-disabled`,effect:`deny`,match:{tools:e},denyReason:`Tool disabled by configuration`}]}}function N(e,t){let{readonlyTools:n,writeTools:r}=y(t);switch(e){case`bypass`:return{name:`mode::bypass`,priority:1,enabled:!0,scope:{agents:[`*`]},rules:[{name:`allow-all`,effect:`allow`,match:{}}]};case`readonly`:return{name:`mode::readonly`,priority:1,enabled:!0,scope:{agents:[`*`]},rules:[{name:`allow-reads`,effect:`allow`,match:{condition:e=>n.has(e.toolName)}},{name:`deny-writes`,effect:`deny`,match:{},fallthrough:!0,denyReason:`Read-only mode: write operations are not allowed`}]};case`confirm`:return{name:`mode::confirm`,priority:1,enabled:!0,scope:{agents:[`*`]},rules:[{name:`allow-reads`,effect:`allow`,match:{condition:e=>n.has(e.toolName)}},{name:`ask-writes`,effect:`ask`,match:{tools:[...r]},askPrompt:`Confirm write operation?`}]};case`strict`:return{name:`mode::strict`,priority:9999,enabled:!0,scope:{agents:[`*`]},rules:[{name:`deny-unmatched`,effect:`deny`,match:{},fallthrough:!0,denyReason:`Strict mode: no matching permission policy`}]};default:return{name:`mode::auto`,priority:1,enabled:!0,scope:{agents:[`*`]},rules:[{name:`allow-reads`,effect:`allow`,match:{condition:e=>n.has(e.toolName)}},{name:`auto-writes`,effect:`allow`,match:{tools:[...r]}}]}}}function P(e,t={}){e.registerWithSource(N(`auto`,t.toolSets),`builtin`),e.registerWithSource(C(t.toolSets),`builtin`),e.registerWithSource(D,`builtin`),e.registerWithSource(A,`builtin`),e.registerWithSource(j(t.toolSets),`builtin`)}function F(e){let t=e.trim(),n=/^([^()\s]+)\((.*)\)$/.exec(t);return n?{toolName:n[1]??t,content:(n[2]??``).trim()}:{toolName:t}}function I(e){let t=e.trim();if(!t)return!1;let n=/^([^()\s]+)\((.*)\)$/.exec(t);if(n){let e=(n[1]??``).trim(),t=(n[2]??``).trim();return e.length>0&&t.length>0}return/^[^()\s]+$/.test(t)}function L(e,t){let n=e.trim(),r=t.trim();return r?n===r||n.startsWith(r+` `):!1}const _e=/^cd\s+\S+$/;function R(e,t){let n=t.filter(Boolean);if(n.length===0)return!1;let r=m(e);return r.length===0?!1:r.every(e=>{if(_e.test(e))return!0;let t=e.replace(/^cd\s+\S+\s*&&\s*/,``).trim();return n.some(e=>L(t,e))})}function z(e,t){let n=[];for(let r of t){let t=F(r);t.toolName===e.toolName&&n.push(t)}if(n.length===0)return!1;if(n.some(e=>e.content===void 0))return!0;if(e.toolName===`bash`){let t=typeof e.args?.command==`string`?e.args.command:``;return t?R(t,n.map(e=>e.content)):!1}return!1}function ve(e){let t=e.trim().replace(/^cd\s+\S+\s*&&\s*/,``).trim();if(/[;&|]|`|\$\(|<<|\beval\b/.test(t))return null;let n=t.split(/\s+/).filter(Boolean),r=n[0];if(!r||r.includes(`=`))return null;let i=n[1]&&!n[1].startsWith(`-`)?n[1]:null;return i?`${r} ${i}`:r}const B=e(`@x-otto/hooks:permission`);function V(e,t){return!e.agents||e.agents.length===0?!0:e.agents.includes(`*`)||e.agents.includes(t)}function ye(e,t){return!e.sessions||e.sessions.length===0?!0:e.sessions.includes(`*`)||e.sessions.includes(t)}function be(e,t){return V(e,t.agentName)&&ye(e,t.sessionId)}function xe(e,t){return!(e.tools&&e.tools.length>0&&!e.tools.includes(t.toolName)||e.paths&&e.paths.length>0&&(!t.filePath||!e.paths.some(e=>e.test(t.filePath)))||e.condition&&!e.condition(t))}const Se={effect:`allow`,policyName:`__default__`,ruleName:`__fallthrough__`,timestamp:0,evaluatedPolicies:0};var H=class{policies=[];policySources=new Map;alwaysAllow=new Set;sessionAlwaysAllow=new Map;setAlwaysAllow(e){this.alwaysAllow=new Set(e)}addAlwaysAllow(e){this.alwaysAllow.add(e)}getAlwaysAllow(){return[...this.alwaysAllow]}setSessionAlwaysAllow(e,t){if(e){if(t.length===0){this.sessionAlwaysAllow.delete(e);return}this.sessionAlwaysAllow.set(e,new Set(t))}}addSessionAlwaysAllow(e,t){if(!e||!t)return;let n=this.sessionAlwaysAllow.get(e)??new Set;n.add(t),this.sessionAlwaysAllow.set(e,n)}getSessionAlwaysAllow(e){return[...this.sessionAlwaysAllow.get(e)??[]]}clearSessionAlwaysAllow(e){this.sessionAlwaysAllow.delete(e)}register(e){this.unregister(e.name),this.policies.push(e),this.policies.sort((e,t)=>e.priority-t.priority),B.debug({name:e.name,priority:e.priority,rules:e.rules.length},`Permission policy registered`)}registerWithSource(e,t){this.policySources.set(e.name,t),this.register(e)}getSource(e){return this.policySources.get(e)}registerAll(e){for(let t of e)this.register(t)}unregister(e){let t=this.policies.findIndex(t=>t.name===e);return t>=0?(this.policies.splice(t,1),this.policySources.delete(e),B.debug({name:e},`Permission policy unregistered`),!0):!1}has(e){return this.policies.some(t=>t.name===e)}evaluate(e){let t=0,n=[];for(let r of this.policies)if(r.enabled&&be(r.scope,e)){t++;for(let t of r.rules)xe(t.match,e)&&n.push({effect:t.effect,policyName:r.name,ruleName:t.name,priority:r.priority,reason:t.effect===`deny`?t.denyReason:t.askPrompt,safety:r.safety===!0,fallthrough:t.fallthrough===!0})}let r=n.some(e=>e.policyName===`mode::auto`||e.policyName===`mode::bypass`),i=(e,n)=>{let r=n.reduce((e,t)=>t.priority<e.priority?t:e);return{effect:e,policyName:r.policyName,ruleName:r.ruleName,reason:r.reason,timestamp:Date.now(),evaluatedPolicies:t,safety:r.safety}},a=n=>{if(n.length===0)return null;let a=n.filter(e=>e.effect===`deny`);if(a.length>0)return i(`deny`,a);let o=n.filter(e=>e.effect===`ask`);if(o.length>0){if(r)return{effect:`allow`,policyName:`mode::auto-override`,ruleName:o[0].ruleName,timestamp:Date.now(),evaluatedPolicies:t};let n=z(e,[...this.alwaysAllow,...this.sessionAlwaysAllow.get(e.sessionId)??[]]),a=o.filter(e=>e.safety||!n);return a.length===0?{effect:`allow`,policyName:`user::always-allow`,ruleName:e.toolName,timestamp:Date.now(),evaluatedPolicies:t}:i(`ask`,a)}let s=n.filter(e=>e.effect===`allow`);return s.length>0?i(`allow`,s):null},o=n.filter(e=>!e.fallthrough),s=n.filter(e=>e.fallthrough),c=a(o),l=a(s);return c?.effect===`deny`||c?.effect===`allow`?c:l?.effect===`deny`?l:(c??l)||{...Se,timestamp:Date.now(),evaluatedPolicies:t}}getEffective(e){return this.policies.filter(t=>t.enabled&&V(t.scope,e))}getAll(){return[...this.policies]}getAllWithSource(){return this.policies.map(e=>({...e,source:this.policySources.get(e.name)}))}clear(){this.policies=[],B.debug(`All permission policies cleared`)}};function U(e={}){let t=new H;return P(t,e),t}const W=1024,Ce=/\([^)]*(?:[*+]|\{\d+,\d*\})[^)]*\)(?:[*+]|\{\d+,\d*\})/;function G(e,t){if(e.length>W)return B.warn({rule:t,length:e.length,max:W},`Permission path pattern exceeds max length — rule skipped (ReDoS guard)`),null;if(Ce.test(e))return B.warn({rule:t,pattern:e},`Permission path pattern has nested quantifiers (catastrophic backtracking risk) — rule skipped (ReDoS guard)`),null;try{return new RegExp(e)}catch(n){return B.warn({rule:t,pattern:e,error:n instanceof Error?n.message:String(n)},`Permission path pattern failed to compile — rule skipped`),null}}function we(e){if((e.schemaVersion??0)>1)return B.warn({policy:e.name,schemaVersion:e.schemaVersion,supported:1},`Permission policy requires newer schema version than this build supports — refusing to compile (would silently drop unknown fields and risk a lockout rule). Upgrade the otto build, or remove schemaVersion from the policy config.`),{name:e.name,priority:e.priority??50,enabled:!1,scope:{},rules:[]};let t=[];for(let n of e.rules){let e;if(n.paths&&n.paths.length>0){let t=[],r=!1;for(let e of n.paths){let i=G(e,n.name);if(i===null){r=!0;break}t.push(i)}if(r)continue;e=t}let r=!!(n.commands&&n.commands.length>0),i=n.tools&&n.tools.length>0||e&&e.length>0||r;if((n.effect===`deny`||n.effect===`ask`)&&!i){B.warn({rule:n.name,effect:n.effect},`Skipping deny/ask rule with no match dimension (tools/paths/commands all empty) — would match every tool call and lock the agent. Likely misconfig or dist/config version drift.`);continue}t.push({name:n.name,effect:n.effect,match:{tools:n.tools,paths:e,condition:r?e=>{let t=(n.commands??[]).map(e=>G(e,n.name)).filter(e=>e!==null);return t.length===0?!1:b(String(e.args.command??``),t)||x(e.toolName,e.args,t)}:void 0},denyReason:n.deny_reason,askPrompt:n.ask_prompt})}return{name:e.name,priority:e.priority??50,enabled:e.enabled??!0,scope:{agents:e.scope?.agents,sessions:e.scope?.sessions},rules:t}}var K=class{entries=[];maxEntries;constructor(e=1e3){this.maxEntries=e}record(e,t){this.entries.push({timestamp:t.timestamp,sessionId:e.sessionId,agentName:e.agentName,toolName:e.toolName,filePath:e.filePath,decision:t}),this.entries.length>this.maxEntries&&this.entries.splice(0,this.entries.length-this.maxEntries)}recordAutoDecision(e){let t=e.timestamp??Date.now();this.entries.push({timestamp:t,sessionId:e.sessionId,agentName:e.agentName,toolName:e.toolName,decision:{effect:e.effect,policyName:e.policyName,ruleName:e.toolName,reason:e.reason,timestamp:t,evaluatedPolicies:0}}),this.entries.length>this.maxEntries&&this.entries.splice(0,this.entries.length-this.maxEntries)}getEntries(e){let t=this.entries;return e?.sessionId&&(t=t.filter(t=>t.sessionId===e.sessionId)),e?.effect&&(t=t.filter(t=>t.decision.effect===e.effect)),t===this.entries?this.entries.slice():t}getDenyCount(e){return this.getEntries({sessionId:e,effect:`deny`}).length}getAskCount(e){return this.getEntries({sessionId:e,effect:`ask`}).length}clear(e){e?this.entries=this.entries.filter(t=>t.sessionId!==e):this.entries=[]}get size(){return this.entries.length}};function q(e){return e.safety?`high`:`medium`}function Te(e){let n=[];for(let r of e)if(n.push(r),typeof r==`string`){let e=t(r);e!==r&&n.push(e)}return n}const J=`tool.execute.before`;function Ee(e,t,n,r){let i={timing:J,toolName:n.toolName,args:n.args,agentName:n.agentName,sessionId:n.sessionId,metadata:{}},a=Te(n.paths&&n.paths.length>0?n.paths:[void 0]),o=e.evaluate({...i,filePath:a[0]}),s=a[0];for(let t=1;t<a.length;t++){let n=e.evaluate({...i,filePath:a[t]});(n.effect===`deny`||n.effect===`ask`&&o.effect===`allow`)&&(o=n,s=a[t])}let c={...i,filePath:s};if(t?.record(c,o),o.effect===`deny`){r.cancelled=!0,r.decision=`deny`,r.decisionReason=o.reason??o.ruleName,r.cancelReason=`Permission denied: ${r.decisionReason}`;return}o.effect===`ask`?(r.decision=`ask`,r.decisionReason=o.reason??`Requires confirmation`,r.risk=q(o)):r.decision!==`ask`&&r.decision!==`deny`&&(r.decision=`allow`)}function Y(e,t){return n({name:`permission-guard`,timing:J,priority:5,handle:(n,r)=>Ee(e,t,n,r)})}const X={fileWriteTools:[`write`,`edit`,`edit-diff`]};function De(e){if(e.has(`permission-guard`))return;let t=U({toolSets:X});return e.register(Y(t,new K)),t}function Oe(e){try{return r(e)}catch{return}}function Z(e){let n=new Set;for(let r of e){let e=t(r);n.add(e);let i=Oe(e);i&&i!==e&&n.add(i)}return[...n]}function ke(e,t){return e===t||e.startsWith(t.endsWith(`/`)?t:`${t}/`)}function Q(e,t){let n=Z(t);return Z([e]).some(e=>n.some(t=>ke(e,t)))}function Ae(e,t){let n=e.writePaths??[],r=e.network===!0;for(let e of n)if(Q(e,t.deniedRoots))return{verdict:`deny`,reason:`write to protected path "${e}" is never allowed (escape guard)`};if(t.mode===`bypass`||n.length===0&&!r)return{verdict:`auto-allow`};let i=n.every(e=>Q(e,t.writableRoots)),a=!r||t.networkAllowed;return i&&a?{verdict:`auto-allow`}:t.mode===`strict`||t.mode===`readonly`?{verdict:`deny`,reason:`${i?`network access`:`write outside the sandbox writable roots`} is not permitted in ${t.mode} mode`}:{verdict:`ask`,reason:`${i?`network access`:`write outside the sandbox writable roots`} requires approval (will run with sandbox bypassed for this operation)`}}function $(e,n){return[t(e,`.otto`),t(n,`.otto`)]}function je(e,n,r,i=[]){let a=[t(n),t(r),`/tmp`];if(e!==`strict`&&e!==`readonly`)for(let e of i)a.push(t(e));return[...new Set(a)]}var Me=class{signals=new Map;clock;constructor(e=()=>Date.now()){this.clock=e}record(e,t,n){let r=`${e}:${t}`,i=this.clock(),a=this.signals.get(r);a?(a.count++,a.lastSeen=i,n&&(a.detail=n)):this.signals.set(r,{kind:e,signature:t,count:1,firstSeen:i,lastSeen:i,detail:n})}recurring(e=3){return[...this.signals.values()].filter(t=>t.count>=e).sort((e,t)=>t.count-e.count)}all(){return[...this.signals.values()].sort((e,t)=>t.count-e.count)}clear(){this.signals.clear()}};function Ne(e){let t=e.content;if(!Array.isArray(t))return;let n=t.map(e=>e&&typeof e==`object`&&`text`in e?String(e.text??``):``).join(` `).trim();return n?n.split(`
4
- `)[0].slice(0,120):void 0}function Pe(e){return n({name:`failure-signal-recorder`,timing:`tool.execute.after`,priority:14,handle(t){t.result?.isError&&e.record(`tool-error`,t.toolName,Ne(t.result))}})}function Fe(e){return n({name:`failure-signal-permission-deny`,timing:`tool.execute.before`,priority:90,handle(t,n){n?.decision===`deny`&&e.record(`permission-denied`,t.toolName,n.decisionReason)}})}var Ie=class{proposed=new Set;minCount;clock;constructor(e,t={}){this.signals=e,this.minCount=t.minCount??3,this.clock=t.clock??(()=>Date.now())}propose(){let e=[];for(let t of this.signals.recurring(this.minCount)){let n=`${t.kind}:${t.signature}`;this.proposed.has(n)||(this.proposed.add(n),e.push({id:n,signature:t.signature,kind:`investigate-fix`,directive:Le(t),evidence:{signalKind:t.kind,count:t.count,detail:t.detail},createdAt:this.clock()}))}return e}reset(){this.proposed.clear()}};function Le(e){return e.kind===`tool-error`?`工具「${e.signature}」反复失败(${e.count} 次${e.detail?`,如「${e.detail}」`:``})。调查根因并修复:定位失败路径、补健壮性或修 bug,跑测试验证。`:`反复出现「${e.kind}: ${e.signature}」(${e.count} 次)。调查并消除。`}export{X as BASELINE_PERMISSION_TOOL_SETS,A as CREDENTIAL_READ_POLICY,D as DESTRUCTIVE_COMMAND_POLICY,Ie as Diagnoser,Me as FailureSignalStore,S as PROTECTED_PATH_PATTERNS,K as PermissionAuditLog,H as PermissionPolicyRegistry,Ae as assessSandboxSafety,ve as bashAlwaysAllowPrefix,R as bashCommandCovered,we as compilePolicyFromSetting,je as computeSandboxRoots,M as createDisabledToolsPolicy,ge as createEgressAllowlistPolicy,Pe as createFailureSignalHook,C as createFileGuardPolicy,j as createOttoStateDomainPolicy,Fe as createPermissionDenyHook,Y as createPermissionGuardHook,N as createPermissionModePolicy,U as createPermissionRegistry,ie as createPermissionToolSetsFromRegistry,$ as defaultDeniedRoots,m as extractShellCommands,re as extractWriteTargets,I as isWellFormedAllowEntry,F as parseAllowEntry,De as provisionBaselineSecurity,q as riskFromDecision,z as toolCallCoveredByAllow};
5
- //# sourceMappingURL=index.js.map
1
+ import { homedir } from "node:os";
2
+ import { ABSOLUTE_PROTECTION_CLASSES, CREDENTIAL_PATH_PATTERNS, DEFAULT_OFFERED_SCOPES, PERMISSION_MODE_FIELD_SPEC, PERMISSION_MODE_SETTING_KEY, PERMISSION_OFFERED_SCOPES_KEY, PERMISSION_PROJECT_MODES_FIELD_SPEC, SANDBOX_NETWORK_SETTING_KEY, SANDBOX_SESSION_DATA_SUBPATHS, SLOTS, SettingWriteRejected, TIMINGS, TOOL_NAMES, adoptPermissionMode, adoptPermissionModeOfField, authorityIdOf, canonicalJson, canonicalToolName, classifyProtectedPath, commandContributionKey, credentialCommandPatterns, effectivePermissionMode, effectsOf, hostCoveredBy, isConfigurableSandboxMode, isPermissionMode, isReadonlyEffects, isSandboxMode, isUnrestrictedPermission, isWiderSandboxMode, list, projectPermissionModeOf, settingLayerValues, uniqueFlat, workspaceKeyOf } from "@x-otto/kernel";
3
+ import { createSignal, defineComponent, untrack } from "@x-otto/universal";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ import { registerBundle, t } from "@x-otto/i18n";
6
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
+ import { absoluteTargetsResult, analyzeShell, basenameOf, commandMatchesAny, expandBraces, extractReadTargets, extractShellCommands, extractShellCommandsResult, hasUnmodelledSyntax, redirectsOf, splitTopLevel, strictCommandWords, stripPrefixes, tokenize, tokenizeCommand, unwrapInterpreter } from "@x-otto/shell-lex";
8
+ import { realpathSync } from "node:fs";
9
+
10
+ //#region src/locales/en.ts
11
+ const en = {
12
+ "guard.rule.confirm-write": "Confirm write operation?",
13
+ "guard.rule.session-permission-widen": "Widen the permission mode of this session? (see from/to below)",
14
+ "guard.rule.ask-destructive-bash": "This command may be destructive or runs code that cannot be statically checked. Continue?",
15
+ "guard.rule.ask-destructive-mcp-args": "This MCP tool argument may run a destructive or unverifiable command. Continue?",
16
+ "guard.rule.ask-network": "This accesses a network host that is not on the allowlist. Continue?",
17
+ "guard.rule.ask-global-extension-root": "This writes the global extension install root: publishing a workspace plugin or switching its promoted version changes what every workspace loads. Continue?",
18
+ "guard.rule.ask-unmodelled-command": "This call has effects the permission engine cannot fully model; review it before running.",
19
+ "guard.rule.deny-sandbox-denyread-root": "Reading a sandbox credential-protected path is not allowed",
20
+ "guard.rule.deny-sandbox-protected-subtree": "Writing to a sandbox-protected subtree (agent state / git hooks / git config) is not allowed",
21
+ "guard.rule.session-readonly-cap": "Session permission cap: read-only delegation forbids this operation",
22
+ "guard.rule.deny-protected-write": "Writing to a protected path is not allowed",
23
+ "guard.rule.deny-protected-read": "Reading credential or secret files is not allowed",
24
+ "guard.rule.deny-floor-write": "Writing to the trust store or extension decision sources is not allowed",
25
+ "guard.rule.deny-floor-read": "Reading the trust store or extension decision sources is not allowed",
26
+ "guard.rule.deny-untrusted-writes": "This project is not trusted (read-only): every operation except read-only tools is denied. Trust this project and retry.",
27
+ "guard.trust.bypassUntrustedClampOff": "Project is not trusted, but permission.mode is bypass: the read-only clamp for untrusted projects is not applied.",
28
+ "guard.mode.projectBypassIgnored": "Project-level permission.mode=bypass is ignored: bypass is a user-level setting.",
29
+ "guard.rule.ask-protected-write": "This writes to agent or repository control files. Continue?",
30
+ "guard.rule.ask-protected-read": "This reads a file that may contain secrets or session data. Continue?",
31
+ "guard.rule.deny-credential-command": "Accessing credential/secret paths via command is not allowed",
32
+ "guard.rule.deny-network-strict": "Strict mode: network access is limited to allowlisted hosts",
33
+ "guard.rule.readonly-deny": "Read-only mode: write operations are not allowed",
34
+ "guard.rule.readonly-source-floor": "set by the project floor or because the project is not trusted",
35
+ "guard.rule.readonly-source-default": "set by the default permission mode",
36
+ "guard.rule.readonly-source-session": "chosen for this session",
37
+ "guard.rule.strict-deny": "Strict mode: no matching permission policy",
38
+ "guard.policy.specifierInvalid": "rule specifier could not be parsed",
39
+ "guard.policy.patternDetail": " (pattern: {{pattern}})",
40
+ "guard.policy.dispositionBlocking": "conservatively treated as matching everything",
41
+ "guard.policy.dispositionDropped": "dimension dropped (allow does not match everything)",
42
+ "guard.policy.rejectNote": "{{reason}}{{detail}}; {{disposition}}",
43
+ "guard.rule.deny-write-outside-isolated-root": "This session has its own isolated working root: writes must stay inside it so the parent workspace stays read-only",
44
+ "guard.rule.deny-unprovable-write-in-isolated-root": "This session has its own isolated working root and the call does not declare a provable write set, so it cannot be shown to stay inside that root"
45
+ };
46
+
47
+ //#endregion
48
+ //#region src/locales/zh.ts
49
+ const zh = {
50
+ "guard.rule.confirm-write": "确认写入操作?",
51
+ "guard.rule.session-permission-widen": "放宽当前会话的权限模式?(from/to 见下方)",
52
+ "guard.rule.ask-destructive-bash": "该命令可能具有破坏性,或运行无法静态检查的代码。继续?",
53
+ "guard.rule.ask-destructive-mcp-args": "该 MCP 工具参数可能执行破坏性或无法验证的命令。继续?",
54
+ "guard.rule.ask-network": "该调用访问的网络主机不在允许列表内。继续?",
55
+ "guard.rule.ask-global-extension-root": "将写入全局扩展安装根:发布工作区插件或切换其已发布版本,会改变所有工作区装载的内容。继续?",
56
+ "guard.rule.ask-unmodelled-command": "该调用的影响范围无法被权限引擎完整建模(嵌套解释器、展开截断或第三方工具),请先确认再执行。",
57
+ "guard.rule.deny-sandbox-denyread-root": "不允许读取沙箱凭据保护路径",
58
+ "guard.rule.deny-sandbox-protected-subtree": "不允许写入沙箱保护的子树(agent 状态 / git hooks / git config)",
59
+ "guard.rule.session-readonly-cap": "会话权限上限:只读委派不允许此操作",
60
+ "guard.rule.deny-protected-write": "不允许写入受保护路径",
61
+ "guard.rule.deny-protected-read": "不允许读取凭据或密钥文件",
62
+ "guard.rule.deny-floor-write": "不允许写入信任库或扩展决定源",
63
+ "guard.rule.deny-floor-read": "不允许读取信任库或扩展决定源",
64
+ "guard.rule.deny-untrusted-writes": "当前项目未受信(只读):除只读工具外的一切操作均被拒绝。信任本项目后重试。",
65
+ "guard.trust.bypassUntrustedClampOff": "项目未受信,但 permission.mode 为 bypass:未受信项目的只读夹持不生效。",
66
+ "guard.mode.projectBypassIgnored": "项目层的 permission.mode=bypass 已忽略:bypass 只允许在用户层设置。",
67
+ "guard.rule.ask-protected-write": "这会写入 agent 或仓库的控制文件。继续?",
68
+ "guard.rule.ask-protected-read": "这会读取可能包含密钥或会话数据的文件。继续?",
69
+ "guard.rule.deny-credential-command": "不允许通过命令访问凭据/密钥路径",
70
+ "guard.rule.deny-network-strict": "严格模式:只允许访问允许列表内的网络主机",
71
+ "guard.rule.readonly-deny": "只读模式:不允许写操作",
72
+ "guard.rule.readonly-source-floor": "由项目下限或项目未受信导致",
73
+ "guard.rule.readonly-source-default": "由默认权限模式导致",
74
+ "guard.rule.readonly-source-session": "本会话选择了只读",
75
+ "guard.rule.strict-deny": "严格模式:没有匹配的权限策略",
76
+ "guard.policy.specifierInvalid": "规则 specifier 无法解析",
77
+ "guard.policy.patternDetail": "(pattern: {{pattern}})",
78
+ "guard.policy.dispositionBlocking": "已按匹配一切保守处理",
79
+ "guard.policy.dispositionDropped": "该维度已丢弃(allow 不匹配一切)",
80
+ "guard.policy.rejectNote": "{{reason}}{{detail}};{{disposition}}",
81
+ "guard.rule.deny-write-outside-isolated-root": "本会话有自己的隔离工作根:写入必须留在其中,父工作区对该子会话保持只读",
82
+ "guard.rule.deny-unprovable-write-in-isolated-root": "本会话有自己的隔离工作根,而该调用未声明可证明的写入集,无法证明写入留在根内"
83
+ };
84
+
85
+ //#endregion
86
+ //#region src/libs/i18n.ts
87
+ const MESSAGES = {
88
+ en,
89
+ zh
90
+ };
91
+ registerBundle("guard", MESSAGES);
92
+ const ruleKey = (ruleName) => `guard.rule.${ruleName}`;
93
+ const guardT = (key, values) => t(key, values);
94
+ const askReasonText = (ruleName, fallback) => {
95
+ if (ruleName === void 0) return fallback;
96
+ const key = ruleKey(ruleName);
97
+ const translated = t(key);
98
+ return translated === key ? fallback : translated;
99
+ };
100
+
101
+ //#endregion
102
+ //#region src/rules/mcp.ts
103
+ const MCP_PREFIX = "mcp__";
104
+ function mcpSpecOf(text) {
105
+ if (!text.startsWith("mcp__")) return void 0;
106
+ const body = text.slice(5);
107
+ if (body.endsWith("__*")) {
108
+ const server = body.slice(0, -3);
109
+ return server.length > 0 ? {
110
+ server,
111
+ wildcard: true
112
+ } : void 0;
113
+ }
114
+ const parts = body.split("__");
115
+ const server = parts[0] ?? "";
116
+ if (server.length === 0) return void 0;
117
+ if (parts.length === 1) return { server };
118
+ const tool = parts.slice(1).join("__");
119
+ return tool.length > 0 ? {
120
+ server,
121
+ tool
122
+ } : void 0;
123
+ }
124
+ function mcpTargetOf(toolName) {
125
+ if (!toolName.startsWith("mcp__")) return void 0;
126
+ const body = toolName.slice(5);
127
+ const separator = body.indexOf("__");
128
+ if (separator <= 0) return void 0;
129
+ return {
130
+ server: body.slice(0, separator),
131
+ tool: body.slice(separator + 2)
132
+ };
133
+ }
134
+ function mcpTargetOfContext(toolName, identity) {
135
+ if (identity?.kind === "mcp") return {
136
+ server: identity.server,
137
+ tool: identity.tool
138
+ };
139
+ return mcpTargetOf(toolName);
140
+ }
141
+ function mcpSpecMatches(spec, target) {
142
+ if (spec.server !== target.server) return false;
143
+ if (spec.wildcard === true || spec.tool === void 0) return true;
144
+ return target.tool === spec.tool;
145
+ }
146
+ function mcpToolMatches(toolName, rule, identity) {
147
+ const trimmed = rule.trim();
148
+ if (trimmed === toolName) return true;
149
+ const spec = mcpSpecOf(trimmed);
150
+ if (spec === void 0) return false;
151
+ const target = mcpTargetOfContext(toolName, identity);
152
+ return target === void 0 ? false : mcpSpecMatches(spec, target);
153
+ }
154
+ function mcpToolMatchesAny(toolName, rules, identity) {
155
+ return rules.some((rule) => mcpToolMatches(toolName, rule, identity));
156
+ }
157
+
158
+ //#endregion
159
+ //#region src/engine/command-semantics.ts
160
+ const has = (argv, ...flags) => argv.some((token) => flags.includes(token.split("=")[0]));
161
+ const shortFlag = (argv, letter) => argv.some((token) => /^-[a-zA-Z]+$/.test(token) && token.includes(letter));
162
+ function gitSub(argv) {
163
+ let index = 1;
164
+ while (index < argv.length) {
165
+ const token = argv[index];
166
+ if (token === "-C" || token === "-c" || token === "--git-dir" || token === "--work-tree") {
167
+ index += 2;
168
+ continue;
169
+ }
170
+ if (token.startsWith("-")) {
171
+ index += 1;
172
+ continue;
173
+ }
174
+ break;
175
+ }
176
+ return {
177
+ sub: argv[index],
178
+ rest: argv.slice(index + 1)
179
+ };
180
+ }
181
+ function gitRule(argv) {
182
+ const { sub, rest } = gitSub(argv);
183
+ switch (sub) {
184
+ case "push": {
185
+ const forced = has(rest, "--force", "--force-with-lease", "--mirror", "--delete", "--prune");
186
+ const flagged = shortFlag(rest, "f") || shortFlag(rest, "d");
187
+ const refspec = rest.some((token) => !token.startsWith("-") && (token.startsWith("+") || token.startsWith(":")));
188
+ return forced || flagged || refspec ? "rewrite-remote" : void 0;
189
+ }
190
+ case "reset": return has(rest, "--hard", "--merge", "--keep") ? "irreversible" : void 0;
191
+ case "clean": return !shortFlag(rest, "n") && !has(rest, "--dry-run") ? "irreversible" : void 0;
192
+ case "checkout": return has(rest, "--", ".", "-f", "--force") ? "irreversible" : void 0;
193
+ case "restore": return rest.some((token) => !token.startsWith("-")) && !has(rest, "--staged") ? "irreversible" : void 0;
194
+ case "stash": return rest[0] === "drop" || rest[0] === "clear" ? "irreversible" : void 0;
195
+ case "branch": return shortFlag(rest, "D") || (shortFlag(rest, "d") || has(rest, "--delete")) && (shortFlag(rest, "f") || has(rest, "--force")) ? "irreversible" : void 0;
196
+ case "tag": return has(rest, "-d", "--delete") ? "irreversible" : void 0;
197
+ default: return;
198
+ }
199
+ }
200
+ const PUBLISHERS = {
201
+ npm: "publish",
202
+ pnpm: "publish",
203
+ yarn: "publish",
204
+ bun: "publish",
205
+ cargo: "publish",
206
+ gem: "push",
207
+ poetry: "publish",
208
+ twine: "upload"
209
+ };
210
+ const IRREVERSIBLE_COMMANDS = new Set([
211
+ "rm",
212
+ "rmdir",
213
+ "unlink",
214
+ "shred",
215
+ "wipefs",
216
+ "blkdiscard",
217
+ "mkswap",
218
+ "sgdisk",
219
+ "fdisk",
220
+ "parted"
221
+ ]);
222
+ const PROCESS_COMMANDS = new Set([
223
+ "kill",
224
+ "pkill",
225
+ "killall",
226
+ "shutdown",
227
+ "reboot",
228
+ "halt",
229
+ "poweroff"
230
+ ]);
231
+ const PRIVILEGE_WRAPPERS = new Set([
232
+ "sudo",
233
+ "doas",
234
+ "su",
235
+ "pkexec"
236
+ ]);
237
+ const OWNERSHIP_COMMANDS = new Set([
238
+ "chmod",
239
+ "chown",
240
+ "chgrp"
241
+ ]);
242
+ const RULES = [
243
+ {
244
+ category: "irreversible",
245
+ test: (argv) => IRREVERSIBLE_COMMANDS.has(basenameOf(argv[0] ?? ""))
246
+ },
247
+ {
248
+ category: "irreversible",
249
+ test: (argv) => /^mkfs(\.|$)/.test(basenameOf(argv[0] ?? ""))
250
+ },
251
+ {
252
+ category: "irreversible",
253
+ test: (argv) => basenameOf(argv[0] ?? "") === "dd" && argv.some((token) => token.startsWith("of=") || token === "of")
254
+ },
255
+ {
256
+ category: "irreversible",
257
+ test: (argv) => basenameOf(argv[0] ?? "") === "find" && has(argv, "-delete", "-fls", "-fprint")
258
+ },
259
+ {
260
+ category: "irreversible",
261
+ test: (argv) => basenameOf(argv[0] ?? "") === "git" && gitRule(argv) === "irreversible"
262
+ },
263
+ {
264
+ category: "rewrite-remote",
265
+ test: (argv) => basenameOf(argv[0] ?? "") === "git" && gitRule(argv) === "rewrite-remote"
266
+ },
267
+ {
268
+ category: "privilege",
269
+ test: (argv) => PRIVILEGE_WRAPPERS.has(basenameOf(argv[0] ?? ""))
270
+ },
271
+ {
272
+ category: "privilege",
273
+ test: (argv) => OWNERSHIP_COMMANDS.has(basenameOf(argv[0] ?? "")) && (shortFlag(argv.slice(1), "R") || has(argv, "--recursive") || argv.slice(1).some((token) => token.startsWith("/")))
274
+ },
275
+ {
276
+ category: "publish",
277
+ test: (argv) => {
278
+ const verb = PUBLISHERS[basenameOf(argv[0] ?? "")];
279
+ return verb !== void 0 && argv.slice(1).find((token) => !token.startsWith("-")) === verb;
280
+ }
281
+ },
282
+ {
283
+ category: "process",
284
+ test: (argv) => PROCESS_COMMANDS.has(basenameOf(argv[0] ?? "")) && !has(argv.slice(1), "-l", "-L", "-0")
285
+ }
286
+ ];
287
+ const SQL_DESTRUCTIVE = /\b(?:drop\s+table|drop\s+database|truncate\s+table)\b/i;
288
+ const TRUNCATING_HEADS = new Set([":", "true"]);
289
+ const DEVICE_WRITE = />\s*\/dev\/(?:sd|nvme|disk|hd)/i;
290
+ function truncates(argv) {
291
+ const head = argv[0];
292
+ if (head === void 0) return false;
293
+ const truncating = redirectsOf(argv).find((redirect) => (redirect.operator === ">" || redirect.operator === ">|") && redirect.target !== "/dev/null");
294
+ if (truncating === void 0) return false;
295
+ return truncating.index === 0 || TRUNCATING_HEADS.has(head);
296
+ }
297
+ function classifyInvocation(command) {
298
+ if (command.length === 0) return {
299
+ categories: [],
300
+ truncated: false
301
+ };
302
+ const expansion = extractShellCommandsResult(command);
303
+ const found = /* @__PURE__ */ new Set();
304
+ for (const fragment of expansion.fragments) {
305
+ const argv = tokenize(fragment);
306
+ for (const rule of RULES) if (rule.test(argv)) found.add(rule.category);
307
+ if (truncates(argv)) found.add("truncate");
308
+ if (SQL_DESTRUCTIVE.test(fragment)) found.add("irreversible");
309
+ if (DEVICE_WRITE.test(fragment)) found.add("irreversible");
310
+ }
311
+ return {
312
+ categories: [...found],
313
+ truncated: expansion.truncated
314
+ };
315
+ }
316
+
317
+ //#endregion
318
+ //#region src/engine/command-triggers.ts
319
+ const SUSPICIOUS_PATTERN = /(\beval\s|\btrap\s|(?:curl|wget)\b[^|;&]*\|\s*(?:sudo\s+)?(?:ba|z|d)?sh\b|:\s*\(\s*\)\s*\{[^}]*:\s*\|\s*:|base64\s+(?:-d|--decode)\b[^|]*\|)/i;
320
+ const INTERPRETER_INLINE_EXEC = /\b(?:python[0-9.]*|pythonw|pypy[0-9]*|node|nodejs|deno|bun|perl|ruby|php|osascript|Rscript|pwsh|powershell(?:\.exe)?)\b[^|;&\n]*?(?:\s-{1,2}(?:c|e|r|E|p|eval|Command|EncodedCommand)\b|\s*<<)/i;
321
+ function commandTriggersGuard(command) {
322
+ if (!command) return false;
323
+ const fragments = extractShellCommands(command);
324
+ if (classifyInvocation(command).categories.length > 0) return true;
325
+ return fragments.some((fragment) => hasUnmodelledSyntax(fragment) || SUSPICIOUS_PATTERN.test(fragment) || INTERPRETER_INLINE_EXEC.test(fragment));
326
+ }
327
+ function mcpArgsMatchAny(toolName, argumentList, patterns) {
328
+ if (!toolName.startsWith("mcp__")) return false;
329
+ return Object.values(argumentList).some((value) => typeof value === "string" && commandMatchesAny(value, patterns));
330
+ }
331
+ function mcpAnyArgTriggersGuard(toolName, argumentList) {
332
+ if (!toolName.startsWith("mcp__")) return false;
333
+ return Object.values(argumentList).some((value) => typeof value === "string" && commandTriggersGuard(value));
334
+ }
335
+
336
+ //#endregion
337
+ //#region src/engine/facts.ts
338
+ function trustedEffects(input) {
339
+ if (input.provenance === "first-party" || input.provenance === "bundled" || input.effects.completeness === "incomplete") return input.effects;
340
+ return effectsOf({
341
+ ...input.effects,
342
+ completeness: "incomplete"
343
+ });
344
+ }
345
+ function contextOf(input, identity, cap, mode) {
346
+ const effects = trustedEffects(input);
347
+ return {
348
+ toolName: input.call.name,
349
+ arguments: input.call.arguments,
350
+ effects,
351
+ provenance: input.provenance,
352
+ readonly: isReadonlyEffects(effects),
353
+ sandboxEscalatable: input.sandboxEscalatable === true,
354
+ sessionId: input.ctx.sessionId,
355
+ cwd: input.ctx.cwd,
356
+ ...input.ctx.isolatedRoot !== void 0 ? { isolatedRoot: input.ctx.isolatedRoot } : {},
357
+ ...identity !== void 0 ? { identity } : {},
358
+ ...cap !== void 0 ? { cap } : {},
359
+ ...mode !== void 0 ? { mode } : {},
360
+ ...input.origin !== void 0 ? { origin: input.origin } : {}
361
+ };
362
+ }
363
+ function factsOf(input, identity, cap, mode) {
364
+ return contextOf(input, identity, cap, mode);
365
+ }
366
+ function pathsOf(ctx, access) {
367
+ return (access === "read" ? ctx.effects.reads : ctx.effects.writes).filter((path) => isAbsolute(path));
368
+ }
369
+ function commandOf(context) {
370
+ return context.effects.exec?.command;
371
+ }
372
+ function commandTextOf(context) {
373
+ return commandOf(context) ?? "";
374
+ }
375
+
376
+ //#endregion
377
+ //#region src/rules/specifier.ts
378
+ const LEGACY_EXACT_SEPARATOR = "!=";
379
+ const DOMAIN_PREFIX = "domain:";
380
+ const SUBTREE_SUFFIX = "/**";
381
+ const PREFIX_TOKENS = 2;
382
+ const ACTION_PREFIX = "action:";
383
+ function qualifierSpec(tool, qualifier) {
384
+ if (qualifier.length === 0) return void 0;
385
+ if (qualifier.startsWith(ACTION_PREFIX)) {
386
+ const action = qualifier.slice(7).trim();
387
+ return action.length === 0 ? void 0 : {
388
+ kind: "action",
389
+ tool,
390
+ action
391
+ };
392
+ }
393
+ if (qualifier.startsWith("=")) {
394
+ const command = qualifier.slice(1);
395
+ return command.length === 0 ? void 0 : {
396
+ kind: "exact",
397
+ tool,
398
+ command
399
+ };
400
+ }
401
+ if (qualifier.startsWith(DOMAIN_PREFIX)) {
402
+ const host = qualifier.slice(7).trim().toLowerCase();
403
+ return host.length === 0 ? void 0 : {
404
+ kind: "domain",
405
+ tool,
406
+ host
407
+ };
408
+ }
409
+ if (tool === TOOL_NAMES.bash) {
410
+ const prefix = tokenize(qualifier);
411
+ return prefix.length === 0 ? void 0 : {
412
+ kind: "prefix",
413
+ tool,
414
+ prefix
415
+ };
416
+ }
417
+ if (isAbsolute(qualifier) || qualifier.startsWith("~") || qualifier.startsWith(".") || qualifier.includes("/")) return {
418
+ kind: "path",
419
+ tool,
420
+ glob: qualifier
421
+ };
422
+ return {
423
+ kind: "domain",
424
+ tool,
425
+ host: qualifier.trim().toLowerCase()
426
+ };
427
+ }
428
+ function parseRule(raw) {
429
+ const separator = raw.indexOf(LEGACY_EXACT_SEPARATOR);
430
+ if (separator >= 0 && !raw.slice(0, separator).includes("(")) {
431
+ const tool = raw.slice(0, separator).trim();
432
+ const command = raw.slice(separator + 2);
433
+ return tool.length === 0 || command.length === 0 ? void 0 : {
434
+ kind: "exact",
435
+ tool,
436
+ command
437
+ };
438
+ }
439
+ const text = raw.trim();
440
+ if (text.length === 0) return void 0;
441
+ if (text === "*") return void 0;
442
+ const match = /^([^()\s]+)\((.*)\)$/s.exec(text);
443
+ if (match !== null) return qualifierSpec(match[1], match[2].trim());
444
+ if (/[()\s]/.test(text)) return void 0;
445
+ const mcp = mcpSpecOf(text);
446
+ if (mcp !== void 0) return {
447
+ kind: "mcp",
448
+ server: mcp.server,
449
+ ...mcp.tool !== void 0 ? { tool: mcp.tool } : {}
450
+ };
451
+ return {
452
+ kind: "tool",
453
+ tool: text
454
+ };
455
+ }
456
+ function ruleOfGrant(grant) {
457
+ if (grant.kind !== "tool") return void 0;
458
+ if (grant.grantKey === void 0) return {
459
+ kind: "tool",
460
+ tool: grant.toolName
461
+ };
462
+ if (grant.exact === true) return {
463
+ kind: "exact",
464
+ tool: grant.toolName,
465
+ command: grant.grantKey
466
+ };
467
+ return qualifierSpec(grant.toolName, grant.grantKey);
468
+ }
469
+ function qualifierOf(spec) {
470
+ switch (spec.kind) {
471
+ case "tool":
472
+ case "mcp": return;
473
+ case "action": return `${ACTION_PREFIX}${spec.action}`;
474
+ case "prefix": return spec.prefix.join(" ");
475
+ case "exact": return `=${spec.command}`;
476
+ case "path": return spec.glob;
477
+ case "domain": return `${DOMAIN_PREFIX}${spec.host}`;
478
+ }
479
+ }
480
+ function formatRule(spec) {
481
+ if (spec.kind === "mcp") return spec.tool === void 0 ? `${MCP_PREFIX}${spec.server}__*` : `${MCP_PREFIX}${spec.server}__${spec.tool}`;
482
+ const qualifier = qualifierOf(spec);
483
+ return qualifier === void 0 ? spec.tool : `${spec.tool}(${qualifier})`;
484
+ }
485
+ function grantOfRule(spec) {
486
+ if (spec.kind === "mcp") return {
487
+ kind: "tool",
488
+ toolName: formatRule(spec)
489
+ };
490
+ if (spec.kind === "tool") return {
491
+ kind: "tool",
492
+ toolName: spec.tool
493
+ };
494
+ if (spec.kind === "action") return {
495
+ kind: "tool",
496
+ toolName: spec.tool,
497
+ grantKey: `${ACTION_PREFIX}${spec.action}`
498
+ };
499
+ if (spec.kind === "exact") return {
500
+ kind: "tool",
501
+ toolName: spec.tool,
502
+ grantKey: spec.command,
503
+ exact: true
504
+ };
505
+ return {
506
+ kind: "tool",
507
+ toolName: spec.tool,
508
+ grantKey: qualifierOf(spec)
509
+ };
510
+ }
511
+ function isLeaf(fragment) {
512
+ return splitTopLevel(fragment).length === 1 && stripPrefixes(fragment) === fragment && unwrapInterpreter(fragment) === null && !/^\s*[({]/.test(fragment);
513
+ }
514
+ function leafCommands(command) {
515
+ return extractShellCommands(command).filter(isLeaf).map(leafOf).filter((leaf) => leaf.argv.length > 0).filter((leaf) => !(leaf.argv[0] === "cd" && leaf.argv.length <= 2));
516
+ }
517
+ function leafOf(fragment) {
518
+ const analysis = analyzeShell(fragment);
519
+ if (analysis.status === "ok" && analysis.commands.length === 1) {
520
+ const command = analysis.commands[0];
521
+ if (command !== void 0) return {
522
+ argv: command.words.flatMap((word) => expandBraces(word)),
523
+ redirects: analysis.redirects
524
+ };
525
+ }
526
+ const argv = tokenize(fragment);
527
+ return {
528
+ argv,
529
+ redirects: redirectsOf(argv)
530
+ };
531
+ }
532
+ const FD_DUPLICATION_OPERATORS = new Set([">&", "<&"]);
533
+ function redirectsToFile(leaf) {
534
+ return leaf.redirects.some((redirect) => !FD_DUPLICATION_OPERATORS.has(redirect.operator) && redirect.target !== "/dev/null" && !redirect.target.startsWith("&"));
535
+ }
536
+ function startsWith(argv, prefix) {
537
+ return prefix.length <= argv.length && prefix.every((token, index) => argv[index] === token);
538
+ }
539
+ function hostCovered(host, entry) {
540
+ const normalized = entry.replace(/^\*?\./, "");
541
+ return normalized.length > 0 && (host === normalized || host.endsWith(`.${normalized}`));
542
+ }
543
+ function absoluteGlob(glob, ctx) {
544
+ const base = ctx.cwd ?? "/";
545
+ return isAbsolute(glob) ? resolve(glob) : resolve(base, glob);
546
+ }
547
+ function pathCovered(raw, glob, ctx) {
548
+ const path = resolve(raw);
549
+ if (glob.endsWith(SUBTREE_SUFFIX)) {
550
+ const root = absoluteGlob(glob.slice(0, -3) || "/", ctx);
551
+ return path === root || path.startsWith(root.endsWith(sep) ? root : root + sep);
552
+ }
553
+ return path === absoluteGlob(glob, ctx);
554
+ }
555
+ function mcpTargetOfCall(ctx) {
556
+ return mcpTargetOfContext(ctx.toolName, ctx.identity);
557
+ }
558
+ function hostsOf(ctx) {
559
+ return ctx.effects.network.map((target) => target.host.toLowerCase());
560
+ }
561
+ function rulesCover(rules, ctx) {
562
+ const target = mcpTargetOfCall(ctx);
563
+ const relevant = rules.filter((rule) => rule.kind === "mcp" ? target !== void 0 && rule.server === target.server && (rule.tool === void 0 || rule.tool === target.tool) : canonicalToolName(rule.tool) === canonicalToolName(ctx.toolName));
564
+ if (relevant.length === 0) return false;
565
+ if (relevant.some((rule) => rule.kind === "tool" || rule.kind === "mcp")) return true;
566
+ const action = actionOfCall(ctx);
567
+ if (action !== void 0 && relevant.some((rule) => rule.kind === "action" && rule.action === action)) return true;
568
+ if (relevant.every((rule) => rule.kind === "action")) return false;
569
+ const command = commandOf(ctx);
570
+ if (command !== void 0 && command.length > 0) {
571
+ if (relevant.some((rule) => rule.kind === "exact" && rule.command === command)) return true;
572
+ const prefixes = relevant.flatMap((rule) => rule.kind === "prefix" ? [rule.prefix] : []);
573
+ if (prefixes.length > 0 && strictCommandWords(command) !== void 0) {
574
+ const leaves = leafCommands(command);
575
+ if (leaves.length > 0 && leaves.every((leaf) => !redirectsToFile(leaf) && prefixes.some((prefix) => startsWith(leaf.argv, prefix)))) return true;
576
+ }
577
+ }
578
+ const hosts = hostsOf(ctx);
579
+ const domains = relevant.flatMap((rule) => rule.kind === "domain" ? [rule.host] : []);
580
+ const globs = relevant.flatMap((rule) => rule.kind === "path" ? [rule.glob] : []);
581
+ const writes = ctx.effects.writes;
582
+ const domainOk = hosts.every((host) => domains.some((entry) => hostCovered(host, entry)));
583
+ const pathOk = writes.every((path) => globs.some((glob) => pathCovered(path, glob, ctx)));
584
+ return (hosts.length > 0 || writes.length > 0) && domainOk && pathOk && (hosts.length === 0 || domains.length > 0);
585
+ }
586
+ function exactRulesCover(rules, ctx) {
587
+ const action = actionOfCall(ctx);
588
+ if (action !== void 0 && rules.some((rule) => rule.kind === "action" && canonicalToolName(rule.tool) === canonicalToolName(ctx.toolName) && rule.action === action)) return true;
589
+ const command = commandOf(ctx);
590
+ if (command !== void 0 && command.length > 0) {
591
+ if (rules.some((rule) => rule.kind === "exact" && canonicalToolName(rule.tool) === canonicalToolName(ctx.toolName) && rule.command === command)) return true;
592
+ }
593
+ const hosts = hostsOf(ctx);
594
+ if (hosts.length > 0) {
595
+ const domains = rules.filter((rule) => rule.kind === "domain" && canonicalToolName(rule.tool) === canonicalToolName(ctx.toolName));
596
+ if (domains.length > 0 && hosts.every((host) => domains.some((rule) => hostCovered(host, rule.host)))) return true;
597
+ }
598
+ return false;
599
+ }
600
+ function bashGrant(ctx, command, exact) {
601
+ const exactRule = {
602
+ kind: "exact",
603
+ tool: ctx.toolName,
604
+ command
605
+ };
606
+ if (exact || commandTriggersGuard(command)) return exactRule;
607
+ if (strictCommandWords(command) === void 0) return exactRule;
608
+ const leaves = leafCommands(command);
609
+ const first = leaves[0];
610
+ if (first === void 0 || leaves.some(redirectsToFile)) return exactRule;
611
+ if (extractShellCommands(command).some((fragment) => /^\s*cd\s/.test(fragment))) return exactRule;
612
+ const prefix = first.argv.slice(0, PREFIX_TOKENS);
613
+ return leaves.every((leaf) => startsWith(leaf.argv, prefix)) ? {
614
+ kind: "prefix",
615
+ tool: ctx.toolName,
616
+ prefix
617
+ } : exactRule;
618
+ }
619
+ function commonDirectory(paths) {
620
+ const split = paths.map((path) => dirname(path).split(sep));
621
+ const first = split[0];
622
+ let length = first.length;
623
+ for (const parts of split.slice(1)) {
624
+ let index = 0;
625
+ while (index < length && parts[index] === first[index]) index += 1;
626
+ length = index;
627
+ }
628
+ const joined = first.slice(0, length).join(sep);
629
+ return joined.length === 0 ? sep : joined;
630
+ }
631
+ function actionOfCall(ctx) {
632
+ const value = ctx.arguments["action"];
633
+ return typeof value === "string" && value.length > 0 ? value : void 0;
634
+ }
635
+ function grantRuleFor(ctx, options = {}) {
636
+ const command = commandOf(ctx);
637
+ if (ctx.toolName === TOOL_NAMES.bash) return command === void 0 || command.length === 0 ? void 0 : bashGrant(ctx, command, options.exact === true);
638
+ if (options.exact === true) return void 0;
639
+ if (mcpTargetOfCall(ctx) !== void 0) return {
640
+ kind: "tool",
641
+ tool: ctx.toolName
642
+ };
643
+ const action = actionOfCall(ctx);
644
+ if (action !== void 0 && ctx.effects.writes.length === 0 && hostsOf(ctx).length === 0) return {
645
+ kind: "action",
646
+ tool: ctx.toolName,
647
+ action
648
+ };
649
+ const writes = ctx.effects.writes;
650
+ const hosts = hostsOf(ctx);
651
+ if (writes.length > 0 && hosts.length === 0) {
652
+ const directory = commonDirectory(writes);
653
+ if (directory !== sep && directory !== options.home) return {
654
+ kind: "path",
655
+ tool: ctx.toolName,
656
+ glob: `${directory}${SUBTREE_SUFFIX}`
657
+ };
658
+ return writes.length === 1 ? {
659
+ kind: "path",
660
+ tool: ctx.toolName,
661
+ glob: writes[0]
662
+ } : void 0;
663
+ }
664
+ if (hosts.length > 0) return hosts.length === 1 && writes.length === 0 ? {
665
+ kind: "domain",
666
+ tool: ctx.toolName,
667
+ host: hosts[0]
668
+ } : void 0;
669
+ return {
670
+ kind: "tool",
671
+ tool: ctx.toolName
672
+ };
673
+ }
674
+ const ANY_TOOL = "*";
675
+ const READ_TOOL = TOOL_NAMES.read;
676
+ function toolApplies(rule, ctx) {
677
+ if (rule.kind === "mcp") {
678
+ const target = mcpTargetOfCall(ctx);
679
+ if (target === void 0) return false;
680
+ if (target.server !== rule.server) return false;
681
+ return rule.tool === void 0 || rule.tool === target.tool;
682
+ }
683
+ if (rule.tool === ANY_TOOL) return rule.kind === "path" || rule.kind === "domain";
684
+ if (rule.kind === "path" && rule.tool === READ_TOOL) return true;
685
+ return canonicalToolName(rule.tool) === canonicalToolName(ctx.toolName);
686
+ }
687
+ function ruleMatches(rule, ctx) {
688
+ if (!toolApplies(rule, ctx)) return false;
689
+ switch (rule.kind) {
690
+ case "tool":
691
+ case "mcp": return true;
692
+ case "exact": return commandOf(ctx) === rule.command;
693
+ case "prefix": {
694
+ const command = commandOf(ctx);
695
+ if (command === void 0 || command.length === 0) return false;
696
+ const leaves = leafCommands(command);
697
+ return leaves.length > 0 && leaves.every((leaf) => !redirectsToFile(leaf) && startsWith(leaf.argv, rule.prefix));
698
+ }
699
+ case "path": return (rule.tool === READ_TOOL ? ctx.effects.reads : rule.tool === ANY_TOOL ? [...ctx.effects.reads, ...ctx.effects.writes] : ctx.effects.writes).some((path) => pathCovered(path, rule.glob, ctx));
700
+ case "domain": return hostsOf(ctx).some((host) => hostCovered(host, rule.host));
701
+ case "action": return actionOfCall(ctx) === rule.action;
702
+ }
703
+ }
704
+
705
+ //#endregion
706
+ //#region src/engine/always-allow.ts
707
+ function sameGrant(a, b) {
708
+ if (a.kind !== b.kind) return false;
709
+ if (a.kind === "tool" && b.kind === "tool") return a.toolName === b.toolName && a.grantKey === b.grantKey && a.exact === b.exact;
710
+ if (a.kind === "escalation" && b.kind === "escalation") return a.toolName === b.toolName && a.command === b.command && a.canonicalCwd === b.canonicalCwd && a.approvedMode === b.approvedMode;
711
+ return false;
712
+ }
713
+ function encodeGrants(entries) {
714
+ return {
715
+ v: 1,
716
+ grants: entries.map((entry) => ({ ...entry }))
717
+ };
718
+ }
719
+ function isGrantEnvelope(raw) {
720
+ return typeof raw === "object" && raw !== null && raw.v === 1 && Array.isArray(raw.grants);
721
+ }
722
+ function decodeGrant(raw) {
723
+ if (typeof raw !== "object" || raw === null) return void 0;
724
+ const o = raw;
725
+ if (o.kind === "tool") {
726
+ if (typeof o.toolName !== "string" || o.toolName.length === 0) return void 0;
727
+ if (o.grantKey !== void 0 && typeof o.grantKey !== "string") return void 0;
728
+ if (o.exact !== void 0 && typeof o.exact !== "boolean") return void 0;
729
+ if (o.exact === true && typeof o.grantKey !== "string") return void 0;
730
+ if (o.grantKey === void 0) return {
731
+ kind: "tool",
732
+ toolName: o.toolName
733
+ };
734
+ if (o.exact === true) return {
735
+ kind: "tool",
736
+ toolName: o.toolName,
737
+ grantKey: o.grantKey,
738
+ exact: true
739
+ };
740
+ return {
741
+ kind: "tool",
742
+ toolName: o.toolName,
743
+ grantKey: o.grantKey
744
+ };
745
+ }
746
+ if (o.kind === "escalation") {
747
+ if (typeof o.toolName !== "string" || o.toolName.length === 0) return void 0;
748
+ if (typeof o.command !== "string" || o.command.length === 0) return void 0;
749
+ if (typeof o.canonicalCwd !== "string" || o.canonicalCwd.length === 0) return void 0;
750
+ if (!isSandboxMode(o.approvedMode) || !isSandboxMode(o.standingMode)) return void 0;
751
+ if (typeof o.authorizationRevision !== "number" || !Number.isFinite(o.authorizationRevision)) return void 0;
752
+ if (typeof o.authorizationKey !== "string" || o.authorizationKey.length === 0) return void 0;
753
+ return {
754
+ kind: "escalation",
755
+ toolName: o.toolName,
756
+ command: o.command,
757
+ canonicalCwd: o.canonicalCwd,
758
+ approvedMode: o.approvedMode,
759
+ standingMode: o.standingMode,
760
+ authorizationRevision: o.authorizationRevision,
761
+ authorizationKey: o.authorizationKey
762
+ };
763
+ }
764
+ }
765
+ function decodeGrants(raw) {
766
+ if (!isGrantEnvelope(raw)) return [];
767
+ const out = [];
768
+ for (const item of raw.grants) {
769
+ const grant = decodeGrant(item);
770
+ if (grant !== void 0) out.push(grant);
771
+ }
772
+ return out;
773
+ }
774
+ function rulesOf(entries) {
775
+ const rules = [];
776
+ for (const entry of entries) {
777
+ const rule = typeof entry === "string" ? parseRule(entry) : ruleOfGrant(entry);
778
+ if (rule !== void 0) rules.push(rule);
779
+ }
780
+ return rules;
781
+ }
782
+ function toolCallCoveredByExactGrant(context, entries) {
783
+ return exactRulesCover(rulesOf(entries), context);
784
+ }
785
+ function toolCallCoveredByAllow(context, entries) {
786
+ return rulesCover(rulesOf(entries), context);
787
+ }
788
+
789
+ //#endregion
790
+ //#region src/engine/evaluate.ts
791
+ const SESSION_CAP_POLICY_NAME = "builtin::session-cap";
792
+ const MODE_POLICY_NAME = "builtin::mode";
793
+ const SESSION_READONLY_CAP_RULE = "session-readonly-cap";
794
+ function matchesScope(scope, ctx) {
795
+ if (!scope.sessions || scope.sessions.length === 0) return true;
796
+ return scope.sessions.includes("*") || scope.sessions.includes(ctx.sessionId);
797
+ }
798
+ function matchesRule(match, ctx) {
799
+ if (match.tools && match.tools.length > 0) {
800
+ if (!mcpToolMatchesAny(ctx.toolName, match.tools, ctx.identity)) return false;
801
+ }
802
+ if (match.condition) {
803
+ if (!match.condition(ctx)) return false;
804
+ }
805
+ return true;
806
+ }
807
+ function applyBaseline(context, grants, baseline) {
808
+ const mode = context.mode ?? baseline;
809
+ if (mode === "auto") return {
810
+ effect: "allow",
811
+ policyName: "__baseline__",
812
+ ruleName: mode,
813
+ by: "baseline"
814
+ };
815
+ if (mode === "confirm") {
816
+ if (context.readonly) return {
817
+ effect: "allow",
818
+ policyName: "__baseline__",
819
+ ruleName: "confirm-read",
820
+ by: "baseline"
821
+ };
822
+ if (toolCallCoveredByAllow(context, [...grants.alwaysAllow(), ...grants.session(context.sessionId)])) return {
823
+ effect: "allow",
824
+ policyName: "__grant__",
825
+ ruleName: "confirm-write",
826
+ by: "grant"
827
+ };
828
+ return {
829
+ effect: "ask",
830
+ policyName: "__baseline__",
831
+ ruleName: "confirm-write",
832
+ reason: askReasonText("confirm-write", "Confirm write operation?"),
833
+ by: "baseline"
834
+ };
835
+ }
836
+ if (mode === "readonly") {
837
+ if (context.readonly) return {
838
+ effect: "allow",
839
+ policyName: "__baseline__",
840
+ ruleName: "readonly-read",
841
+ by: "baseline"
842
+ };
843
+ return {
844
+ effect: "deny",
845
+ policyName: "__baseline__",
846
+ ruleName: "readonly-deny",
847
+ reason: askReasonText("readonly-deny", "Read-only mode: write operations are not allowed"),
848
+ by: "baseline"
849
+ };
850
+ }
851
+ return {
852
+ effect: "deny",
853
+ policyName: "__baseline__",
854
+ ruleName: "strict-deny",
855
+ reason: askReasonText("strict-deny", "Strict mode: no matching permission policy"),
856
+ by: "baseline"
857
+ };
858
+ }
859
+ function evaluate(policies, context, grants, baseline) {
860
+ if (context.cap?.readonly === true && !context.readonly) return {
861
+ effect: "deny",
862
+ policyName: SESSION_CAP_POLICY_NAME,
863
+ ruleName: SESSION_READONLY_CAP_RULE,
864
+ reason: askReasonText(SESSION_READONLY_CAP_RULE, "Session permission cap: read-only delegation forbids this operation"),
865
+ safety: true,
866
+ by: "policy"
867
+ };
868
+ const finalize = (decision) => decision.effect === "ask" && context.origin === "system" ? {
869
+ ...decision,
870
+ effect: "allow",
871
+ by: "system"
872
+ } : decision;
873
+ const mode = context.mode ?? baseline;
874
+ if (isUnrestrictedPermission(mode)) return {
875
+ effect: "allow",
876
+ policyName: "__baseline__",
877
+ ruleName: "bypass",
878
+ by: "baseline",
879
+ unrestricted: true
880
+ };
881
+ const matches = [];
882
+ const facts = context;
883
+ if (mode === "readonly" && !context.readonly) matches.push({
884
+ effect: "deny",
885
+ policyName: MODE_POLICY_NAME,
886
+ ruleName: "readonly-deny",
887
+ priority: 0,
888
+ reason: "Read-only mode: write operations are not allowed",
889
+ safety: true
890
+ });
891
+ for (const policy of policies) {
892
+ if (!policy.enabled) continue;
893
+ if (!matchesScope(policy.scope, facts)) continue;
894
+ for (const rule of policy.rules) if (matchesRule(rule.match, facts)) matches.push({
895
+ effect: rule.effect,
896
+ policyName: policy.name,
897
+ ruleName: rule.name,
898
+ priority: policy.priority,
899
+ reason: rule.effect === "deny" ? rule.denyReason : rule.askPrompt,
900
+ safety: rule.safety ?? policy.safety ?? false
901
+ });
902
+ }
903
+ const pick = (effect, pool) => {
904
+ const top = pool.reduce((a, b) => b.priority < a.priority ? b : a);
905
+ return {
906
+ effect,
907
+ policyName: top.policyName,
908
+ ruleName: top.ruleName,
909
+ reason: top.reason === void 0 ? void 0 : askReasonText(top.ruleName, top.reason),
910
+ safety: top.safety !== false
911
+ };
912
+ };
913
+ const denies = matches.filter((m) => m.effect === "deny");
914
+ if (denies.length > 0) return finalize({
915
+ ...pick("deny", denies),
916
+ by: "policy"
917
+ });
918
+ const asks = matches.filter((m) => m.effect === "ask");
919
+ if (asks.length > 0) {
920
+ const entries = [...grants.alwaysAllow(), ...grants.session(context.sessionId)];
921
+ const toolAllowed = toolCallCoveredByAllow(context, entries);
922
+ const exactCovered = toolCallCoveredByExactGrant(context, entries);
923
+ const blocking = asks.filter((m) => m.safety && !exactCovered || !toolAllowed);
924
+ if (blocking.length === 0) return finalize({
925
+ effect: "allow",
926
+ policyName: "__grant__",
927
+ ruleName: asks[0].ruleName,
928
+ by: "grant"
929
+ });
930
+ return finalize({
931
+ ...pick("ask", blocking),
932
+ by: "policy"
933
+ });
934
+ }
935
+ const allows = matches.filter((m) => m.effect === "allow");
936
+ if (allows.length > 0) return finalize({
937
+ ...pick("allow", allows),
938
+ by: "policy"
939
+ });
940
+ return finalize(applyBaseline(context, grants, baseline));
941
+ }
942
+
943
+ //#endregion
944
+ //#region src/engine/policy-set.ts
945
+ function samePolicies(a, b) {
946
+ return a.length === b.length && a.every((policy, index) => policy === b[index]);
947
+ }
948
+ function createPolicySet() {
949
+ const holdings = /* @__PURE__ */ new Set();
950
+ const listeners = /* @__PURE__ */ new Set();
951
+ let revisionCounter = 0;
952
+ let nextOrder = 0;
953
+ let cached;
954
+ function changed() {
955
+ revisionCounter += 1;
956
+ cached = void 0;
957
+ for (const listener of listeners) listener();
958
+ }
959
+ function snapshot() {
960
+ if (cached !== void 0) return cached;
961
+ const ranked = [...holdings].flatMap((holding) => holding.policies.map((policy, index) => ({
962
+ policy,
963
+ order: holding.order,
964
+ index
965
+ })));
966
+ ranked.sort((a, b) => a.policy.priority - b.policy.priority || a.order - b.order || a.index - b.index);
967
+ cached = Object.freeze(ranked.map((entry) => entry.policy));
968
+ return cached;
969
+ }
970
+ return {
971
+ contribute(owner, policies) {
972
+ const holding = {
973
+ owner,
974
+ order: nextOrder++,
975
+ policies: [...policies]
976
+ };
977
+ holdings.add(holding);
978
+ changed();
979
+ let active = true;
980
+ return {
981
+ replace(next) {
982
+ if (!active) throw new Error(`policy lease "${owner}" was disposed`);
983
+ if (samePolicies(holding.policies, next)) return;
984
+ holding.policies = [...next];
985
+ changed();
986
+ },
987
+ dispose() {
988
+ if (!active) return;
989
+ active = false;
990
+ holdings.delete(holding);
991
+ changed();
992
+ }
993
+ };
994
+ },
995
+ snapshot,
996
+ revision: () => revisionCounter,
997
+ onChange(listener) {
998
+ listeners.add(listener);
999
+ return () => {
1000
+ listeners.delete(listener);
1001
+ };
1002
+ }
1003
+ };
1004
+ }
1005
+
1006
+ //#endregion
1007
+ //#region src/engine/permission-engine.ts
1008
+ const readonlySourceFallback = {
1009
+ floor: "set by the project floor or because the project is not trusted",
1010
+ default: "set by the default permission mode",
1011
+ session: "chosen for this session"
1012
+ };
1013
+ function sameEntries(a, b) {
1014
+ return a.size === b.size && [...a].every((entry) => b.has(entry));
1015
+ }
1016
+ function covers(superset, subset) {
1017
+ return [...subset].every((entry) => superset.has(entry));
1018
+ }
1019
+ function createPermissionEngine(sessionAllow = () => []) {
1020
+ const generation = randomUUID();
1021
+ const policies = createPolicySet();
1022
+ const listeners = /* @__PURE__ */ new Set();
1023
+ let baseline = "auto";
1024
+ let floor;
1025
+ let alwaysAllow = /* @__PURE__ */ new Set();
1026
+ let tightenings = 0;
1027
+ const notify = () => {
1028
+ for (const listener of listeners) listener();
1029
+ };
1030
+ policies.onChange(notify);
1031
+ const grants = {
1032
+ alwaysAllow: () => [...alwaysAllow],
1033
+ session: sessionAllow
1034
+ };
1035
+ return {
1036
+ policies,
1037
+ baseline: () => baseline,
1038
+ floor: () => floor,
1039
+ setBaseline(mode) {
1040
+ if (baseline === mode) return;
1041
+ baseline = mode;
1042
+ tightenings += 1;
1043
+ notify();
1044
+ },
1045
+ setFloor(mode) {
1046
+ if (floor === mode) return;
1047
+ floor = mode;
1048
+ tightenings += 1;
1049
+ notify();
1050
+ },
1051
+ modeFor: (chosen) => effectivePermissionMode({
1052
+ adopted: baseline,
1053
+ floor,
1054
+ chosen
1055
+ }),
1056
+ sessionMode: (session) => effectivePermissionMode({
1057
+ adopted: baseline,
1058
+ floor,
1059
+ chosen: session?.permissionMode,
1060
+ capReadonly: session?.permissionCap?.readonly === true
1061
+ }),
1062
+ setAlwaysAllow(entries) {
1063
+ const next = new Set(entries);
1064
+ if (sameEntries(alwaysAllow, next)) return;
1065
+ const previous = alwaysAllow;
1066
+ alwaysAllow = next;
1067
+ if (!covers(next, previous)) {
1068
+ tightenings += 1;
1069
+ notify();
1070
+ }
1071
+ },
1072
+ evaluate: (context) => {
1073
+ const decision = evaluate(policies.snapshot(), context, grants, baseline);
1074
+ if (decision.effect !== "deny" || decision.ruleName !== "readonly-deny") return decision;
1075
+ const effective = context.mode ?? baseline;
1076
+ const source = floor === "readonly" && effective === "readonly" ? baseline === "readonly" && context.mode === void 0 ? "default" : "floor" : context.mode === void 0 || context.mode === baseline ? "default" : "session";
1077
+ return {
1078
+ ...decision,
1079
+ reason: `${decision.reason ?? ""} (${askReasonText(`readonly-source-${source}`, readonlySourceFallback[source])})`
1080
+ };
1081
+ },
1082
+ revision: () => policies.revision() + tightenings,
1083
+ conditionFingerprint: (sessionId, sessionGrants) => canonicalJson({
1084
+ generation,
1085
+ revision: policies.revision() + tightenings,
1086
+ baseline,
1087
+ floor,
1088
+ alwaysAllow: [...alwaysAllow].sort(),
1089
+ sessionGrants: [...new Set([...sessionAllow(sessionId), ...sessionGrants ?? []].map(canonicalJson))].sort()
1090
+ }),
1091
+ onChange(listener) {
1092
+ listeners.add(listener);
1093
+ return () => {
1094
+ listeners.delete(listener);
1095
+ };
1096
+ }
1097
+ };
1098
+ }
1099
+
1100
+ //#endregion
1101
+ //#region src/permission-conditions.ts
1102
+ function createPermissionConditionReader(deps) {
1103
+ return { async query(input) {
1104
+ const manager = deps.sessions();
1105
+ const meta = typeof manager.peekMeta === "function" ? await manager.peekMeta(input.sessionId) : void 0;
1106
+ const standing = deps.sandboxSnapshot?.(input.cwd, input.executionRoot);
1107
+ const grants = [...deps.ledger.getLoaded(input.sessionId), ...decodeGrants(meta?.config?.sessionGrants)];
1108
+ const fingerprint = canonicalJson({
1109
+ engine: deps.engine.conditionFingerprint(input.sessionId, grants),
1110
+ grants: [...new Set(grants.map(canonicalJson))].sort(),
1111
+ cap: meta?.config?.permissionCap,
1112
+ mode: deps.engine.modeFor(meta?.config?.permissionMode),
1113
+ sandbox: standing === void 0 ? void 0 : {
1114
+ revision: standing.revision,
1115
+ authority: authorityIdOf(standing.state),
1116
+ state: standing.state,
1117
+ policy: standing.policy
1118
+ }
1119
+ });
1120
+ return Object.freeze({ fingerprint });
1121
+ } };
1122
+ }
1123
+
1124
+ //#endregion
1125
+ //#region src/permission-mode-state.ts
1126
+ function createPermissionModeStateReader(engine, options = {}) {
1127
+ let isReady = false;
1128
+ const listeners = /* @__PURE__ */ new Set();
1129
+ return {
1130
+ reader: {
1131
+ snapshot() {
1132
+ if (!isReady) return;
1133
+ return {
1134
+ generation: engine,
1135
+ baseline: engine.baseline(),
1136
+ revision: engine.revision()
1137
+ };
1138
+ },
1139
+ sessionMode(session) {
1140
+ if (!isReady) return;
1141
+ return engine.sessionMode(session);
1142
+ },
1143
+ trustClamped() {
1144
+ return options.trustClamped?.() === true;
1145
+ },
1146
+ subscribe(listener) {
1147
+ listeners.add(listener);
1148
+ const stop = engine.onChange(listener);
1149
+ return () => {
1150
+ listeners.delete(listener);
1151
+ stop();
1152
+ };
1153
+ }
1154
+ },
1155
+ setReady(nextReady) {
1156
+ if (isReady === nextReady) return;
1157
+ isReady = nextReady;
1158
+ for (const listener of listeners) listener();
1159
+ }
1160
+ };
1161
+ }
1162
+
1163
+ //#endregion
1164
+ //#region src/policies/destructive.ts
1165
+ const DESTRUCTIVE_COMMAND_POLICY = {
1166
+ name: "builtin::destructive-guard",
1167
+ priority: 15,
1168
+ enabled: true,
1169
+ safety: true,
1170
+ scope: {},
1171
+ rules: [{
1172
+ name: "ask-destructive-bash",
1173
+ effect: "ask",
1174
+ match: { condition: (ctx) => commandTriggersGuard(commandTextOf(ctx)) },
1175
+ askPrompt: "This command may be destructive or runs code that cannot be statically checked. Continue?"
1176
+ }, {
1177
+ name: "ask-destructive-mcp-args",
1178
+ effect: "ask",
1179
+ match: { condition: (ctx) => mcpAnyArgTriggersGuard(ctx.toolName, ctx.arguments) },
1180
+ askPrompt: "This MCP tool argument may run a destructive or unverifiable command. Continue?"
1181
+ }]
1182
+ };
1183
+
1184
+ //#endregion
1185
+ //#region src/engine/resource-completeness.ts
1186
+ function unmodelledCommand(ctx) {
1187
+ return ctx.effects.completeness === "incomplete";
1188
+ }
1189
+ function expandTargets(targets, cwd, options) {
1190
+ const home = options.home;
1191
+ return targets.map((target) => options.expandHome && home !== void 0 && (target === "~" || target.startsWith("~/")) ? resolve(home, target === "~" ? "." : target.slice(2)) : target).map((target) => isAbsolute(target) ? target : cwd !== void 0 && cwd.length > 0 ? resolve(cwd, target) : target).filter((target) => isAbsolute(target));
1192
+ }
1193
+ function readTargetsOf(ctx, options) {
1194
+ const declared = expandTargets(pathsOf(ctx, "read"), ctx.cwd, options);
1195
+ if (ctx.effects.completeness === "complete") return {
1196
+ targets: declared,
1197
+ completeness: "complete"
1198
+ };
1199
+ const derived = expandTargets(extractReadTargets(commandTextOf(ctx)).targets, ctx.cwd, options);
1200
+ return {
1201
+ targets: [...new Set([...declared, ...derived])],
1202
+ completeness: "incomplete"
1203
+ };
1204
+ }
1205
+ function writeTargetsOf(ctx, options) {
1206
+ const declared = expandTargets(pathsOf(ctx, "write"), ctx.cwd, options);
1207
+ if (ctx.effects.completeness === "complete") return {
1208
+ targets: declared,
1209
+ completeness: "complete"
1210
+ };
1211
+ const derived = absoluteTargetsResult({
1212
+ cwd: ctx.cwd,
1213
+ command: commandOf(ctx)
1214
+ }, {
1215
+ home: options.home ?? "",
1216
+ expandHome: options.expandHome && options.home !== void 0
1217
+ });
1218
+ return {
1219
+ targets: [...new Set([...declared, ...derived.targets])],
1220
+ completeness: "incomplete"
1221
+ };
1222
+ }
1223
+
1224
+ //#endregion
1225
+ //#region src/policies/protected-resources.ts
1226
+ const PROTECTION_RULES = Object.freeze({
1227
+ system: {
1228
+ tier: "system",
1229
+ read: "allow",
1230
+ write: "deny"
1231
+ },
1232
+ credential: {
1233
+ tier: "credential",
1234
+ read: "deny",
1235
+ write: "deny"
1236
+ },
1237
+ "runtime-state": {
1238
+ tier: "runtime-state",
1239
+ read: "ask",
1240
+ write: "deny"
1241
+ },
1242
+ "control-plane": {
1243
+ tier: "control-plane",
1244
+ read: "allow",
1245
+ write: "ask"
1246
+ },
1247
+ "trust-store": {
1248
+ tier: "trust-store",
1249
+ read: "deny",
1250
+ write: "deny"
1251
+ },
1252
+ "extension-decision-sources": {
1253
+ tier: "extension-decision-sources",
1254
+ read: "deny",
1255
+ write: "deny"
1256
+ }
1257
+ });
1258
+ function isAbsoluteProtectionTier(tier) {
1259
+ return ABSOLUTE_PROTECTION_CLASSES.includes(tier);
1260
+ }
1261
+ const SYSTEM_ROOTS = [
1262
+ "/etc",
1263
+ "/usr",
1264
+ "/sys",
1265
+ "/proc",
1266
+ "/bin",
1267
+ "/sbin",
1268
+ "/boot"
1269
+ ];
1270
+ const OTTO_DIR = CREDENTIAL_PATH_PATTERNS.otto.directory;
1271
+ const PROTECTED_RESOURCES = Object.freeze([
1272
+ ...SYSTEM_ROOTS.map((value) => ({
1273
+ tier: "system",
1274
+ kind: "absolute-prefix",
1275
+ value
1276
+ })),
1277
+ ...CREDENTIAL_PATH_PATTERNS.dirs.map((value) => ({
1278
+ tier: "credential",
1279
+ kind: "segment",
1280
+ value
1281
+ })),
1282
+ {
1283
+ tier: "credential",
1284
+ kind: "segment",
1285
+ value: CREDENTIAL_PATH_PATTERNS.otto.mcpDir
1286
+ },
1287
+ {
1288
+ tier: "credential",
1289
+ kind: "home-relative",
1290
+ value: `${OTTO_DIR}/${CREDENTIAL_PATH_PATTERNS.otto.authFile}`
1291
+ },
1292
+ {
1293
+ tier: "credential",
1294
+ kind: "home-relative",
1295
+ value: `${OTTO_DIR}/${CREDENTIAL_PATH_PATTERNS.otto.authDir}`
1296
+ },
1297
+ {
1298
+ tier: "runtime-state",
1299
+ kind: "suffix-under",
1300
+ value: ".lock",
1301
+ within: ".otto"
1302
+ },
1303
+ {
1304
+ tier: "runtime-state",
1305
+ kind: "segment",
1306
+ value: ".otto/sessions"
1307
+ },
1308
+ {
1309
+ tier: "runtime-state",
1310
+ kind: "segment",
1311
+ value: ".otto/logs"
1312
+ },
1313
+ {
1314
+ tier: "runtime-state",
1315
+ kind: "segment",
1316
+ value: ".otto/wal"
1317
+ },
1318
+ {
1319
+ tier: "runtime-state",
1320
+ kind: "segment",
1321
+ value: ".otto/recovery"
1322
+ },
1323
+ {
1324
+ tier: "runtime-state",
1325
+ kind: "segment",
1326
+ value: ".otto/recovery-archive"
1327
+ },
1328
+ {
1329
+ tier: "runtime-state",
1330
+ kind: "segment",
1331
+ value: ".otto/archives"
1332
+ },
1333
+ {
1334
+ tier: "runtime-state",
1335
+ kind: "segment",
1336
+ value: ".otto/.locks"
1337
+ },
1338
+ {
1339
+ tier: "runtime-state",
1340
+ kind: "segment",
1341
+ value: ".otto/pending"
1342
+ },
1343
+ {
1344
+ tier: "runtime-state",
1345
+ kind: "segment",
1346
+ value: ".otto/diagnostics"
1347
+ },
1348
+ {
1349
+ tier: "runtime-state",
1350
+ kind: "segment",
1351
+ value: ".otto/subagent-artifacts"
1352
+ },
1353
+ {
1354
+ tier: "runtime-state",
1355
+ kind: "segment",
1356
+ value: ".otto/extension-state"
1357
+ },
1358
+ {
1359
+ tier: "runtime-state",
1360
+ kind: "segment",
1361
+ value: ".otto/schedules"
1362
+ },
1363
+ {
1364
+ tier: "runtime-state",
1365
+ kind: "segment",
1366
+ value: ".otto/timers"
1367
+ },
1368
+ {
1369
+ tier: "runtime-state",
1370
+ kind: "segment",
1371
+ value: ".otto/plugins"
1372
+ },
1373
+ {
1374
+ tier: "runtime-state",
1375
+ kind: "segment",
1376
+ value: ".otto/plugin-trust.json"
1377
+ },
1378
+ {
1379
+ tier: "runtime-state",
1380
+ kind: "segment",
1381
+ value: ".otto/config.json"
1382
+ },
1383
+ {
1384
+ tier: "runtime-state",
1385
+ kind: "segment",
1386
+ value: ".otto/AGENTS.md"
1387
+ },
1388
+ {
1389
+ tier: "runtime-state",
1390
+ kind: "segment",
1391
+ value: ".otto/MEMORY.md"
1392
+ },
1393
+ {
1394
+ tier: "runtime-state",
1395
+ kind: "segment",
1396
+ value: ".otto/memory"
1397
+ },
1398
+ {
1399
+ tier: "runtime-state",
1400
+ kind: "segment",
1401
+ value: ".otto/local/MEMORY.md"
1402
+ },
1403
+ {
1404
+ tier: "runtime-state",
1405
+ kind: "segment",
1406
+ value: ".otto/local/memory"
1407
+ },
1408
+ {
1409
+ tier: "runtime-state",
1410
+ kind: "segment",
1411
+ value: ".otto/lessons.json"
1412
+ },
1413
+ {
1414
+ tier: "runtime-state",
1415
+ kind: "segment",
1416
+ value: ".otto/local/lessons.json"
1417
+ },
1418
+ {
1419
+ tier: "control-plane",
1420
+ kind: "segment",
1421
+ value: ".otto/skills"
1422
+ },
1423
+ {
1424
+ tier: "control-plane",
1425
+ kind: "segment",
1426
+ value: ".otto/agents"
1427
+ },
1428
+ {
1429
+ tier: "control-plane",
1430
+ kind: "segment",
1431
+ value: ".otto/hooks"
1432
+ },
1433
+ {
1434
+ tier: "control-plane",
1435
+ kind: "segment",
1436
+ value: ".claude"
1437
+ },
1438
+ {
1439
+ tier: "control-plane",
1440
+ kind: "segment",
1441
+ value: ".github/workflows"
1442
+ },
1443
+ {
1444
+ tier: "control-plane",
1445
+ kind: "segment",
1446
+ value: ".git/hooks"
1447
+ },
1448
+ {
1449
+ tier: "control-plane",
1450
+ kind: "segment",
1451
+ value: ".git/config"
1452
+ },
1453
+ {
1454
+ tier: "control-plane",
1455
+ kind: "segment",
1456
+ value: ".vscode/tasks.json"
1457
+ },
1458
+ {
1459
+ tier: "control-plane",
1460
+ kind: "segment",
1461
+ value: ".mcp.json"
1462
+ },
1463
+ {
1464
+ tier: "control-plane",
1465
+ kind: "workspace-root-file",
1466
+ value: "AGENTS.md"
1467
+ },
1468
+ {
1469
+ tier: "control-plane",
1470
+ kind: "workspace-root-file",
1471
+ value: "CLAUDE.md"
1472
+ },
1473
+ {
1474
+ tier: "control-plane",
1475
+ kind: "home-relative",
1476
+ value: ".gitconfig"
1477
+ },
1478
+ {
1479
+ tier: "control-plane",
1480
+ kind: "home-relative",
1481
+ value: ".bashrc"
1482
+ },
1483
+ {
1484
+ tier: "control-plane",
1485
+ kind: "home-relative",
1486
+ value: ".zshrc"
1487
+ },
1488
+ {
1489
+ tier: "control-plane",
1490
+ kind: "home-relative",
1491
+ value: ".bash_profile"
1492
+ },
1493
+ {
1494
+ tier: "control-plane",
1495
+ kind: "home-relative",
1496
+ value: ".zprofile"
1497
+ },
1498
+ {
1499
+ tier: "control-plane",
1500
+ kind: "home-relative",
1501
+ value: ".profile"
1502
+ },
1503
+ {
1504
+ tier: "control-plane",
1505
+ kind: "basename",
1506
+ value: ".env",
1507
+ readAsk: true
1508
+ }
1509
+ ]);
1510
+ const DARWIN_ALIASES = [
1511
+ ["/private/etc", "/etc"],
1512
+ ["/private/var", "/var"],
1513
+ ["/private/tmp", "/tmp"]
1514
+ ];
1515
+ function isCaseInsensitive(platform) {
1516
+ return platform === "darwin" || platform === "win32";
1517
+ }
1518
+ function foldAlias(path, platform) {
1519
+ if (platform !== "darwin") return path;
1520
+ for (const [alias, canonical] of DARWIN_ALIASES) if (path === alias || path.startsWith(alias + "/")) return canonical + path.slice(alias.length);
1521
+ return path;
1522
+ }
1523
+ function resolveExistingPrefix(path, realpath) {
1524
+ const pending = [];
1525
+ let current = path;
1526
+ for (;;) try {
1527
+ return pending.length === 0 ? realpath(current) : join(realpath(current), ...pending.reverse());
1528
+ } catch {
1529
+ const parent = dirname(current);
1530
+ if (parent === current) return path;
1531
+ pending.push(basename(current));
1532
+ current = parent;
1533
+ }
1534
+ }
1535
+ function createPathNormalizer(options) {
1536
+ const realpath = options.realpath ?? ((path) => realpathSync.native(path));
1537
+ const caseInsensitive = isCaseInsensitive(options.platform);
1538
+ return {
1539
+ caseInsensitive,
1540
+ normalize(path) {
1541
+ if (!isAbsolute(path)) return path;
1542
+ const folded = foldAlias(resolveExistingPrefix(resolve(path), realpath), options.platform);
1543
+ return caseInsensitive ? folded.toLowerCase() : folded;
1544
+ }
1545
+ };
1546
+ }
1547
+ function within(root, target) {
1548
+ return target === root || target.startsWith(root.endsWith(sep) ? root : root + sep);
1549
+ }
1550
+ function containsSegment(target, segment) {
1551
+ return target.includes(`/${segment}/`) || target.endsWith(`/${segment}`);
1552
+ }
1553
+ function matches(matcher, target, context) {
1554
+ const norm = (value) => context.normalizer.normalize(value);
1555
+ const value = context.normalizer.caseInsensitive ? matcher.value.toLowerCase() : matcher.value;
1556
+ switch (matcher.kind) {
1557
+ case "absolute-prefix": return within(norm(matcher.value), target);
1558
+ case "segment": return containsSegment(target, value);
1559
+ case "home-relative": return context.home !== void 0 && within(norm(join(context.home, matcher.value)), target);
1560
+ case "workspace-root-file": return context.workspaceRoot !== void 0 && target === norm(join(context.workspaceRoot, matcher.value));
1561
+ case "basename": {
1562
+ const name = basename(target);
1563
+ return name === value || name.startsWith(value + ".");
1564
+ }
1565
+ case "suffix-under": {
1566
+ const parent = context.normalizer.caseInsensitive ? (matcher.within ?? "").toLowerCase() : matcher.within ?? "";
1567
+ return target.endsWith(value) && target.includes(`/${parent}/`);
1568
+ }
1569
+ }
1570
+ }
1571
+ function classifyPath(target, access, context) {
1572
+ const normalized = context.normalizer.normalize(target);
1573
+ for (const root of context.credentialRoots ?? []) {
1574
+ const expanded = context.home !== void 0 && (root === "~" || root.startsWith("~/")) ? join(context.home, root.slice(1)) : root;
1575
+ if (within(context.normalizer.normalize(expanded), normalized)) return {
1576
+ tier: "credential",
1577
+ verdict: "deny",
1578
+ matcher: root
1579
+ };
1580
+ }
1581
+ let best;
1582
+ if (context.ottoHome !== void 0) {
1583
+ const floorClass = classifyProtectedPath(normalized, context.normalizer.normalize(context.ottoHome));
1584
+ if (floorClass !== void 0) {
1585
+ const rule = PROTECTION_RULES[floorClass];
1586
+ return {
1587
+ tier: floorClass,
1588
+ verdict: access === "read" ? rule.read : rule.write,
1589
+ matcher: floorClass
1590
+ };
1591
+ }
1592
+ const ottoHome = context.normalizer.normalize(context.ottoHome);
1593
+ if (within(ottoHome, normalized)) {
1594
+ const path = relative(ottoHome, normalized).split(sep);
1595
+ for (const subpath of SANDBOX_SESSION_DATA_SUBPATHS) if (subpath.replace(/^\.otto\//, "").split("/").every((segment, index) => path[index] === segment)) return {
1596
+ tier: "runtime-state",
1597
+ verdict: access === "read" ? "ask" : "deny",
1598
+ matcher: subpath
1599
+ };
1600
+ }
1601
+ }
1602
+ for (const matcher of PROTECTED_RESOURCES) {
1603
+ if (!matches(matcher, normalized, context)) continue;
1604
+ const rule = PROTECTION_RULES[matcher.tier];
1605
+ const verdict = access === "read" ? matcher.readAsk === true ? "ask" : rule.read : rule.write;
1606
+ if (verdict === "allow") continue;
1607
+ if (best === void 0 || severity(verdict) > severity(best.verdict)) best = {
1608
+ tier: matcher.tier,
1609
+ verdict,
1610
+ matcher: matcher.value
1611
+ };
1612
+ }
1613
+ return best;
1614
+ }
1615
+ function severity(verdict) {
1616
+ return verdict === "deny" ? 2 : verdict === "ask" ? 1 : 0;
1617
+ }
1618
+
1619
+ //#endregion
1620
+ //#region src/policies/protected.ts
1621
+ const PROTECTED_POLICY_NAME = "builtin::protected";
1622
+ const PROTECTED_POLICY_PRIORITY = 10;
1623
+ const ARGUMENT_SCAN_DEPTH = 4;
1624
+ const CREDENTIAL_COMMAND_PATTERNS = credentialCommandPatterns();
1625
+ function withoutExactTokens(command, paths) {
1626
+ if (paths.length === 0) return command;
1627
+ return tokenizeCommand(command).filter((token) => !paths.includes(token.unquoted)).map((token) => token.raw).join(" ");
1628
+ }
1629
+ function looksLikePath(value) {
1630
+ return value.length > 0 && value.length < 4096 && !/\s/.test(value) && /[/.]/.test(value);
1631
+ }
1632
+ function argumentPaths(value, home, cwd, depth) {
1633
+ if (depth > ARGUMENT_SCAN_DEPTH) return [];
1634
+ if (typeof value === "string") {
1635
+ if (isAbsolute(value)) return [value];
1636
+ if (home !== void 0 && (value === "~" || value.startsWith("~/"))) return [resolve(home, value === "~" ? "." : value.slice(2))];
1637
+ if (cwd !== void 0 && looksLikePath(value)) return [resolve(cwd, value)];
1638
+ return [];
1639
+ }
1640
+ if (Array.isArray(value)) return value.flatMap((item) => argumentPaths(item, home, cwd, depth + 1));
1641
+ if (value !== null && typeof value === "object") return Object.values(value).flatMap((item) => argumentPaths(item, home, cwd, depth + 1));
1642
+ return [];
1643
+ }
1644
+ function createProtectedPolicy(options = {}) {
1645
+ const normalizer = options.normalizer ?? createPathNormalizer({ platform: process.platform });
1646
+ const fallbackHome = options.home ?? homedir();
1647
+ const homeOf = (ctx) => options.sandboxSnapshot?.(ctx.cwd, ctx.isolatedRoot)?.policy.home ?? fallbackHome;
1648
+ const targetsOf = (ctx, access) => {
1649
+ const home = homeOf(ctx);
1650
+ const expansion = {
1651
+ home,
1652
+ expandHome: home !== void 0
1653
+ };
1654
+ const declared = access === "read" ? readTargetsOf(ctx, expansion).targets : writeTargetsOf(ctx, expansion).targets;
1655
+ if (ctx.provenance === "first-party") return declared;
1656
+ return [...declared, ...argumentPaths(ctx.arguments, home, ctx.cwd, 0)];
1657
+ };
1658
+ const strongest = (ctx, access) => {
1659
+ const home = homeOf(ctx);
1660
+ const context = {
1661
+ home,
1662
+ ottoHome: options.ottoHome ?? (home === void 0 ? void 0 : `${home}/.otto`),
1663
+ workspaceRoot: options.workspaceRoot ?? ctx.cwd,
1664
+ credentialRoots: options.credentialRoots ?? [],
1665
+ normalizer
1666
+ };
1667
+ let best;
1668
+ let firstDeny;
1669
+ for (const target of targetsOf(ctx, access)) {
1670
+ const match = classifyPath(target, access, context);
1671
+ if (match !== void 0 && isAbsoluteProtectionTier(match.tier)) return match;
1672
+ if (excepted(ctx, access, normalizer.normalize(target))) continue;
1673
+ if (match === void 0) continue;
1674
+ if (match.verdict === "deny") {
1675
+ firstDeny ??= match;
1676
+ continue;
1677
+ }
1678
+ best ??= match;
1679
+ }
1680
+ return firstDeny ?? best;
1681
+ };
1682
+ const readExceptions = (ctx) => options.sandboxSnapshot?.(ctx.cwd, ctx.isolatedRoot)?.policy.allowRead ?? [];
1683
+ const excepted = (ctx, access, target) => access === "read" && readExceptions(ctx).some((path) => normalizer.normalize(path) === target);
1684
+ const mentionsCredential = (ctx) => {
1685
+ const home = homeOf(ctx);
1686
+ const exceptions = readExceptions(ctx).flatMap((path) => path.startsWith(`${home}/`) ? [path, `~${path.slice(home.length)}`] : [path]);
1687
+ return commandMatchesAny(withoutExactTokens(commandTextOf(ctx), exceptions), CREDENTIAL_COMMAND_PATTERNS) || mcpArgsMatchAny(ctx.toolName, ctx.arguments, CREDENTIAL_COMMAND_PATTERNS);
1688
+ };
1689
+ const verdictRule = (access, verdict, reason) => ({
1690
+ name: `${verdict}-protected-${access}`,
1691
+ effect: verdict,
1692
+ match: { condition: (ctx) => {
1693
+ const match = strongest(ctx, access);
1694
+ return match?.verdict === verdict && !isAbsoluteProtectionTier(match.tier);
1695
+ } },
1696
+ ...verdict === "deny" ? { denyReason: reason } : { askPrompt: reason }
1697
+ });
1698
+ const floorRule = (access, reason) => ({
1699
+ name: `deny-floor-${access}`,
1700
+ effect: "deny",
1701
+ match: { condition: (ctx) => {
1702
+ const match = strongest(ctx, access);
1703
+ return match !== void 0 && isAbsoluteProtectionTier(match.tier);
1704
+ } },
1705
+ denyReason: reason,
1706
+ safety: true
1707
+ });
1708
+ const sandboxProtected = (ctx, access) => {
1709
+ const snapshot = options.sandboxSnapshot?.(ctx.cwd, ctx.isolatedRoot);
1710
+ if (snapshot === void 0) return false;
1711
+ const cwd = ctx.cwd ?? process.cwd();
1712
+ return targetsOf(ctx, access).some((target) => {
1713
+ if (excepted(ctx, access, normalizer.normalize(target))) return false;
1714
+ return snapshot.protection(access, cwd, target).verdict !== "none";
1715
+ });
1716
+ };
1717
+ return {
1718
+ name: PROTECTED_POLICY_NAME,
1719
+ priority: 10,
1720
+ enabled: true,
1721
+ safety: true,
1722
+ scope: {},
1723
+ rules: [
1724
+ floorRule("write", "Writing to the trust store or extension decision sources is not allowed"),
1725
+ floorRule("read", "Reading the trust store or extension decision sources is not allowed"),
1726
+ verdictRule("write", "deny", "Writing to a protected path is not allowed"),
1727
+ {
1728
+ name: "deny-write-outside-isolated-root",
1729
+ effect: "deny",
1730
+ match: { condition: (ctx) => writesOutsideIsolatedRoot(ctx) },
1731
+ denyReason: "This session runs with its own isolated working root: writes must stay inside it so the parent workspace stays read-only for the child"
1732
+ },
1733
+ {
1734
+ name: "deny-unprovable-write-in-isolated-root",
1735
+ effect: "deny",
1736
+ match: { condition: (ctx) => unprovableWriteInIsolatedRoot(ctx) },
1737
+ denyReason: "This session runs with its own isolated working root and the call does not declare a provable write set, so it cannot be shown to stay inside that root"
1738
+ },
1739
+ verdictRule("read", "deny", "Reading credential or secret files is not allowed"),
1740
+ {
1741
+ name: "deny-credential-command",
1742
+ effect: "deny",
1743
+ match: { condition: mentionsCredential },
1744
+ denyReason: "Accessing credential/secret paths via command is not allowed"
1745
+ },
1746
+ {
1747
+ name: "deny-sandbox-protected-subtree",
1748
+ effect: "deny",
1749
+ match: { condition: (ctx) => sandboxProtected(ctx, "write") },
1750
+ denyReason: "Writing to a sandbox-protected subtree (agent state / git hooks / git config) is not allowed"
1751
+ },
1752
+ {
1753
+ name: "deny-sandbox-denyread-root",
1754
+ effect: "deny",
1755
+ match: { condition: (ctx) => sandboxProtected(ctx, "read") },
1756
+ denyReason: "Reading a sandbox credential-protected path is not allowed"
1757
+ },
1758
+ verdictRule("write", "ask", "This writes to agent or repository control files. Continue?"),
1759
+ verdictRule("read", "ask", "This reads a file that may contain secrets or session data. Continue?")
1760
+ ]
1761
+ };
1762
+ }
1763
+ function writesOutsideIsolatedRoot(ctx) {
1764
+ const root = ctx.isolatedRoot;
1765
+ if (root === void 0 || root === "") return false;
1766
+ const resolvedRoot = resolve(root);
1767
+ const base = ctx.cwd === void 0 ? resolvedRoot : resolve(ctx.cwd);
1768
+ for (const declared of ctx.effects.writes) {
1769
+ const absolute = isAbsolute(declared) ? resolve(declared) : resolve(base, declared);
1770
+ if (absolute !== resolvedRoot && !absolute.startsWith(`${resolvedRoot}${sep}`)) return true;
1771
+ }
1772
+ return false;
1773
+ }
1774
+ function unprovableWriteInIsolatedRoot(ctx) {
1775
+ const root = ctx.isolatedRoot;
1776
+ if (root === void 0 || root === "") return false;
1777
+ if (ctx.readonly) return false;
1778
+ return ctx.effects.completeness === "incomplete";
1779
+ }
1780
+
1781
+ //#endregion
1782
+ //#region src/policies/unmodelled.ts
1783
+ const UNMODELLED_POLICY_NAME = "builtin::unmodelled";
1784
+ const UNMODELLED_COMMAND_RULE = "ask-unmodelled-command";
1785
+ const UNMODELLED_POLICY = {
1786
+ name: UNMODELLED_POLICY_NAME,
1787
+ priority: 30,
1788
+ enabled: true,
1789
+ scope: {},
1790
+ rules: [{
1791
+ name: UNMODELLED_COMMAND_RULE,
1792
+ effect: "ask",
1793
+ safety: true,
1794
+ match: { condition: (ctx) => !ctx.readonly && unmodelledCommand(ctx) },
1795
+ askPrompt: "This call has effects the permission engine cannot fully model; review it before running."
1796
+ }]
1797
+ };
1798
+
1799
+ //#endregion
1800
+ //#region src/policies/builtin.ts
1801
+ const BUILTIN_POLICY_OWNER = "builtin";
1802
+ function builtinPolicies(options = {}) {
1803
+ return [
1804
+ createProtectedPolicy(options),
1805
+ DESTRUCTIVE_COMMAND_POLICY,
1806
+ UNMODELLED_POLICY
1807
+ ];
1808
+ }
1809
+
1810
+ //#endregion
1811
+ //#region src/policies/plugin.ts
1812
+ const PLUGIN_OWNER_PREFIX = "plugin:";
1813
+ const DENY_INVALID_PLUGIN_POLICY_NAME = "guard::invalid-plugin-policy";
1814
+ const MIN_PRIORITY = 40;
1815
+ const MIN_SAFETY_PRIORITY = 12;
1816
+ const MAX_PRIORITY = 90;
1817
+ const DEFAULT_PRIORITY = 60;
1818
+ const INVALID_PLUGIN_PRIORITY = -2;
1819
+ function denyInvalidPluginPolicy(reason) {
1820
+ return {
1821
+ name: DENY_INVALID_PLUGIN_POLICY_NAME,
1822
+ priority: INVALID_PLUGIN_PRIORITY,
1823
+ enabled: true,
1824
+ safety: true,
1825
+ scope: {},
1826
+ rules: [{
1827
+ name: DENY_INVALID_PLUGIN_POLICY_NAME,
1828
+ effect: "deny",
1829
+ match: {},
1830
+ denyReason: reason,
1831
+ safety: true
1832
+ }]
1833
+ };
1834
+ }
1835
+ function clamp(priority, safety) {
1836
+ if (priority === void 0 || !Number.isFinite(priority)) return DEFAULT_PRIORITY;
1837
+ return Math.min(MAX_PRIORITY, Math.max(safety ? MIN_SAFETY_PRIORITY : MIN_PRIORITY, priority));
1838
+ }
1839
+ function compileRule(rule) {
1840
+ if (rule.effect !== "deny" && rule.effect !== "ask") return `rule "${String(rule.name)}" has effect "${String(rule.effect)}"; plugins may only deny or ask`;
1841
+ if (!Array.isArray(rule.match) || rule.match.length === 0) return `rule "${rule.name}" has no match specifiers`;
1842
+ const specs = [];
1843
+ for (const text of rule.match) {
1844
+ const spec = typeof text === "string" ? parseRule(text) : void 0;
1845
+ if (spec === void 0) return `rule "${rule.name}" has an invalid specifier "${String(text)}"`;
1846
+ specs.push(spec);
1847
+ }
1848
+ const reason = rule.reason ?? `Blocked by plugin rule ${rule.name}`;
1849
+ return {
1850
+ name: rule.name,
1851
+ effect: rule.effect,
1852
+ match: { condition: (ctx) => specs.some((spec) => ruleMatches(spec, ctx)) },
1853
+ ...rule.effect === "deny" ? { denyReason: reason } : { askPrompt: reason }
1854
+ };
1855
+ }
1856
+ function compilePluginPolicies(owner, contributions) {
1857
+ if (!Array.isArray(contributions)) return {
1858
+ ok: false,
1859
+ reason: "contribution must be an array"
1860
+ };
1861
+ const policies = [];
1862
+ for (const contribution of contributions) {
1863
+ if (typeof contribution?.name !== "string" || !Array.isArray(contribution.rules)) return {
1864
+ ok: false,
1865
+ reason: "each policy needs a string name and a rules array"
1866
+ };
1867
+ const rules = [];
1868
+ for (const rule of contribution.rules) {
1869
+ const compiled = compileRule(rule);
1870
+ if (typeof compiled === "string") return {
1871
+ ok: false,
1872
+ reason: compiled
1873
+ };
1874
+ rules.push(compiled);
1875
+ }
1876
+ policies.push({
1877
+ name: `${owner}/${contribution.name}`,
1878
+ priority: clamp(contribution.priority, contribution.safety === true),
1879
+ enabled: true,
1880
+ safety: contribution.safety === true,
1881
+ scope: {},
1882
+ rules
1883
+ });
1884
+ }
1885
+ return {
1886
+ ok: true,
1887
+ policies
1888
+ };
1889
+ }
1890
+
1891
+ //#endregion
1892
+ //#region src/policies/network.ts
1893
+ const NETWORK_POLICY_NAME = "builtin::network";
1894
+ const NETWORK_RULE = "ask-network";
1895
+ function networkHostsOf(ctx) {
1896
+ return ctx.effects.network.map((target) => target.host.toLowerCase());
1897
+ }
1898
+ function createNetworkPolicy(allowedHosts, baseline) {
1899
+ const allowOf = () => allowedHosts().map((host) => host.trim().toLowerCase()).filter(Boolean);
1900
+ const offList = (ctx) => networkHostsOf(ctx).some((host) => !allowOf().some((entry) => hostCoveredBy(host, entry)));
1901
+ return {
1902
+ name: NETWORK_POLICY_NAME,
1903
+ priority: 20,
1904
+ enabled: true,
1905
+ scope: {},
1906
+ rules: [
1907
+ {
1908
+ name: NETWORK_RULE,
1909
+ effect: "ask",
1910
+ safety: true,
1911
+ match: { condition: (ctx) => (ctx.mode ?? baseline()) !== "strict" && offList(ctx) },
1912
+ askPrompt: "This accesses a network host that is not on the allowlist. Continue?"
1913
+ },
1914
+ {
1915
+ name: "deny-network-strict",
1916
+ effect: "deny",
1917
+ match: { condition: (ctx) => (ctx.mode ?? baseline()) === "strict" && offList(ctx) },
1918
+ denyReason: "Strict mode: network access is limited to allowlisted hosts"
1919
+ },
1920
+ {
1921
+ name: "allow-network-allowlisted",
1922
+ effect: "allow",
1923
+ match: { condition: (ctx) => {
1924
+ const hosts = networkHostsOf(ctx);
1925
+ return hosts.length > 0 && ctx.effects.writes.length === 0 && ctx.effects.exec === void 0 && ctx.effects.completeness === "complete" && hosts.every((host) => allowOf().some((entry) => hostCoveredBy(host, entry)));
1926
+ } }
1927
+ }
1928
+ ]
1929
+ };
1930
+ }
1931
+
1932
+ //#endregion
1933
+ //#region src/grants/scopes.ts
1934
+ const LADDER = [
1935
+ "once",
1936
+ "session",
1937
+ "project",
1938
+ "global"
1939
+ ];
1940
+ function offeredScopesFor(input) {
1941
+ if (!input.hasGrant) return ["once"];
1942
+ const allowed = input.exact ? new Set(["once", "session"]) : new Set(LADDER);
1943
+ return LADDER.filter((scope) => scope === "once" || allowed.has(scope) && input.configured.includes(scope));
1944
+ }
1945
+
1946
+ //#endregion
1947
+ //#region src/approval/ask-plan.ts
1948
+ async function grantToLayer(field, entry, scope) {
1949
+ if (field === void 0) return "degraded";
1950
+ try {
1951
+ await field.update((current = []) => current.includes(entry) ? current : [...current, entry], scope);
1952
+ return "written";
1953
+ } catch (error) {
1954
+ if (error instanceof SettingWriteRejected) return "degraded";
1955
+ throw error;
1956
+ }
1957
+ }
1958
+ function toolPlan(deps, plan) {
1959
+ const { input, context, decision } = plan;
1960
+ const command = commandTextOf(context);
1961
+ const hosts = networkHostsOf(context);
1962
+ const exactCommand = context.toolName === TOOL_NAMES.bash && command.length > 0 && (decision.safety === true || commandTriggersGuard(command) || hosts.length > 0);
1963
+ const safetyExact = decision.safety === true && context.toolName === TOOL_NAMES.bash;
1964
+ const rule = grantRuleFor(context, {
1965
+ exact: exactCommand || safetyExact,
1966
+ ...deps.home !== void 0 ? { home: deps.home } : {}
1967
+ });
1968
+ const grantKey = rule === void 0 || rule.kind === "exact" ? void 0 : qualifierOf(rule);
1969
+ const network = decision.policyName === "builtin::network" && hosts.length > 0;
1970
+ const reason = decision.reason ?? "Confirmation required";
1971
+ const configured = deps.offeredScopesField?.get() ?? DEFAULT_OFFERED_SCOPES;
1972
+ return {
1973
+ request: {
1974
+ kind: "tool",
1975
+ sessionId: input.ctx.sessionId,
1976
+ toolCallId: input.ctx.toolCallId,
1977
+ toolName: input.call.name,
1978
+ argumentList: context.arguments,
1979
+ reason,
1980
+ ...decision.ruleName !== void 0 ? { ruleName: decision.ruleName } : {},
1981
+ ...grantKey !== void 0 ? { grantKey } : {},
1982
+ ...exactCommand ? { exactCommandGrant: true } : {},
1983
+ ...network ? { network: { hosts } } : {},
1984
+ offeredScopes: offeredScopesFor({
1985
+ hasGrant: rule !== void 0,
1986
+ exact: rule?.kind === "exact",
1987
+ configured
1988
+ })
1989
+ },
1990
+ askedReason: network ? `${reason} (${hosts.join(", ")})` : reason,
1991
+ deniedReason: decision.reason ?? "Requires confirmation but not granted",
1992
+ grantOf: async (scope) => {
1993
+ const entry = rule === void 0 ? void 0 : formatRule(rule);
1994
+ if (entry !== void 0 && (scope === "project" || scope === "global")) {
1995
+ if (await grantToLayer(deps.alwaysAllowField, entry, scope) === "written") return { grant: { scope } };
1996
+ return {
1997
+ grant: {
1998
+ scope: "session",
1999
+ degradedFrom: scope
2000
+ },
2001
+ sessionEntry: grantOfRule(rule)
2002
+ };
2003
+ }
2004
+ return {
2005
+ grant: { scope },
2006
+ ...scope === "session" && rule !== void 0 ? { sessionEntry: grantOfRule(rule) } : {}
2007
+ };
2008
+ }
2009
+ };
2010
+ }
2011
+ function askPlanOf(deps, plan) {
2012
+ return {
2013
+ kind: "ask",
2014
+ plan: toolPlan(deps, plan)
2015
+ };
2016
+ }
2017
+
2018
+ //#endregion
2019
+ //#region src/approval/audit.ts
2020
+ function eventOpts(input) {
2021
+ const opts = {};
2022
+ if (input.ctx.turn !== void 0) opts.turn = input.ctx.turn;
2023
+ if (input.ctx.step !== void 0) opts.step = input.ctx.step;
2024
+ return opts;
2025
+ }
2026
+ const AUDIT_RETRY_DELAY_MILLISECONDS = 250;
2027
+ const AUDIT_RETRY_BUDGET_MILLISECONDS = 6e4;
2028
+ function timersOf(report) {
2029
+ if (report === void 0) return void 0;
2030
+ const scoped = report;
2031
+ return scoped.auditTimers ??= /* @__PURE__ */ new Set();
2032
+ }
2033
+ function cancelAuditRetries(report) {
2034
+ const timers = timersOf(report);
2035
+ if (timers === void 0) return;
2036
+ for (const timer of timers) clearTimeout(timer);
2037
+ timers.clear();
2038
+ }
2039
+ function isRetriableRefusal(error) {
2040
+ return (error?.refusal)?.retriable === true;
2041
+ }
2042
+ function reportAuditFailure(report, kind, error) {
2043
+ report?.({
2044
+ code: "PERMISSION_AUDIT_WRITE_FAILED",
2045
+ message: `permission audit write failed (${kind}): ${error instanceof Error ? error.message : String(error)}`
2046
+ });
2047
+ }
2048
+ function retryAuditLater(report, kind, work, waitedMilliseconds) {
2049
+ const timers = timersOf(report);
2050
+ const timer = setTimeout(() => {
2051
+ timers?.delete(timer);
2052
+ try {
2053
+ work();
2054
+ } catch (error) {
2055
+ const waited = waitedMilliseconds + AUDIT_RETRY_DELAY_MILLISECONDS;
2056
+ if (isRetriableRefusal(error) && waited < AUDIT_RETRY_BUDGET_MILLISECONDS) {
2057
+ retryAuditLater(report, kind, work, waited);
2058
+ return;
2059
+ }
2060
+ reportAuditFailure(report, kind, error);
2061
+ }
2062
+ }, AUDIT_RETRY_DELAY_MILLISECONDS);
2063
+ timers?.add(timer);
2064
+ timer.unref?.();
2065
+ }
2066
+ function writeAudit(report, kind, work) {
2067
+ try {
2068
+ work();
2069
+ } catch (error) {
2070
+ if (isRetriableRefusal(error)) {
2071
+ retryAuditLater(report, kind, work, 0);
2072
+ return;
2073
+ }
2074
+ reportAuditFailure(report, kind, error);
2075
+ }
2076
+ }
2077
+ function recordAsked(sessions, input, context, reason, report) {
2078
+ writeAudit(report, "asked", () => {
2079
+ sessions().appendEvent(input.ctx.sessionId, "permission/asked", {
2080
+ toolCallId: input.ctx.toolCallId,
2081
+ toolName: context.toolName,
2082
+ reason
2083
+ }, eventOpts(input));
2084
+ });
2085
+ }
2086
+ function recordDecision(sessions, input, context, decision, resolvedBy, finalDecision, grant, report) {
2087
+ writeAudit(report, "decision", () => {
2088
+ sessions().appendEvent(input.ctx.sessionId, "permission/decision", {
2089
+ toolCallId: input.ctx.toolCallId,
2090
+ toolName: context.toolName,
2091
+ effect: decision.effect,
2092
+ finalDecision,
2093
+ policyName: decision.policyName,
2094
+ ruleName: decision.ruleName,
2095
+ ...decision.reason !== void 0 ? { reason: decision.reason } : {},
2096
+ resolvedBy,
2097
+ ...grant?.scope !== void 0 ? { scope: grant.scope } : {},
2098
+ ...grant?.degradedFrom !== void 0 ? { degradedFrom: grant.degradedFrom } : {},
2099
+ ...grant?.escalation !== void 0 ? { escalation: grant.escalation } : {}
2100
+ }, eventOpts(input));
2101
+ });
2102
+ }
2103
+ function recordExecVerification(sessions, input, verified, report) {
2104
+ writeAudit(report, "execute-verify", () => {
2105
+ sessions().appendEvent(input.ctx.sessionId, "permission/execute-verify", {
2106
+ toolCallId: input.ctx.toolCallId,
2107
+ decision: verified.decision,
2108
+ ...verified.reason !== void 0 ? { reason: verified.reason } : {},
2109
+ ...verified.revision !== void 0 ? { verifiedRevision: verified.revision } : {},
2110
+ ...verified.authorityKey !== void 0 ? { verifiedAuthorityKey: verified.authorityKey } : {},
2111
+ ...verified.capChanged !== void 0 ? { capChanged: verified.capChanged } : {}
2112
+ }, eventOpts(input));
2113
+ });
2114
+ }
2115
+
2116
+ //#endregion
2117
+ //#region src/approval/cap-mode.ts
2118
+ function capModeOverrideOf(capMode, standingMode) {
2119
+ if (capMode === void 0 || standingMode === void 0 || !isConfigurableSandboxMode(capMode)) return;
2120
+ return isWiderSandboxMode(capMode, standingMode) ? capMode : void 0;
2121
+ }
2122
+ function sessionSandboxModeOf(cap, mode) {
2123
+ if (cap?.mode !== void 0) return mode === "readonly" ? "read-only" : cap.mode;
2124
+ return mode === "readonly" ? "read-only" : void 0;
2125
+ }
2126
+ function bypassCapModeOf(cap) {
2127
+ const mode = cap?.mode;
2128
+ return mode !== void 0 && isConfigurableSandboxMode(mode) ? mode : void 0;
2129
+ }
2130
+
2131
+ //#endregion
2132
+ //#region src/approval/bash-escalation.ts
2133
+ function permissionOf(permission) {
2134
+ if (permission !== void 0 && "cap" in permission) return {
2135
+ cap: permission.cap,
2136
+ mode: permission.mode
2137
+ };
2138
+ return {
2139
+ cap: permission,
2140
+ mode: void 0
2141
+ };
2142
+ }
2143
+ function capFingerprintOf(cap) {
2144
+ return canonicalJson(cap === void 0 ? { capped: false } : {
2145
+ capped: true,
2146
+ cap
2147
+ });
2148
+ }
2149
+ function claimOf(input, deps, cap) {
2150
+ const claim = input.ctx.executionSafety?.escalation;
2151
+ const standing = deps.sandboxSnapshot?.(input.ctx.cwd, input.ctx.isolatedRoot);
2152
+ const receipt = claim?.receipt;
2153
+ if (claim === void 0 || receipt === void 0 || receipt.sessionId !== input.ctx.sessionId || receipt.command !== input.call.arguments["command"] || receipt.cwd !== input.ctx.cwd || receipt.executionRoot !== input.ctx.isolatedRoot || standing?.state.kind !== "enforced" || receipt.authority !== authorityIdOf(standing.state) || receipt.revision !== standing.revision || receipt.mode !== standing.policy.mode || !isWiderSandboxMode(receipt.mode, claim.mode)) throw new Error("sandbox escalation claim does not match the standing enforced boundary");
2154
+ if (cap?.readonly === true || cap?.mode !== void 0 && isWiderSandboxMode(cap.mode, claim.mode)) throw new Error("sandbox escalation exceeds the session permission cap");
2155
+ return {
2156
+ claim,
2157
+ standing
2158
+ };
2159
+ }
2160
+ async function authorizeBashEscalation(input, output, deps, permission, signal, isClosed, report) {
2161
+ output.decision = "deny";
2162
+ const { cap, mode } = permissionOf(permission);
2163
+ let audit;
2164
+ let resolvedBy = "policy";
2165
+ let finalDecision = "deny";
2166
+ let grant;
2167
+ try {
2168
+ if (mode === "readonly") throw new Error("sandbox escalation is not available in read-only permission mode");
2169
+ const context = factsOf({
2170
+ ...input,
2171
+ call: {
2172
+ ...input.call,
2173
+ name: TOOL_NAMES.bash
2174
+ }
2175
+ }, void 0, cap, mode);
2176
+ const auditContext = {
2177
+ ...context,
2178
+ toolName: input.call.name
2179
+ };
2180
+ const decision = deps.engine.evaluate(context);
2181
+ audit = {
2182
+ context: auditContext,
2183
+ decision
2184
+ };
2185
+ const { claim, standing } = claimOf(input, deps, cap);
2186
+ const port = deps.sandboxPort?.();
2187
+ const ask = deps.permissionAsk?.();
2188
+ if (port === void 0 || ask === void 0) throw new Error("sandbox escalation requires a sandbox and human confirmation channel");
2189
+ if (decision.effect === "deny") throw new Error(decision.reason ?? decision.ruleName);
2190
+ const revision = deps.engine.revision();
2191
+ recordAsked(deps.sessions, input, auditContext, "sandbox escalation", report);
2192
+ const outcome = await ask.ask({
2193
+ kind: "sandbox",
2194
+ sessionId: input.ctx.sessionId,
2195
+ toolCallId: input.ctx.toolCallId,
2196
+ toolName: input.call.name,
2197
+ argumentList: input.call.arguments,
2198
+ from: standing.policy.mode,
2199
+ to: claim.mode,
2200
+ justification: String(input.call.arguments["justification"]),
2201
+ backend: standing.state.kind === "enforced" ? standing.state.backend : void 0,
2202
+ offeredScopes: ["once"]
2203
+ }, { signal });
2204
+ if (signal.aborted || input.ctx.signal.aborted || isClosed()) {
2205
+ resolvedBy = "aborted";
2206
+ finalDecision = "cancelled";
2207
+ throw new Error("sandbox escalation cancelled while awaiting human confirmation; this receipt is consumed and cannot be reused");
2208
+ }
2209
+ if (outcome.status !== "answered") {
2210
+ resolvedBy = outcome.status === "cancelled" ? "aborted" : "headless";
2211
+ throw new Error(outcome.status === "timed-out" ? "sandbox escalation confirmation timed out; this receipt is consumed and cannot be reused" : outcome.status === "cancelled" ? "sandbox escalation confirmation was cancelled; this receipt is consumed and cannot be reused" : "no human confirmation channel is available for sandbox escalation; this receipt is consumed");
2212
+ }
2213
+ resolvedBy = "human";
2214
+ if (outcome.by !== "human") throw new Error("sandbox escalation requires a human answer; this receipt is consumed and cannot be reused");
2215
+ if (outcome.value.approved !== true || outcome.value.scope !== "once") throw new Error("the user denied this sandbox escalation; this receipt is consumed and cannot be reused");
2216
+ const manager = deps.sessions();
2217
+ const nowCap = typeof manager.peekMeta === "function" ? (await manager.peekMeta(input.ctx.sessionId))?.config?.permissionCap : void 0;
2218
+ if (capFingerprintOf(nowCap) !== capFingerprintOf(cap) || deps.engine.revision() !== revision) {
2219
+ resolvedBy = "aborted";
2220
+ throw new Error("permission conditions changed while awaiting human confirmation");
2221
+ }
2222
+ const after = claimOf(input, deps, nowCap);
2223
+ const snapshot = port.snapshot({
2224
+ cwd: input.ctx.cwd,
2225
+ ...input.ctx.isolatedRoot === void 0 ? {} : { executionRoot: input.ctx.isolatedRoot },
2226
+ mode: claim.mode
2227
+ });
2228
+ if (snapshot.state.kind !== "enforced" || snapshot.policy.mode !== claim.mode || after.standing.state.kind !== "enforced" || snapshot.state.backend !== after.standing.state.backend || authorityIdOf(snapshot.state) === authorityIdOf(after.standing.state)) throw new Error("approved sandbox mode cannot be enforced");
2229
+ grant = {
2230
+ scope: "once",
2231
+ escalation: {
2232
+ from: standing.policy.mode,
2233
+ to: claim.mode
2234
+ }
2235
+ };
2236
+ const authorization = Object.freeze({
2237
+ sessionId: input.ctx.sessionId,
2238
+ toolCallId: input.ctx.toolCallId,
2239
+ guardGeneration: deps.guardGeneration ?? deps,
2240
+ permissionRevision: revision,
2241
+ authorityKey: claim.receipt.authority,
2242
+ capMode: capModeOverrideOf(cap?.mode, after.standing.policy.mode),
2243
+ effects: input.effects,
2244
+ provenance: input.provenance,
2245
+ sandboxEscalatable: input.sandboxEscalatable === true,
2246
+ sandbox: {
2247
+ kind: "restricted",
2248
+ snapshot
2249
+ }
2250
+ });
2251
+ deps.authorizations.add(authorization);
2252
+ output.authorization = authorization;
2253
+ output.sandbox = authorization.sandbox;
2254
+ output.decision = "allow";
2255
+ recordDecision(deps.sessions, input, auditContext, decision, "human", "allow", grant, report);
2256
+ } catch (error) {
2257
+ output.reason = error instanceof Error ? error.message : String(error);
2258
+ if (audit !== void 0) recordDecision(deps.sessions, input, audit.context, audit.decision, resolvedBy, finalDecision, grant, report);
2259
+ }
2260
+ }
2261
+ function verifyBashEscalation(input, output, deps, permission, report) {
2262
+ output.decision = "deny";
2263
+ const { cap, mode } = permissionOf(permission);
2264
+ const authorization = input.authorization;
2265
+ if (authorization === void 0 || !deps.authorizations.delete(authorization)) {
2266
+ output.reason = "sandbox escalation is missing its unconsumed human authorization";
2267
+ recordExecVerification(deps.sessions, input, {
2268
+ decision: "deny",
2269
+ reason: output.reason
2270
+ }, report);
2271
+ return;
2272
+ }
2273
+ try {
2274
+ const { claim, standing } = claimOf(input, deps, cap);
2275
+ const decision = deps.engine.evaluate(factsOf({
2276
+ ...input,
2277
+ call: {
2278
+ ...input.call,
2279
+ name: TOOL_NAMES.bash
2280
+ }
2281
+ }, void 0, cap, mode));
2282
+ if (input.ctx.signal.aborted || decision.effect === "deny" || authorization.guardGeneration !== (deps.guardGeneration ?? deps) || authorization.sessionId !== input.ctx.sessionId || authorization.toolCallId !== input.ctx.toolCallId || authorization.permissionRevision !== deps.engine.revision() || authorization.capMode !== capModeOverrideOf(cap?.mode, standing.policy.mode) || authorization.provenance !== input.provenance || canonicalJson(authorization.effects) !== canonicalJson(input.effects) || authorization.sandbox.kind !== "restricted" || authorization.sandbox.snapshot.state.kind !== "enforced" || authorization.sandbox.snapshot.policy.mode !== claim.mode) throw new Error("sandbox escalation human authorization changed or does not belong to this call");
2283
+ output.authorization = authorization;
2284
+ output.sandbox = authorization.sandbox;
2285
+ output.decision = "allow";
2286
+ recordExecVerification(deps.sessions, input, {
2287
+ decision: "allow",
2288
+ revision: authorization.permissionRevision,
2289
+ authorityKey: authorization.authorityKey
2290
+ }, report);
2291
+ } catch (error) {
2292
+ output.reason = error instanceof Error ? error.message : String(error);
2293
+ recordExecVerification(deps.sessions, input, {
2294
+ decision: "deny",
2295
+ reason: output.reason,
2296
+ revision: authorization.permissionRevision,
2297
+ authorityKey: authorization.authorityKey
2298
+ }, report);
2299
+ }
2300
+ }
2301
+
2302
+ //#endregion
2303
+ //#region src/approval/restart-recovery.ts
2304
+ const WORKER_RESTART_UNKNOWN_RULE = "worker-restart-unknown-outcome";
2305
+ function proposedCallDigestOf(input) {
2306
+ return createHash("sha256").update(canonicalJson({
2307
+ name: input.call.name,
2308
+ arguments: input.call.arguments
2309
+ })).digest("hex");
2310
+ }
2311
+ async function unknownCallsAfterCheckpoint(sessions, sessionId, restartId) {
2312
+ const events = await sessions.eventsOf(sessionId);
2313
+ let checkpointSeq = -1;
2314
+ for (const event of events) if (event.type === "restart/checkpoint" && event.data.restartId === restartId) checkpointSeq = event.seq;
2315
+ if (checkpointSeq < 0) return [];
2316
+ const calls = /* @__PURE__ */ new Map();
2317
+ const unknown = /* @__PURE__ */ new Set();
2318
+ for (const event of events) {
2319
+ if (event.seq <= checkpointSeq) continue;
2320
+ if (event.type === "tool/call") {
2321
+ const data = event.data;
2322
+ calls.set(data.callId, {
2323
+ callId: data.callId,
2324
+ name: data.name,
2325
+ arguments: data.arguments
2326
+ });
2327
+ }
2328
+ if (event.type === "tool/result") {
2329
+ const data = event.data;
2330
+ if (data.error?.code === "tool_outcome_unknown") unknown.add(data.message.toolCallId);
2331
+ }
2332
+ }
2333
+ return [...unknown].flatMap((callId) => {
2334
+ const call = calls.get(callId);
2335
+ return call === void 0 ? [] : [call];
2336
+ });
2337
+ }
2338
+ async function authorizeRestartRecovery(input, output, deps) {
2339
+ const recovery = input.ctx.restartRecovery;
2340
+ if (recovery === void 0) return true;
2341
+ let unknown;
2342
+ try {
2343
+ unknown = await unknownCallsAfterCheckpoint(deps.sessions(), input.ctx.sessionId, recovery.restartId);
2344
+ } catch (error) {
2345
+ output.decision = "deny";
2346
+ output.reason = `restart recovery could not read unknown tool outcomes: ${error instanceof Error ? error.message : String(error)}`;
2347
+ output.ruleName = WORKER_RESTART_UNKNOWN_RULE;
2348
+ output.errorCode = "worker-restart-unknown-unavailable";
2349
+ return false;
2350
+ }
2351
+ if (unknown.length === 0) return true;
2352
+ const digest = proposedCallDigestOf(input);
2353
+ const unknownCallIds = unknown.map((call) => call.callId).sort();
2354
+ const reason = `restart ${recovery.restartId} has unknown tool outcomes (${unknownCallIds.join(", ")}); explicitly allow ${input.call.name} with proposedCallDigest ${digest}`;
2355
+ const ask = deps.permissionAsk?.();
2356
+ if (ask === void 0) {
2357
+ output.decision = "deny";
2358
+ output.reason = reason;
2359
+ output.ruleName = WORKER_RESTART_UNKNOWN_RULE;
2360
+ output.errorCode = "worker-restart-unknown-unavailable";
2361
+ recordRestartDenial(input, deps, reason);
2362
+ return false;
2363
+ }
2364
+ try {
2365
+ const outcome = await ask.ask({
2366
+ kind: "tool",
2367
+ sessionId: input.ctx.sessionId,
2368
+ toolCallId: input.ctx.toolCallId,
2369
+ toolName: input.call.name,
2370
+ argumentList: input.call.arguments ?? {},
2371
+ reason,
2372
+ ruleName: WORKER_RESTART_UNKNOWN_RULE,
2373
+ offeredScopes: ["once"]
2374
+ }, { signal: input.ctx.signal });
2375
+ if (outcome.status === "answered" && outcome.value.approved) return true;
2376
+ } catch {}
2377
+ output.decision = "deny";
2378
+ output.reason = reason;
2379
+ output.ruleName = WORKER_RESTART_UNKNOWN_RULE;
2380
+ output.errorCode = "worker-restart-unknown-denied";
2381
+ recordRestartDenial(input, deps, reason);
2382
+ return false;
2383
+ }
2384
+ function recordRestartDenial(input, deps, reason) {
2385
+ try {
2386
+ deps.sessions().appendEvent(input.ctx.sessionId, "permission/decision", {
2387
+ toolCallId: input.ctx.toolCallId,
2388
+ toolName: input.call.name,
2389
+ effect: "deny",
2390
+ finalDecision: "deny",
2391
+ policyName: "worker-restart-recovery",
2392
+ ruleName: WORKER_RESTART_UNKNOWN_RULE,
2393
+ reason,
2394
+ resolvedBy: "policy"
2395
+ }, {
2396
+ ...input.ctx.turn === void 0 ? {} : { turn: input.ctx.turn },
2397
+ ...input.ctx.step === void 0 ? {} : { step: input.ctx.step }
2398
+ });
2399
+ } catch {}
2400
+ }
2401
+
2402
+ //#endregion
2403
+ //#region src/approval/run.ts
2404
+ async function askOnce(run, request) {
2405
+ const callSignal = run.input.ctx.signal;
2406
+ if (run.ask === void 0) return {
2407
+ outcome: { status: "unavailable" },
2408
+ cancelled: false
2409
+ };
2410
+ if (run.closed() || callSignal.aborted) return {
2411
+ outcome: { status: "cancelled" },
2412
+ cancelled: true
2413
+ };
2414
+ const controller = new AbortController();
2415
+ const untrack = run.track(controller, request.sessionId);
2416
+ let cancelled = false;
2417
+ const onCallAbort = () => controller.abort();
2418
+ let onOwnerAbort;
2419
+ const aborted = new Promise((resolve) => {
2420
+ onOwnerAbort = () => {
2421
+ cancelled = true;
2422
+ resolve({ status: "cancelled" });
2423
+ };
2424
+ controller.signal.addEventListener("abort", onOwnerAbort, { once: true });
2425
+ callSignal.addEventListener("abort", onCallAbort, { once: true });
2426
+ });
2427
+ try {
2428
+ return {
2429
+ outcome: await Promise.race([run.ask.ask(request, { signal: controller.signal }), aborted]),
2430
+ cancelled
2431
+ };
2432
+ } finally {
2433
+ untrack();
2434
+ callSignal.removeEventListener("abort", onCallAbort);
2435
+ if (onOwnerAbort !== void 0) controller.signal.removeEventListener("abort", onOwnerAbort);
2436
+ }
2437
+ }
2438
+ function finish(run, resolvedBy, finalDecision, reason, meta) {
2439
+ recordDecision(run.sessions, run.input, run.context, run.decision, resolvedBy, finalDecision, meta, run.reportAudit);
2440
+ run.output.decision = "deny";
2441
+ run.output.reason = reason;
2442
+ }
2443
+ function unresolved(outcome, fallback) {
2444
+ if (outcome.status === "cancelled") return {
2445
+ resolvedBy: "aborted",
2446
+ reason: "Cancelled while awaiting confirmation"
2447
+ };
2448
+ if (outcome.status === "timed-out") return {
2449
+ resolvedBy: "headless",
2450
+ reason: "Confirmation timed out; this denial is final for this request"
2451
+ };
2452
+ return {
2453
+ resolvedBy: "headless",
2454
+ reason: fallback
2455
+ };
2456
+ }
2457
+ function retired(run) {
2458
+ return run.closed() || !run.grants.active() || run.input.ctx.signal.aborted;
2459
+ }
2460
+ async function runAsk(run, plan) {
2461
+ const { extra } = plan;
2462
+ recordAsked(run.sessions, run.input, run.context, plan.askedReason, run.reportAudit);
2463
+ const result = await askOnce(run, plan.request);
2464
+ if (retired(run) || result.cancelled) {
2465
+ finish(run, "aborted", "cancelled", "Cancelled while awaiting confirmation", extra);
2466
+ return;
2467
+ }
2468
+ const outcome = result.outcome;
2469
+ if (outcome.status !== "answered") {
2470
+ const exit = unresolved(outcome, plan.deniedReason);
2471
+ finish(run, exit.resolvedBy, "deny", exit.reason, extra);
2472
+ return;
2473
+ }
2474
+ if (run.policyChangedSince(run.revisionAtEval)) {
2475
+ finish(run, "aborted", "deny", "Permission policy changed while awaiting confirmation", extra);
2476
+ return;
2477
+ }
2478
+ if (run.sandboxChangedSince()) {
2479
+ finish(run, "aborted", "deny", "Sandbox policy changed while awaiting confirmation", extra);
2480
+ return;
2481
+ }
2482
+ const response = outcome.value;
2483
+ if (response.approved !== true) {
2484
+ finish(run, "human", "deny", plan.deniedReason, extra);
2485
+ return;
2486
+ }
2487
+ const scope = response.scope;
2488
+ const offered = plan.request.offeredScopes;
2489
+ if (scope !== void 0 && !offered.includes(scope)) {
2490
+ finish(run, "human", "deny", `permission scope "${String(scope)}" is not offered for this request`, extra);
2491
+ return;
2492
+ }
2493
+ let meta = extra;
2494
+ if (run.policyChangedSince(run.revisionAtEval)) {
2495
+ finish(run, "aborted", "deny", "Permission policy changed while granting permission", meta);
2496
+ return;
2497
+ }
2498
+ if (run.sandboxChangedSince()) {
2499
+ finish(run, "aborted", "deny", "Sandbox policy changed while granting permission", meta);
2500
+ return;
2501
+ }
2502
+ if (retired(run)) {
2503
+ finish(run, "aborted", "cancelled", "Session retired or request cancelled while granting permission", meta);
2504
+ return;
2505
+ }
2506
+ if (scope !== void 0) {
2507
+ let applied;
2508
+ try {
2509
+ applied = await plan.grantOf(scope);
2510
+ } catch (error) {
2511
+ recordDecision(run.sessions, run.input, run.context, run.decision, "human", "deny", extra, run.reportAudit);
2512
+ throw error;
2513
+ }
2514
+ meta = {
2515
+ ...extra,
2516
+ ...applied.grant
2517
+ };
2518
+ if (applied.sessionEntry !== void 0) {
2519
+ if (await run.grants.add(applied.sessionEntry) === "expired") {
2520
+ finish(run, "aborted", "cancelled", "Session retired while granting permission", meta);
2521
+ return;
2522
+ }
2523
+ }
2524
+ if (retired(run)) {
2525
+ finish(run, "aborted", "cancelled", "Session retired or request cancelled while granting permission", meta);
2526
+ return;
2527
+ }
2528
+ }
2529
+ recordDecision(run.sessions, run.input, run.context, run.decision, "human", "allow", meta, run.reportAudit);
2530
+ run.output.decision = "allow";
2531
+ }
2532
+
2533
+ //#endregion
2534
+ //#region src/approval/hook.ts
2535
+ const GUARD_HOOK_NAME = "guard::tool-call-before";
2536
+ const GUARD_HOOK_OWNER = "guard";
2537
+ const GUARD_HOOK_PRIORITY = 5;
2538
+ const GUARD_HOOK_TIMEOUT_MS = 2147483647;
2539
+ const GUARD_EXECUTE_HOOK_NAME = "guard::tool-call-execute";
2540
+ const GUARD_EXECUTE_HOOK_PRIORITY = 5;
2541
+ const GUARD_EXECUTE_HOOK_TIMEOUT_MS = 2147483647;
2542
+ const BYPASS_ESCALATE_REASON = "bash_escalate is not needed in bypass mode: ordinary bash already runs without a sandbox; use bash directly";
2543
+ async function sessionPermissionOf(sessions, engine, sessionId, runtimeOverride) {
2544
+ const manager = sessions();
2545
+ if (typeof manager.peekMeta !== "function") return {
2546
+ cap: void 0,
2547
+ mode: engine.modeFor(void 0)
2548
+ };
2549
+ try {
2550
+ const meta = await manager.peekMeta(sessionId);
2551
+ const overridden = runtimeOverride?.get(sessionId);
2552
+ return {
2553
+ cap: meta?.config?.permissionCap,
2554
+ mode: engine.modeFor(overridden ?? meta?.config?.permissionMode)
2555
+ };
2556
+ } catch {
2557
+ return {
2558
+ cap: { readonly: true },
2559
+ mode: engine.modeFor(void 0)
2560
+ };
2561
+ }
2562
+ }
2563
+ function buildAuthorization(input, fields) {
2564
+ return Object.freeze({
2565
+ sessionId: input.ctx.sessionId,
2566
+ toolCallId: input.ctx.toolCallId,
2567
+ guardGeneration: fields.guardGeneration,
2568
+ permissionRevision: fields.permissionRevision,
2569
+ authorityKey: fields.authorityKey,
2570
+ capMode: fields.capMode,
2571
+ sessionMode: fields.sessionMode,
2572
+ effects: input.effects,
2573
+ provenance: input.provenance,
2574
+ sandboxEscalatable: input.sandboxEscalatable === true,
2575
+ sandbox: fields.sandbox,
2576
+ approvedRule: fields.approvedRule
2577
+ });
2578
+ }
2579
+ function bypassExecutionOf(cap, port, ctx) {
2580
+ const mode = bypassCapModeOf(cap);
2581
+ if (mode === void 0) return { kind: "unrestricted" };
2582
+ if (port === void 0) return null;
2583
+ return {
2584
+ kind: "restricted",
2585
+ snapshot: port.snapshot({
2586
+ cwd: ctx.cwd,
2587
+ ...ctx.isolatedRoot !== void 0 ? { executionRoot: ctx.isolatedRoot } : {},
2588
+ mode
2589
+ })
2590
+ };
2591
+ }
2592
+ function createGuardHook(deps) {
2593
+ const { engine, sessions, ledger } = deps;
2594
+ const reportAudit = (failure) => {
2595
+ deps.diagnose?.(`${failure.code}: ${failure.message}`);
2596
+ };
2597
+ const guardGeneration = deps.guardGeneration ?? deps;
2598
+ const pending = /* @__PURE__ */ new Map();
2599
+ let closed = false;
2600
+ function cancelPending(sessionId) {
2601
+ for (const [controller, owner] of pending) if (sessionId === void 0 || owner === sessionId) controller.abort();
2602
+ }
2603
+ const unsubscribeEngine = engine.onChange(() => cancelPending());
2604
+ function dispose() {
2605
+ if (closed) return;
2606
+ closed = true;
2607
+ cancelPending();
2608
+ cancelAuditRetries(reportAudit);
2609
+ unsubscribeEngine();
2610
+ }
2611
+ function track(controller, sessionId) {
2612
+ pending.set(controller, sessionId);
2613
+ return () => pending.delete(controller);
2614
+ }
2615
+ return {
2616
+ name: GUARD_HOOK_NAME,
2617
+ owner: GUARD_HOOK_OWNER,
2618
+ timing: TIMINGS.toolCallBefore,
2619
+ kind: "interceptor",
2620
+ priority: 5,
2621
+ timeoutMs: GUARD_HOOK_TIMEOUT_MS,
2622
+ cancelPending,
2623
+ dispose,
2624
+ handle: async (rawInput, rawOutput) => {
2625
+ const input = rawInput;
2626
+ const output = rawOutput;
2627
+ if (closed) {
2628
+ output.decision = "deny";
2629
+ output.reason = "Guard was disposed before permission evaluation started";
2630
+ return;
2631
+ }
2632
+ if (!isReadonlyEffects(input.effects)) {
2633
+ if (!await authorizeRestartRecovery(input, output, deps)) return;
2634
+ }
2635
+ const permission = await sessionPermissionOf(sessions, engine, input.ctx.sessionId, deps.runtimePermissionOverride?.());
2636
+ const bypass = isUnrestrictedPermission(permission.mode);
2637
+ if (input.call.name === "bash_escalate") {
2638
+ if (bypass) {
2639
+ output.decision = "deny";
2640
+ output.reason = BYPASS_ESCALATE_REASON;
2641
+ output.ruleName = "bypass-escalate-unneeded";
2642
+ return;
2643
+ }
2644
+ const controller = new AbortController();
2645
+ const untrack = track(controller, input.ctx.sessionId);
2646
+ const signal = AbortSignal.any([controller.signal, input.ctx.signal]);
2647
+ try {
2648
+ await authorizeBashEscalation(input, output, deps, permission, signal, () => closed, reportAudit);
2649
+ } finally {
2650
+ untrack();
2651
+ }
2652
+ return;
2653
+ }
2654
+ if (bypass) {
2655
+ const identity = deps.toolIdentity?.(input.call.name);
2656
+ const context = factsOf(input, identity, permission.cap, permission.mode);
2657
+ const decision = engine.evaluate(context);
2658
+ if (closed || input.ctx.signal.aborted) {
2659
+ recordDecision(sessions, input, context, decision, "aborted", "cancelled", void 0, reportAudit);
2660
+ output.decision = "deny";
2661
+ output.reason = "Cancelled before permission evaluation completed";
2662
+ return;
2663
+ }
2664
+ if (decision.effect === "deny" || decision.unrestricted !== true) {
2665
+ recordDecision(sessions, input, context, decision, "policy", "deny", void 0, reportAudit);
2666
+ output.decision = "deny";
2667
+ output.reason = decision.reason ?? decision.ruleName;
2668
+ output.ruleName = decision.ruleName;
2669
+ output.errorCode = "TOOL_PERMISSION_DENIED";
2670
+ return;
2671
+ }
2672
+ const sandbox = bypassExecutionOf(permission.cap, deps.sandboxPort?.(), input.ctx);
2673
+ if (sandbox === null) {
2674
+ recordDecision(sessions, input, context, decision, "policy", "deny", void 0, reportAudit);
2675
+ output.decision = "deny";
2676
+ output.reason = "Sandbox is required for this session capability but is not mounted";
2677
+ output.errorCode = "TOOL_PERMISSION_DENIED";
2678
+ return;
2679
+ }
2680
+ recordDecision(sessions, input, context, decision, "policy", "allow", void 0, reportAudit);
2681
+ output.decision = "allow";
2682
+ output.sandbox = sandbox;
2683
+ output.authorization = buildAuthorization(input, {
2684
+ guardGeneration,
2685
+ permissionRevision: engine.revision(),
2686
+ capMode: bypassCapModeOf(permission.cap),
2687
+ sessionMode: permission.mode,
2688
+ sandbox
2689
+ });
2690
+ return;
2691
+ }
2692
+ const grants = ledger.session(input.ctx.sessionId);
2693
+ await grants.load();
2694
+ if (closed) {
2695
+ output.decision = "deny";
2696
+ output.reason = "Guard was disposed while loading session authorization";
2697
+ return;
2698
+ }
2699
+ const identity = deps.toolIdentity?.(input.call.name);
2700
+ const loaded = await sessionPermissionOf(sessions, engine, input.ctx.sessionId, deps.runtimePermissionOverride?.());
2701
+ const cap = loaded.cap;
2702
+ const port = deps.sandboxPort?.();
2703
+ const standing = deps.sandboxSnapshot?.(input.ctx.cwd, input.ctx.isolatedRoot);
2704
+ const standingRevision = standing?.revision;
2705
+ const standingAuthority = authorityIdOf(standing?.state);
2706
+ const standingNow = () => {
2707
+ const now = deps.sandboxSnapshot?.(input.ctx.cwd, input.ctx.isolatedRoot);
2708
+ return {
2709
+ revision: now?.revision,
2710
+ authority: authorityIdOf(now?.state)
2711
+ };
2712
+ };
2713
+ const capMode = capModeOverrideOf(sessionSandboxModeOf(cap, loaded.mode), standing?.policy.mode);
2714
+ const context = factsOf(input, identity, cap, loaded.mode);
2715
+ const decision = engine.evaluate(context);
2716
+ output.ruleName = decision.ruleName;
2717
+ output.errorCode = "TOOL_PERMISSION_DENIED";
2718
+ const revisionAtEval = engine.revision();
2719
+ if (closed || !grants.active() || input.ctx.signal.aborted) {
2720
+ recordDecision(sessions, input, context, decision, "aborted", "cancelled", void 0, reportAudit);
2721
+ output.decision = "deny";
2722
+ output.reason = "Cancelled before permission evaluation completed";
2723
+ return;
2724
+ }
2725
+ if (decision.effect === "deny") {
2726
+ recordDecision(sessions, input, context, decision, "policy", "deny", void 0, reportAudit);
2727
+ output.decision = "deny";
2728
+ output.reason = decision.reason ?? decision.ruleName;
2729
+ return;
2730
+ }
2731
+ if (decision.unrestricted === true) {
2732
+ recordDecision(sessions, input, context, decision, "policy", "allow", void 0, reportAudit);
2733
+ output.decision = "allow";
2734
+ const sandbox = { kind: "unrestricted" };
2735
+ output.sandbox = sandbox;
2736
+ output.authorization = buildAuthorization(input, {
2737
+ guardGeneration,
2738
+ permissionRevision: revisionAtEval,
2739
+ sessionMode: loaded.mode,
2740
+ sandbox
2741
+ });
2742
+ return;
2743
+ }
2744
+ if (port === void 0 || standing?.state.kind === "unrestricted" && !context.readonly) {
2745
+ recordDecision(sessions, input, context, decision, decision.by === "grant" ? "always-allow" : "policy", "deny", void 0, reportAudit);
2746
+ output.decision = "deny";
2747
+ output.reason = "Sandbox is required for this permission mode but is not mounted";
2748
+ return;
2749
+ }
2750
+ const hosts = networkHostsOf(context);
2751
+ const derive = (networkGrants, mode) => {
2752
+ if (engine.revision() !== revisionAtEval) return void 0;
2753
+ const now = standingNow();
2754
+ if (now.revision !== standingRevision || now.authority !== standingAuthority) return void 0;
2755
+ return {
2756
+ kind: "restricted",
2757
+ snapshot: port.snapshot({
2758
+ ...input.ctx.cwd !== void 0 ? { cwd: input.ctx.cwd } : {},
2759
+ ...mode !== void 0 ? { mode } : {},
2760
+ ...networkGrants.length > 0 ? { networkGrants } : {}
2761
+ })
2762
+ };
2763
+ };
2764
+ if (decision.effect === "allow") {
2765
+ const resolvedBy = decision.by === "grant" ? "always-allow" : "policy";
2766
+ const execution = derive(decision.by === "grant" ? hosts : [], capMode);
2767
+ if (execution === void 0) {
2768
+ recordDecision(sessions, input, context, decision, resolvedBy, "deny", void 0, reportAudit);
2769
+ output.decision = "deny";
2770
+ output.reason = "Sandbox policy changed during evaluation; retry the tool call";
2771
+ return;
2772
+ }
2773
+ recordDecision(sessions, input, context, decision, resolvedBy, "allow", void 0, reportAudit);
2774
+ output.decision = "allow";
2775
+ output.sandbox = execution;
2776
+ output.authorization = buildAuthorization(input, {
2777
+ guardGeneration,
2778
+ permissionRevision: revisionAtEval,
2779
+ authorityKey: standingAuthority,
2780
+ capMode,
2781
+ sessionMode: loaded.mode,
2782
+ sandbox: execution
2783
+ });
2784
+ return;
2785
+ }
2786
+ const planned = askPlanOf(deps, {
2787
+ input,
2788
+ context,
2789
+ decision,
2790
+ grants: grants.snapshot(),
2791
+ revisionAtEval
2792
+ });
2793
+ await runAsk({
2794
+ input,
2795
+ context,
2796
+ decision,
2797
+ output,
2798
+ grants,
2799
+ revisionAtEval,
2800
+ sessions,
2801
+ reportAudit,
2802
+ ask: deps.permissionAsk?.(),
2803
+ closed: () => closed,
2804
+ policyChangedSince: (revision) => engine.revision() !== revision,
2805
+ sandboxChangedSince: () => {
2806
+ const now = standingNow();
2807
+ return now.revision !== standingRevision || now.authority !== standingAuthority;
2808
+ },
2809
+ track
2810
+ }, planned.plan);
2811
+ if (output.decision === "allow") {
2812
+ const execution = derive(hosts, capMode);
2813
+ if (execution === void 0) {
2814
+ output.decision = "deny";
2815
+ output.reason = "Sandbox policy changed while awaiting confirmation";
2816
+ return;
2817
+ }
2818
+ output.sandbox = execution;
2819
+ output.authorization = buildAuthorization(input, {
2820
+ guardGeneration,
2821
+ permissionRevision: revisionAtEval,
2822
+ authorityKey: standingAuthority,
2823
+ capMode,
2824
+ sessionMode: loaded.mode,
2825
+ sandbox: execution,
2826
+ approvedRule: {
2827
+ policyName: decision.policyName,
2828
+ ruleName: decision.ruleName
2829
+ }
2830
+ });
2831
+ }
2832
+ }
2833
+ };
2834
+ }
2835
+ function createGuardExecuteVerifier(deps) {
2836
+ const { engine, sessions } = deps;
2837
+ const guardGeneration = deps.guardGeneration ?? deps;
2838
+ const reportAudit = (failure) => {
2839
+ deps.diagnose?.(`${failure.code}: ${failure.message}`);
2840
+ };
2841
+ let closed = false;
2842
+ function dispose() {
2843
+ closed = true;
2844
+ cancelAuditRetries(reportAudit);
2845
+ }
2846
+ return {
2847
+ name: GUARD_EXECUTE_HOOK_NAME,
2848
+ owner: GUARD_HOOK_OWNER,
2849
+ timing: TIMINGS.toolCallExecute,
2850
+ kind: "interceptor",
2851
+ priority: 5,
2852
+ timeoutMs: GUARD_EXECUTE_HOOK_TIMEOUT_MS,
2853
+ dispose,
2854
+ handle: async (rawInput, rawOutput) => {
2855
+ const input = rawInput;
2856
+ const output = rawOutput;
2857
+ if (closed) {
2858
+ output.decision = "deny";
2859
+ output.reason = "Guard was disposed before execute re-verification";
2860
+ return;
2861
+ }
2862
+ const deny = (reason) => {
2863
+ output.decision = "deny";
2864
+ output.reason = reason;
2865
+ };
2866
+ const permission = await sessionPermissionOf(sessions, engine, input.ctx.sessionId, deps.runtimePermissionOverride?.());
2867
+ if (input.call.name === "bash_escalate") {
2868
+ verifyBashEscalation(input, output, deps, permission, reportAudit);
2869
+ return;
2870
+ }
2871
+ const authorization = input.authorization;
2872
+ const ticketValid = authorization !== void 0 && Object.isFrozen(authorization) && authorization.guardGeneration === guardGeneration && authorization.sessionId === input.ctx.sessionId && authorization.toolCallId === input.ctx.toolCallId && authorization.provenance === input.provenance && authorization.sandboxEscalatable === (input.sandboxEscalatable === true) && canonicalJson(authorization.effects) === canonicalJson(input.effects);
2873
+ if (isUnrestrictedPermission(permission.mode)) {
2874
+ if (!(authorization === void 0 || authorization.sessionId === input.ctx.sessionId && authorization.toolCallId === input.ctx.toolCallId)) {
2875
+ deny("authorization does not belong to this tool call");
2876
+ return;
2877
+ }
2878
+ const capped = engine.evaluate(factsOf(input, deps.toolIdentity?.(input.call.name), permission.cap, permission.mode));
2879
+ if (closed) {
2880
+ deny("Guard was disposed during execute re-verification");
2881
+ return;
2882
+ }
2883
+ if (input.ctx.signal.aborted) {
2884
+ deny("Cancelled before execute re-verification completed");
2885
+ return;
2886
+ }
2887
+ if (capped.unrestricted !== true) {
2888
+ output.ruleName = capped.ruleName;
2889
+ output.errorCode = "TOOL_PERMISSION_DENIED";
2890
+ deny(capped.reason ?? capped.ruleName);
2891
+ return;
2892
+ }
2893
+ const sandbox = bypassExecutionOf(permission.cap, deps.sandboxPort?.(), input.ctx);
2894
+ if (sandbox === null) {
2895
+ output.errorCode = "TOOL_PERMISSION_DENIED";
2896
+ deny("Sandbox is required for this session capability but is not mounted");
2897
+ return;
2898
+ }
2899
+ const capMode = bypassCapModeOf(permission.cap);
2900
+ if (sandbox.kind === "restricted" && authorization?.capMode !== capMode) {
2901
+ deny("session capability changed since approval");
2902
+ return;
2903
+ }
2904
+ output.decision = "allow";
2905
+ output.sandbox = sandbox;
2906
+ output.authorization = buildAuthorization(input, {
2907
+ guardGeneration,
2908
+ permissionRevision: engine.revision(),
2909
+ capMode,
2910
+ sessionMode: permission.mode,
2911
+ sandbox
2912
+ });
2913
+ return;
2914
+ }
2915
+ if (authorization?.sandbox.kind === "unrestricted") {
2916
+ deny("permission mode tightened since approval");
2917
+ return;
2918
+ }
2919
+ const identity = deps.toolIdentity?.(input.call.name);
2920
+ const cap = permission.cap;
2921
+ const context = factsOf(input, identity, cap, permission.mode);
2922
+ const decision = engine.evaluate(context);
2923
+ output.ruleName = decision.ruleName;
2924
+ output.errorCode = "TOOL_PERMISSION_DENIED";
2925
+ const verifiedRevision = engine.revision();
2926
+ const standing = deps.sandboxSnapshot?.(input.ctx.cwd, input.ctx.isolatedRoot);
2927
+ const verifiedAuthority = authorityIdOf(standing?.state);
2928
+ const capMode = capModeOverrideOf(sessionSandboxModeOf(cap, permission.mode), standing?.policy.mode);
2929
+ const record = (reason, capChanged) => {
2930
+ recordExecVerification(sessions, input, {
2931
+ decision: "deny",
2932
+ reason,
2933
+ revision: verifiedRevision,
2934
+ authorityKey: verifiedAuthority,
2935
+ capChanged
2936
+ }, reportAudit);
2937
+ deny(reason);
2938
+ };
2939
+ if (decision.effect === "deny") {
2940
+ record(decision.reason ?? decision.ruleName, false);
2941
+ return;
2942
+ }
2943
+ if (!ticketValid) {
2944
+ record(authorization === void 0 ? "execute re-verification requires the per-call authorization record" : "authorization guard generation changed since approval", false);
2945
+ return;
2946
+ }
2947
+ if (authorization.permissionRevision !== verifiedRevision) {
2948
+ record("permission policy revision changed since approval", false);
2949
+ return;
2950
+ }
2951
+ if (authorization.authorityKey !== verifiedAuthority) {
2952
+ record("sandbox authority changed since approval", false);
2953
+ return;
2954
+ }
2955
+ if (authorization.capMode !== capMode) {
2956
+ record("session capability changed since approval", true);
2957
+ return;
2958
+ }
2959
+ if ((authorization.sessionMode ?? engine.modeFor(void 0)) !== permission.mode) {
2960
+ record("session permission mode changed since approval", true);
2961
+ return;
2962
+ }
2963
+ if (decision.effect === "ask") {
2964
+ const approved = authorization.approvedRule;
2965
+ if (approved === void 0 || approved.policyName !== decision.policyName || approved.ruleName !== decision.ruleName) {
2966
+ record(`execute re-verification requires approval for rule "${decision.ruleName}"`, false);
2967
+ return;
2968
+ }
2969
+ }
2970
+ output.decision = "allow";
2971
+ output.sandbox = authorization.sandbox;
2972
+ output.authorization = authorization;
2973
+ }
2974
+ };
2975
+ }
2976
+
2977
+ //#endregion
2978
+ //#region src/approval/escalation-receipt.ts
2979
+ const ESCALATION_RECEIPT_LIMIT = 256;
2980
+ function createEscalationReceiptProtocol(id, sandbox) {
2981
+ const ordinaryTools = /* @__PURE__ */ new WeakSet();
2982
+ const escalationTools = /* @__PURE__ */ new WeakSet();
2983
+ const receipts = /* @__PURE__ */ new Map();
2984
+ const standingOf = (ctx) => sandbox()?.snapshot({
2985
+ cwd: ctx.cwd,
2986
+ ...ctx.isolatedRoot === void 0 ? {} : { executionRoot: ctx.isolatedRoot }
2987
+ });
2988
+ const verify = (claim, ctx) => {
2989
+ const receipt = claim.receipt;
2990
+ const standing = standingOf(ctx);
2991
+ if (receipt.sessionId !== ctx.sessionId || receipt.cwd !== ctx.cwd || receipt.executionRoot !== ctx.isolatedRoot || standing?.state.kind !== "enforced" || receipt.authority !== authorityIdOf(standing.state) || receipt.revision !== standing.revision || receipt.mode !== standing.policy.mode) throw new Error("sandbox denial receipt no longer matches this execution boundary");
2992
+ };
2993
+ return {
2994
+ bindBashTools(ordinary, escalation) {
2995
+ ordinaryTools.add(ordinary);
2996
+ escalationTools.add(escalation);
2997
+ },
2998
+ claim(tool, input, ctx) {
2999
+ if (!escalationTools.has(tool)) throw new Error("sandbox escalation requires the bound builtin bash entry");
3000
+ const receiptId = input["denial_receipt"];
3001
+ const receipt = typeof receiptId === "string" ? receipts.get(receiptId) : void 0;
3002
+ if (receipt === void 0 || receipt.command !== input["command"]) throw new Error("sandbox denial receipt is missing, consumed, or belongs to another command");
3003
+ const mode = input["sandbox_permissions"];
3004
+ if (mode !== "workspace-write" && mode !== "danger-full-access" || !isWiderSandboxMode(receipt.mode, mode)) throw new Error("sandbox denial receipt does not permit this mode");
3005
+ const claim = Object.freeze({
3006
+ receipt,
3007
+ mode
3008
+ });
3009
+ verify(claim, ctx);
3010
+ receipts.delete(receipt.id);
3011
+ return claim;
3012
+ },
3013
+ verify,
3014
+ observer(tool, command, ctx, execution) {
3015
+ if (!ordinaryTools.has(tool) || execution?.kind !== "restricted" || execution.snapshot.state.kind !== "enforced") return;
3016
+ const snapshot = execution.snapshot;
3017
+ const authority = authorityIdOf(snapshot.state);
3018
+ if (authority === void 0) return;
3019
+ let observed = false;
3020
+ return Object.freeze({ observe(verdict) {
3021
+ if (observed || ctx.signal.aborted || !verdict.denied || verdict.runnerFailed || verdict.attribution !== "denied") return;
3022
+ observed = true;
3023
+ const mode = snapshot.policy.mode;
3024
+ if (!isConfigurableSandboxMode(mode)) return;
3025
+ const narrowed = mode;
3026
+ const receipt = Object.freeze({
3027
+ id: id.generate(),
3028
+ sessionId: ctx.sessionId,
3029
+ command,
3030
+ cwd: ctx.cwd,
3031
+ executionRoot: ctx.isolatedRoot,
3032
+ authority,
3033
+ revision: snapshot.revision,
3034
+ mode: narrowed
3035
+ });
3036
+ try {
3037
+ verify({
3038
+ receipt,
3039
+ mode: receipt.mode
3040
+ }, ctx);
3041
+ } catch {
3042
+ return;
3043
+ }
3044
+ if (receipts.has(receipt.id)) return;
3045
+ receipts.set(receipt.id, receipt);
3046
+ while (receipts.size > 256) {
3047
+ const oldest = receipts.keys().next().value;
3048
+ if (oldest === void 0) break;
3049
+ receipts.delete(oldest);
3050
+ }
3051
+ return receipt.id;
3052
+ } });
3053
+ }
3054
+ };
3055
+ }
3056
+ function isSandboxEscalationPort(value) {
3057
+ if (value === null || typeof value !== "object") return false;
3058
+ const port = value;
3059
+ return typeof port.bindBashTools === "function" && typeof port.claim === "function" && typeof port.verify === "function" && typeof port.observer === "function";
3060
+ }
3061
+
3062
+ //#endregion
3063
+ //#region src/session-meta-ledger.ts
3064
+ function createSessionMetaLedgerState() {
3065
+ return {
3066
+ states: /* @__PURE__ */ new Map(),
3067
+ chains: /* @__PURE__ */ new Map()
3068
+ };
3069
+ }
3070
+ function createSessionMetaLedger(options, state = createSessionMetaLedgerState()) {
3071
+ const { sessions, read, write, parse } = options;
3072
+ const identity = options.identity ?? ((a, b) => a === b);
3073
+ const { states, chains } = state;
3074
+ function report(phase, error) {
3075
+ try {
3076
+ options.onFailure?.(phase, error);
3077
+ } catch {
3078
+ return;
3079
+ }
3080
+ }
3081
+ function enqueue(id, work) {
3082
+ const next = (chains.get(id) ?? Promise.resolve()).then(work, work);
3083
+ const settled = next.catch(() => void 0);
3084
+ chains.set(id, settled);
3085
+ settled.then(() => {
3086
+ if (chains.get(id) === settled) chains.delete(id);
3087
+ });
3088
+ return next;
3089
+ }
3090
+ function load(id, sessionState) {
3091
+ if (!sessionState.isActive) return Promise.resolve(false);
3092
+ if (sessionState.loaded) return Promise.resolve(true);
3093
+ if (sessionState.isLoading) return sessionState.isLoading;
3094
+ const operation = (chains.get(id) ?? Promise.resolve()).then(async () => {
3095
+ if (!sessionState.isActive) return false;
3096
+ try {
3097
+ const meta = await sessions().get(id);
3098
+ if (!sessionState.isActive || meta == null) return false;
3099
+ const restored = parse(read(meta.config));
3100
+ for (const entry of restored) if (!sessionState.entries.some((current) => identity(current, entry))) sessionState.entries.push(entry);
3101
+ sessionState.loaded = true;
3102
+ return true;
3103
+ } catch (error) {
3104
+ if (sessionState.isActive) report("load", error);
3105
+ return false;
3106
+ }
3107
+ });
3108
+ sessionState.isLoading = operation;
3109
+ operation.then(() => {
3110
+ if (sessionState.isLoading === operation) sessionState.isLoading = void 0;
3111
+ });
3112
+ return operation;
3113
+ }
3114
+ async function waitForLoad(id, sessionState) {
3115
+ let timer;
3116
+ const deadline = new Promise((resolve) => {
3117
+ timer = setTimeout(() => {
3118
+ if (sessionState.isActive) report("load", /* @__PURE__ */ new Error("grant loading timed out; using current session snapshot"));
3119
+ resolve(false);
3120
+ }, options.persistWaitTimeoutMs ?? 5e3);
3121
+ timer.unref?.();
3122
+ });
3123
+ try {
3124
+ return await Promise.race([load(id, sessionState), deadline]);
3125
+ } finally {
3126
+ if (timer !== void 0) clearTimeout(timer);
3127
+ }
3128
+ }
3129
+ function session(id) {
3130
+ let existing = states.get(id);
3131
+ if (!existing) {
3132
+ existing = {
3133
+ isActive: true,
3134
+ loaded: false,
3135
+ entries: []
3136
+ };
3137
+ states.set(id, existing);
3138
+ }
3139
+ const sessionState = existing;
3140
+ return {
3141
+ active: () => sessionState.isActive,
3142
+ snapshot: () => sessionState.isActive ? [...sessionState.entries] : [],
3143
+ load: () => waitForLoad(id, sessionState),
3144
+ add(entry) {
3145
+ if (!sessionState.isActive) return Promise.resolve("expired");
3146
+ const index = sessionState.entries.findIndex((current) => identity(current, entry));
3147
+ if (index < 0) sessionState.entries.push(entry);
3148
+ else sessionState.entries[index] = entry;
3149
+ const loaded = load(id, sessionState);
3150
+ let notified = false;
3151
+ const notify = (error) => {
3152
+ if (notified) return;
3153
+ notified = true;
3154
+ report("persist", error);
3155
+ };
3156
+ const operation = enqueue(id, async () => {
3157
+ if (!sessionState.isActive) return "expired";
3158
+ if (!await loaded) {
3159
+ if (!sessionState.isActive) return "expired";
3160
+ notify(/* @__PURE__ */ new Error("grant retained in memory: session metadata unavailable"));
3161
+ return "memory";
3162
+ }
3163
+ if (!sessionState.isActive) return "expired";
3164
+ try {
3165
+ await sessions().updateMeta(id, { config: write([...sessionState.entries]) });
3166
+ return sessionState.isActive ? "persisted" : "expired";
3167
+ } catch (error) {
3168
+ if (!sessionState.isActive) return "expired";
3169
+ notify(error);
3170
+ return "memory";
3171
+ }
3172
+ });
3173
+ let timer;
3174
+ const deadline = new Promise((resolve) => {
3175
+ timer = setTimeout(() => {
3176
+ if (sessionState.isActive) notify(/* @__PURE__ */ new Error("grant retained in memory: persistence timed out"));
3177
+ resolve(sessionState.isActive ? "memory" : "expired");
3178
+ }, options.persistWaitTimeoutMs ?? 5e3);
3179
+ timer.unref?.();
3180
+ });
3181
+ return Promise.race([operation, deadline]).finally(() => {
3182
+ if (timer !== void 0) clearTimeout(timer);
3183
+ });
3184
+ }
3185
+ };
3186
+ }
3187
+ return {
3188
+ session,
3189
+ async get(id) {
3190
+ const handle = session(id);
3191
+ await handle.load();
3192
+ return handle.snapshot();
3193
+ },
3194
+ getLoaded: (id) => [...states.get(id)?.entries ?? []],
3195
+ isLoaded: (id) => states.get(id)?.loaded === true,
3196
+ ensureLoaded: (id) => session(id).load(),
3197
+ add: (id, entry) => session(id).add(entry),
3198
+ forgetSession(id) {
3199
+ const sessionState = states.get(id);
3200
+ if (sessionState) {
3201
+ sessionState.isActive = false;
3202
+ sessionState.entries = [];
3203
+ }
3204
+ states.delete(id);
3205
+ }
3206
+ };
3207
+ }
3208
+
3209
+ //#endregion
3210
+ //#region src/settings/compile.ts
3211
+ const POLICY_SCHEMA_VERSION = 1;
3212
+ function isBlockingEffect(effect) {
3213
+ return effect === "deny" || effect === "ask";
3214
+ }
3215
+ function rejectNote(name, text, effect) {
3216
+ const detail = guardT("guard.policy.patternDetail", { pattern: text });
3217
+ const disposition = isBlockingEffect(effect) ? guardT("guard.policy.dispositionBlocking") : guardT("guard.policy.dispositionDropped");
3218
+ return {
3219
+ name,
3220
+ reason: guardT("guard.policy.rejectNote", {
3221
+ reason: guardT("guard.policy.specifierInvalid"),
3222
+ detail,
3223
+ disposition
3224
+ })
3225
+ };
3226
+ }
3227
+ function compilePolicyFromSetting(setting) {
3228
+ const disabledRules = [];
3229
+ if ((setting.schemaVersion ?? 0) > 1) throw new TypeError(`permission policy "${setting.name}" declares schemaVersion ${setting.schemaVersion}, but this guard only supports up to ${1}`);
3230
+ const rules = [];
3231
+ for (const rc of setting.rules) {
3232
+ const specs = [];
3233
+ const declared = (rc.match?.length ?? 0) > 0;
3234
+ for (const text of rc.match ?? []) {
3235
+ const spec = parseRule(text);
3236
+ if (spec !== void 0) {
3237
+ specs.push(spec);
3238
+ continue;
3239
+ }
3240
+ if (isBlockingEffect(rc.effect)) throw new TypeError(`rule "${rc.name}" has an invalid specifier "${text}" under a blocking (${rc.effect}) effect`);
3241
+ disabledRules.push(rejectNote(rc.name, text, rc.effect));
3242
+ }
3243
+ const hasSpecs = specs.length > 0;
3244
+ const hasTools = rc.tools !== void 0 && rc.tools.length > 0;
3245
+ if (!hasSpecs && !hasTools) {
3246
+ if (isBlockingEffect(rc.effect)) throw new TypeError(`rule "${rc.name}" has no match dimension (needs at least one specifier or tool) under a blocking (${rc.effect}) effect`);
3247
+ if (declared) continue;
3248
+ }
3249
+ rules.push({
3250
+ name: rc.name,
3251
+ effect: rc.effect,
3252
+ match: {
3253
+ tools: rc.tools,
3254
+ condition: hasSpecs ? (ctx) => specs.some((spec) => ruleMatches(spec, ctx)) : void 0
3255
+ },
3256
+ denyReason: rc.deny_reason,
3257
+ askPrompt: rc.ask_prompt
3258
+ });
3259
+ }
3260
+ return {
3261
+ name: setting.name,
3262
+ priority: setting.priority ?? 50,
3263
+ enabled: setting.enabled ?? true,
3264
+ scope: { sessions: setting.scope?.sessions },
3265
+ rules,
3266
+ ...disabledRules.length > 0 ? { disabledRules } : {}
3267
+ };
3268
+ }
3269
+
3270
+ //#endregion
3271
+ //#region src/settings/validation.ts
3272
+ const RESERVED_PREFIXES = [
3273
+ "builtin::",
3274
+ "guard::",
3275
+ "plugin:",
3276
+ "__"
3277
+ ];
3278
+ const RETIRED_RULE_FIELDS = ["paths", "commands"];
3279
+ function record$1(value) {
3280
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3281
+ }
3282
+ function validateStringList(value, path) {
3283
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) throw new TypeError(`${path} must be an array of strings`);
3284
+ }
3285
+ function optionalStrings(value, path) {
3286
+ if (value !== void 0) validateStringList(value, path);
3287
+ }
3288
+ function optionalText(value, path) {
3289
+ if (value !== void 0 && typeof value !== "string") throw new TypeError(`${path} must be a string`);
3290
+ }
3291
+ function validatePermission(value) {
3292
+ if (!record$1(value)) throw new TypeError("permissions entries must be objects");
3293
+ const name = value.name;
3294
+ if (typeof name !== "string" || name.length === 0) throw new TypeError("permissions.name must be a non-empty string");
3295
+ const path = `permissions[${name}]`;
3296
+ if (RESERVED_PREFIXES.some((prefix) => name.startsWith(prefix))) throw new TypeError(`${path}.name must not use a reserved prefix`);
3297
+ if (!Array.isArray(value.rules)) throw new TypeError(`${path}.rules must be an array`);
3298
+ if (value.enabled !== void 0 && typeof value.enabled !== "boolean") throw new TypeError(`${path}.enabled must be a boolean`);
3299
+ for (const key of ["priority", "schemaVersion"]) if (value[key] !== void 0 && (typeof value[key] !== "number" || !Number.isFinite(value[key]))) throw new TypeError(`${path}.${key} must be a finite number`);
3300
+ if (value.scope !== void 0) {
3301
+ if (!record$1(value.scope)) throw new TypeError(`${path}.scope must be an object`);
3302
+ optionalStrings(value.scope.sessions, `${path}.scope.sessions`);
3303
+ }
3304
+ for (const [index, rule] of value.rules.entries()) {
3305
+ const rulePath = `${path}.rules[${index}]`;
3306
+ if (!record$1(rule) || typeof rule.name !== "string" || rule.effect !== "allow" && rule.effect !== "deny" && rule.effect !== "ask") throw new TypeError(`${rulePath} must have a string name and allow/deny/ask effect`);
3307
+ for (const key of RETIRED_RULE_FIELDS) if (rule[key] !== void 0) throw new TypeError(`${rulePath}.${key} regex rules were removed; run \`otto permissions migrate\` to convert them to match`);
3308
+ for (const key of ["tools", "match"]) optionalStrings(rule[key], `${rulePath}.${key}`);
3309
+ optionalText(rule.deny_reason, `${rulePath}.deny_reason`);
3310
+ optionalText(rule.ask_prompt, `${rulePath}.ask_prompt`);
3311
+ }
3312
+ }
3313
+ function shapeOfPolicy(value) {
3314
+ if (!record$1(value)) return false;
3315
+ if (typeof value.name !== "string" || value.name.length === 0) return false;
3316
+ if (!Array.isArray(value.rules)) return false;
3317
+ return value.rules.every((rule) => record$1(rule) && typeof rule.name === "string" && (rule.effect === "allow" || rule.effect === "deny" || rule.effect === "ask"));
3318
+ }
3319
+ function parsePermissionListSetting(raw) {
3320
+ if (!Array.isArray(raw) || !raw.every(shapeOfPolicy)) return void 0;
3321
+ return raw;
3322
+ }
3323
+
3324
+ //#endregion
3325
+ //#region src/settings/sync.ts
3326
+ function layersOf(field) {
3327
+ return settingLayerValues(field);
3328
+ }
3329
+ function arraysOf(layers, key) {
3330
+ return layers.map((value) => {
3331
+ if (value === void 0) return [];
3332
+ if (!Array.isArray(value)) throw new TypeError(`${key} must be an array in every configured layer`);
3333
+ return value;
3334
+ });
3335
+ }
3336
+ function mergePermissions(layers) {
3337
+ const byName = /* @__PURE__ */ new Map();
3338
+ for (const items of arraysOf(layers, "permissions")) for (const item of items) {
3339
+ if (typeof item !== "object" || item === null || Array.isArray(item)) throw new TypeError("permissions entries must be objects");
3340
+ validatePermission(item);
3341
+ byName.set(item.name, item);
3342
+ }
3343
+ return [...byName.values()];
3344
+ }
3345
+ const SETTINGS_POLICY_OWNER = "settings";
3346
+ function readPermissionSettings(fields) {
3347
+ const mode = fields.mode.get();
3348
+ const permissions = layersOf(fields.permissions);
3349
+ const allow = layersOf(fields.alwaysAllow);
3350
+ return {
3351
+ permissionMode: mode,
3352
+ permissions: mergePermissions(permissions),
3353
+ alwaysAllow: uniqueFlat(arraysOf(allow, "permission.alwaysAllow"))
3354
+ };
3355
+ }
3356
+ function compileSettingPolicies(snapshot, allowedHosts, engine) {
3357
+ if (!isPermissionMode(snapshot.permissionMode)) throw new TypeError("invalid permission_mode");
3358
+ validateStringList(snapshot.alwaysAllow, "permission.alwaysAllow");
3359
+ if (!Array.isArray(snapshot.permissions)) throw new TypeError("permissions must be an array");
3360
+ const next = [];
3361
+ next.push(createNetworkPolicy(allowedHosts, () => engine.baseline()));
3362
+ for (const pc of snapshot.permissions) {
3363
+ validatePermission(pc);
3364
+ next.push(compilePolicyFromSetting(pc));
3365
+ }
3366
+ return next;
3367
+ }
3368
+ function createSettingsSync(engine, allowedHosts) {
3369
+ let lease;
3370
+ let appliedKey;
3371
+ return {
3372
+ apply(snapshot) {
3373
+ const next = compileSettingPolicies(snapshot, allowedHosts, engine);
3374
+ const key = JSON.stringify({ permissions: snapshot.permissions });
3375
+ const notes = next.flatMap((policy) => (policy.disabledRules ?? []).map((note) => `${policy.name}/${note.name}: ${note.reason}`));
3376
+ if (lease !== void 0 && key === appliedKey) {
3377
+ engine.setAlwaysAllow(snapshot.alwaysAllow);
3378
+ return notes;
3379
+ }
3380
+ if (lease === void 0) lease = engine.policies.contribute(SETTINGS_POLICY_OWNER, next);
3381
+ else lease.replace(next);
3382
+ engine.setAlwaysAllow(snapshot.alwaysAllow);
3383
+ appliedKey = key;
3384
+ return notes;
3385
+ },
3386
+ dispose() {
3387
+ lease?.dispose();
3388
+ lease = void 0;
3389
+ appliedKey = void 0;
3390
+ }
3391
+ };
3392
+ }
3393
+
3394
+ //#endregion
3395
+ //#region src/settings/migrate.ts
3396
+ const PATH_TOOL = "*";
3397
+ const SHELL_TOOL = TOOL_NAMES.bash;
3398
+ function unescape(text) {
3399
+ let out = "";
3400
+ for (let index = 0; index < text.length; index++) {
3401
+ const char = text[index];
3402
+ if (char === "\\") {
3403
+ const next = text[index + 1];
3404
+ if (next === void 0 || /[A-Za-z0-9]/.test(next)) return void 0;
3405
+ out += next;
3406
+ index++;
3407
+ continue;
3408
+ }
3409
+ if (".*+?()[]{}|^$".includes(char)) return void 0;
3410
+ out += char;
3411
+ }
3412
+ return out;
3413
+ }
3414
+ function pathPatternToSpecifier(pattern) {
3415
+ if (!pattern.startsWith("^/")) return void 0;
3416
+ const directory = pattern.endsWith("/");
3417
+ const exact = pattern.endsWith("$") && !pattern.endsWith("\\$");
3418
+ if (!directory && !exact) return void 0;
3419
+ const literal = unescape(pattern.slice(1, exact ? -1 : void 0));
3420
+ if (literal === void 0 || literal.length === 0) return void 0;
3421
+ const specifier = directory ? `${PATH_TOOL}(${literal}**)` : `${PATH_TOOL}(${literal})`;
3422
+ return parseRule(specifier) === void 0 ? void 0 : specifier;
3423
+ }
3424
+ const COMMAND_TERMINATORS = [
3425
+ "(?:\\s|$)",
3426
+ "(\\s|$)",
3427
+ "$"
3428
+ ];
3429
+ function commandPatternToSpecifier(pattern) {
3430
+ if (!pattern.startsWith("^")) return void 0;
3431
+ const terminator = COMMAND_TERMINATORS.find((suffix) => pattern.endsWith(suffix));
3432
+ if (terminator === void 0) return void 0;
3433
+ const literals = pattern.slice(1, -terminator.length).split(/\\s\+|\\s/).map(unescape);
3434
+ if (literals.some((word) => word === void 0 || word.length === 0 || /[\s()]/.test(word))) return;
3435
+ const specifier = `${SHELL_TOOL}(${literals.join(" ")})`;
3436
+ return parseRule(specifier) === void 0 ? void 0 : specifier;
3437
+ }
3438
+ function record(value) {
3439
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3440
+ }
3441
+ function migratePermissions(value) {
3442
+ if (!Array.isArray(value)) return {
3443
+ permissions: [],
3444
+ converted: 0,
3445
+ leftovers: [],
3446
+ changed: false
3447
+ };
3448
+ let converted = 0;
3449
+ let changed = false;
3450
+ const leftovers = [];
3451
+ return {
3452
+ permissions: value.map((policy) => {
3453
+ if (!record(policy) || !Array.isArray(policy.rules)) return policy;
3454
+ const rules = policy.rules.map((rule) => {
3455
+ if (!record(rule) || rule.paths === void 0 && rule.commands === void 0) return rule;
3456
+ const { paths, commands, ...rest } = rule;
3457
+ const match = [];
3458
+ const pending = [];
3459
+ const dimensions = [
3460
+ rest.match,
3461
+ paths,
3462
+ commands
3463
+ ].filter((list) => Array.isArray(list) && list.length > 0).length;
3464
+ const blocking = rule.effect === "deny" || rule.effect === "ask";
3465
+ const shellOnly = Array.isArray(rule.tools) && rule.tools.length === 1 && rule.tools[0] === SHELL_TOOL;
3466
+ const commandConvert = (pattern) => blocking && shellOnly ? commandPatternToSpecifier(pattern) : void 0;
3467
+ const combined = dimensions > 1;
3468
+ const collect = (field, list, convert) => {
3469
+ if (!Array.isArray(list)) return;
3470
+ for (const pattern of list) {
3471
+ const text = String(pattern);
3472
+ const specifier = combined ? void 0 : convert(text);
3473
+ if (specifier === void 0) {
3474
+ pending.push({
3475
+ policy: String(policy.name),
3476
+ rule: String(rule.name),
3477
+ field,
3478
+ pattern: text
3479
+ });
3480
+ continue;
3481
+ }
3482
+ match.push(specifier);
3483
+ converted++;
3484
+ }
3485
+ };
3486
+ collect("paths", paths, pathPatternToSpecifier);
3487
+ collect("commands", commands, commandConvert);
3488
+ if (pending.length > 0) {
3489
+ leftovers.push(...pending);
3490
+ return rule;
3491
+ }
3492
+ changed = true;
3493
+ return {
3494
+ ...rest,
3495
+ match: [...Array.isArray(rest.match) ? rest.match : [], ...match]
3496
+ };
3497
+ });
3498
+ return {
3499
+ ...policy,
3500
+ rules
3501
+ };
3502
+ }),
3503
+ converted,
3504
+ leftovers,
3505
+ changed
3506
+ };
3507
+ }
3508
+
3509
+ //#endregion
3510
+ //#region src/commands/permissions-commands.ts
3511
+ const PERMISSIONS_COMMAND_OWNER = "guard";
3512
+ const PERMISSIONS_KEY = "permissions";
3513
+ const LAYERS = ["global", "project"];
3514
+ const LEFTOVER_EXIT_CODE = 2;
3515
+ registerBundle(PERMISSIONS_COMMAND_OWNER, {
3516
+ en: {
3517
+ "guard::permissions.migrate.summary": "Convert removed paths/commands regex rules to match (dry run unless --write)",
3518
+ "guard::permissions.unavailable": "Settings are not available in this environment",
3519
+ "guard::permissions.projectUnreadable": "[project] no readable project permissions (none configured, or the project is not trusted: run `otto trust` first)",
3520
+ "guard::permissions.leftover": "[{{scope}}] {{policy}} / {{rule}}: {{field}} {{pattern}} cannot be converted without changing its meaning; rewrite this rule with match by hand",
3521
+ "guard::permissions.notRewritten": "[{{scope}}] not rewritten: the layer would still contain removed fields; fix the rules above first",
3522
+ "guard::permissions.convertible": "[{{scope}}] {{count}} pattern(s) convertible to match",
3523
+ "guard::permissions.preview": "{{json}}",
3524
+ "guard::permissions.readFailed": "[{{scope}}] read failed: {{detail}}",
3525
+ "guard::permissions.writeFailed": "[{{scope}}] write failed: {{detail}}",
3526
+ "guard::permissions.rewritten": "[{{scope}}] permissions rewritten",
3527
+ "guard::permissions.dryRun": "dry run; pass --write to save the converted rules",
3528
+ "guard::permissions.show.summary": "Show permission mode, policies and always-allow entries",
3529
+ "guard::permissions.revoke.summary": "Remove one always-allow entry from a scope",
3530
+ "guard::permissions.revoke.missing": "No always-allow entry matched \"{{entry}}\"",
3531
+ "guard::permissions.revoke.done": "Removed \"{{entry}}\" from {{scopes}}",
3532
+ "guard::permissions.show.body": "{{json}}"
3533
+ },
3534
+ zh: {
3535
+ "guard::permissions.migrate.summary": "把已移除的 paths/commands 正则规则转成 match(不加 --write 时只预览)",
3536
+ "guard::permissions.unavailable": "当前环境无法读写设置",
3537
+ "guard::permissions.projectUnreadable": "[project] 没有可读的项目权限配置(未配置,或项目未受信:请先运行 `otto trust`)",
3538
+ "guard::permissions.leftover": "[{{scope}}] {{policy}} / {{rule}}:{{field}} {{pattern}} 无法在不改变语义的前提下转换,请手动改写为 match",
3539
+ "guard::permissions.notRewritten": "[{{scope}}] 未写回:该层写回后仍含已移除字段;请先修正上面的规则",
3540
+ "guard::permissions.convertible": "[{{scope}}] 有 {{count}} 条 pattern 可转为 match",
3541
+ "guard::permissions.preview": "{{json}}",
3542
+ "guard::permissions.readFailed": "[{{scope}}] 读取失败:{{detail}}",
3543
+ "guard::permissions.writeFailed": "[{{scope}}] 写入失败:{{detail}}",
3544
+ "guard::permissions.rewritten": "[{{scope}}] 权限已改写",
3545
+ "guard::permissions.dryRun": "预览模式;加 --write 保存转换后的规则",
3546
+ "guard::permissions.show.summary": "查看权限模式、策略与 always-allow 条目",
3547
+ "guard::permissions.revoke.summary": "从指定作用域删除一条 always-allow 条目",
3548
+ "guard::permissions.revoke.missing": "没有匹配 \"{{entry}}\" 的 always-allow 条目",
3549
+ "guard::permissions.revoke.done": "已从 {{scopes}} 删除 \"{{entry}}\"",
3550
+ "guard::permissions.show.body": "{{json}}"
3551
+ }
3552
+ });
3553
+ function item(name, level, params) {
3554
+ return {
3555
+ key: `${PERMISSIONS_COMMAND_OWNER}::permissions.${name}`,
3556
+ level,
3557
+ ...params === void 0 ? {} : { params }
3558
+ };
3559
+ }
3560
+ async function migrate(settings, write) {
3561
+ const items = [];
3562
+ const plans = [];
3563
+ let blocked = 0;
3564
+ const values = /* @__PURE__ */ new Map();
3565
+ for (const scope of LAYERS) try {
3566
+ values.set(scope, settings.get(PERMISSIONS_KEY, scope));
3567
+ } catch (error) {
3568
+ return {
3569
+ kind: "messages",
3570
+ items: [item("readFailed", "error", {
3571
+ scope,
3572
+ detail: error instanceof Error ? error.message : String(error)
3573
+ })],
3574
+ exitCode: 1
3575
+ };
3576
+ }
3577
+ for (const scope of LAYERS) {
3578
+ const value = values.get(scope);
3579
+ if (scope === "project" && value === void 0) items.push(item("projectUnreadable", "info"));
3580
+ const migration = migratePermissions(value);
3581
+ for (const leftover of migration.leftovers) items.push(item("leftover", "warning", {
3582
+ scope,
3583
+ policy: leftover.policy,
3584
+ rule: leftover.rule,
3585
+ field: leftover.field,
3586
+ pattern: JSON.stringify(leftover.pattern)
3587
+ }));
3588
+ blocked += migration.leftovers.length;
3589
+ if (migration.leftovers.length > 0) {
3590
+ if (migration.changed) items.push(item("notRewritten", "warning", { scope }));
3591
+ continue;
3592
+ }
3593
+ if (!migration.changed) continue;
3594
+ items.push(item("convertible", "info", {
3595
+ scope,
3596
+ count: migration.converted
3597
+ }));
3598
+ if (!write) items.push(item("preview", "info", { json: JSON.stringify(migration.permissions, null, 2) }));
3599
+ plans.push({
3600
+ scope,
3601
+ permissions: migration.permissions
3602
+ });
3603
+ }
3604
+ if (write) for (const plan of plans) {
3605
+ try {
3606
+ await settings.set(PERMISSIONS_KEY, plan.permissions, plan.scope);
3607
+ } catch (error) {
3608
+ const detail = error instanceof Error ? error.message : String(error);
3609
+ items.push(item("writeFailed", "error", {
3610
+ scope: plan.scope,
3611
+ detail
3612
+ }));
3613
+ return {
3614
+ kind: "messages",
3615
+ items,
3616
+ exitCode: 1
3617
+ };
3618
+ }
3619
+ items.push(item("rewritten", "success", { scope: plan.scope }));
3620
+ }
3621
+ else items.push(item("dryRun", "info"));
3622
+ return {
3623
+ kind: "messages",
3624
+ items,
3625
+ exitCode: blocked > 0 ? LEFTOVER_EXIT_CODE : 0
3626
+ };
3627
+ }
3628
+ const ALWAYS_ALLOW_KEY = "permission.alwaysAllow";
3629
+ function readSetting(settings, key, scope) {
3630
+ try {
3631
+ return settings.get(key, scope);
3632
+ } catch {
3633
+ return;
3634
+ }
3635
+ }
3636
+ async function show(settings) {
3637
+ const payload = {
3638
+ mode: readSetting(settings, "permission.mode", "global"),
3639
+ alwaysAllow: {
3640
+ global: readSetting(settings, ALWAYS_ALLOW_KEY, "global"),
3641
+ project: readSetting(settings, ALWAYS_ALLOW_KEY, "project")
3642
+ },
3643
+ policies: {
3644
+ global: readSetting(settings, PERMISSIONS_KEY, "global"),
3645
+ project: readSetting(settings, PERMISSIONS_KEY, "project")
3646
+ },
3647
+ offeredScopes: readSetting(settings, "permission.offeredScopes", "global")
3648
+ };
3649
+ return {
3650
+ kind: "messages",
3651
+ items: [item("show.body", "info", { json: JSON.stringify(payload, null, 2) })],
3652
+ exitCode: 0
3653
+ };
3654
+ }
3655
+ async function revoke(settings, entry, scopes) {
3656
+ const removed = [];
3657
+ for (const scope of scopes) {
3658
+ const current = readSetting(settings, ALWAYS_ALLOW_KEY, scope);
3659
+ if (!Array.isArray(current) || !current.includes(entry)) continue;
3660
+ const next = current.filter((value) => value !== entry);
3661
+ try {
3662
+ await settings.set(ALWAYS_ALLOW_KEY, next, scope);
3663
+ removed.push(scope);
3664
+ } catch (error) {
3665
+ return {
3666
+ kind: "messages",
3667
+ items: [item("writeFailed", "error", {
3668
+ scope,
3669
+ detail: error instanceof Error ? error.message : String(error)
3670
+ })],
3671
+ exitCode: 1
3672
+ };
3673
+ }
3674
+ }
3675
+ if (removed.length === 0) return {
3676
+ kind: "messages",
3677
+ items: [item("revoke.missing", "warning", { entry })],
3678
+ exitCode: 1
3679
+ };
3680
+ return {
3681
+ kind: "messages",
3682
+ items: [item("revoke.done", "success", {
3683
+ entry,
3684
+ scopes: removed.join(", ")
3685
+ })],
3686
+ exitCode: 0
3687
+ };
3688
+ }
3689
+ function createPermissionsCommands() {
3690
+ return [
3691
+ {
3692
+ path: ["permissions", "migrate"],
3693
+ summary: `${PERMISSIONS_COMMAND_OWNER}::permissions.migrate.summary`,
3694
+ group: "other",
3695
+ surfaces: ["cli"],
3696
+ argSpecs: [{
3697
+ name: "write",
3698
+ flag: "write",
3699
+ kind: "boolean"
3700
+ }],
3701
+ run: async (context, invocation) => {
3702
+ const settings = context.resolve(SLOTS.settingsAdmin) ?? context.resolve(SLOTS.settings);
3703
+ if (settings === void 0) return {
3704
+ kind: "message",
3705
+ key: "guard::permissions.unavailable",
3706
+ level: "error"
3707
+ };
3708
+ return migrate(settings, invocation.flags.has("write"));
3709
+ }
3710
+ },
3711
+ {
3712
+ path: ["permissions", "show"],
3713
+ summary: `${PERMISSIONS_COMMAND_OWNER}::permissions.show.summary`,
3714
+ group: "other",
3715
+ surfaces: ["cli"],
3716
+ run: async (context) => {
3717
+ const settings = context.resolve(SLOTS.settingsAdmin) ?? context.resolve(SLOTS.settings);
3718
+ if (settings === void 0) return {
3719
+ kind: "message",
3720
+ key: "guard::permissions.unavailable",
3721
+ level: "error"
3722
+ };
3723
+ return show(settings);
3724
+ }
3725
+ },
3726
+ {
3727
+ path: ["permissions", "revoke"],
3728
+ summary: `${PERMISSIONS_COMMAND_OWNER}::permissions.revoke.summary`,
3729
+ group: "other",
3730
+ surfaces: ["cli"],
3731
+ argSpecs: [
3732
+ {
3733
+ name: "entry",
3734
+ kind: "value",
3735
+ isRequired: true
3736
+ },
3737
+ {
3738
+ name: "project",
3739
+ flag: "project",
3740
+ kind: "boolean"
3741
+ },
3742
+ {
3743
+ name: "global",
3744
+ flag: "global",
3745
+ kind: "boolean"
3746
+ }
3747
+ ],
3748
+ run: async (context, invocation) => {
3749
+ const settings = context.resolve(SLOTS.settingsAdmin) ?? context.resolve(SLOTS.settings);
3750
+ if (settings === void 0) return {
3751
+ kind: "message",
3752
+ key: "guard::permissions.unavailable",
3753
+ level: "error"
3754
+ };
3755
+ const entry = invocation.values.get("entry")?.[0];
3756
+ if (entry === void 0 || entry.length === 0) return {
3757
+ kind: "message",
3758
+ key: "guard::permissions.revoke.missing",
3759
+ level: "warning"
3760
+ };
3761
+ const selected = [];
3762
+ if (invocation.flags.has("global")) selected.push("global");
3763
+ if (invocation.flags.has("project")) selected.push("project");
3764
+ return revoke(settings, entry, selected.length > 0 ? selected : ["global", "project"]);
3765
+ }
3766
+ }
3767
+ ];
3768
+ }
3769
+
3770
+ //#endregion
3771
+ //#region src/component.ts
3772
+ const INVALID_SETTINGS_POLICY_NAME = "guard::invalid-settings";
3773
+ const INVALID_SETTINGS_PRIORITY = -2;
3774
+ const READONLY_TRUST_PRIORITY = -1;
3775
+ function createContributionFingerprint() {
3776
+ let unserializableSequence = 0;
3777
+ return (value) => {
3778
+ try {
3779
+ return JSON.stringify(value) ?? "undefined";
3780
+ } catch {
3781
+ unserializableSequence += 1;
3782
+ return `unserializable:${unserializableSequence}`;
3783
+ }
3784
+ };
3785
+ }
3786
+ const GUARD_FIELD_SPECS = Object.freeze({
3787
+ mode: PERMISSION_MODE_FIELD_SPEC,
3788
+ permissions: {
3789
+ key: "permissions",
3790
+ default: [],
3791
+ ownership: "trusted-project",
3792
+ parse: parsePermissionListSetting
3793
+ },
3794
+ alwaysAllow: {
3795
+ key: "permission.alwaysAllow",
3796
+ default: [],
3797
+ ownership: "trusted-project",
3798
+ parse: list,
3799
+ legacy: { aliases: ["permission_always_allow"] }
3800
+ },
3801
+ offeredScopes: {
3802
+ key: PERMISSION_OFFERED_SCOPES_KEY,
3803
+ default: [...DEFAULT_OFFERED_SCOPES],
3804
+ ownership: "trusted-project",
3805
+ legacy: { aliases: ["permission_offered_scopes"] },
3806
+ parse: (raw) => {
3807
+ if (!Array.isArray(raw)) return void 0;
3808
+ const valid = [
3809
+ "once",
3810
+ "session",
3811
+ "project",
3812
+ "global"
3813
+ ];
3814
+ const filtered = raw.filter((value) => typeof value === "string" && valid.includes(value));
3815
+ return filtered.length > 0 ? filtered : void 0;
3816
+ }
3817
+ }
3818
+ });
3819
+ function baselineModeOf(field, projectDefault) {
3820
+ return adoptPermissionModeOfField(field, projectDefault);
3821
+ }
3822
+ const Guard = defineComponent("Guard", (ctx, options) => {
3823
+ const hooks = ctx.consume(SLOTS.hooks);
3824
+ const settings = ctx.consume(SLOTS.settings);
3825
+ const hostOverrides = ctx.consume(SLOTS.hostSettingsOverrides);
3826
+ const sessions = ctx.consume(SLOTS.sessions);
3827
+ const projectTrust = ctx.maybe(SLOTS.projectTrust);
3828
+ const sandbox = ctx.maybe(SLOTS.sandbox);
3829
+ const toolCatalog = ctx.maybe(SLOTS.toolCatalog);
3830
+ const sandboxEscalation = ctx.resource("sandbox-escalation", () => createEscalationReceiptProtocol(options.id, sandbox), () => {}, {
3831
+ hmr: "preserve",
3832
+ validate: isSandboxEscalationPort
3833
+ });
3834
+ ctx.provide(SLOTS.sandboxEscalation, () => sandboxEscalation);
3835
+ for (const declaration of createPermissionsCommands()) {
3836
+ const key = commandContributionKey(PERMISSIONS_COMMAND_OWNER, declaration.path);
3837
+ ctx.contribute(SLOTS.commands, key, declaration);
3838
+ }
3839
+ const permissionAsk = ctx.maybe(SLOTS.permissionAsk);
3840
+ const grantState = ctx.resource("session-grants-state", () => createSessionMetaLedgerState(), () => {}, { hmr: "preserve" });
3841
+ const ledger = createSessionMetaLedger({
3842
+ sessions,
3843
+ read: (config) => config?.sessionGrants,
3844
+ write: (entries) => ({ sessionGrants: encodeGrants(entries) }),
3845
+ parse: decodeGrants,
3846
+ identity: sameGrant,
3847
+ onFailure: (phase, error) => {
3848
+ hooks().emitAndWait(TIMINGS.runtimeDiagnostic, {
3849
+ source: "guard",
3850
+ severity: "warning",
3851
+ message: `Grant ${phase} failed; retained for this session: ${String(error)}`
3852
+ }).catch(() => void 0);
3853
+ }
3854
+ }, grantState);
3855
+ const engine = ctx.resource("permission-engine", () => createPermissionEngine((id) => ledger.getLoaded(id)), () => {}, { hmr: "preserve" });
3856
+ const conditions = createPermissionConditionReader({
3857
+ engine,
3858
+ ledger,
3859
+ sessions,
3860
+ sandboxSnapshot: (cwd, executionRoot) => sandbox()?.snapshot({
3861
+ ...cwd === void 0 ? {} : { cwd },
3862
+ ...executionRoot === void 0 ? {} : { executionRoot }
3863
+ })
3864
+ });
3865
+ ctx.provide(SLOTS.permissionConditions, () => conditions);
3866
+ const permissionModeState = createPermissionModeStateReader(engine, { trustClamped: () => isTrustClamped() });
3867
+ ctx.provide(SLOTS.permissionModeState, () => permissionModeState.reader);
3868
+ ctx.effect(() => () => permissionModeState.setReady(false));
3869
+ ctx.effect(() => {
3870
+ const lease = engine.policies.contribute(BUILTIN_POLICY_OWNER, builtinPolicies({
3871
+ sandboxSnapshot: (cwd, executionRoot) => sandbox()?.snapshot({
3872
+ ...cwd !== void 0 ? { cwd } : {},
3873
+ ...executionRoot !== void 0 ? { executionRoot } : {}
3874
+ }),
3875
+ ...options.credentialRoots === void 0 ? {} : { credentialRoots: options.credentialRoots },
3876
+ ...options.cwd === void 0 ? {} : { workspaceRoot: options.cwd },
3877
+ ...options.home === void 0 ? {} : { home: options.home },
3878
+ ...options.ottoHome === void 0 ? {} : { ottoHome: options.ottoHome }
3879
+ }));
3880
+ return () => lease.dispose();
3881
+ });
3882
+ let fields;
3883
+ let guard;
3884
+ let lastSandboxPolicy;
3885
+ const projectKey = options.cwd === void 0 ? void 0 : workspaceKeyOf({ root: options.cwd });
3886
+ ctx.effect(() => {
3887
+ const mode = settings().registerField(GUARD_FIELD_SPECS.mode, "guard");
3888
+ const permissions = settings().registerField(GUARD_FIELD_SPECS.permissions, "guard");
3889
+ const alwaysAllow = settings().registerField(GUARD_FIELD_SPECS.alwaysAllow, "guard");
3890
+ const offeredScopes = settings().registerField(GUARD_FIELD_SPECS.offeredScopes, "guard");
3891
+ const projectModes = settings().registerField(PERMISSION_PROJECT_MODES_FIELD_SPEC, "guard");
3892
+ fields = {
3893
+ mode,
3894
+ permissions,
3895
+ alwaysAllow,
3896
+ offeredScopes,
3897
+ projectModes
3898
+ };
3899
+ return () => {
3900
+ fields = void 0;
3901
+ mode.dispose();
3902
+ permissions.dispose();
3903
+ alwaysAllow.dispose();
3904
+ offeredScopes.dispose();
3905
+ projectModes.dispose();
3906
+ };
3907
+ });
3908
+ const modeBelowClamp = () => {
3909
+ const mode = fields?.mode;
3910
+ if (mode === void 0) return void 0;
3911
+ const merged = [
3912
+ "env",
3913
+ "project",
3914
+ "global",
3915
+ "default"
3916
+ ].map((layer) => mode.get(layer)).find((value) => value !== void 0);
3917
+ if (merged === void 0) return;
3918
+ const readBelowClamp = (layer) => layer === void 0 ? merged : layer === "overrides" ? void 0 : mode.get(layer);
3919
+ return adoptPermissionMode(readBelowClamp).adopted;
3920
+ };
3921
+ let reconcileTrustClamp;
3922
+ const [isTrustClamped, setTrustClamped] = createSignal(false);
3923
+ ctx.effect(() => {
3924
+ const trust = projectTrust?.();
3925
+ const hostSettings = hostOverrides();
3926
+ const policyName = "guard::readonly-trust";
3927
+ let policyLease;
3928
+ let overlay;
3929
+ let cancelled = false;
3930
+ let bypassWarningIssued = false;
3931
+ const release = () => {
3932
+ overlay?.dispose();
3933
+ overlay = void 0;
3934
+ policyLease?.dispose();
3935
+ policyLease = void 0;
3936
+ setTrustClamped(false);
3937
+ };
3938
+ const applyTrust = (state, mode) => {
3939
+ if (cancelled) return;
3940
+ if (state.status === "decided" && state.record !== "readonly") {
3941
+ bypassWarningIssued = false;
3942
+ release();
3943
+ return;
3944
+ }
3945
+ if (mode !== void 0 && isUnrestrictedPermission(mode)) {
3946
+ release();
3947
+ if (!bypassWarningIssued) {
3948
+ bypassWarningIssued = true;
3949
+ hooks().emitAndWait(TIMINGS.runtimeDiagnostic, {
3950
+ source: "guard",
3951
+ severity: "warning",
3952
+ message: guardT("guard.trust.bypassUntrustedClampOff")
3953
+ }).catch(() => void 0);
3954
+ }
3955
+ return;
3956
+ }
3957
+ bypassWarningIssued = false;
3958
+ if (overlay !== void 0) return;
3959
+ policyLease = engine.policies.contribute(policyName, [{
3960
+ name: policyName,
3961
+ priority: READONLY_TRUST_PRIORITY,
3962
+ enabled: true,
3963
+ scope: {},
3964
+ safety: true,
3965
+ rules: [{
3966
+ name: "deny-untrusted-writes",
3967
+ effect: "deny",
3968
+ match: { condition: (context) => !context.readonly },
3969
+ denyReason: "This project is not trusted (read-only): every operation except read-only tools is denied. Trust this project and retry."
3970
+ }]
3971
+ }]);
3972
+ overlay = hostSettings.override({
3973
+ [PERMISSION_MODE_SETTING_KEY]: "readonly",
3974
+ [SANDBOX_NETWORK_SETTING_KEY]: "deny"
3975
+ }, policyName);
3976
+ setTrustClamped(true);
3977
+ };
3978
+ const state = trust === void 0 ? { status: "pending" } : trust.state();
3979
+ reconcileTrustClamp = (mode) => applyTrust(state, mode);
3980
+ applyTrust(state, untrack(modeBelowClamp));
3981
+ return () => {
3982
+ cancelled = true;
3983
+ reconcileTrustClamp = void 0;
3984
+ release();
3985
+ };
3986
+ });
3987
+ ctx.effect(() => {
3988
+ const mode = modeBelowClamp();
3989
+ reconcileTrustClamp?.(mode);
3990
+ });
3991
+ const pluginPolicies = ctx.consumeAll(SLOTS.permissionPolicies);
3992
+ const pluginLeases = /* @__PURE__ */ new Map();
3993
+ const contributionFingerprint = createContributionFingerprint();
3994
+ const diagnose = (severity, message) => {
3995
+ hooks().emitAndWait(TIMINGS.runtimeDiagnostic, {
3996
+ source: "guard",
3997
+ severity,
3998
+ message
3999
+ }).catch(() => void 0);
4000
+ };
4001
+ ctx.effect(() => () => {
4002
+ for (const held of pluginLeases.values()) held.lease.dispose();
4003
+ pluginLeases.clear();
4004
+ });
4005
+ ctx.effect(() => {
4006
+ const current = pluginPolicies();
4007
+ for (const [id, held] of pluginLeases) {
4008
+ if (current.has(id)) continue;
4009
+ held.lease.dispose();
4010
+ pluginLeases.delete(id);
4011
+ }
4012
+ for (const [id, value] of current) {
4013
+ const held = pluginLeases.get(id);
4014
+ const owner = `${PLUGIN_OWNER_PREFIX}${id}`;
4015
+ const fingerprint = contributionFingerprint(value);
4016
+ const compiled = /^[\w.@:-]+$/.test(id) ? compilePluginPolicies(owner, value) : {
4017
+ ok: false,
4018
+ reason: "contribution key must be a non-empty identifier"
4019
+ };
4020
+ if (!compiled.ok) {
4021
+ const reason = `Plugin permission policy "${id}" rejected: ${compiled.reason}`;
4022
+ if (held !== void 0 && held.kind === "valid") {
4023
+ if (held.failedFingerprint === fingerprint) continue;
4024
+ pluginLeases.set(id, {
4025
+ kind: "valid",
4026
+ lease: held.lease,
4027
+ fingerprint: held.fingerprint,
4028
+ failedFingerprint: fingerprint
4029
+ });
4030
+ diagnose("error", reason);
4031
+ continue;
4032
+ }
4033
+ if (held !== void 0 && held.kind === "failed") {
4034
+ if (held.fingerprint === fingerprint) continue;
4035
+ held.lease.replace([denyInvalidPluginPolicy(reason)]);
4036
+ pluginLeases.set(id, {
4037
+ kind: "failed",
4038
+ lease: held.lease,
4039
+ fingerprint
4040
+ });
4041
+ diagnose("error", reason);
4042
+ continue;
4043
+ }
4044
+ pluginLeases.set(id, {
4045
+ kind: "failed",
4046
+ lease: engine.policies.contribute(owner, [denyInvalidPluginPolicy(reason)]),
4047
+ fingerprint
4048
+ });
4049
+ diagnose("error", reason);
4050
+ continue;
4051
+ }
4052
+ if (held !== void 0 && held.kind === "valid" && held.fingerprint === fingerprint) continue;
4053
+ if (held !== void 0) {
4054
+ held.lease.replace(compiled.policies);
4055
+ pluginLeases.set(id, {
4056
+ kind: "valid",
4057
+ lease: held.lease,
4058
+ fingerprint
4059
+ });
4060
+ } else pluginLeases.set(id, {
4061
+ kind: "valid",
4062
+ lease: engine.policies.contribute(owner, compiled.policies),
4063
+ fingerprint
4064
+ });
4065
+ }
4066
+ });
4067
+ const settingsSync = createSettingsSync(engine, () => sandbox()?.snapshot().policy.allowedHosts ?? []);
4068
+ let lastDisabled;
4069
+ let invalidSettingsLease;
4070
+ let settingsApplied = false;
4071
+ let lastSettingsError;
4072
+ ctx.effect(() => () => {
4073
+ settingsSync.dispose();
4074
+ invalidSettingsLease?.dispose();
4075
+ invalidSettingsLease = void 0;
4076
+ });
4077
+ ctx.effect(() => {
4078
+ const mode = fields?.mode;
4079
+ if (mode === void 0) {
4080
+ permissionModeState.setReady(false);
4081
+ return;
4082
+ }
4083
+ const baseline = baselineModeOf(mode, projectPermissionModeOf(fields?.projectModes.get(), projectKey));
4084
+ engine.setBaseline(baseline.adopted);
4085
+ engine.setFloor(isTrustClamped() ? "readonly" : mode.get("project"));
4086
+ if (baseline.ignoredProjectBypass) diagnose("warning", guardT("guard.mode.projectBypassIgnored"));
4087
+ permissionModeState.setReady(true);
4088
+ return () => permissionModeState.setReady(false);
4089
+ });
4090
+ ctx.effect(() => {
4091
+ if (!fields) return;
4092
+ try {
4093
+ const snapshot = readPermissionSettings(fields);
4094
+ const notes = settingsSync.apply(snapshot);
4095
+ const disabled = notes.length === 0 ? void 0 : notes.join("; ");
4096
+ if (disabled !== void 0 && disabled !== lastDisabled) diagnose("warning", `Permission rules could not be compiled: ${disabled}`);
4097
+ lastDisabled = disabled;
4098
+ invalidSettingsLease?.dispose();
4099
+ invalidSettingsLease = void 0;
4100
+ settingsApplied = true;
4101
+ lastSettingsError = void 0;
4102
+ } catch (error) {
4103
+ if (!settingsApplied && invalidSettingsLease === void 0) invalidSettingsLease = engine.policies.contribute(INVALID_SETTINGS_POLICY_NAME, [{
4104
+ name: INVALID_SETTINGS_POLICY_NAME,
4105
+ priority: INVALID_SETTINGS_PRIORITY,
4106
+ enabled: true,
4107
+ scope: {},
4108
+ safety: true,
4109
+ rules: [{
4110
+ name: "deny-invalid-settings",
4111
+ effect: "deny",
4112
+ match: {},
4113
+ denyReason: "Invalid permission settings; correct the configuration before continuing.",
4114
+ safety: true
4115
+ }]
4116
+ }]);
4117
+ const message = `Permission settings rejected; ${settingsApplied ? "previous policies retained" : "tools blocked"}: ${error instanceof Error ? error.message : String(error)}`;
4118
+ if (message !== lastSettingsError) {
4119
+ lastSettingsError = message;
4120
+ hooks().emitAndWait(TIMINGS.runtimeDiagnostic, {
4121
+ source: "guard",
4122
+ severity: "error",
4123
+ message
4124
+ }).catch(() => void 0);
4125
+ }
4126
+ }
4127
+ });
4128
+ const runOverrides = /* @__PURE__ */ new Map();
4129
+ const overridePort = {
4130
+ get: (sessionId) => runOverrides.get(sessionId),
4131
+ set: (sessionId, mode) => {
4132
+ if (mode === void 0) runOverrides.delete(sessionId);
4133
+ else runOverrides.set(sessionId, mode);
4134
+ },
4135
+ clear: () => runOverrides.clear()
4136
+ };
4137
+ ctx.provide(SLOTS.permissionRunOverride, () => overridePort);
4138
+ ctx.effect(() => {
4139
+ const guardGeneration = {};
4140
+ const authorizations = /* @__PURE__ */ new WeakSet();
4141
+ const hook = createGuardHook({
4142
+ guardGeneration,
4143
+ authorizations,
4144
+ engine,
4145
+ ledger,
4146
+ sessions,
4147
+ runtimePermissionOverride: () => ctx.maybe(SLOTS.permissionRunOverride)(),
4148
+ permissionAsk: () => permissionAsk(),
4149
+ home: options.home ?? homedir(),
4150
+ toolIdentity: (toolName) => toolCatalog?.()?.get(toolName)?.tool.identity,
4151
+ diagnose: (message) => diagnose("warning", message),
4152
+ sandboxSnapshot: (cwd, executionRoot) => sandbox()?.snapshot({
4153
+ ...cwd !== void 0 ? { cwd } : {},
4154
+ ...executionRoot !== void 0 ? { executionRoot } : {}
4155
+ }),
4156
+ sandboxPort: () => sandbox(),
4157
+ sandboxBackend: () => {
4158
+ const state = sandbox()?.snapshot().state;
4159
+ return state?.kind === "enforced" ? state.backend : void 0;
4160
+ },
4161
+ ...fields !== void 0 ? {
4162
+ alwaysAllowField: fields.alwaysAllow,
4163
+ offeredScopesField: fields.offeredScopes
4164
+ } : {}
4165
+ });
4166
+ guard = hook;
4167
+ const executeVerifier = createGuardExecuteVerifier({
4168
+ guardGeneration,
4169
+ authorizations,
4170
+ engine,
4171
+ ledger,
4172
+ sessions,
4173
+ runtimePermissionOverride: () => ctx.maybe(SLOTS.permissionRunOverride)(),
4174
+ toolIdentity: (toolName) => toolCatalog?.()?.get(toolName)?.tool.identity,
4175
+ sandboxSnapshot: (cwd, executionRoot) => sandbox()?.snapshot({
4176
+ ...cwd !== void 0 ? { cwd } : {},
4177
+ ...executionRoot !== void 0 ? { executionRoot } : {}
4178
+ }),
4179
+ sandboxPort: () => sandbox(),
4180
+ sandboxBackend: () => {
4181
+ const state = sandbox()?.snapshot().state;
4182
+ return state?.kind === "enforced" ? state.backend : void 0;
4183
+ }
4184
+ });
4185
+ ctx.contribute(`hook:${hook.timing}`, hook.name, hook);
4186
+ ctx.contribute(`hook:${executeVerifier.timing}`, executeVerifier.name, executeVerifier);
4187
+ ctx.contribute(`hook:${TIMINGS.agentSessionDetached}`, "guard::session-detached", {
4188
+ name: "guard::session-detached",
4189
+ timing: TIMINGS.agentSessionDetached,
4190
+ kind: "observer",
4191
+ handle: (input) => {
4192
+ hook.cancelPending(input.sessionId);
4193
+ ledger.forgetSession(input.sessionId);
4194
+ }
4195
+ });
4196
+ return () => {
4197
+ hook.dispose();
4198
+ executeVerifier.dispose();
4199
+ guard = void 0;
4200
+ };
4201
+ });
4202
+ ctx.effect(() => {
4203
+ const port = sandbox();
4204
+ if (port === void 0) return;
4205
+ const snapshot = port.snapshot(options.cwd !== void 0 ? { cwd: options.cwd } : void 0);
4206
+ const key = `${String(snapshot.revision)}|${authorityIdOf(snapshot.state)}`;
4207
+ if (lastSandboxPolicy === void 0) {
4208
+ lastSandboxPolicy = key;
4209
+ return;
4210
+ }
4211
+ if (key !== lastSandboxPolicy) {
4212
+ lastSandboxPolicy = key;
4213
+ guard?.cancelPending();
4214
+ }
4215
+ });
4216
+ });
4217
+
4218
+ //#endregion
4219
+ export { GUARD_FIELD_SPECS, Guard, PROTECTED_RESOURCES, PROTECTION_RULES, askReasonText, classifyPath, commandPatternToSpecifier, createPathNormalizer, createPermissionsCommands, migratePermissions, pathPatternToSpecifier, ruleKey };