@inkeep/open-knowledge 0.0.0-dev-20260430215257 → 0.0.0-dev-20260430220014

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.
Files changed (37) hide show
  1. package/dist/cli.mjs +225 -223
  2. package/dist/constants-BJgA-R9A.mjs +2 -0
  3. package/dist/{dist-CSvz1VhR.mjs → dist-7GgIDlwG.mjs} +24 -24
  4. package/dist/{dist-U4KUxqv5.mjs → dist-BnZHVzE4.mjs} +1 -1
  5. package/dist/index.mjs +1 -1
  6. package/dist/{init-CoBzPU71.mjs → init-4hOSMFgg.mjs} +3 -3
  7. package/dist/init-74HGAC-m.mjs +1 -0
  8. package/dist/init-D0BylGY2.mjs +1 -0
  9. package/dist/{init-Do3bEm3B.mjs → init-DTaM2KXE.mjs} +2 -2
  10. package/dist/loader-CcIQcrAC.mjs +1 -0
  11. package/dist/{loader-BegmfMFA.mjs → loader-xw-iBLcB.mjs} +2 -2
  12. package/dist/paths-CTQx5S3f.mjs +2 -0
  13. package/dist/paths-EnLHpVly.mjs +1 -0
  14. package/dist/preview-CfADaMr4.mjs +1 -0
  15. package/dist/{preview-BREahqzv.mjs → preview-mARzyxNL.mjs} +2 -2
  16. package/dist/public/assets/{ActivityModeContent-CUpTfvqt.js → ActivityModeContent-DWssAqaG.js} +1 -1
  17. package/dist/public/assets/{DocumentContext-CS3dbEFb.js → DocumentContext-GbmGcVzS.js} +1 -1
  18. package/dist/public/assets/{SettingsPane-C5lIVObs.js → SettingsPane-HKf0Vtow.js} +1 -1
  19. package/dist/public/assets/{SourceEditor-PEgx-NCm.js → SourceEditor-D5eu9Dbl.js} +1 -1
  20. package/dist/public/assets/{clipboard-CvirH7Hp.js → clipboard-D2LwhWD3.js} +1 -1
  21. package/dist/public/assets/{config-validation-events-Irg9X5oj.js → config-validation-events-5erczoJ8.js} +1 -1
  22. package/dist/public/assets/index-MyoVlmF1.js +1840 -0
  23. package/dist/public/index.html +4 -4
  24. package/dist/src-4CHmk5b7.mjs +1 -0
  25. package/dist/{start-C3TQYA3J.mjs → start-B6JuLc0Q.mjs} +2 -2
  26. package/dist/start-BneKCKPF.mjs +1 -0
  27. package/package.json +1 -1
  28. package/dist/constants-CKleSPG-.mjs +0 -2
  29. package/dist/init-BN0U8twb.mjs +0 -1
  30. package/dist/init-CZrCa_vj.mjs +0 -1
  31. package/dist/loader-QaZ7INwj.mjs +0 -1
  32. package/dist/paths-opiKEaCC.mjs +0 -2
  33. package/dist/paths-rUSBGS5c.mjs +0 -1
  34. package/dist/preview-D3e-de44.mjs +0 -1
  35. package/dist/public/assets/index-C947BPi_.js +0 -1840
  36. package/dist/src-Cwx2WBLv.mjs +0 -1
  37. package/dist/start-B00zNiq_.mjs +0 -1
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{i as e,o as t,t as n}from"./chunk-FK9Q3tQk.mjs";import{t as r}from"./esm-wByiX8MO.mjs";import{$ as i,A as a,At as o,Ct as s,Ft as c,I as l,It as u,Lt as d,Mt as f,N as p,Nt as m,Ot as h,Pt as g,Q as _,Rt as v,St as y,Tt as b,_t as x,bt as S,ct as ee,dt as te,ft as ne,g as re,gt as C,ht as w,jt as ie,kt as ae,lt as T,mt as E,n as oe,ot as se,pt as ce,st as le,ut as ue,v as de,vt as fe,wt as pe,x as me,xt as D,y as he,yt as ge}from"./dist-BEzp6mq0.mjs";import{n as _e,r as ve,t as ye}from"./dist-bundle-BSdjl7Rj.mjs";import{i as be,r as xe}from"./constants-CKleSPG-.mjs";import{n as Se,t as Ce}from"./paths-opiKEaCC.mjs";import{l as we,o as Te,s as Ee}from"./server-lock-n3Y5JWNv-3o7br8XE.mjs";import{i as De}from"./git-handle-BhGnmvTB-BMB_49Sb.mjs";import{A as Oe,C as ke,Ct as Ae,Et as je,F as Me,an as Ne,in as Pe,nn as Fe,on as Ie,rn as Le}from"./dist-CSvz1VhR.mjs";import{a as Re,i as ze,n as Be,t as Ve}from"./server-C3JdctFI.mjs";import{t as He}from"./is-object-CEU0BgQ5.mjs";import{i as Ue,n as We,r as Ge,t as Ke}from"./loader-BegmfMFA.mjs";import{r as qe}from"./init-CoBzPU71.mjs";import{i as Je,n as Ye,o as Xe,r as Ze,s as Qe,t as $e}from"./colors-BdAXRiXe.mjs";import{t as et}from"./chunk-YNYSPYQ5-CzQORSqg.mjs";import{a as tt,c as nt,d as rt,f as it,h as at,i as ot,l as st,m as ct,n as lt,o as ut,p as dt,r as ft,s as pt,t as mt,u as ht}from"./chunk-GFQRA5P5-BHvTMkvm.mjs";import{A as gt,B as _t,C as vt,D as yt,E as bt,F as xt,H as St,I as Ct,L as wt,M as Tt,N as Et,O as Dt,P as Ot,S as kt,T as At,V as jt,_ as Mt,a as Nt,b as Pt,c as Ft,d as It,f as O,g as Lt,h as Rt,i as zt,j as Bt,k as Vt,l as Ht,m as Ut,n as Wt,o as Gt,p as Kt,r as qt,s as Jt,t as Yt,u as Xt,v as Zt,w as Qt,x as $t,y as en,z as tn}from"./chunk-FEIOJCZD-BWy7d-Eh.mjs";import{a as nn,c as rn,d as an,i as on,l as sn,n as cn,o as ln,r as un,s as k,t as dn,u as fn}from"./chunk-XHM67O4N-CAZ8iQv5.mjs";import{n as pn,r as mn,t as hn}from"./chunk-R6VWJ2ZL-Bz4BqhV-.mjs";import{r as gn}from"./chunk-CWQS3NFK-7eq8cfme.mjs";import"./chunk-DXB73IDG-B5N_TdmL.mjs";import{n as _n,t as vn}from"./chunk-5QMZ5MUS-O2hLndhl.mjs";import{n as yn,t as bn}from"./chunk-A5O5YHGN-Bb__rfH8.mjs";import{n as xn,r as Sn,t as Cn}from"./chunk-OJDRYQWQ-D39lhrQA.mjs";import{r as wn,t as Tn}from"./chunk-24IMIIXA-B3GEYoJz.mjs";import{n as En}from"./chunk-3THT3N7L-DTzOHNvT.mjs";import{t as Dn}from"./chunk-44UOCSGV-D5MNKiyC.mjs";import{o as On,s as kn}from"./start-C3TQYA3J.mjs";import"./src-Cwx2WBLv.mjs";import{execFileSync as An,spawn as jn}from"node:child_process";import*as Mn from"node:path";import Nn,{basename as Pn,dirname as Fn,isAbsolute as In,join as Ln,relative as Rn,resolve as zn}from"node:path";import*as A from"node:fs";import{appendFileSync as Bn,closeSync as Vn,existsSync as Hn,mkdirSync as Un,openSync as Wn,readFileSync as Gn,readdirSync as Kn,realpathSync as qn,statSync as Jn,unlinkSync as Yn,writeFileSync as Xn}from"node:fs";import Zn from"node:process";import{homedir as Qn,hostname as $n,platform as er}from"node:os";import{AsyncLocalStorage as tr,AsyncResource as nr}from"node:async_hooks";import{stripVTControlCharacters as rr,styleText as ir}from"node:util";import*as ar from"node:readline";import{fileURLToPath as or}from"node:url";import{randomUUID as sr}from"node:crypto";import{mkdir as cr,readFile as lr,readdir as ur,stat as dr}from"node:fs/promises";import{setTimeout as fr}from"node:timers/promises";import{createServer as pr,request as mr}from"node:http";import{lookup as hr}from"node:dns";import{createInterface as gr}from"node:readline/promises";var _r=v();const vr=`open-knowledge`;var yr=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(vr,e).getPassword();return n==null?null:JSON.parse(n)}catch{return null}}async set(e,t,n,r){let{Entry:i}=await import(`@napi-rs/keyring`),a=new i(vr,e),o={login:t,token:n,...r};a.setPassword(JSON.stringify(o))}async clear(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{new t(vr,e).deletePassword()}catch{}}},br=class{backend=`file`;authFile;constructor(e){this.authFile=e??Ln(Qn(),`.open-knowledge`,`auth.yml`)}read(){if(!Hn(this.authFile))return{};try{return(0,_r.parse)(Gn(this.authFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=Fn(this.authFile);Hn(t)||Un(t,{recursive:!0,mode:448}),Xn(this.authFile,(0,_r.stringify)(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}};async function xr(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(vr,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
2
+ import{i as e,o as t,t as n}from"./chunk-FK9Q3tQk.mjs";import{t as r}from"./esm-wByiX8MO.mjs";import{$ as i,A as a,At as o,Ct as s,Ft as c,I as l,It as u,Lt as d,Mt as f,N as p,Nt as m,Ot as h,Pt as g,Q as _,Rt as v,St as y,Tt as b,_t as x,bt as S,ct as ee,dt as te,ft as ne,g as re,gt as C,ht as w,jt as ie,kt as ae,lt as T,mt as E,n as oe,ot as se,pt as ce,st as le,ut as ue,v as de,vt as fe,wt as pe,x as me,xt as D,y as he,yt as ge}from"./dist-BEzp6mq0.mjs";import{n as _e,r as ve,t as ye}from"./dist-bundle-BSdjl7Rj.mjs";import{i as be,r as xe}from"./constants-BJgA-R9A.mjs";import{n as Se,t as Ce}from"./paths-CTQx5S3f.mjs";import{l as we,o as Te,s as Ee}from"./server-lock-n3Y5JWNv-3o7br8XE.mjs";import{i as De}from"./git-handle-BhGnmvTB-BMB_49Sb.mjs";import{A as Oe,C as ke,Ct as Ae,Et as je,F as Me,an as Ne,in as Pe,nn as Fe,on as Ie,rn as Le}from"./dist-7GgIDlwG.mjs";import{a as Re,i as ze,n as Be,t as Ve}from"./server-C3JdctFI.mjs";import{t as He}from"./is-object-CEU0BgQ5.mjs";import{i as Ue,n as We,r as Ge,t as Ke}from"./loader-xw-iBLcB.mjs";import{r as qe}from"./init-4hOSMFgg.mjs";import{i as Je,n as Ye,o as Xe,r as Ze,s as Qe,t as $e}from"./colors-BdAXRiXe.mjs";import{t as et}from"./chunk-YNYSPYQ5-CzQORSqg.mjs";import{a as tt,c as nt,d as rt,f as it,h as at,i as ot,l as st,m as ct,n as lt,o as ut,p as dt,r as ft,s as pt,t as mt,u as ht}from"./chunk-GFQRA5P5-BHvTMkvm.mjs";import{A as gt,B as _t,C as vt,D as yt,E as bt,F as xt,H as St,I as Ct,L as wt,M as Tt,N as Et,O as Dt,P as Ot,S as kt,T as At,V as jt,_ as Mt,a as Nt,b as Pt,c as Ft,d as It,f as O,g as Lt,h as Rt,i as zt,j as Bt,k as Vt,l as Ht,m as Ut,n as Wt,o as Gt,p as Kt,r as qt,s as Jt,t as Yt,u as Xt,v as Zt,w as Qt,x as $t,y as en,z as tn}from"./chunk-FEIOJCZD-BWy7d-Eh.mjs";import{a as nn,c as rn,d as an,i as on,l as sn,n as cn,o as ln,r as un,s as k,t as dn,u as fn}from"./chunk-XHM67O4N-CAZ8iQv5.mjs";import{n as pn,r as mn,t as hn}from"./chunk-R6VWJ2ZL-Bz4BqhV-.mjs";import{r as gn}from"./chunk-CWQS3NFK-7eq8cfme.mjs";import"./chunk-DXB73IDG-B5N_TdmL.mjs";import{n as _n,t as vn}from"./chunk-5QMZ5MUS-O2hLndhl.mjs";import{n as yn,t as bn}from"./chunk-A5O5YHGN-Bb__rfH8.mjs";import{n as xn,r as Sn,t as Cn}from"./chunk-OJDRYQWQ-D39lhrQA.mjs";import{r as wn,t as Tn}from"./chunk-24IMIIXA-B3GEYoJz.mjs";import{n as En}from"./chunk-3THT3N7L-DTzOHNvT.mjs";import{t as Dn}from"./chunk-44UOCSGV-D5MNKiyC.mjs";import{o as On,s as kn}from"./start-B6JuLc0Q.mjs";import"./src-4CHmk5b7.mjs";import{execFileSync as An,spawn as jn}from"node:child_process";import*as Mn from"node:path";import Nn,{basename as Pn,dirname as Fn,isAbsolute as In,join as Ln,relative as Rn,resolve as zn}from"node:path";import*as A from"node:fs";import{appendFileSync as Bn,closeSync as Vn,existsSync as Hn,mkdirSync as Un,openSync as Wn,readFileSync as Gn,readdirSync as Kn,realpathSync as qn,statSync as Jn,unlinkSync as Yn,writeFileSync as Xn}from"node:fs";import Zn from"node:process";import{homedir as Qn,hostname as $n,platform as er}from"node:os";import{AsyncLocalStorage as tr,AsyncResource as nr}from"node:async_hooks";import{stripVTControlCharacters as rr,styleText as ir}from"node:util";import*as ar from"node:readline";import{fileURLToPath as or}from"node:url";import{randomUUID as sr}from"node:crypto";import{mkdir as cr,readFile as lr,readdir as ur,stat as dr}from"node:fs/promises";import{setTimeout as fr}from"node:timers/promises";import{createServer as pr,request as mr}from"node:http";import{lookup as hr}from"node:dns";import{createInterface as gr}from"node:readline/promises";var _r=v();const vr=`open-knowledge`;var yr=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(vr,e).getPassword();return n==null?null:JSON.parse(n)}catch{return null}}async set(e,t,n,r){let{Entry:i}=await import(`@napi-rs/keyring`),a=new i(vr,e),o={login:t,token:n,...r};a.setPassword(JSON.stringify(o))}async clear(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{new t(vr,e).deletePassword()}catch{}}},br=class{backend=`file`;authFile;constructor(e){this.authFile=e??Ln(Qn(),`.open-knowledge`,`auth.yml`)}read(){if(!Hn(this.authFile))return{};try{return(0,_r.parse)(Gn(this.authFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=Fn(this.authFile);Hn(t)||Un(t,{recursive:!0,mode:448}),Xn(this.authFile,(0,_r.stringify)(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}};async function xr(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(vr,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
3
3
  `),new yr}catch{return process.stderr.write(`[auth] token storage: file (~/.open-knowledge/auth.yml)
4
4
  `),new br(e)}}async function Sr(e,t,n){let r=Cr(await wr(e)).host??``;if(!r)return 1;let i=await n.get(r);if(i==null)return 1;let a=e=>e.replace(/[\r\n]/g,``);return t.write(`username=${a(i.login)}\npassword=${a(i.token)}\n`),0}function Cr(e){let t={};for(let n of e.split(`
5
5
  `)){let e=n.trim();if(e===``)continue;let r=e.indexOf(`=`);r!==-1&&(t[e.slice(0,r)]=e.slice(r+1))}return t}function wr(e){return new Promise((t,n)=>{let r=[];e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r).toString(`utf-8`))),e.on(`error`,n)})}function Tr(e){let t=new r(`git-credential`);return t.description(`Git credential helper (git credential-helper protocol)`),t.command(`get`).description(`Lookup credentials from TokenStore (called by git)`).action(async()=>{let t=await e(),n=await Sr(process.stdin,process.stdout,t);process.exit(n)}),t}function Er(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function Dr(e,t,n){let r={baseUrl:Er(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new _e(`${i.data.error_description} (${i.data.error}, ${i.data.error_uri})`,400,{request:e.endpoint.merge(t,r)});throw n.response=i,n}return i}async function Or(e){let t=e.request||ye,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),Dr(t,`POST /login/device/code`,n)}async function kr(e){let t=await Dr(e.request||ye,`POST /login/oauth/access_token`,{client_id:e.clientId,device_code:e.code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`}),n={clientType:e.clientType,clientId:e.clientId,token:t.data.access_token,scopes:t.data.scope.split(/\s+/).filter(Boolean)};if(`clientSecret`in e&&(n.clientSecret=e.clientSecret),e.clientType===`github-app`){if(`refresh_token`in t.data){let e=new Date(t.headers.date).getTime();n.refreshToken=t.data.refresh_token,n.expiresAt=Ar(e,t.data.expires_in),n.refreshTokenExpiresAt=Ar(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function Ar(e,t){return new Date(e+t*1e3).toISOString()}async function jr(e,t){let n=Mr(e,t.auth);if(n)return n;let{data:r}=await Or({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await Pr(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function Mr(e,t){if(t.refresh===!0||!e.authentication)return!1;if(e.clientType===`github-app`)return e.authentication;let n=e.authentication;return(`scopes`in t&&t.scopes||e.scopes).join(` `)===n.scopes.join(` `)?n:!1}async function Nr(e){await new Promise(t=>setTimeout(t,e*1e3))}async function Pr(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await kr({...i,clientType:`oauth-app`}):await kr({...i,clientType:`github-app`});return{type:`token`,tokenType:`oauth`,...a}}catch(i){if(!i.response)throw i;let a=i.response.data.error;if(a===`authorization_pending`)return await Nr(r.interval),Pr(e,t,n,r);if(a===`slow_down`)return await Nr(r.interval+7),Pr(e,t,n,r);throw i}}async function Fr(e,t){return jr(e,{auth:t})}async function Ir(e,t,n,r){let i=t.endpoint.merge(n,r);if(/\/login\/(oauth\/access_token|device\/code)$/.test(i.url))return t(i);let{token:a}=await jr(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var Lr=`0.0.0-development`;function Rr(e){let t=e.request||ye.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${Lr} ${ve()}`}}),{request:n=t,...r}=e,i=e.clientType===`github-app`?{...r,clientType:`github-app`,request:n}:{...r,clientType:`oauth-app`,request:n,scopes:e.scopes||[]};if(!e.clientId)throw Error(`[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)`);if(!e.onVerification)throw Error(`[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)`);return Object.assign(Fr.bind(null,i),{hook:Ir.bind(null,i)})}async function zr(e){let{clientId:t,scopes:n=[`repo`,`read:user`,`user:email`],onVerification:r,host:i}=e,a=i&&i!==`github.com`?`https://${i}/api/v3`:`https://api.github.com`,o=Rr({clientType:`oauth-app`,clientId:t,scopes:n,onVerification:async e=>{await r({verificationUri:e.verification_uri,userCode:e.user_code,expiresIn:e.expires_in,interval:e.interval})},request:a===`https://api.github.com`?void 0:(await import(`./dist-bundle-BmF5_Mcp.mjs`)).request.defaults({baseUrl:a})}),s;try{s=await o({type:`oauth`})}catch(e){if(e instanceof Error){let t=e.message.toLowerCase();throw t.includes(`access_denied`)?Error(`Device-flow authorization was denied.`):t.includes(`expired_token`)||t.includes(`timeout`)||t.includes(`timed out`)?Error(`Device-flow code expired before authorization — please try again.`):Error(`GitHub sign-in failed: ${e.message}`)}throw e}return{token:s.token,tokenType:s.tokenType,scopes:s.scopes??[]}}function Br(e){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??e?.github?.oauthAppClientId??`Ov23liqlSd0V1MwR6rhI`}const Vr=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function Hr(e){let t=e.toLowerCase().replace(/:\d+$/,``);Vr.has(t)&&(process.stderr.write(`Error: ${e} is not a GitHub host. Only GitHub and GitHub Enterprise Server are supported.\n`),process.exit(1))}function Ur(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Wr(e,t,n,r=zr){let i=Br(n),{host:a,json:o}=e;Hr(a),o||process.stderr.write(`Logging in to ${a}…\n`);let s=await r({clientId:i,host:a===`github.com`?void 0:a,onVerification:e=>{e.userCode,e.verificationUri,o?Ur(!0,{type:`verification`,user_code:e.userCode,verification_uri:e.verificationUri,expires_in:e.expiresIn}):process.stderr.write(`Open: ${e.verificationUri}\nEnter code: ${e.userCode}\n`)}}),c=`unknown`,l,u;try{let e=a===`github.com`?`https://api.github.com`:`https://${a}/api/v3`,t=await fetch(`${e}/user`,{headers:{Authorization:`Bearer ${s.token}`,"User-Agent":`open-knowledge-cli`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();c=e.login??c,l=e.name??void 0,u=e.email??void 0}}catch{}await t.set(a,c,s.token,{gitProtocol:`https`,name:l,email:u}),o?Ur(!0,{type:`complete`,host:a,login:c}):process.stderr.write(`✓ Logged in as ${c} on ${a}\n`)}function Gr(e,t){return new r(`login`).description(`Authenticate with GitHub via Device Flow`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSONL progress events`,!1).action(async n=>{await Wr(n,await t(),e())})}const Kr=e=>e.name===`enter`||e.name===`return`;var qr=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},Jr=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},Yr=class extends Error{name=`ExitPromptError`},Xr=class extends Error{name=`HookError`},Zr=class extends Error{name=`ValidationError`};const Qr=new tr;function $r(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function ei(e,t){let n=$r(e);return Qr.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function ti(){let e=Qr.getStore();if(!e)throw new Xr(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function ni(){return ti().rl}function ri(e){return nr.bind((...t)=>{let n=ti(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function ii(e){let t=ti(),{index:n}=t,r=e({get(){return t.hooks[n]},set(e){t.hooks[n]=e},initialized:n in t.hooks});return t.index++,r}function ai(){ti().handleChange()}const oi={queue(e){let t=ti(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(ni());if(r!=null&&typeof r!=`function`)throw new Zr(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=ti();ri(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=ti();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function si(e){return typeof e==`function`}function ci(e){return ii(t=>{let n=nr.bind(function(e){t.get()!==e&&(t.set(e),ai())});if(t.initialized)return[t.get(),n];let r=si(e)?e():e;return t.set(r),[r,n]})}function li(e,t){ii(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&oi.queue(e),n.set(t)})}function ui(){return Zn.platform.startsWith(`win`)?!!Zn.env.CI||!!Zn.env.WT_SESSION||!!Zn.env.TERMINUS_SUBLIME||Zn.env.ConEmuTask===`{cmd::Cmder}`||Zn.env.TERM_PROGRAM===`Terminus-Sublime`||Zn.env.TERM_PROGRAM===`vscode`||Zn.env.TERM===`xterm-256color`||Zn.env.TERM===`alacritty`||Zn.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:Zn.env.TERM!==`linux`}const di={circleQuestionMark:`(?)`,questionMarkPrefix:`(?)`,square:`█`,squareDarkShade:`▓`,squareMediumShade:`▒`,squareLightShade:`░`,squareTop:`▀`,squareBottom:`▄`,squareLeft:`▌`,squareRight:`▐`,squareCenter:`■`,bullet:`●`,dot:`․`,ellipsis:`…`,pointerSmall:`›`,triangleUp:`▲`,triangleUpSmall:`▴`,triangleDown:`▼`,triangleDownSmall:`▾`,triangleLeftSmall:`◂`,triangleRightSmall:`▸`,home:`⌂`,heart:`♥`,musicNote:`♪`,musicNoteBeamed:`♫`,arrowUp:`↑`,arrowDown:`↓`,arrowLeft:`←`,arrowRight:`→`,arrowLeftRight:`↔`,arrowUpDown:`↕`,almostEqual:`≈`,notEqual:`≠`,lessOrEqual:`≤`,greaterOrEqual:`≥`,identical:`≡`,infinity:`∞`,subscriptZero:`₀`,subscriptOne:`₁`,subscriptTwo:`₂`,subscriptThree:`₃`,subscriptFour:`₄`,subscriptFive:`₅`,subscriptSix:`₆`,subscriptSeven:`₇`,subscriptEight:`₈`,subscriptNine:`₉`,oneHalf:`½`,oneThird:`⅓`,oneQuarter:`¼`,oneFifth:`⅕`,oneSixth:`⅙`,oneEighth:`⅛`,twoThirds:`⅔`,twoFifths:`⅖`,threeQuarters:`¾`,threeFifths:`⅗`,threeEighths:`⅜`,fourFifths:`⅘`,fiveSixths:`⅚`,fiveEighths:`⅝`,sevenEighths:`⅞`,line:`─`,lineBold:`━`,lineDouble:`═`,lineDashed0:`┄`,lineDashed1:`┅`,lineDashed2:`┈`,lineDashed3:`┉`,lineDashed4:`╌`,lineDashed5:`╍`,lineDashed6:`╴`,lineDashed7:`╶`,lineDashed8:`╸`,lineDashed9:`╺`,lineDashed10:`╼`,lineDashed11:`╾`,lineDashed12:`−`,lineDashed13:`–`,lineDashed14:`‐`,lineDashed15:`⁃`,lineVertical:`│`,lineVerticalBold:`┃`,lineVerticalDouble:`║`,lineVerticalDashed0:`┆`,lineVerticalDashed1:`┇`,lineVerticalDashed2:`┊`,lineVerticalDashed3:`┋`,lineVerticalDashed4:`╎`,lineVerticalDashed5:`╏`,lineVerticalDashed6:`╵`,lineVerticalDashed7:`╷`,lineVerticalDashed8:`╹`,lineVerticalDashed9:`╻`,lineVerticalDashed10:`╽`,lineVerticalDashed11:`╿`,lineDownLeft:`┐`,lineDownLeftArc:`╮`,lineDownBoldLeftBold:`┓`,lineDownBoldLeft:`┒`,lineDownLeftBold:`┑`,lineDownDoubleLeftDouble:`╗`,lineDownDoubleLeft:`╖`,lineDownLeftDouble:`╕`,lineDownRight:`┌`,lineDownRightArc:`╭`,lineDownBoldRightBold:`┏`,lineDownBoldRight:`┎`,lineDownRightBold:`┍`,lineDownDoubleRightDouble:`╔`,lineDownDoubleRight:`╓`,lineDownRightDouble:`╒`,lineUpLeft:`┘`,lineUpLeftArc:`╯`,lineUpBoldLeftBold:`┛`,lineUpBoldLeft:`┚`,lineUpLeftBold:`┙`,lineUpDoubleLeftDouble:`╝`,lineUpDoubleLeft:`╜`,lineUpLeftDouble:`╛`,lineUpRight:`└`,lineUpRightArc:`╰`,lineUpBoldRightBold:`┗`,lineUpBoldRight:`┖`,lineUpRightBold:`┕`,lineUpDoubleRightDouble:`╚`,lineUpDoubleRight:`╙`,lineUpRightDouble:`╘`,lineUpDownLeft:`┤`,lineUpBoldDownBoldLeftBold:`┫`,lineUpBoldDownBoldLeft:`┨`,lineUpDownLeftBold:`┥`,lineUpBoldDownLeftBold:`┩`,lineUpDownBoldLeftBold:`┪`,lineUpDownBoldLeft:`┧`,lineUpBoldDownLeft:`┦`,lineUpDoubleDownDoubleLeftDouble:`╣`,lineUpDoubleDownDoubleLeft:`╢`,lineUpDownLeftDouble:`╡`,lineUpDownRight:`├`,lineUpBoldDownBoldRightBold:`┣`,lineUpBoldDownBoldRight:`┠`,lineUpDownRightBold:`┝`,lineUpBoldDownRightBold:`┡`,lineUpDownBoldRightBold:`┢`,lineUpDownBoldRight:`┟`,lineUpBoldDownRight:`┞`,lineUpDoubleDownDoubleRightDouble:`╠`,lineUpDoubleDownDoubleRight:`╟`,lineUpDownRightDouble:`╞`,lineDownLeftRight:`┬`,lineDownBoldLeftBoldRightBold:`┳`,lineDownLeftBoldRightBold:`┯`,lineDownBoldLeftRight:`┰`,lineDownBoldLeftBoldRight:`┱`,lineDownBoldLeftRightBold:`┲`,lineDownLeftRightBold:`┮`,lineDownLeftBoldRight:`┭`,lineDownDoubleLeftDoubleRightDouble:`╦`,lineDownDoubleLeftRight:`╥`,lineDownLeftDoubleRightDouble:`╤`,lineUpLeftRight:`┴`,lineUpBoldLeftBoldRightBold:`┻`,lineUpLeftBoldRightBold:`┷`,lineUpBoldLeftRight:`┸`,lineUpBoldLeftBoldRight:`┹`,lineUpBoldLeftRightBold:`┺`,lineUpLeftRightBold:`┶`,lineUpLeftBoldRight:`┵`,lineUpDoubleLeftDoubleRightDouble:`╩`,lineUpDoubleLeftRight:`╨`,lineUpLeftDoubleRightDouble:`╧`,lineUpDownLeftRight:`┼`,lineUpBoldDownBoldLeftBoldRightBold:`╋`,lineUpDownBoldLeftBoldRightBold:`╈`,lineUpBoldDownLeftBoldRightBold:`╇`,lineUpBoldDownBoldLeftRightBold:`╊`,lineUpBoldDownBoldLeftBoldRight:`╉`,lineUpBoldDownLeftRight:`╀`,lineUpDownBoldLeftRight:`╁`,lineUpDownLeftBoldRight:`┽`,lineUpDownLeftRightBold:`┾`,lineUpBoldDownBoldLeftRight:`╂`,lineUpDownLeftBoldRightBold:`┿`,lineUpBoldDownLeftBoldRight:`╃`,lineUpBoldDownLeftRightBold:`╄`,lineUpDownBoldLeftBoldRight:`╅`,lineUpDownBoldLeftRightBold:`╆`,lineUpDoubleDownDoubleLeftDoubleRightDouble:`╬`,lineUpDoubleDownDoubleLeftRight:`╫`,lineUpDownLeftDoubleRightDouble:`╪`,lineCross:`╳`,lineBackslash:`╲`,lineSlash:`╱`},fi={tick:`✔`,info:`ℹ`,warning:`⚠`,cross:`✘`,squareSmall:`◻`,squareSmallFilled:`◼`,circle:`◯`,circleFilled:`◉`,circleDotted:`◌`,circleDouble:`◎`,circleCircle:`ⓞ`,circleCross:`ⓧ`,circlePipe:`Ⓘ`,radioOn:`◉`,radioOff:`◯`,checkboxOn:`☒`,checkboxOff:`☐`,checkboxCircleOn:`ⓧ`,checkboxCircleOff:`Ⓘ`,pointer:`❯`,triangleUpOutline:`△`,triangleLeft:`◀`,triangleRight:`▶`,lozenge:`◆`,lozengeOutline:`◇`,hamburger:`☰`,smiley:`㋡`,mustache:`෴`,star:`★`,play:`▶`,nodejs:`⬢`,oneSeventh:`⅐`,oneNinth:`⅑`,oneTenth:`⅒`},pi={tick:`√`,info:`i`,warning:`‼`,cross:`×`,squareSmall:`□`,squareSmallFilled:`■`,circle:`( )`,circleFilled:`(*)`,circleDotted:`( )`,circleDouble:`( )`,circleCircle:`(○)`,circleCross:`(×)`,circlePipe:`(│)`,radioOn:`(*)`,radioOff:`( )`,checkboxOn:`[×]`,checkboxOff:`[ ]`,checkboxCircleOn:`(×)`,checkboxCircleOff:`( )`,pointer:`>`,triangleUpOutline:`∆`,triangleLeft:`◄`,triangleRight:`►`,lozenge:`♦`,lozengeOutline:`◊`,hamburger:`≡`,smiley:`☺`,mustache:`┌─┐`,star:`✶`,play:`►`,nodejs:`♦`,oneSeventh:`1/7`,oneNinth:`1/9`,oneTenth:`1/10`},mi={...di,...fi},hi={...di,...pi},gi=ui()?mi:hi;Object.entries(fi);const _i={prefix:{idle:ir(`blue`,`?`),done:ir(`green`,gi.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>ir(`yellow`,e))},style:{answer:e=>ir(`cyan`,e),message:e=>ir(`bold`,e),error:e=>ir(`red`,`> ${e}`),defaultAnswer:e=>ir(`dim`,`(${e})`),help:e=>ir(`dim`,e),highlight:e=>ir(`cyan`,e),key:e=>ir(`cyan`,ir(`bold`,`<${e}>`))}};function vi(e){if(typeof e!=`object`||!e)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function yi(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=vi(n)&&vi(r)?yi(n,r):r}return t}function bi(...e){return yi(_i,...e.filter(e=>e!=null))}function xi({status:e=`idle`,theme:t}){let[n,r]=ci(!1),[i,a]=ci(0),{prefix:o,spinner:s}=bi(t);return li(()=>{if(e===`loading`){let e,t=-1,n=setTimeout(()=>{r(!0),e=setInterval(()=>{t+=1,a(t%s.frames.length)},s.interval)},300);return()=>{clearTimeout(n),clearInterval(e)}}else r(!1)},[e]),n?s.frames[i]:typeof o==`string`?o:o[e===`loading`?`idle`:e]??o.idle}function Si(e){return ci({current:e})[0]}function Ci(e){let t=Si(e);t.current=e,li(e=>{let n=!1,r=ri((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var wi=n(((t,n)=>{n.exports=i;function r(t){let n={defaultWidth:0,output:process.stdout,tty:e(`tty`)};return t?(Object.keys(n).forEach(function(e){t[e]||(t[e]=n[e])}),t):n}function i(e){let t=r(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let e=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(e)&&e!==0)return e}return t.defaultWidth}}));const Ti=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),Ei=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Di=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,Oi=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,ki=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ai=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,ji=/\t{1,1000}/y,Mi=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,Ni=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Pi=/\p{M}+/gu,Fi={limit:1/0,ellipsis:``},Ii=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Ii(i,Fi,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[Ni,l],[Oi,0],[ki,o],[ji,s],[Mi,c],[Ai,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(Pi,``)){let t=e.codePointAt(0)||0;if(S=Ei(t)?2:Di(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===Ai?Ti(e.slice(p,n.lastIndex)):n===Mi?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},Li={limit:1/0,ellipsis:``,ellipsisWidth:0},Ri=(e,t={})=>Ii(e,Li,t).width,zi=`]8;;`,Bi=RegExp(`(?:\\[(?<code>\\d+)m|\\${zi}(?<uri>.*))`,`y`),Vi=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},Hi=e=>`[${e}m`,Ui=e=>`${zi}${e}`,Wi=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:Ri(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=Ri(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(zi,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},Gi=e=>{let t=e.split(` `),n=t.length;for(;n&&!Ri(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Ki=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=Ri(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=Ri(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),Wi(s,r,t),c=Ri(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Wi(s,r,t),c=Ri(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Wi(s,r,t),c=Ri(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>Gi(e)));let l=s.join(`
@@ -21,10 +21,10 @@ import{i as e,o as t,t as n}from"./chunk-FK9Q3tQk.mjs";import{t as r}from"./esm-
21
21
  `),process.exit(1)}await t.set(r,c,a,{gitProtocol:`https`,name:l,email:u}),i?process.stdout.write(`${JSON.stringify({type:`complete`,host:r,login:c})}\n`):process.stderr.write(`✓ PAT stored for ${c} on ${r}\n`)}function To(e){return new r(`pat`).description(`Store a Personal Access Token`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await wo(t,await e())})}async function Eo(e,t){let{host:n,json:r}=e;Hr(n);let i=await t.get(n);i??(process.stderr.write(`Not logged in to ${n}\n`),process.exit(1));let a=n===`github.com`?void 0:`https://${n}/api/v3`,o=new Co({auth:i.token,...a?{baseUrl:a}:{}}),s=[];for await(let e of o.paginate.iterator(o.repos.listForAuthenticatedUser,{per_page:100,sort:`updated`}))for(let t of e.data)s.push({full_name:t.full_name,clone_url:t.clone_url,private:t.private});if(r)process.stdout.write(`${JSON.stringify({type:`repos`,host:n,repos:s})}\n`);else for(let e of s)process.stdout.write(`${e.full_name} ${e.clone_url}\n`)}function Do(e){return new r(`repos`).description(`List accessible repositories`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await Eo(t,await e())})}async function Oo(e,t){let{host:n}=e;await t.clear(n),process.stderr.write(`✓ Signed out from ${n}\n`)}function ko(e){return new r(`signout`).description(`Remove stored credentials`).option(`--host <host>`,`GitHub hostname`,`github.com`).action(async t=>{await Oo(t,await e())})}async function Ao(e,t){let{host:n,json:r}=e;Hr(n);let i=await t.get(n);i??(r?process.stdout.write(`${JSON.stringify({type:`status`,host:n,authenticated:!1})}\n`):process.stderr.write(`Not logged in to ${n}\n`),process.exit(1));let a=n===`github.com`?void 0:`https://${n}/api/v3`,o=new Co({auth:i.token,...a?{baseUrl:a}:{}});try{let{data:e}=await o.users.getAuthenticated();r?process.stdout.write(`${JSON.stringify({type:`status`,host:n,authenticated:!0,login:e.login,name:e.name,email:e.email})}\n`):process.stderr.write(`✓ Logged in as ${e.login} on ${n}\n`)}catch{r?process.stdout.write(JSON.stringify({type:`status`,host:n,authenticated:!1,error:`token invalid`})+`
22
22
  `):process.stderr.write(`✗ Token invalid for ${n}\n`),process.exit(1)}}function jo(e){return new r(`status`).description(`Show authentication status`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await Ao(t,await e())})}function Mo(e){let t=new r(`auth`);t.description(`GitHub authentication management`);let n=()=>xr(),i=e??(()=>({}));return t.addCommand(Gr(i,n)),t.addCommand(jo(n)),t.addCommand(Do(n)),t.addCommand(ko(n)),t.addCommand(To(n)),t.addCommand(Tr(n)),t}function No(e,t,n={}){let r=Ee(e,t);if(!Hn(r))return{status:`missing`,lockPath:r};let i;try{i=JSON.parse(Gn(r,`utf-8`))}catch{return{status:`corrupt`,lockPath:r}}if(!i||typeof i!=`object`||typeof i.pid!=`number`)return{status:`corrupt`,lockPath:r};let a=i,o=n.host??$n();return a.hostname===o?(n.isAlive??Te)(a.pid)?{status:`alive`,lockPath:r,lock:a}:{status:`dead-pid`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a}}function Po(e,t){let n=[];for(let[r,i]of[[`server`,e],[`ui`,t]])(i.status===`dead-pid`||i.status===`corrupt`)&&n.push({name:r,lockPath:i.lockPath,reason:i.status});return{prune:n}}function Fo(e){let t=e.inspect??(t=>No(e.lockDir,t)),n=e.unlink??(e=>Yn(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Po(t(`server`),t(`ui`));if(a.prune.length===0)return r(`No stale locks.`),{pruned:[],failed:[]};let o=[],s=[];for(let e of a.prune)try{n(e.lockPath),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}if(o.length>0){let e=o.map(e=>`${e.name} (${e.reason})`).join(`, `);r(`Pruned ${o.length} stale lock${o.length===1?``:`s`}: ${e}`)}return s.length>0&&i(`Failed to prune: ${s.map(({target:e,error:t})=>`${e.name} (${e.lockPath}): ${t}`).join(`; `)}`),{pruned:o,failed:s}}function Io(e){return new r(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{Fo({lockDir:Se(Ce(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}function Lo(){try{let e=An(`gh`,[`auth`,`token`],{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3}).trim();return e.length===0?{available:!1}:{available:!0,token:e}}catch{return{available:!1}}}async function Ro(e,t,n={},r=Lo){if(!n.skipGhDetect&&r().available)return{tier:`A`,credentialArgs:[`-c`,`credential.helper=!gh auth git-credential`]};let i=await t.get(e);return i==null?{tier:`none`,credentialArgs:[]}:{tier:i.gitProtocol===`ssh`?`C`:`B`,credentialArgs:[`-c`,`credential.helper=!open-knowledge auth git-credential`]}}function zo(e){return e.replace(/:\d+$/,``)}function Bo(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:zo(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:zo(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:zo(e[1]),owner:e[2],name:e[3]}}{let e=/^(?:[\w.-]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e?.[1].includes(`.`)||e&&t.startsWith(`git@`))return{protocol:`ssh`,hostname:e[1],owner:e[2],name:e[3]}}{let e=/^git:([\w.-]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:e[1],owner:e[2],name:e[3]}}if(!t.includes(`://`)&&!t.includes(`@`)&&!t.startsWith(`/`)){let e=/^([\w.-]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e)return{protocol:`https`,hostname:`github.com`,owner:e[1],name:e[2]}}return null}const Vo=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function Ho(e){let t=/^([\w ]+):\s+(\d+)%/.exec(e.trim());if(!t)return null;let n=t[1].toLowerCase(),r=Number(t[2]);for(let[e,i,a]of Vo)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function Uo(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Wo(e,t,n,r=process.cwd()){let i=Bo(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=t.dir?zn(r,t.dir):zn(r,i.name);if(Hn(a)&&Kn(a).length>0)throw Error(`Target directory is not empty: ${a}`);let o=await xr(),s=await Ro(i.hostname,o,{}),c=De({baseDir:r,config:s.credentialArgs.length>=2?[s.credentialArgs[1]]:[],unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`}),l=-1;c.outputHandler((e,n,r)=>{r.on(`data`,e=>{let n=e.toString(`utf-8`);for(let e of n.split(`
23
23
  `)){let n=Ho(e);n&&n.pct!==l&&(l=n.pct,Uo(t.json,{type:`progress`,pct:n.pct,stage:n.stage}),t.json||process.stderr.write(`\r Cloning… ${n.pct}%`))}})}),await c.clone(e,a,[`--progress`]),t.json||process.stderr.write(`
24
- `);try{let{runInit:e}=await import(`./init-BN0U8twb.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?Uo(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?Uo(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{Go(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?Uo(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function Go(e){let t=Ln(e,`.git`,`info`,`exclude`);if(!Hn(t))return`no-exclude`;let n=Gn(t,`utf-8`),r=new Set([i,`${i}/`,`/${i}`,`/${i}/`]);return n.split(`
24
+ `);try{let{runInit:e}=await import(`./init-D0BylGY2.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?Uo(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?Uo(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{Go(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?Uo(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function Go(e){let t=Ln(e,`.git`,`info`,`exclude`);if(!Hn(t))return`no-exclude`;let n=Gn(t,`utf-8`),r=new Set([i,`${i}/`,`/${i}`,`/${i}/`]);return n.split(`
25
25
  `).map(e=>e.trim()).some(e=>r.has(e))?`already-present`:(Xn(t,`${n}${n.length===0||n.endsWith(`
26
26
  `)?``:`
27
- `}${i}/\n`,`utf-8`),`appended`)}function Ko(e){return new r(`clone`).description(`Clone a git repository and open it`).argument(`<url>`,`Repository URL or owner/repo shorthand`).argument(`[dir]`,`Target directory (default: ./<repo-name>)`).option(`--json`,`Output JSONL progress events`,!1).action(async(t,n,r)=>{let i=e();try{let a=await Wo(t,{json:r.json,dir:n},i);if(r.json)Uo(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-B00zNiq_.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?Uo(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}const qo=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`]];function Jo(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??We;try{let{sources:n}=r(e.cwd);return t(`✓ Configuration valid (sources: ${n.length===0?`defaults only`:n.join(`, `)})`),{ok:!0}}catch(e){return n(e instanceof Error?e.message:String(e)),{ok:!1}}}function Yo(e){let t=(0,_r.parseDocument)(Gn(e,`utf-8`));if(t.errors.length>0)throw Error(`Could not parse ${e}: ${t.errors.map(e=>e.message).join(`; `)}`);let n=[];for(let e of qo)t.hasIn(e)&&n.push(e.join(`.`));return n}function Xo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Zo(e){let t={};for(let n of e){let e=t;for(let t=0;t<n.length-1;t++){let r=n[t],i=e[r],a=Xo(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function Qo(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`both`,i=e.dryRun??!1,a=e.cwd??process.cwd(),o=e.writeConfigPatchFn??Re,s=[];(r===`project`||r===`both`)&&s.push({scope:`project`,absPath:ze(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&s.push({scope:`user`,absPath:ze(`user`,a,e.homedirOverride)});let c=[],u=!0;for(let{scope:t,absPath:n}of s){if(!Hn(n)){c.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=Yo(n)}catch(e){let r=e instanceof Error?e.message:String(e);c.push({path:n,scope:t,found:[],removed:[],error:r}),u=!1;continue}if(r.length===0||i){c.push({path:n,scope:t,found:r,removed:[]});continue}let s=await o({cwd:a,scope:t,patch:Zo(qo.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!s.ok){c.push({path:n,scope:t,found:r,removed:[],error:l(s.error)}),u=!1;continue}c.push({path:n,scope:t,found:r,removed:r})}for(let e of c)e.error&&n(`✗ ${e.path}: ${e.error}`);let d=c.some(e=>e.error!==void 0),f=c.reduce((e,t)=>e+t.found.length,0);if(f===0&&!d)t(`No deprecated fields found.`);else if(f>0)for(let e of c)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(i?`[dry-run] ${e.path}: would remove ${e.found.length} field(s): ${e.found.join(`, `)}`:`✓ ${e.path}: removed ${e.removed.length} field(s): ${e.removed.join(`, `)}`));return{outcomes:c,ok:u}}function $o(){let e=new r(`config`).description(`Inspect and maintain Open Knowledge configuration files`);return e.command(`validate`).description(`Validate the merged config (defaults → user → project)`).action(()=>{Jo({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields (sync.*, persistence.{debounceMs,maxDebounceMs}, server.port) idempotently`).option(`--scope <scope>`,`Which scope to migrate: project | user | both`,`both`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=e.scope;if(t!==`project`&&t!==`user`&&t!==`both`){console.error(`Invalid --scope: ${t}. Expected: project | user | both`),process.exitCode=2;return}(await Qo({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}function es(e=Qn()){return Ln(e,`Downloads`,`openknowledge.skill`)}function ts(e,t,n){try{return t===`darwin`?(n(`open`,[e],{detached:!0,stdio:`ignore`}).unref(),{ok:!0}):t===`win32`?(n(`cmd`,[`/c`,`start`,`""`,e],{detached:!0,stdio:`ignore`}).unref(),{ok:!0}):t===`linux`?(n(`xdg-open`,[e],{detached:!0,stdio:`ignore`}).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired. Use --no-open and open the file manually.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function ns(e={}){let t=zn(e.out??es()),n=e.platformName??er(),r=e.spawnFn??jn;try{await cr(Fn(t),{recursive:!0})}catch(e){return{status:`failed`,message:`${Ze(`Error:`)} could not create output directory: ${e instanceof Error?e.message:String(e)}`,exitCode:1}}let i;try{i=await Me({outputPath:t,skipVersionCheck:!0})}catch(e){return{status:`failed`,message:`${Ze(`Error:`)} build failed — ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(e.noOpen)return{status:`built`,outputPath:i.outputPath,size:i.size,sha256:i.sha256,cliVersion:i.cliVersion,skillVersion:i.skillVersion,message:[Xe(`Built ${i.outputPath}`),Ye(` ${i.size} bytes • sha256 ${i.sha256.slice(0,12)}…`),Je(` Open the Claude Desktop App, then: ${$e(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`)].join(`
27
+ `}${i}/\n`,`utf-8`),`appended`)}function Ko(e){return new r(`clone`).description(`Clone a git repository and open it`).argument(`<url>`,`Repository URL or owner/repo shorthand`).argument(`[dir]`,`Target directory (default: ./<repo-name>)`).option(`--json`,`Output JSONL progress events`,!1).action(async(t,n,r)=>{let i=e();try{let a=await Wo(t,{json:r.json,dir:n},i);if(r.json)Uo(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-BneKCKPF.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?Uo(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}const qo=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`]];function Jo(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??We;try{let{sources:n}=r(e.cwd);return t(`✓ Configuration valid (sources: ${n.length===0?`defaults only`:n.join(`, `)})`),{ok:!0}}catch(e){return n(e instanceof Error?e.message:String(e)),{ok:!1}}}function Yo(e){let t=(0,_r.parseDocument)(Gn(e,`utf-8`));if(t.errors.length>0)throw Error(`Could not parse ${e}: ${t.errors.map(e=>e.message).join(`; `)}`);let n=[];for(let e of qo)t.hasIn(e)&&n.push(e.join(`.`));return n}function Xo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Zo(e){let t={};for(let n of e){let e=t;for(let t=0;t<n.length-1;t++){let r=n[t],i=e[r],a=Xo(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function Qo(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`both`,i=e.dryRun??!1,a=e.cwd??process.cwd(),o=e.writeConfigPatchFn??Re,s=[];(r===`project`||r===`both`)&&s.push({scope:`project`,absPath:ze(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&s.push({scope:`user`,absPath:ze(`user`,a,e.homedirOverride)});let c=[],u=!0;for(let{scope:t,absPath:n}of s){if(!Hn(n)){c.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=Yo(n)}catch(e){let r=e instanceof Error?e.message:String(e);c.push({path:n,scope:t,found:[],removed:[],error:r}),u=!1;continue}if(r.length===0||i){c.push({path:n,scope:t,found:r,removed:[]});continue}let s=await o({cwd:a,scope:t,patch:Zo(qo.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!s.ok){c.push({path:n,scope:t,found:r,removed:[],error:l(s.error)}),u=!1;continue}c.push({path:n,scope:t,found:r,removed:r})}for(let e of c)e.error&&n(`✗ ${e.path}: ${e.error}`);let d=c.some(e=>e.error!==void 0),f=c.reduce((e,t)=>e+t.found.length,0);if(f===0&&!d)t(`No deprecated fields found.`);else if(f>0)for(let e of c)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(i?`[dry-run] ${e.path}: would remove ${e.found.length} field(s): ${e.found.join(`, `)}`:`✓ ${e.path}: removed ${e.removed.length} field(s): ${e.removed.join(`, `)}`));return{outcomes:c,ok:u}}function $o(){let e=new r(`config`).description(`Inspect and maintain Open Knowledge configuration files`);return e.command(`validate`).description(`Validate the merged config (defaults → user → project)`).action(()=>{Jo({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields (sync.*, persistence.{debounceMs,maxDebounceMs}, server.port) idempotently`).option(`--scope <scope>`,`Which scope to migrate: project | user | both`,`both`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=e.scope;if(t!==`project`&&t!==`user`&&t!==`both`){console.error(`Invalid --scope: ${t}. Expected: project | user | both`),process.exitCode=2;return}(await Qo({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}function es(e=Qn()){return Ln(e,`Downloads`,`openknowledge.skill`)}function ts(e,t,n){try{return t===`darwin`?(n(`open`,[e],{detached:!0,stdio:`ignore`}).unref(),{ok:!0}):t===`win32`?(n(`cmd`,[`/c`,`start`,`""`,e],{detached:!0,stdio:`ignore`}).unref(),{ok:!0}):t===`linux`?(n(`xdg-open`,[e],{detached:!0,stdio:`ignore`}).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired. Use --no-open and open the file manually.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function ns(e={}){let t=zn(e.out??es()),n=e.platformName??er(),r=e.spawnFn??jn;try{await cr(Fn(t),{recursive:!0})}catch(e){return{status:`failed`,message:`${Ze(`Error:`)} could not create output directory: ${e instanceof Error?e.message:String(e)}`,exitCode:1}}let i;try{i=await Me({outputPath:t,skipVersionCheck:!0})}catch(e){return{status:`failed`,message:`${Ze(`Error:`)} build failed — ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(e.noOpen)return{status:`built`,outputPath:i.outputPath,size:i.size,sha256:i.sha256,cliVersion:i.cliVersion,skillVersion:i.skillVersion,message:[Xe(`Built ${i.outputPath}`),Ye(` ${i.size} bytes • sha256 ${i.sha256.slice(0,12)}…`),Je(` Open the Claude Desktop App, then: ${$e(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`)].join(`
28
28
  `),exitCode:0};let a=ts(i.outputPath,n,r);return a.ok?{status:`installed`,outputPath:i.outputPath,size:i.size,sha256:i.sha256,cliVersion:i.cliVersion,skillVersion:i.skillVersion,message:[Xe(`Built ${i.outputPath}`),Ye(` ${i.size} bytes • sha256 ${i.sha256.slice(0,12)}… • CLI v${i.cliVersion}`),Je(` Claude Desktop App opened. Now upload the file manually:`),` 1. ${$e(`Customize`)} (sidebar) → ${$e(`Skills`)}`,` 2. Click the ${$e(`+`)} button`,` 3. Click ${$e(`Create skill`)}`,` 4. Click ${$e(`Upload skill`)}`,` 5. Pick ${$e(`openknowledge.skill`)} from Downloads`,Ye(` If Claude Desktop didn't open, open it and start at step 1. The file is at ${i.outputPath}`)].join(`
29
29
  `),exitCode:0}:{status:`built`,outputPath:i.outputPath,size:i.size,sha256:i.sha256,cliVersion:i.cliVersion,skillVersion:i.skillVersion,message:[Xe(`Built ${i.outputPath}`),Qe(` Handoff failed: ${a.message}`),Je(` Open the Claude Desktop App, then: ${$e(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`)].join(`
30
30
  `),exitCode:0}}function rs(){return new r(`install-skill`).description("Build openknowledge.skill and open the Claude Desktop App so you can upload it for Claude Chat & Cowork. Not needed for Claude Code — `ok init` covers that separately.").option(`--out <path>`,`Custom output path (default: ~/Downloads/openknowledge.skill)`).option(`--no-open`,`Build the file but skip the OS file-association handoff`).action(async e=>{let t=await ns({out:e.out,noOpen:!e.open});process.stdout.write(`${t.message}\n`),t.exitCode!==0&&process.exit(t.exitCode)})}var j;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(j||={});var is;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(is||={});const M=j.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),as=e=>{switch(typeof e){case`undefined`:return M.undefined;case`string`:return M.string;case`number`:return Number.isNaN(e)?M.nan:M.number;case`boolean`:return M.boolean;case`function`:return M.function;case`bigint`:return M.bigint;case`symbol`:return M.symbol;case`object`:return Array.isArray(e)?M.array:e===null?M.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?M.promise:typeof Map<`u`&&e instanceof Map?M.map:typeof Set<`u`&&e instanceof Set?M.set:typeof Date<`u`&&e instanceof Date?M.date:M.object;default:return M.unknown}},N=j.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var os=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,j.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};os.create=e=>new os(e);const ss=(e,t)=>{let n;switch(e.code){case N.invalid_type:n=e.received===M.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,j.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${j.joinValues(e.keys,`, `)}`;break;case N.invalid_union:n=`Invalid input`;break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${j.joinValues(e.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${j.joinValues(e.options)}, received '${e.received}'`;break;case N.invalid_arguments:n=`Invalid function arguments`;break;case N.invalid_return_type:n=`Invalid function return type`;break;case N.invalid_date:n=`Invalid date`;break;case N.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:j.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case N.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case N.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case N.custom:n=`Invalid input`;break;case N.invalid_intersection_types:n=`Intersection results could not be merged`;break;case N.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case N.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,j.assertNever(e)}return{message:n}};let cs=ss;function ls(){return cs}const us=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function P(e,t){let n=ls(),r=us({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===ss?void 0:ss].filter(e=>!!e)});e.common.issues.push(r)}var ds=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return F;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return F;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const F=Object.freeze({status:`aborted`}),fs=e=>({status:`dirty`,value:e}),ps=e=>({status:`valid`,value:e}),ms=e=>e.status===`aborted`,hs=e=>e.status===`dirty`,gs=e=>e.status===`valid`,_s=e=>typeof Promise<`u`&&e instanceof Promise;var I;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(I||={});var vs=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const ys=(e,t)=>{if(gs(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){return this._error||=new os(e.common.issues),this._error}}};function L(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var R=class{get description(){return this._def.description}_getType(e){return as(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:as(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ds,ctx:{common:e.parent.common,data:e.data,parsedType:as(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(_s(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:as(e)};return ys(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:as(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return gs(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>gs(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:as(e)},r=this._parse({data:e,path:n.path,parent:n});return ys(n,await(_s(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:N.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new xc({schema:this,typeName:z.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return Sc.create(this,this._def)}nullable(){return Cc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nc.create(this)}promise(){return bc.create(this,this._def)}or(e){return ac.create([this,e],this._def)}and(e){return lc.create(this,e,this._def)}transform(e){return new xc({...L(this._def),schema:this,typeName:z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new wc({...L(this._def),innerType:this,defaultValue:t,typeName:z.ZodDefault})}brand(){return new Dc({typeName:z.ZodBranded,type:this,...L(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new Tc({...L(this._def),innerType:this,catchValue:t,typeName:z.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Oc.create(this,e)}readonly(){return kc.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const bs=/^c[^\s-]{8,}$/i,xs=/^[0-9a-z]+$/,Ss=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Cs=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ws=/^[a-z0-9_-]{21}$/i,Ts=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Es=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Ds=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Os;const ks=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,As=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,js=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ms=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ns=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ps=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Fs=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,Is=RegExp(`^${Fs}$`);function Ls(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function Rs(e){return RegExp(`^${Ls(e)}$`)}function zs(e){let t=`${Fs}T${Ls(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Bs(e,t){return!!((t===`v4`||!t)&&ks.test(e)||(t===`v6`||!t)&&js.test(e))}function Vs(e,t){if(!Ts.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function Hs(e,t){return!!((t===`v4`||!t)&&As.test(e)||(t===`v6`||!t)&&Ms.test(e))}var Us=class e extends R{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.string,received:t.parsedType}),F}let t=new ds,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?P(n,{code:N.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&P(n,{code:N.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Ds.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`email`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)Os||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),Os.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`emoji`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Cs.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`uuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)ws.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`nanoid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)bs.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`cuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)xs.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`cuid2`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Ss.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`ulid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),P(n,{validation:`url`,code:N.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`regex`,code:N.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?zs(r).test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Is.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Rs(r).test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Es.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`duration`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Bs(e.data,r.version)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`ip`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Vs(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`jwt`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Hs(e.data,r.version)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`cidr`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Ns.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`base64`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Ps.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`base64url`,code:N.invalid_string,message:r.message}),t.dirty()):j.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:N.invalid_string,...I.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...I.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...I.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...I.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...I.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...I.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...I.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...I.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...I.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...I.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...I.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...I.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...I.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...I.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...I.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...I.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...I.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...I.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...I.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...I.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...I.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...I.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...I.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...I.errToObj(t)})}nonempty(e){return this.min(1,I.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Us.create=e=>new Us({checks:[],typeName:z.ZodString,coerce:e?.coerce??!1,...L(e)});function Ws(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var Gs=class e extends R{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==M.number){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.number,received:t.parsedType}),F}let t,n=new ds;for(let r of this._def.checks)r.kind===`int`?j.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),P(t,{code:N.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Ws(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),P(t,{code:N.not_finite,message:r.message}),n.dirty()):j.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,I.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,I.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,I.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,I.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:I.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:I.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:I.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:I.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:I.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:I.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&j.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};Gs.create=e=>new Gs({checks:[],typeName:z.ZodNumber,coerce:e?.coerce||!1,...L(e)});var Ks=class e extends R{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==M.bigint)return this._getInvalidInput(e);let t,n=new ds;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):j.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.bigint,received:t.parsedType}),F}gte(e,t){return this.setLimit(`min`,e,!0,I.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,I.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,I.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,I.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:I.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:I.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Ks.create=e=>new Ks({checks:[],typeName:z.ZodBigInt,coerce:e?.coerce??!1,...L(e)});var qs=class extends R{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.boolean,received:t.parsedType}),F}return ps(e.data)}};qs.create=e=>new qs({typeName:z.ZodBoolean,coerce:e?.coerce||!1,...L(e)});var Js=class e extends R{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.date,received:t.parsedType}),F}if(Number.isNaN(e.data.getTime()))return P(this._getOrReturnCtx(e),{code:N.invalid_date}),F;let t=new ds,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):j.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:I.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:I.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};Js.create=e=>new Js({checks:[],coerce:e?.coerce||!1,typeName:z.ZodDate,...L(e)});var Ys=class extends R{_parse(e){if(this._getType(e)!==M.symbol){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.symbol,received:t.parsedType}),F}return ps(e.data)}};Ys.create=e=>new Ys({typeName:z.ZodSymbol,...L(e)});var Xs=class extends R{_parse(e){if(this._getType(e)!==M.undefined){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.undefined,received:t.parsedType}),F}return ps(e.data)}};Xs.create=e=>new Xs({typeName:z.ZodUndefined,...L(e)});var Zs=class extends R{_parse(e){if(this._getType(e)!==M.null){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.null,received:t.parsedType}),F}return ps(e.data)}};Zs.create=e=>new Zs({typeName:z.ZodNull,...L(e)});var Qs=class extends R{constructor(){super(...arguments),this._any=!0}_parse(e){return ps(e.data)}};Qs.create=e=>new Qs({typeName:z.ZodAny,...L(e)});var $s=class extends R{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ps(e.data)}};$s.create=e=>new $s({typeName:z.ZodUnknown,...L(e)});var ec=class extends R{_parse(e){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.never,received:t.parsedType}),F}};ec.create=e=>new ec({typeName:z.ZodNever,...L(e)});var tc=class extends R{_parse(e){if(this._getType(e)!==M.undefined){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.void,received:t.parsedType}),F}return ps(e.data)}};tc.create=e=>new tc({typeName:z.ZodVoid,...L(e)});var nc=class e extends R{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==M.array)return P(t,{code:N.invalid_type,expected:M.array,received:t.parsedType}),F;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(P(t,{code:e?N.too_big:N.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(P(t,{code:N.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(P(t,{code:N.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new vs(t,e,t.path,n)))).then(e=>ds.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new vs(t,e,t.path,n)));return ds.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:I.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:I.toString(n)}})}nonempty(e){return this.min(1,e)}};nc.create=(e,t)=>new nc({type:e,minLength:null,maxLength:null,exactLength:null,typeName:z.ZodArray,...L(t)});function rc(e){if(e instanceof ic){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Sc.create(rc(r))}return new ic({...e._def,shape:()=>t})}else if(e instanceof nc)return new nc({...e._def,type:rc(e.element)});else if(e instanceof Sc)return Sc.create(rc(e.unwrap()));else if(e instanceof Cc)return Cc.create(rc(e.unwrap()));else if(e instanceof uc)return uc.create(e.items.map(e=>rc(e)));else return e}var ic=class e extends R{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape();return this._cached={shape:e,keys:j.objectKeys(e)},this._cached}_parse(e){if(this._getType(e)!==M.object){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.object,received:t.parsedType}),F}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof ec&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new vs(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof ec){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(P(n,{code:N.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new vs(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>ds.mergeObjectSync(t,e)):ds.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return I.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:I.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:z.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of j.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of j.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return rc(this)}partial(t){let n={};for(let e of j.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of j.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof Sc;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return _c(j.objectKeys(this.shape))}};ic.create=(e,t)=>new ic({shape:()=>e,unknownKeys:`strip`,catchall:ec.create(),typeName:z.ZodObject,...L(t)}),ic.strictCreate=(e,t)=>new ic({shape:()=>e,unknownKeys:`strict`,catchall:ec.create(),typeName:z.ZodObject,...L(t)}),ic.lazycreate=(e,t)=>new ic({shape:e,unknownKeys:`strip`,catchall:ec.create(),typeName:z.ZodObject,...L(t)});var ac=class extends R{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new os(e.ctx.common.issues));return P(t,{code:N.invalid_union,unionErrors:n}),F}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new os(e));return P(t,{code:N.invalid_union,unionErrors:i}),F}}get options(){return this._def.options}};ac.create=(e,t)=>new ac({options:e,typeName:z.ZodUnion,...L(t)});const oc=e=>e instanceof hc?oc(e.schema):e instanceof xc?oc(e.innerType()):e instanceof gc?[e.value]:e instanceof vc?e.options:e instanceof yc?j.objectValues(e.enum):e instanceof wc?oc(e._def.innerType):e instanceof Xs?[void 0]:e instanceof Zs?[null]:e instanceof Sc?[void 0,...oc(e.unwrap())]:e instanceof Cc?[null,...oc(e.unwrap())]:e instanceof Dc||e instanceof kc?oc(e.unwrap()):e instanceof Tc?oc(e._def.innerType):[];var sc=class e extends R{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==M.object)return P(t,{code:N.invalid_type,expected:M.object,received:t.parsedType}),F;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(P(t,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),F)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=oc(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:z.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...L(r)})}};function cc(e,t){let n=as(e),r=as(t);if(e===t)return{valid:!0,data:e};if(n===M.object&&r===M.object){let n=j.objectKeys(t),r=j.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=cc(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===M.array&&r===M.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=cc(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===M.date&&r===M.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var lc=class extends R{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(ms(e)||ms(r))return F;let i=cc(e.value,r.value);return i.valid?((hs(e)||hs(r))&&t.dirty(),{status:t.value,value:i.data}):(P(n,{code:N.invalid_intersection_types}),F)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};lc.create=(e,t,n)=>new lc({left:e,right:t,typeName:z.ZodIntersection,...L(n)});var uc=class e extends R{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return P(n,{code:N.invalid_type,expected:M.array,received:n.parsedType}),F;if(n.data.length<this._def.items.length)return P(n,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),F;!this._def.rest&&n.data.length>this._def.items.length&&(P(n,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new vs(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>ds.mergeArray(t,e)):ds.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};uc.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new uc({items:e,typeName:z.ZodTuple,rest:null,...L(t)})};var dc=class e extends R{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.object)return P(n,{code:N.invalid_type,expected:M.object,received:n.parsedType}),F;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new vs(n,e,n.path,e)),value:a._parse(new vs(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?ds.mergeObjectAsync(t,r):ds.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof R?new e({keyType:t,valueType:n,typeName:z.ZodRecord,...L(r)}):new e({keyType:Us.create(),valueType:t,typeName:z.ZodRecord,...L(n)})}},fc=class extends R{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.map)return P(n,{code:N.invalid_type,expected:M.map,received:n.parsedType}),F;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new vs(n,e,n.path,[a,`key`])),value:i._parse(new vs(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return F;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return F;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};fc.create=(e,t,n)=>new fc({valueType:t,keyType:e,typeName:z.ZodMap,...L(n)});var pc=class e extends R{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return P(n,{code:N.invalid_type,expected:M.set,received:n.parsedType}),F;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(P(n,{code:N.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(P(n,{code:N.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return F;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new vs(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:I.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};pc.create=(e,t)=>new pc({valueType:e,minSize:null,maxSize:null,typeName:z.ZodSet,...L(t)});var mc=class e extends R{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==M.function)return P(t,{code:N.invalid_type,expected:M.function,received:t.parsedType}),F;function n(e,n){return us({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ls(),ss].filter(e=>!!e),issueData:{code:N.invalid_arguments,argumentsError:n}})}function r(e,n){return us({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ls(),ss].filter(e=>!!e),issueData:{code:N.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof bc){let e=this;return ps(async function(...t){let o=new os([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return ps(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new os([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new os([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:uc.create(t).rest($s.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||uc.create([]).rest($s.create()),returns:n||$s.create(),typeName:z.ZodFunction,...L(r)})}},hc=class extends R{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};hc.create=(e,t)=>new hc({getter:e,typeName:z.ZodLazy,...L(t)});var gc=class extends R{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return P(t,{received:t.data,code:N.invalid_literal,expected:this._def.value}),F}return{status:`valid`,value:e.data}}get value(){return this._def.value}};gc.create=(e,t)=>new gc({value:e,typeName:z.ZodLiteral,...L(t)});function _c(e,t){return new vc({values:e,typeName:z.ZodEnum,...L(t)})}var vc=class e extends R{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return P(t,{expected:j.joinValues(n),received:t.parsedType,code:N.invalid_type}),F}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return P(t,{received:t.data,code:N.invalid_enum_value,options:n}),F}return ps(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};vc.create=_c;var yc=class extends R{_parse(e){let t=j.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){let e=j.objectValues(t);return P(n,{expected:j.joinValues(e),received:n.parsedType,code:N.invalid_type}),F}if(this._cache||=new Set(j.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=j.objectValues(t);return P(n,{received:n.data,code:N.invalid_enum_value,options:e}),F}return ps(e.data)}get enum(){return this._def.values}};yc.create=(e,t)=>new yc({values:e,typeName:z.ZodNativeEnum,...L(t)});var bc=class extends R{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==M.promise&&t.common.async===!1?(P(t,{code:N.invalid_type,expected:M.promise,received:t.parsedType}),F):ps((t.parsedType===M.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};bc.create=(e,t)=>new bc({type:e,typeName:z.ZodPromise,...L(t)});var xc=class extends R{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{P(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return F;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?F:r.status===`dirty`||t.value===`dirty`?fs(r.value):r});{if(t.value===`aborted`)return F;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?F:r.status===`dirty`||t.value===`dirty`?fs(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?F:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?F:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!gs(e))return F;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>gs(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):F);j.assertNever(r)}};xc.create=(e,t,n)=>new xc({schema:e,typeName:z.ZodEffects,effect:t,...L(n)}),xc.createWithPreprocess=(e,t,n)=>new xc({schema:t,effect:{type:`preprocess`,transform:e},typeName:z.ZodEffects,...L(n)});var Sc=class extends R{_parse(e){return this._getType(e)===M.undefined?ps(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Sc.create=(e,t)=>new Sc({innerType:e,typeName:z.ZodOptional,...L(t)});var Cc=class extends R{_parse(e){return this._getType(e)===M.null?ps(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Cc.create=(e,t)=>new Cc({innerType:e,typeName:z.ZodNullable,...L(t)});var wc=class extends R{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};wc.create=(e,t)=>new wc({innerType:e,typeName:z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...L(t)});var Tc=class extends R{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return _s(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new os(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new os(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Tc.create=(e,t)=>new Tc({innerType:e,typeName:z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...L(t)});var Ec=class extends R{_parse(e){if(this._getType(e)!==M.nan){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.nan,received:t.parsedType}),F}return{status:`valid`,value:e.data}}};Ec.create=e=>new Ec({typeName:z.ZodNaN,...L(e)});var Dc=class extends R{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},Oc=class e extends R{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?F:e.status===`dirty`?(t.dirty(),fs(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?F:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:z.ZodPipeline})}},kc=class extends R{_parse(e){let t=this._def.innerType._parse(e),n=e=>(gs(e)&&(e.value=Object.freeze(e.value)),e);return _s(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};kc.create=(e,t)=>new kc({innerType:e,typeName:z.ZodReadonly,...L(t)}),ic.lazycreate;var z;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(z||={}),Us.create,Gs.create,Ec.create,Ks.create,qs.create,Js.create,Ys.create,Xs.create,Zs.create,Qs.create,$s.create,ec.create,tc.create,nc.create;const Ac=ic.create;ic.strictCreate,ac.create,sc.create,lc.create,uc.create,dc.create,fc.create,pc.create,mc.create,hc.create,gc.create,vc.create,yc.create,bc.create,xc.create,Sc.create,Cc.create,xc.createWithPreprocess,Oc.create;const jc=d(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);ae.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>o(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>f(e,t,n),e.parseAsync=async(t,n)=>ie(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>m(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>g(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),Mc=d(`ZodMiniObject`,(e,t)=>{h.init(e,t),jc.init(e,t),c(e,`shape`,()=>t.shape)});function Nc(e,t){return new Mc({type:`object`,shape:e??{},...u(t)})}function Pc(e){return!!e._zod}function Fc(e){let t=Object.values(e);if(t.length===0)return Nc({});let n=t.every(Pc),r=t.every(e=>!Pc(e));if(n)return Nc(e);if(r)return Ac(e);throw Error(`Mixed Zod versions detected in object shape.`)}function Ic(e,t){return Pc(e)?f(e,t):e.safeParse(t)}async function Lc(e,t){return Pc(e)?await m(e,t):await e.safeParseAsync(t)}function Rc(e){if(!e)return;let t;if(t=Pc(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function zc(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return Fc(e)}}if(Pc(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function Bc(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function Vc(e){return e.description}function Hc(e){if(Pc(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function Uc(e){if(Pc(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}const Wc=`2025-11-25`,Gc=[Wc,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Kc=`io.modelcontextprotocol/related-task`,qc=te(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),Jc=y([D(),C().int()]),Yc=D();w({ttl:C().optional(),pollInterval:C().optional()});const Xc=x({ttl:C().optional()}),Zc=x({taskId:D()}),Qc=w({progressToken:Jc.optional(),[Kc]:Zc.optional()}),$c=x({_meta:Qc.optional()}),el=$c.extend({task:Xc.optional()}),tl=e=>el.safeParse(e).success,nl=x({method:D(),params:$c.loose().optional()}),rl=x({_meta:Qc.optional()}),il=x({method:D(),params:rl.loose().optional()}),al=w({_meta:Qc.optional()}),ol=y([D(),C().int()]),sl=x({jsonrpc:E(`2.0`),id:ol,...nl.shape}).strict(),cl=e=>sl.safeParse(e).success,ll=x({jsonrpc:E(`2.0`),...il.shape}).strict(),ul=e=>ll.safeParse(e).success,dl=x({jsonrpc:E(`2.0`),id:ol,result:al}).strict(),fl=e=>dl.safeParse(e).success;var B;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(B||={});const pl=x({jsonrpc:E(`2.0`),id:ol.optional(),error:x({code:C().int(),message:D(),data:s().optional()})}).strict(),ml=e=>pl.safeParse(e).success,hl=y([sl,ll,dl,pl]);y([dl,pl]);const gl=al.strict(),_l=rl.extend({requestId:ol.optional(),reason:D().optional()}),vl=il.extend({method:E(`notifications/cancelled`),params:_l}),yl=x({icons:T(x({src:D(),mimeType:D().optional(),sizes:T(D()).optional(),theme:le([`light`,`dark`]).optional()})).optional()}),bl=x({name:D(),title:D().optional()}),xl=bl.extend({...bl.shape,...yl.shape,version:D(),websiteUrl:D().optional(),description:D().optional()}),Sl=ge(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ce(x({form:ce(x({applyDefaults:ue().optional()}),S(D(),s())).optional(),url:qc.optional()}),S(D(),s()).optional())),Cl=w({list:qc.optional(),cancel:qc.optional(),requests:w({sampling:w({createMessage:qc.optional()}).optional(),elicitation:w({create:qc.optional()}).optional()}).optional()}),wl=w({list:qc.optional(),cancel:qc.optional(),requests:w({tools:w({call:qc.optional()}).optional()}).optional()}),Tl=x({experimental:S(D(),qc).optional(),sampling:x({context:qc.optional(),tools:qc.optional()}).optional(),elicitation:Sl.optional(),roots:x({listChanged:ue().optional()}).optional(),tasks:Cl.optional(),extensions:S(D(),qc).optional()}),El=$c.extend({protocolVersion:D(),capabilities:Tl,clientInfo:xl}),Dl=nl.extend({method:E(`initialize`),params:El}),Ol=x({experimental:S(D(),qc).optional(),logging:qc.optional(),completions:qc.optional(),prompts:x({listChanged:ue().optional()}).optional(),resources:x({subscribe:ue().optional(),listChanged:ue().optional()}).optional(),tools:x({listChanged:ue().optional()}).optional(),tasks:wl.optional(),extensions:S(D(),qc).optional()}),kl=al.extend({protocolVersion:D(),capabilities:Ol,serverInfo:xl,instructions:D().optional()}),Al=il.extend({method:E(`notifications/initialized`),params:rl.optional()}),jl=nl.extend({method:E(`ping`),params:$c.optional()}),Ml=x({progress:C(),total:fe(C()),message:fe(D())}),Nl=x({...rl.shape,...Ml.shape,progressToken:Jc}),Pl=il.extend({method:E(`notifications/progress`),params:Nl}),Fl=$c.extend({cursor:Yc.optional()}),Il=nl.extend({params:Fl.optional()}),Ll=al.extend({nextCursor:Yc.optional()}),Rl=le([`working`,`input_required`,`completed`,`failed`,`cancelled`]),zl=x({taskId:D(),status:Rl,ttl:y([C(),ee()]),createdAt:D(),lastUpdatedAt:D(),pollInterval:fe(C()),statusMessage:fe(D())}),Bl=al.extend({task:zl}),Vl=rl.merge(zl),Hl=il.extend({method:E(`notifications/tasks/status`),params:Vl}),Ul=nl.extend({method:E(`tasks/get`),params:$c.extend({taskId:D()})}),Wl=al.merge(zl),Gl=nl.extend({method:E(`tasks/result`),params:$c.extend({taskId:D()})});al.loose();const Kl=Il.extend({method:E(`tasks/list`)}),ql=Ll.extend({tasks:T(zl)}),Jl=nl.extend({method:E(`tasks/cancel`),params:$c.extend({taskId:D()})}),Yl=al.merge(zl),Xl=x({uri:D(),mimeType:fe(D()),_meta:S(D(),s()).optional()}),Zl=Xl.extend({text:D()}),Ql=D().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),$l=Xl.extend({blob:Ql}),eu=le([`user`,`assistant`]),tu=x({audience:T(eu).optional(),priority:C().min(0).max(1).optional(),lastModified:pe({offset:!0}).optional()}),nu=x({...bl.shape,...yl.shape,uri:D(),description:fe(D()),mimeType:fe(D()),size:fe(C()),annotations:tu.optional(),_meta:fe(w({}))}),ru=x({...bl.shape,...yl.shape,uriTemplate:D(),description:fe(D()),mimeType:fe(D()),annotations:tu.optional(),_meta:fe(w({}))}),iu=Il.extend({method:E(`resources/list`)}),au=Ll.extend({resources:T(nu)}),ou=Il.extend({method:E(`resources/templates/list`)}),su=Ll.extend({resourceTemplates:T(ru)}),cu=$c.extend({uri:D()}),lu=cu,uu=nl.extend({method:E(`resources/read`),params:lu}),du=al.extend({contents:T(y([Zl,$l]))}),fu=il.extend({method:E(`notifications/resources/list_changed`),params:rl.optional()}),pu=cu,mu=nl.extend({method:E(`resources/subscribe`),params:pu}),hu=cu,gu=nl.extend({method:E(`resources/unsubscribe`),params:hu}),_u=rl.extend({uri:D()}),vu=il.extend({method:E(`notifications/resources/updated`),params:_u}),yu=x({name:D(),description:fe(D()),required:fe(ue())}),bu=x({...bl.shape,...yl.shape,description:fe(D()),arguments:fe(T(yu)),_meta:fe(w({}))}),xu=Il.extend({method:E(`prompts/list`)}),Su=Ll.extend({prompts:T(bu)}),Cu=$c.extend({name:D(),arguments:S(D(),D()).optional()}),wu=nl.extend({method:E(`prompts/get`),params:Cu}),Tu=x({type:E(`text`),text:D(),annotations:tu.optional(),_meta:S(D(),s()).optional()}),Eu=x({type:E(`image`),data:Ql,mimeType:D(),annotations:tu.optional(),_meta:S(D(),s()).optional()}),Du=x({type:E(`audio`),data:Ql,mimeType:D(),annotations:tu.optional(),_meta:S(D(),s()).optional()}),Ou=x({type:E(`tool_use`),name:D(),id:D(),input:S(D(),s()),_meta:S(D(),s()).optional()}),ku=x({type:E(`resource`),resource:y([Zl,$l]),annotations:tu.optional(),_meta:S(D(),s()).optional()}),Au=y([Tu,Eu,Du,nu.extend({type:E(`resource_link`)}),ku]),ju=x({role:eu,content:Au}),Mu=al.extend({description:D().optional(),messages:T(ju)}),Nu=il.extend({method:E(`notifications/prompts/list_changed`),params:rl.optional()}),Pu=x({title:D().optional(),readOnlyHint:ue().optional(),destructiveHint:ue().optional(),idempotentHint:ue().optional(),openWorldHint:ue().optional()}),Fu=x({taskSupport:le([`required`,`optional`,`forbidden`]).optional()}),Iu=x({...bl.shape,...yl.shape,description:D().optional(),inputSchema:x({type:E(`object`),properties:S(D(),qc).optional(),required:T(D()).optional()}).catchall(s()),outputSchema:x({type:E(`object`),properties:S(D(),qc).optional(),required:T(D()).optional()}).catchall(s()).optional(),annotations:Pu.optional(),execution:Fu.optional(),_meta:S(D(),s()).optional()}),Lu=Il.extend({method:E(`tools/list`)}),Ru=Ll.extend({tools:T(Iu)}),zu=al.extend({content:T(Au).default([]),structuredContent:S(D(),s()).optional(),isError:ue().optional()});zu.or(al.extend({toolResult:s()}));const Bu=el.extend({name:D(),arguments:S(D(),s()).optional()}),Vu=nl.extend({method:E(`tools/call`),params:Bu}),Hu=il.extend({method:E(`notifications/tools/list_changed`),params:rl.optional()});x({autoRefresh:ue().default(!0),debounceMs:C().int().nonnegative().default(300)});const Uu=le([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Wu=$c.extend({level:Uu}),Gu=nl.extend({method:E(`logging/setLevel`),params:Wu}),Ku=rl.extend({level:Uu,logger:D().optional(),data:s()}),qu=il.extend({method:E(`notifications/message`),params:Ku}),Ju=x({hints:T(x({name:D().optional()})).optional(),costPriority:C().min(0).max(1).optional(),speedPriority:C().min(0).max(1).optional(),intelligencePriority:C().min(0).max(1).optional()}),Yu=x({mode:le([`auto`,`required`,`none`]).optional()}),Xu=x({type:E(`tool_result`),toolUseId:D().describe(`The unique identifier for the corresponding tool call.`),content:T(Au).default([]),structuredContent:x({}).loose().optional(),isError:ue().optional(),_meta:S(D(),s()).optional()}),Zu=ne(`type`,[Tu,Eu,Du]),Qu=ne(`type`,[Tu,Eu,Du,Ou,Xu]),$u=x({role:eu,content:y([Qu,T(Qu)]),_meta:S(D(),s()).optional()}),ed=el.extend({messages:T($u),modelPreferences:Ju.optional(),systemPrompt:D().optional(),includeContext:le([`none`,`thisServer`,`allServers`]).optional(),temperature:C().optional(),maxTokens:C().int(),stopSequences:T(D()).optional(),metadata:qc.optional(),tools:T(Iu).optional(),toolChoice:Yu.optional()}),td=nl.extend({method:E(`sampling/createMessage`),params:ed}),nd=al.extend({model:D(),stopReason:fe(le([`endTurn`,`stopSequence`,`maxTokens`]).or(D())),role:eu,content:Zu}),rd=al.extend({model:D(),stopReason:fe(le([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(D())),role:eu,content:y([Qu,T(Qu)])}),id=x({type:E(`boolean`),title:D().optional(),description:D().optional(),default:ue().optional()}),ad=x({type:E(`string`),title:D().optional(),description:D().optional(),minLength:C().optional(),maxLength:C().optional(),format:le([`email`,`uri`,`date`,`date-time`]).optional(),default:D().optional()}),od=x({type:le([`number`,`integer`]),title:D().optional(),description:D().optional(),minimum:C().optional(),maximum:C().optional(),default:C().optional()}),sd=x({type:E(`string`),title:D().optional(),description:D().optional(),enum:T(D()),default:D().optional()}),cd=x({type:E(`string`),title:D().optional(),description:D().optional(),oneOf:T(x({const:D(),title:D()})),default:D().optional()}),ld=y([y([x({type:E(`string`),title:D().optional(),description:D().optional(),enum:T(D()),enumNames:T(D()).optional(),default:D().optional()}),y([sd,cd]),y([x({type:E(`array`),title:D().optional(),description:D().optional(),minItems:C().optional(),maxItems:C().optional(),items:x({type:E(`string`),enum:T(D())}),default:T(D()).optional()}),x({type:E(`array`),title:D().optional(),description:D().optional(),minItems:C().optional(),maxItems:C().optional(),items:x({anyOf:T(x({const:D(),title:D()}))}),default:T(D()).optional()})])]),id,ad,od]),ud=y([el.extend({mode:E(`form`).optional(),message:D(),requestedSchema:x({type:E(`object`),properties:S(D(),ld),required:T(D()).optional()})}),el.extend({mode:E(`url`),message:D(),elicitationId:D(),url:D().url()})]),dd=nl.extend({method:E(`elicitation/create`),params:ud}),fd=rl.extend({elicitationId:D()}),pd=il.extend({method:E(`notifications/elicitation/complete`),params:fd}),md=al.extend({action:le([`accept`,`decline`,`cancel`]),content:ge(e=>e===null?void 0:e,S(D(),y([D(),C(),ue(),T(D())])).optional())}),hd=x({type:E(`ref/resource`),uri:D()}),gd=x({type:E(`ref/prompt`),name:D()}),_d=$c.extend({ref:y([gd,hd]),argument:x({name:D(),value:D()}),context:x({arguments:S(D(),D()).optional()}).optional()}),vd=nl.extend({method:E(`completion/complete`),params:_d});function yd(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function bd(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const xd=al.extend({completion:w({values:T(D()).max(100),total:fe(C().int()),hasMore:fe(ue())})}),Sd=x({uri:D().startsWith(`file://`),name:D().optional(),_meta:S(D(),s()).optional()}),Cd=nl.extend({method:E(`roots/list`),params:$c.optional()}),wd=al.extend({roots:T(Sd)}),Td=il.extend({method:E(`notifications/roots/list_changed`),params:rl.optional()});y([jl,Dl,vd,Gu,wu,xu,iu,ou,uu,mu,gu,Vu,Lu,Ul,Gl,Kl,Jl]),y([vl,Pl,Al,Td,Hl]),y([gl,nd,rd,md,wd,Wl,ql,Bl]),y([jl,td,dd,Cd,Ul,Gl,Kl,Jl]),y([vl,Pl,qu,vu,fu,Hu,Nu,Hl,pd]),y([gl,kl,xd,Mu,Su,au,su,du,zu,Ru,Wl,ql,Bl]);var V=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===B.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Ed(e.elicitations,n)}return new e(t,n,r)}},Ed=class extends V{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(B.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Dd(e){return e===`completed`||e===`failed`||e===`cancelled`}const Od=Symbol(`Let zodToJsonSchema decide on which parser to use`),kd={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},Ad=e=>typeof e==`string`?{...kd,name:e}:{...kd,...e},jd=e=>{let t=Ad(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function Md(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function H(e,t,n,r,i){e[t]=n,Md(e,t,r,i)}const Nd=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function Pd(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?Nd(t,e.currentPath):t.join(`/`)}}function Fd(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==z.ZodAny&&(n.items=U(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&H(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&H(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(H(n,`minItems`,e.exactLength.value,e.exactLength.message,t),H(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Id(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?H(n,`minimum`,r.value,r.message,t):H(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),H(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?H(n,`maximum`,r.value,r.message,t):H(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),H(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:H(n,`multipleOf`,r.value,r.message,t);break}return n}function Ld(){return{type:`boolean`}}function Rd(e,t){return U(e.type._def,t)}const zd=(e,t)=>U(e.innerType._def,t);function Bd(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>Bd(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return Vd(e,t)}}const Vd=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:H(n,`minimum`,r.value,r.message,t);break;case`max`:H(n,`maximum`,r.value,r.message,t);break}return n};function Hd(e,t){return{...U(e.innerType._def,t),default:e.defaultValue()}}function Ud(e,t){return t.effectStrategy===`input`?U(e.schema._def,t):Pd(t)}function Wd(e){return{type:`string`,enum:Array.from(e.values)}}const Gd=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Kd(e,t){let n=[U(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),U(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(Gd(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function qd(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}let Jd;const Yd={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Jd===void 0&&(Jd=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),Jd),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Xd(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:H(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:H(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:ef(n,`email`,r.message,t);break;case`format:idn-email`:ef(n,`idn-email`,r.message,t);break;case`pattern:zod`:tf(n,Yd.email,r.message,t);break}break;case`url`:ef(n,`uri`,r.message,t);break;case`uuid`:ef(n,`uuid`,r.message,t);break;case`regex`:tf(n,r.regex,r.message,t);break;case`cuid`:tf(n,Yd.cuid,r.message,t);break;case`cuid2`:tf(n,Yd.cuid2,r.message,t);break;case`startsWith`:tf(n,RegExp(`^${Zd(r.value,t)}`),r.message,t);break;case`endsWith`:tf(n,RegExp(`${Zd(r.value,t)}$`),r.message,t);break;case`datetime`:ef(n,`date-time`,r.message,t);break;case`date`:ef(n,`date`,r.message,t);break;case`time`:ef(n,`time`,r.message,t);break;case`duration`:ef(n,`duration`,r.message,t);break;case`length`:H(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),H(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:tf(n,RegExp(Zd(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&ef(n,`ipv4`,r.message,t),r.version!==`v4`&&ef(n,`ipv6`,r.message,t);break;case`base64url`:tf(n,Yd.base64url,r.message,t);break;case`jwt`:tf(n,Yd.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&tf(n,Yd.ipv4Cidr,r.message,t),r.version!==`v4`&&tf(n,Yd.ipv6Cidr,r.message,t);break;case`emoji`:tf(n,Yd.emoji(),r.message,t);break;case`ulid`:tf(n,Yd.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:ef(n,`binary`,r.message,t);break;case`contentEncoding:base64`:H(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:tf(n,Yd.base64,r.message,t);break}break;case`nanoid`:tf(n,Yd.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function Zd(e,t){return t.patternStrategy===`escape`?$d(e):e}const Qd=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function $d(e){let t=``;for(let n=0;n<e.length;n++)Qd.has(e[n])||(t+=`\\`),t+=e[n];return t}function ef(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):H(e,`format`,t,n,r)}function tf(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:nf(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):H(e,`pattern`,nf(t,r),n,r)}function nf(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
@@ -56,7 +56,7 @@ Open Knowledge accretes a persistent wiki through three workflow tools, mapped t
56
56
 
57
57
  Karpathy's insight: "The tedious part of maintaining a knowledge base is not the reading or the thinking — it's the bookkeeping." Humans abandon wikis because maintenance costs exceed perceived value. These tools exist so an agent can do the bookkeeping (fetching, summarizing, cross-linking, superseding) without fatigue. Follow the steps below faithfully — skipping the cross-linking, supersedes chains, or raw-source preservation is what turns a useful wiki back into an abandoned one.
58
58
 
59
- `}async function eh(e,t){return typeof e==`function`?await e(t):e}async function th(e,t){return typeof e==`function`?await e(t):e}async function nh(e,t,n){let r;try{r=await e(n)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}try{let e=await th(t,r);return{ok:!0,cwd:r,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function rh(e,t,n,r){let i=await nh(e,t,r);if(!i.ok)return i;let{cwd:a,config:o}=i;try{return{ok:!0,cwd:a,config:o,url:await eh(n,a)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function ih(e){let t=e.toLowerCase();return t.endsWith(`.md`)?{ok:!0,docName:e.slice(0,-3)}:t.endsWith(`.mdx`)?{ok:!0,docName:e.slice(0,-4)}:t.endsWith(`.markdown`)?{ok:!1,error:`Error: docName "${e}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`}:{ok:!0,docName:e}}async function ah(e,t){let n;try{n=await fetch(`${e}${t}`,{signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}try{return await n.json()}catch{return{ok:!1,error:`Server returned HTTP ${n.status} with non-JSON body`}}}async function oh(e,t,n){let r;try{r=await fetch(`${e}${t}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:n?JSON.stringify(n):void 0,signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}try{return await r.json()}catch{return{ok:!1,error:`Server returned HTTP ${r.status} with non-JSON body`}}}function sh(e,t){return`${$m(`consolidate`)}Promote existing research on this topic into a canonical article inside the project content directory. **Canonical, not provisional** — the output is the source of truth for future agents.
59
+ `}async function eh(e,t){return typeof e==`function`?await e(t):e}async function th(e,t){return typeof e==`function`?await e(t):e}async function nh(e,t,n){let r;try{r=await e(n)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}try{let e=await th(t,r);return{ok:!0,cwd:r,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function rh(e,t,n,r){let i=await nh(e,t,r);if(!i.ok)return i;let{cwd:a,config:o}=i;try{return{ok:!0,cwd:a,config:o,url:await eh(n,a)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function ih(e){let t=e.toLowerCase();return t.endsWith(`.md`)?{ok:!0,docName:e.slice(0,-3)}:t.endsWith(`.mdx`)?{ok:!0,docName:e.slice(0,-4)}:t.endsWith(`.markdown`)?{ok:!1,error:`Error: docName "${e}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`}:{ok:!0,docName:e}}async function ah(e,t){let n;try{n=await fetch(`${e}${t}`,{signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}try{return await n.json()}catch{return{ok:!1,error:`Server returned HTTP ${n.status} with non-JSON body`}}}async function oh(e,t,n){let r;try{r=await fetch(`${e}${t}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:n?JSON.stringify(n):void 0,signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}try{return await r.json()}catch{return{ok:!1,error:`Server returned HTTP ${r.status} with non-JSON body`}}}function sh(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{existing:t,incoming:n,to:r}=e;return typeof t==`string`&&typeof n==`string`&&typeof r==`string`?[{existing:t,incoming:n,to:r}]:[]}):[]}function ch(e,t){return`${$m(`consolidate`)}Promote existing research on this topic into a canonical article inside the project content directory. **Canonical, not provisional** — the output is the source of truth for future agents.
60
60
 
61
61
  Topic: ${e}
62
62
 
@@ -203,48 +203,48 @@ superseded_by: <path-to-new-canonical-article>.md
203
203
  - **Don't delete research articles** — they are the trail; keep them with a \`superseded_by\` marker
204
204
  - **Don't rewrite research prose verbatim** — canonical articles have a different voice (direct, decided) than research (exploratory, provisional)
205
205
  - **Don't skip the supersedes / superseded_by links** — the audit trail matters for future readers
206
- `}const ch=[`Promote research into a canonical article inside the project content directory. Canonical, not provisional — the output is the source of truth for future agents.`,``,`**Use when:**`,`- A team has made a decision after research and wants the outcome committed as canonical knowledge`,`- Compacting several provisional research notes into one authoritative article`,`- A developer asks to "consolidate" or "finalize" knowledge on a topic`,``,`**Triggers on:**`,`- "consolidate", "finalize", "promote to canonical", "make this official"`,`- User says the team has decided and wants the outcome written as canonical`,`- Research has stabilized and a destination article is needed`].join(`
207
- `);function lh(e,t){e.tool(`consolidate`,ch,{topic:D().describe(`The topic to consolidate into a canonical article`),cwd:D().optional().describe(qm)},async e=>{let n=await nh(t.resolveCwd,t.config,e.cwd);return n.ok?q(sh(e.topic,n.config.content.dir),{previewUrl:null}):K(`Error: ${n.error}`,!0)})}function uh(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}function dh(e){return e.endsWith(`/`)?e.slice(0,-1):e}function fh(e){try{return new URL(e),!0}catch{return!1}}async function ph(e,t,n){let r=n??await t.resolveCwd(),i=await th(t.config,r),a=Ce(i,r);return _h(e,{config:i,lockDir:Se(a),contentDir:a})}function mh(e){try{let t=je(e.lockDir);if(t&&t.port>0)return{baseUrl:`http://localhost:${t.port}`,port:t.port}}catch(t){process.stderr.write(`[preview-url] readUiLock failed at ${e.lockDir} while building ui block: ${t instanceof Error?t.message:String(t)}\n`)}return{baseUrl:null,port:null}}async function hh(e,t){let n=t??await e.resolveCwd(),r=await th(e.config,n),i=Ce(r,n),a={config:r,lockDir:Se(i),contentDir:i};return{resolve:e=>_h(e,a),ui:mh(a)}}function gh(e){let t=e.toLowerCase();return t.endsWith(`.md`)?e.slice(0,-3):t.endsWith(`.mdx`)?e.slice(0,-4):e}function _h(e,t){let n=`/#/${uh(e)}`;if(process.env.OK_ELECTRON_PROTOCOL_HOST===`1`&&t.contentDir)try{let n=qn(t.contentDir);return{url:`openknowledge://open?project=${encodeURIComponent(n)}&doc=${encodeURIComponent(e)}`,source:`electron-protocol`}}catch(e){process.stderr.write(`[preview-url] realpathSync failed for ${t.contentDir}, falling through to http sources: ${e instanceof Error?e.message:String(e)}\n`)}let r=process.env.OPEN_KNOWLEDGE_PREVIEW_BASE_URL;if(r&&fh(r))return{url:`${dh(r)}${n}`,source:`env`};try{let e=je(t.lockDir);if(e&&e.port>0)return{url:`http://localhost:${e.port}${n}`,source:`lock`}}catch(e){process.stderr.write(`[preview-url] readUiLock failed at ${t.lockDir}, falling through to config: ${e instanceof Error?e.message:String(e)}\n`)}let i=t.config.preview?.baseUrl;return i&&fh(i)?{url:`${dh(i)}${n}`,source:`config`}:null}const vh=[`[Requires: Hocuspocus server] Find-and-replace on a live document via the CRDT layer.`,`The patch is applied through Hocuspocus and propagated to all connected editors in real-time.`,"Use `offset` when you need to patch an exact occurrence; omit it to preserve first-match behavior.",``,"**When rewriting prose, add `[[wiki-links]]` aggressively.** If the replacement mentions other documents or entities that should have their own page, link them as `[[Page Name]]`. Over-linking is the goal; underlinked documents lose their value in backlink-driven navigation.",``,`**Parameters:**`,"- `docName` — Document name, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `find` — Text to find (exact match)","- `replace` — Replacement text","- `offset` (optional) — Exact occurrence to patch, as a JavaScript string offset in the current markdown. If the document changed and the text no longer matches there, the server returns a stale-target error; re-run `suggest_links` to get fresh offsets.",'- `summary` — Optional one-line user-outcome description of this edit (≤80 chars). Appears as a bullet in the document timeline so readers can scan intent without opening every diff. Prefer outcome phrasing ("Fixed token-refresh race") over structural ("Changed 1 line"). Avoid including secrets or PII — summaries are persisted to git history.'].join(`
208
- `);function yh(e,t){e.tool(`edit_document`,vh,{docName:D().describe(`Document name to edit`),find:D().describe(`Text to find (exact match)`),replace:D().describe(`Replacement text`),offset:C().int().min(0).optional().describe(`Exact occurrence to patch, as a JavaScript string offset in the current markdown`),summary:Jm,cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:a}=n;if(!a)return K(Ym,!0);let o=ih(e.docName);if(!o.ok)return K(o.error,!0);let s=t.identityRef?.current,c=await oh(a,`/api/agent-patch`,{docName:o.docName,find:e.find,replace:e.replace,offset:e.offset,...e.summary===void 0?{}:{summary:e.summary},...s?{agentId:s.connectionId,agentName:s.displayName,clientName:s.clientInfo?.name,colorSeed:s.colorSeed}:{}});if(!c.ok)return K(`Error: ${c.error}`,!0);let l=Se(Ce(i,r)),u=_h(o.docName,{config:i,lockDir:l}),d=typeof c.subscriberCount==`number`?c.subscriberCount:void 0,f=(typeof c.systemSubscriberCount==`number`?c.systemSubscriberCount:void 0)===0,p=d===0,m=c.summary&&typeof c.summary==`object`?c.summary:void 0,h=typeof m?.hint==`string`?m.hint:void 0,g=[`Edit applied successfully.`];u&&g.push(`Preview: ${u.url}`),f&&g.push(u?`Open ${u.url} in your preview browser.`:`No preview attached. Start the UI.`),h&&g.push(h);let _=g.join(`
209
- `);if(!u&&!f&&!p&&!m)return K(_);let v={};return u&&(v.previewUrl=u.url,v.previewUrlSource=u.source),f&&(v.warning={message:`Open the previewUrl in your preview browser.`,action:`attach-preview-once`,previewUrl:u?.url??null}),m&&(v.summary=m),q(_,v)})}const bh=new Set([`cat`,`ls`,`grep`,`find`]),xh=/\b[\w./-]+\.(md|mdx)\b/g;function Sh(e){return/\.(md|mdx)$/.test(e)}function Ch(e){let t=e.trim();return t?(t=t.replace(/\/+/g,`/`),t.startsWith(`./`)&&(t=t.slice(2)),t.endsWith(`/`)&&(t=t.slice(0,-1)),t):``}function wh(e){return e.args.slice(1)}function Th(e){return e.filter(e=>!e.startsWith(`-`))}function Eh(e){return Th(wh(e)).filter(Sh)}function Dh(e,t){let n=Th(wh(t)),r=n.length>0?n[n.length-1]:``,i=r&&r!==`.`?Ch(r):``,a=[];i&&a.push(i);for(let t of e.split(`
210
- `)){let e=t.trim();if(!e||/\.[a-z0-9]+$/i.test(e)&&!Sh(e))continue;let n=i?`${i}/${e}`:e;a.push(n)}return a}function Oh(e){let t=[];for(let n of e.split(`
211
- `)){if(!n)continue;let e=n.indexOf(`:`);if(e<0)continue;let r=Ch(n.slice(0,e));Sh(r)&&t.push(r)}return t}function kh(e){let t=[];for(let n of e.split(`
212
- `)){let e=Ch(n);e&&Sh(e)&&t.push(e)}return t}function Ah(e){return Th(wh(e)).filter(Sh)}function jh(e){return Th(wh(e)).length>0}function Mh(e){let t=[],n=e.matchAll(xh);for(let e of n)t.push(Ch(e[0]));return t}function Nh(e,t){let n=null;for(let e=t.length-1;e>=0;e--){let r=t[e];if(bh.has(r.command)){n=r;break}if((r.command===`head`||r.command===`tail`)&&jh(r)){n=r;break}}let r;if(!n)r=Mh(e);else{switch(n.command){case`cat`:r=Eh(n);break;case`ls`:r=Dh(e,n);break;case`grep`:r=Oh(e);break;case`find`:r=kh(e);break;case`head`:case`tail`:r=Ah(n);break;default:r=Mh(e)}r.length===0&&(r=Mh(e))}let i=new Set,a=[];for(let e of r){let t=Ch(e);!t||i.has(t)||(i.add(t),a.push(t))}return a}var Ph=[{name:`echo`,load:async()=>(await import(`./echo-O45JWWI2-CX34tpdA.mjs`)).echoCommand},{name:`cat`,load:async()=>(await import(`./cat-RDUMLXKC-BBkiYZHY.mjs`)).catCommand},{name:`printf`,load:async()=>(await import(`./printf-CX64KX2P-CqRH1fcx.mjs`)).printfCommand},{name:`ls`,load:async()=>(await import(`./ls-KSXFZCWH-DqDgh03N.mjs`)).lsCommand},{name:`mkdir`,load:async()=>(await import(`./mkdir-TDEMSB6C-BJEISkIZ.mjs`)).mkdirCommand},{name:`rmdir`,load:async()=>(await import(`./rmdir-XTQXT7RK-qEC715ec.mjs`)).rmdirCommand},{name:`touch`,load:async()=>(await import(`./touch-DX2IJOQ4-lH1eyelO.mjs`)).touchCommand},{name:`rm`,load:async()=>(await import(`./rm-RTZG23RL-DlEnXUAF.mjs`)).rmCommand},{name:`cp`,load:async()=>(await import(`./cp-XOYR4ABJ-bKEUBRiq.mjs`)).cpCommand},{name:`mv`,load:async()=>(await import(`./mv-Z6MORUFL-BmfrJjSs.mjs`)).mvCommand},{name:`ln`,load:async()=>(await import(`./ln-4TRFBYAT-CVLYmUk7.mjs`)).lnCommand},{name:`chmod`,load:async()=>(await import(`./chmod-SYMGL4JA-CrZnOwHN.mjs`)).chmodCommand},{name:`pwd`,load:async()=>(await import(`./pwd-D4OZ7N27-CKM9OA6o.mjs`)).pwdCommand},{name:`readlink`,load:async()=>(await import(`./readlink-MI4GCHJF-Ck2tsjqo.mjs`)).readlinkCommand},{name:`head`,load:async()=>(await import(`./head-HT2B6D2J-BbfykFhC.mjs`)).headCommand},{name:`tail`,load:async()=>(await import(`./tail-S5ULNTJU-BWlMoVaY.mjs`)).tailCommand},{name:`wc`,load:async()=>(await import(`./wc-TQB3VNOX-DJ8k4PUj.mjs`)).wcCommand},{name:`stat`,load:async()=>(await import(`./stat-BT5A227F-DpCEGAGw.mjs`)).statCommand},{name:`grep`,load:async()=>(await import(`./grep-3AIAIJVR-fpYA0UVG.mjs`)).grepCommand},{name:`fgrep`,load:async()=>(await import(`./grep-3AIAIJVR-fpYA0UVG.mjs`)).fgrepCommand},{name:`egrep`,load:async()=>(await import(`./grep-3AIAIJVR-fpYA0UVG.mjs`)).egrepCommand},{name:`rg`,load:async()=>(await import(`./rg-FOQSCCX3-B6b10f2I.mjs`)).rgCommand},{name:`sed`,load:async()=>(await import(`./sed-VFTTATXJ-SJAhm12K.mjs`)).sedCommand},{name:`awk`,load:async()=>(await import(`./awk2-POPGKRAI-Cc3gWubt.mjs`)).awkCommand2},{name:`sort`,load:async()=>(await import(`./sort-DCNRDA7U-B9r9vaz_.mjs`)).sortCommand},{name:`uniq`,load:async()=>(await import(`./uniq-SUNANL47-DQSg6ulH.mjs`)).uniqCommand},{name:`comm`,load:async()=>(await import(`./comm-5SLSESQG-PpE3c4ZK.mjs`)).commCommand},{name:`cut`,load:async()=>(await import(`./cut-OPC3VAGB-DFILWBLt.mjs`)).cutCommand},{name:`paste`,load:async()=>(await import(`./paste-7N6AFSDS-DZ1UxLP-.mjs`)).pasteCommand},{name:`tr`,load:async()=>(await import(`./tr-2HXZRDSW-WTWP1Y3I.mjs`)).trCommand},{name:`rev`,load:async()=>(await import(`./rev-XOSYPP45-dyxz7TNM.mjs`)).rev},{name:`nl`,load:async()=>(await import(`./nl-U5YJDM32-CwKzmNae.mjs`)).nl},{name:`fold`,load:async()=>(await import(`./fold-LDSORVYE-DhorwB1M.mjs`)).fold},{name:`expand`,load:async()=>(await import(`./expand-DTNXU4LQ-Def0IjrD.mjs`)).expand},{name:`unexpand`,load:async()=>(await import(`./unexpand-RGTMIGZM-CvVeOYsA.mjs`)).unexpand},{name:`strings`,load:async()=>(await import(`./strings-7PLOGTPD-Bc3LcdUK.mjs`)).strings},{name:`split`,load:async()=>(await import(`./split-SITCSYCZ-CVEBVG_b.mjs`)).split},{name:`column`,load:async()=>(await import(`./column-WLPMMSTS-B7r8iBQX.mjs`)).column},{name:`join`,load:async()=>(await import(`./join-GG2LDHE5-C6rITFRb.mjs`)).join},{name:`tee`,load:async()=>(await import(`./tee-O7VXZDCO-BZ-Wtr3X.mjs`)).teeCommand},{name:`find`,load:async()=>(await import(`./find-TPUOAIUQ-C0CUhYWB.mjs`)).findCommand},{name:`basename`,load:async()=>(await import(`./basename-AA2KJYZQ-DpGE_2LJ.mjs`)).basenameCommand},{name:`dirname`,load:async()=>(await import(`./dirname-LEMTZZFS-DM2ha26y.mjs`)).dirnameCommand},{name:`tree`,load:async()=>(await import(`./tree-LYXBS7DC-B0XAnWvf.mjs`)).treeCommand},{name:`du`,load:async()=>(await import(`./du-WO2ENHXQ-DK5I7PKg.mjs`)).duCommand},{name:`env`,load:async()=>(await import(`./env-5EPCWSXR-C0C0-iCD.mjs`)).envCommand},{name:`printenv`,load:async()=>(await import(`./env-5EPCWSXR-C0C0-iCD.mjs`)).printenvCommand},{name:`alias`,load:async()=>(await import(`./alias-JE7RI5QX-B6svpkRM.mjs`)).aliasCommand},{name:`unalias`,load:async()=>(await import(`./alias-JE7RI5QX-B6svpkRM.mjs`)).unaliasCommand},{name:`history`,load:async()=>(await import(`./history-J4QRNGRO-CxkOfNgO.mjs`)).historyCommand},{name:`xargs`,load:async()=>(await import(`./xargs-I6EZUCYF-BTL0Cz6j.mjs`)).xargsCommand},{name:`true`,load:async()=>(await import(`./true-WHJNXCHG-CfyqCtO-.mjs`)).trueCommand},{name:`false`,load:async()=>(await import(`./true-WHJNXCHG-CfyqCtO-.mjs`)).falseCommand},{name:`clear`,load:async()=>(await import(`./clear-5CZ5X4YR-CQ9G2b6A.mjs`)).clearCommand},{name:`bash`,load:async()=>(await import(`./bash-IJWYRKFO-zBASRHFa.mjs`)).bashCommand},{name:`sh`,load:async()=>(await import(`./bash-IJWYRKFO-zBASRHFa.mjs`)).shCommand},{name:`jq`,load:async()=>(await import(`./jq-ODXZBPLY-DwKW_5e4.mjs`)).jqCommand},{name:`base64`,load:async()=>(await import(`./base64-4YMZCVJ5-BYz2VU1K.mjs`)).base64Command},{name:`diff`,load:async()=>(await import(`./diff-HJF2MPDN-BRsHJrES.mjs`)).diffCommand},{name:`date`,load:async()=>(await import(`./date-DD7FVA2V-B1vw27vz.mjs`)).dateCommand},{name:`sleep`,load:async()=>(await import(`./sleep-VZFPZFWA-2i5JaN6o.mjs`)).sleepCommand},{name:`timeout`,load:async()=>(await import(`./timeout-VRKMCG72-CGi8Ki9F.mjs`)).timeoutCommand},{name:`time`,load:async()=>(await import(`./time-DEUO3QV2-DGu9Jt8t.mjs`)).timeCommand},{name:`seq`,load:async()=>(await import(`./seq-RN5ZUASB-BH9pwR7X.mjs`)).seqCommand},{name:`expr`,load:async()=>(await import(`./expr-5T3UU5KE-CpNcSEhS.mjs`)).exprCommand},{name:`md5sum`,load:async()=>(await import(`./md5sum-INMIK4DX-3q3X2_Bl.mjs`)).md5sumCommand},{name:`sha1sum`,load:async()=>(await import(`./sha1sum-VJPNLNU6-7wFUSeyx.mjs`)).sha1sumCommand},{name:`sha256sum`,load:async()=>(await import(`./sha256sum-PI32XWXY-RLxkSiqX.mjs`)).sha256sumCommand},{name:`file`,load:async()=>(await import(`./file-ZIGAJ4YS-C1Mgh9Dx.mjs`)).fileCommand},{name:`html-to-markdown`,load:async()=>(await import(`./html-to-markdown-TFCECAGV-DYB58Aq3.mjs`)).htmlToMarkdownCommand},{name:`help`,load:async()=>(await import(`./help-VVWX7SA5-rfn2xlDJ.mjs`)).helpCommand},{name:`which`,load:async()=>(await import(`./which-XZHEH76L-CLG5qPgv.mjs`)).whichCommand},{name:`tac`,load:async()=>(await import(`./tac-SJGXQ4T2-Cp7URH3w.mjs`)).tac},{name:`hostname`,load:async()=>(await import(`./hostname-BK6HG2DE-C1nZ6rEU.mjs`)).hostname},{name:`whoami`,load:async()=>(await import(`./whoami-DGKU3D2X-DO5vmoPX.mjs`)).whoami},{name:`od`,load:async()=>(await import(`./od-VJEF2UR5-CIYaWeFb.mjs`)).od},{name:`gzip`,load:async()=>(await import(`./gzip-AQXSGOVS-ZJPD6VJq.mjs`)).gzipCommand},{name:`gunzip`,load:async()=>(await import(`./gzip-AQXSGOVS-ZJPD6VJq.mjs`)).gunzipCommand},{name:`zcat`,load:async()=>(await import(`./gzip-AQXSGOVS-ZJPD6VJq.mjs`)).zcatCommand}];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Ph.push({name:`tar`,load:async()=>(await import(`./tar-ANUBEFJY-_2-XJ8OD.mjs`)).tarCommand}),Ph.push({name:`yq`,load:async()=>(await import(`./yq-MJMAR36V-CPQTwsxW.mjs`)).yqCommand}),Ph.push({name:`xan`,load:async()=>(await import(`./xan-BXDXYEIB-BUzA9fZa.mjs`)).xanCommand}),Ph.push({name:`sqlite3`,load:async()=>(await import(`./sqlite3-56UMWEY3-htZnl7uZ.mjs`)).sqlite3Command}));var Fh=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Fh.push({name:`python3`,load:async()=>(await import(`./python3-AUFTPCU6-BS26F1oD.mjs`)).python3Command}),Fh.push({name:`python`,load:async()=>(await import(`./python3-AUFTPCU6-BS26F1oD.mjs`)).pythonCommand}));var Ih=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Ih.push({name:`js-exec`,load:async()=>(await import(`./js-exec-M6UR76J5-C3ExU6nu.mjs`)).jsExecCommand}),Ih.push({name:`node`,load:async()=>(await import(`./js-exec-M6UR76J5-C3ExU6nu.mjs`)).nodeStubCommand}));var Lh=[{name:`curl`,load:async()=>(await import(`./curl-47BFPSFW-KKVaDuOB.mjs`)).curlCommand}],Rh=new Map;function zh(e){return{name:e.name,async execute(t,n){let r=Rh.get(e.name);if(r||(r=await vn.runTrustedAsync(()=>e.load()),Rh.set(e.name,r)),n.coverage&&(typeof __BROWSER__>`u`||!__BROWSER__)){let{emitFlagCoverage:r}=await import(`./flag-coverage-QT4N2Z44-CirEjvTd.mjs`);r(n.coverage,e.name,t)}return r.execute(t,n)}}}function Bh(e){return(e?Ph.filter(t=>e.includes(t.name)):Ph).map(zh)}function Vh(){return Lh.map(zh)}function Hh(){return Fh.map(zh)}function Uh(){return Ih.map(zh)}function Wh(e){return`load`in e&&typeof e.load==`function`}function Gh(e){let t=null;return{name:e.name,trusted:!0,async execute(n,r){return t||=await e.load(),t.execute(n,r)}}}var Kh=new TextEncoder;function qh(e){return typeof e==`object`&&!!e&&!(e instanceof Uint8Array)&&`content`in e}var Jh=class{data=new Map;constructor(e){if(this.data.set(`/`,{type:`directory`,mode:493,mtime:new Date}),e)for(let[t,n]of Object.entries(e))typeof n==`function`?this.writeFileLazy(t,n):qh(n)?this.writeFileSync(t,n.content,void 0,{mode:n.mode,mtime:n.mtime}):this.writeFileSync(t,n)}ensureParentDirs(e){let t=rn(e);t!==`/`&&(this.data.has(t)||(this.ensureParentDirs(t),this.data.set(t,{type:`directory`,mode:493,mtime:new Date})))}writeFileSync(e,t,n,r){k(e,`write`);let i=on(e);this.ensureParentDirs(i);let a=mn(t,pn(n));this.data.set(i,{type:`file`,content:a,mode:r?.mode??420,mtime:r?.mtime??new Date})}writeFileLazy(e,t,n){k(e,`write`);let r=on(e);this.ensureParentDirs(r),this.data.set(r,{type:`file`,lazy:t,mode:n?.mode??420,mtime:n?.mtime??new Date})}async materializeLazy(e,t){let n=await t.lazy(),r={type:`file`,content:typeof n==`string`?Kh.encode(n):n,mode:t.mode,mtime:t.mtime};return this.data.set(e,r),r}async readFile(e,t){return hn(await this.readFileBuffer(e),pn(t))}async readFileBuffer(e){k(e,`open`);let t=this.resolvePathWithSymlinks(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, open '${e}'`);if(n.type!==`file`)throw Error(`EISDIR: illegal operation on a directory, read '${e}'`);if(`lazy`in n){let e=await this.materializeLazy(t,n);return e.content instanceof Uint8Array?e.content:Kh.encode(e.content)}return n.content instanceof Uint8Array?n.content:Kh.encode(n.content)}async writeFile(e,t,n){this.writeFileSync(e,t,n)}async appendFile(e,t,n){k(e,`append`);let r=on(e),i=this.data.get(r);if(i&&i.type===`directory`)throw Error(`EISDIR: illegal operation on a directory, write '${e}'`);let a=mn(t,pn(n));if(i?.type===`file`){let e=i;`lazy`in e&&(e=await this.materializeLazy(r,e));let t=`content`in e&&e.content instanceof Uint8Array?e.content:Kh.encode(`content`in e?e.content:``),n=new Uint8Array(t.length+a.length);n.set(t),n.set(a,t.length),this.data.set(r,{type:`file`,content:n,mode:e.mode,mtime:new Date})}else this.writeFileSync(e,t,n)}async exists(e){if(e.includes(`\0`))return!1;try{let t=this.resolvePathWithSymlinks(e);return this.data.has(t)}catch{return!1}}async stat(e){k(e,`stat`);let t=this.resolvePathWithSymlinks(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, stat '${e}'`);n.type===`file`&&`lazy`in n&&(n=await this.materializeLazy(t,n));let r=0;return n.type===`file`&&`content`in n&&n.content&&(r=n.content instanceof Uint8Array?n.content.length:Kh.encode(n.content).length),{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date}}async lstat(e){k(e,`lstat`);let t=this.resolveIntermediateSymlinks(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, lstat '${e}'`);if(n.type===`symlink`)return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:n.mode,size:n.target.length,mtime:n.mtime||new Date};n.type===`file`&&`lazy`in n&&(n=await this.materializeLazy(t,n));let r=0;return n.type===`file`&&`content`in n&&n.content&&(r=n.content instanceof Uint8Array?n.content.length:Kh.encode(n.content).length),{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date}}resolveIntermediateSymlinks(e){let t=on(e);if(t===`/`)return`/`;let n=t.slice(1).split(`/`);if(n.length<=1)return t;let r=``,i=new Set;for(let t=0;t<n.length-1;t++){let a=n[t];r=`${r}/${a}`;let o=this.data.get(r),s=0;for(;o&&o.type===`symlink`&&s<40;){if(i.has(r))throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`);i.add(r),r=fn(r,o.target),o=this.data.get(r),s++}if(s>=40)throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`)}return`${r}/${n[n.length-1]}`}resolvePathWithSymlinks(e){let t=on(e);if(t===`/`)return`/`;let n=t.slice(1).split(`/`),r=``,i=new Set;for(let t of n){r=`${r}/${t}`;let n=this.data.get(r),a=0;for(;n&&n.type===`symlink`&&a<40;){if(i.has(r))throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`);i.add(r),r=fn(r,n.target),n=this.data.get(r),a++}if(a>=40)throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`)}return r}async mkdir(e,t){this.mkdirSync(e,t)}mkdirSync(e,t){k(e,`mkdir`);let n=on(e);if(this.data.has(n)){if(this.data.get(n)?.type===`file`)throw Error(`EEXIST: file already exists, mkdir '${e}'`);if(!t?.recursive)throw Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let r=rn(n);if(r!==`/`&&!this.data.has(r))if(t?.recursive)this.mkdirSync(r,{recursive:!0});else throw Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.data.set(n,{type:`directory`,mode:493,mtime:new Date})}async readdir(e){return(await this.readdirWithFileTypes(e)).map(e=>e.name)}async readdirWithFileTypes(e){k(e,`scandir`);let t=on(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);let r=new Set;for(;n&&n.type===`symlink`;){if(r.has(t))throw Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);r.add(t),t=fn(t,n.target),n=this.data.get(t)}if(!n)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);if(n.type!==`directory`)throw Error(`ENOTDIR: not a directory, scandir '${e}'`);let i=t===`/`?`/`:`${t}/`,a=new Map;for(let[e,n]of this.data.entries())if(e!==t&&e.startsWith(i)){let t=e.slice(i.length),r=t.split(`/`)[0];r&&!t.includes(`/`,r.length)&&!a.has(r)&&a.set(r,{name:r,isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:n.type===`symlink`})}return Array.from(a.values()).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}async rm(e,t){k(e,`rm`);let n=on(e),r=this.data.get(n);if(!r){if(t?.force)return;throw Error(`ENOENT: no such file or directory, rm '${e}'`)}if(r.type===`directory`){let r=await this.readdir(n);if(r.length>0){if(!t?.recursive)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let e of r){let r=sn(n,e);await this.rm(r,t)}}}this.data.delete(n)}async cp(e,t,n){k(e,`cp`),k(t,`cp`);let r=on(e),i=on(t),a=this.data.get(r);if(!a)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(a.type===`file`)if(this.ensureParentDirs(i),`content`in a){let e=a.content instanceof Uint8Array?new Uint8Array(a.content):a.content;this.data.set(i,{...a,content:e})}else this.data.set(i,{...a});else if(a.type===`symlink`)this.ensureParentDirs(i),this.data.set(i,{...a});else if(a.type===`directory`){if(!n?.recursive)throw Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(i,{recursive:!0});let t=await this.readdir(r);for(let e of t){let t=sn(r,e),a=sn(i,e);await this.cp(t,a,n)}}}async mv(e,t){await this.cp(e,t,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,t){return an(e,t)}async chmod(e,t){k(e,`chmod`);let n=on(e),r=this.data.get(n);if(!r)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);r.mode=t}async symlink(e,t){k(t,`symlink`);let n=on(t);if(this.data.has(n))throw Error(`EEXIST: file already exists, symlink '${t}'`);this.ensureParentDirs(n),this.data.set(n,{type:`symlink`,target:e,mode:511,mtime:new Date})}async link(e,t){k(e,`link`),k(t,`link`);let n=on(e),r=on(t),i=this.data.get(n);if(!i)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(i.type!==`file`)throw Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(r))throw Error(`EEXIST: file already exists, link '${t}'`);let a=i;`lazy`in a&&(a=await this.materializeLazy(n,a)),this.ensureParentDirs(r),this.data.set(r,{type:`file`,content:a.content,mode:a.mode,mtime:a.mtime})}async readlink(e){k(e,`readlink`);let t=on(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, readlink '${e}'`);if(n.type!==`symlink`)throw Error(`EINVAL: invalid argument, readlink '${e}'`);return n.target}async realpath(e){k(e,`realpath`);let t=this.resolvePathWithSymlinks(e);if(!this.data.has(t))throw Error(`ENOENT: no such file or directory, realpath '${e}'`);return t}async utimes(e,t,n){k(e,`utimes`);let r=on(e),i=this.resolvePathWithSymlinks(r),a=this.data.get(i);if(!a)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);a.mtime=n}};function Yh(e){let t=e;return typeof t.mkdirSync==`function`&&typeof t.writeFileSync==`function`}function Xh(e,t){e.mkdirSync(`/bin`,{recursive:!0}),e.mkdirSync(`/usr/bin`,{recursive:!0}),t&&(e.mkdirSync(`/home/user`,{recursive:!0}),e.mkdirSync(`/tmp`,{recursive:!0}))}function Zh(e){e.mkdirSync(`/dev`,{recursive:!0}),e.writeFileSync(`/dev/null`,``),e.writeFileSync(`/dev/zero`,new Uint8Array),e.writeFileSync(`/dev/stdin`,``),e.writeFileSync(`/dev/stdout`,``),e.writeFileSync(`/dev/stderr`,``)}function Qh(e,t){e.mkdirSync(`/proc/self/fd`,{recursive:!0}),e.writeFileSync(`/proc/version`,`${jt}
206
+ `}const lh=[`Promote research into a canonical article inside the project content directory. Canonical, not provisional — the output is the source of truth for future agents.`,``,`**Use when:**`,`- A team has made a decision after research and wants the outcome committed as canonical knowledge`,`- Compacting several provisional research notes into one authoritative article`,`- A developer asks to "consolidate" or "finalize" knowledge on a topic`,``,`**Triggers on:**`,`- "consolidate", "finalize", "promote to canonical", "make this official"`,`- User says the team has decided and wants the outcome written as canonical`,`- Research has stabilized and a destination article is needed`].join(`
207
+ `);function uh(e,t){e.tool(`consolidate`,lh,{topic:D().describe(`The topic to consolidate into a canonical article`),cwd:D().optional().describe(qm)},async e=>{let n=await nh(t.resolveCwd,t.config,e.cwd);return n.ok?q(ch(e.topic,n.config.content.dir),{previewUrl:null}):K(`Error: ${n.error}`,!0)})}function dh(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}function fh(e){return e.endsWith(`/`)?e.slice(0,-1):e}function ph(e){try{return new URL(e),!0}catch{return!1}}async function mh(e,t,n){let r=n??await t.resolveCwd(),i=await th(t.config,r),a=Ce(i,r);return vh(e,{config:i,lockDir:Se(a),contentDir:a})}function hh(e){try{let t=je(e.lockDir);if(t&&t.port>0)return{baseUrl:`http://localhost:${t.port}`,port:t.port}}catch(t){process.stderr.write(`[preview-url] readUiLock failed at ${e.lockDir} while building ui block: ${t instanceof Error?t.message:String(t)}\n`)}return{baseUrl:null,port:null}}async function gh(e,t){let n=t??await e.resolveCwd(),r=await th(e.config,n),i=Ce(r,n),a={config:r,lockDir:Se(i),contentDir:i};return{resolve:e=>vh(e,a),ui:hh(a)}}function _h(e){let t=e.toLowerCase();return t.endsWith(`.md`)?e.slice(0,-3):t.endsWith(`.mdx`)?e.slice(0,-4):e}function vh(e,t){let n=`/#/${dh(e)}`;if(process.env.OK_ELECTRON_PROTOCOL_HOST===`1`&&t.contentDir)try{let n=qn(t.contentDir);return{url:`openknowledge://open?project=${encodeURIComponent(n)}&doc=${encodeURIComponent(e)}`,source:`electron-protocol`}}catch(e){process.stderr.write(`[preview-url] realpathSync failed for ${t.contentDir}, falling through to http sources: ${e instanceof Error?e.message:String(e)}\n`)}let r=process.env.OPEN_KNOWLEDGE_PREVIEW_BASE_URL;if(r&&ph(r))return{url:`${fh(r)}${n}`,source:`env`};try{let e=je(t.lockDir);if(e&&e.port>0)return{url:`http://localhost:${e.port}${n}`,source:`lock`}}catch(e){process.stderr.write(`[preview-url] readUiLock failed at ${t.lockDir}, falling through to config: ${e instanceof Error?e.message:String(e)}\n`)}let i=t.config.preview?.baseUrl;return i&&ph(i)?{url:`${fh(i)}${n}`,source:`config`}:null}const yh=[`[Requires: Hocuspocus server] Find-and-replace on a live document via the CRDT layer.`,`The patch is applied through Hocuspocus and propagated to all connected editors in real-time.`,"Use `offset` when you need to patch an exact occurrence; omit it to preserve first-match behavior.",``,"**When rewriting prose, add `[[wiki-links]]` aggressively.** If the replacement mentions other documents or entities that should have their own page, link them as `[[Page Name]]`. Over-linking is the goal; underlinked documents lose their value in backlink-driven navigation.",``,`**Parameters:**`,"- `docName` — Document name, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `find` — Text to find (exact match)","- `replace` — Replacement text","- `offset` (optional) — Exact occurrence to patch, as a JavaScript string offset in the current markdown. If the document changed and the text no longer matches there, the server returns a stale-target error; re-run `suggest_links` to get fresh offsets.",'- `summary` — Optional one-line user-outcome description of this edit (≤80 chars). Appears as a bullet in the document timeline so readers can scan intent without opening every diff. Prefer outcome phrasing ("Fixed token-refresh race") over structural ("Changed 1 line"). Avoid including secrets or PII — summaries are persisted to git history.'].join(`
208
+ `);function bh(e,t){e.tool(`edit_document`,yh,{docName:D().describe(`Document name to edit`),find:D().describe(`Text to find (exact match)`),replace:D().describe(`Replacement text`),offset:C().int().min(0).optional().describe(`Exact occurrence to patch, as a JavaScript string offset in the current markdown`),summary:Jm,cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:a}=n;if(!a)return K(Ym,!0);let o=ih(e.docName);if(!o.ok)return K(o.error,!0);let s=t.identityRef?.current,c=await oh(a,`/api/agent-patch`,{docName:o.docName,find:e.find,replace:e.replace,offset:e.offset,...e.summary===void 0?{}:{summary:e.summary},...s?{agentId:s.connectionId,agentName:s.displayName,clientName:s.clientInfo?.name,colorSeed:s.colorSeed}:{}});if(!c.ok)return K(`Error: ${c.error}`,!0);let l=Se(Ce(i,r)),u=vh(o.docName,{config:i,lockDir:l}),d=typeof c.subscriberCount==`number`?c.subscriberCount:void 0,f=(typeof c.systemSubscriberCount==`number`?c.systemSubscriberCount:void 0)===0,p=d===0,m=c.summary&&typeof c.summary==`object`?c.summary:void 0,h=typeof m?.hint==`string`?m.hint:void 0,g=[`Edit applied successfully.`];u&&g.push(`Preview: ${u.url}`),f&&g.push(u?`Open ${u.url} in your preview browser.`:`No preview attached. Start the UI.`),h&&g.push(h);let _=g.join(`
209
+ `);if(!u&&!f&&!p&&!m)return K(_);let v={};return u&&(v.previewUrl=u.url,v.previewUrlSource=u.source),f&&(v.warning={message:`Open the previewUrl in your preview browser.`,action:`attach-preview-once`,previewUrl:u?.url??null}),m&&(v.summary=m),q(_,v)})}const xh=new Set([`cat`,`ls`,`grep`,`find`]),Sh=/\b[\w./-]+\.(md|mdx)\b/g;function Ch(e){return/\.(md|mdx)$/.test(e)}function wh(e){let t=e.trim();return t?(t=t.replace(/\/+/g,`/`),t.startsWith(`./`)&&(t=t.slice(2)),t.endsWith(`/`)&&(t=t.slice(0,-1)),t):``}function Th(e){return e.args.slice(1)}function Eh(e){return e.filter(e=>!e.startsWith(`-`))}function Dh(e){return Eh(Th(e)).filter(Ch)}function Oh(e,t){let n=Eh(Th(t)),r=n.length>0?n[n.length-1]:``,i=r&&r!==`.`?wh(r):``,a=[];i&&a.push(i);for(let t of e.split(`
210
+ `)){let e=t.trim();if(!e||/\.[a-z0-9]+$/i.test(e)&&!Ch(e))continue;let n=i?`${i}/${e}`:e;a.push(n)}return a}function kh(e){let t=[];for(let n of e.split(`
211
+ `)){if(!n)continue;let e=n.indexOf(`:`);if(e<0)continue;let r=wh(n.slice(0,e));Ch(r)&&t.push(r)}return t}function Ah(e){let t=[];for(let n of e.split(`
212
+ `)){let e=wh(n);e&&Ch(e)&&t.push(e)}return t}function jh(e){return Eh(Th(e)).filter(Ch)}function Mh(e){return Eh(Th(e)).length>0}function Nh(e){let t=[],n=e.matchAll(Sh);for(let e of n)t.push(wh(e[0]));return t}function Ph(e,t){let n=null;for(let e=t.length-1;e>=0;e--){let r=t[e];if(xh.has(r.command)){n=r;break}if((r.command===`head`||r.command===`tail`)&&Mh(r)){n=r;break}}let r;if(!n)r=Nh(e);else{switch(n.command){case`cat`:r=Dh(n);break;case`ls`:r=Oh(e,n);break;case`grep`:r=kh(e);break;case`find`:r=Ah(e);break;case`head`:case`tail`:r=jh(n);break;default:r=Nh(e)}r.length===0&&(r=Nh(e))}let i=new Set,a=[];for(let e of r){let t=wh(e);!t||i.has(t)||(i.add(t),a.push(t))}return a}var Fh=[{name:`echo`,load:async()=>(await import(`./echo-O45JWWI2-CX34tpdA.mjs`)).echoCommand},{name:`cat`,load:async()=>(await import(`./cat-RDUMLXKC-BBkiYZHY.mjs`)).catCommand},{name:`printf`,load:async()=>(await import(`./printf-CX64KX2P-CqRH1fcx.mjs`)).printfCommand},{name:`ls`,load:async()=>(await import(`./ls-KSXFZCWH-DqDgh03N.mjs`)).lsCommand},{name:`mkdir`,load:async()=>(await import(`./mkdir-TDEMSB6C-BJEISkIZ.mjs`)).mkdirCommand},{name:`rmdir`,load:async()=>(await import(`./rmdir-XTQXT7RK-qEC715ec.mjs`)).rmdirCommand},{name:`touch`,load:async()=>(await import(`./touch-DX2IJOQ4-lH1eyelO.mjs`)).touchCommand},{name:`rm`,load:async()=>(await import(`./rm-RTZG23RL-DlEnXUAF.mjs`)).rmCommand},{name:`cp`,load:async()=>(await import(`./cp-XOYR4ABJ-bKEUBRiq.mjs`)).cpCommand},{name:`mv`,load:async()=>(await import(`./mv-Z6MORUFL-BmfrJjSs.mjs`)).mvCommand},{name:`ln`,load:async()=>(await import(`./ln-4TRFBYAT-CVLYmUk7.mjs`)).lnCommand},{name:`chmod`,load:async()=>(await import(`./chmod-SYMGL4JA-CrZnOwHN.mjs`)).chmodCommand},{name:`pwd`,load:async()=>(await import(`./pwd-D4OZ7N27-CKM9OA6o.mjs`)).pwdCommand},{name:`readlink`,load:async()=>(await import(`./readlink-MI4GCHJF-Ck2tsjqo.mjs`)).readlinkCommand},{name:`head`,load:async()=>(await import(`./head-HT2B6D2J-BbfykFhC.mjs`)).headCommand},{name:`tail`,load:async()=>(await import(`./tail-S5ULNTJU-BWlMoVaY.mjs`)).tailCommand},{name:`wc`,load:async()=>(await import(`./wc-TQB3VNOX-DJ8k4PUj.mjs`)).wcCommand},{name:`stat`,load:async()=>(await import(`./stat-BT5A227F-DpCEGAGw.mjs`)).statCommand},{name:`grep`,load:async()=>(await import(`./grep-3AIAIJVR-fpYA0UVG.mjs`)).grepCommand},{name:`fgrep`,load:async()=>(await import(`./grep-3AIAIJVR-fpYA0UVG.mjs`)).fgrepCommand},{name:`egrep`,load:async()=>(await import(`./grep-3AIAIJVR-fpYA0UVG.mjs`)).egrepCommand},{name:`rg`,load:async()=>(await import(`./rg-FOQSCCX3-B6b10f2I.mjs`)).rgCommand},{name:`sed`,load:async()=>(await import(`./sed-VFTTATXJ-SJAhm12K.mjs`)).sedCommand},{name:`awk`,load:async()=>(await import(`./awk2-POPGKRAI-Cc3gWubt.mjs`)).awkCommand2},{name:`sort`,load:async()=>(await import(`./sort-DCNRDA7U-B9r9vaz_.mjs`)).sortCommand},{name:`uniq`,load:async()=>(await import(`./uniq-SUNANL47-DQSg6ulH.mjs`)).uniqCommand},{name:`comm`,load:async()=>(await import(`./comm-5SLSESQG-PpE3c4ZK.mjs`)).commCommand},{name:`cut`,load:async()=>(await import(`./cut-OPC3VAGB-DFILWBLt.mjs`)).cutCommand},{name:`paste`,load:async()=>(await import(`./paste-7N6AFSDS-DZ1UxLP-.mjs`)).pasteCommand},{name:`tr`,load:async()=>(await import(`./tr-2HXZRDSW-WTWP1Y3I.mjs`)).trCommand},{name:`rev`,load:async()=>(await import(`./rev-XOSYPP45-dyxz7TNM.mjs`)).rev},{name:`nl`,load:async()=>(await import(`./nl-U5YJDM32-CwKzmNae.mjs`)).nl},{name:`fold`,load:async()=>(await import(`./fold-LDSORVYE-DhorwB1M.mjs`)).fold},{name:`expand`,load:async()=>(await import(`./expand-DTNXU4LQ-Def0IjrD.mjs`)).expand},{name:`unexpand`,load:async()=>(await import(`./unexpand-RGTMIGZM-CvVeOYsA.mjs`)).unexpand},{name:`strings`,load:async()=>(await import(`./strings-7PLOGTPD-Bc3LcdUK.mjs`)).strings},{name:`split`,load:async()=>(await import(`./split-SITCSYCZ-CVEBVG_b.mjs`)).split},{name:`column`,load:async()=>(await import(`./column-WLPMMSTS-B7r8iBQX.mjs`)).column},{name:`join`,load:async()=>(await import(`./join-GG2LDHE5-C6rITFRb.mjs`)).join},{name:`tee`,load:async()=>(await import(`./tee-O7VXZDCO-BZ-Wtr3X.mjs`)).teeCommand},{name:`find`,load:async()=>(await import(`./find-TPUOAIUQ-C0CUhYWB.mjs`)).findCommand},{name:`basename`,load:async()=>(await import(`./basename-AA2KJYZQ-DpGE_2LJ.mjs`)).basenameCommand},{name:`dirname`,load:async()=>(await import(`./dirname-LEMTZZFS-DM2ha26y.mjs`)).dirnameCommand},{name:`tree`,load:async()=>(await import(`./tree-LYXBS7DC-B0XAnWvf.mjs`)).treeCommand},{name:`du`,load:async()=>(await import(`./du-WO2ENHXQ-DK5I7PKg.mjs`)).duCommand},{name:`env`,load:async()=>(await import(`./env-5EPCWSXR-C0C0-iCD.mjs`)).envCommand},{name:`printenv`,load:async()=>(await import(`./env-5EPCWSXR-C0C0-iCD.mjs`)).printenvCommand},{name:`alias`,load:async()=>(await import(`./alias-JE7RI5QX-B6svpkRM.mjs`)).aliasCommand},{name:`unalias`,load:async()=>(await import(`./alias-JE7RI5QX-B6svpkRM.mjs`)).unaliasCommand},{name:`history`,load:async()=>(await import(`./history-J4QRNGRO-CxkOfNgO.mjs`)).historyCommand},{name:`xargs`,load:async()=>(await import(`./xargs-I6EZUCYF-BTL0Cz6j.mjs`)).xargsCommand},{name:`true`,load:async()=>(await import(`./true-WHJNXCHG-CfyqCtO-.mjs`)).trueCommand},{name:`false`,load:async()=>(await import(`./true-WHJNXCHG-CfyqCtO-.mjs`)).falseCommand},{name:`clear`,load:async()=>(await import(`./clear-5CZ5X4YR-CQ9G2b6A.mjs`)).clearCommand},{name:`bash`,load:async()=>(await import(`./bash-IJWYRKFO-zBASRHFa.mjs`)).bashCommand},{name:`sh`,load:async()=>(await import(`./bash-IJWYRKFO-zBASRHFa.mjs`)).shCommand},{name:`jq`,load:async()=>(await import(`./jq-ODXZBPLY-DwKW_5e4.mjs`)).jqCommand},{name:`base64`,load:async()=>(await import(`./base64-4YMZCVJ5-BYz2VU1K.mjs`)).base64Command},{name:`diff`,load:async()=>(await import(`./diff-HJF2MPDN-BRsHJrES.mjs`)).diffCommand},{name:`date`,load:async()=>(await import(`./date-DD7FVA2V-B1vw27vz.mjs`)).dateCommand},{name:`sleep`,load:async()=>(await import(`./sleep-VZFPZFWA-2i5JaN6o.mjs`)).sleepCommand},{name:`timeout`,load:async()=>(await import(`./timeout-VRKMCG72-CGi8Ki9F.mjs`)).timeoutCommand},{name:`time`,load:async()=>(await import(`./time-DEUO3QV2-DGu9Jt8t.mjs`)).timeCommand},{name:`seq`,load:async()=>(await import(`./seq-RN5ZUASB-BH9pwR7X.mjs`)).seqCommand},{name:`expr`,load:async()=>(await import(`./expr-5T3UU5KE-CpNcSEhS.mjs`)).exprCommand},{name:`md5sum`,load:async()=>(await import(`./md5sum-INMIK4DX-3q3X2_Bl.mjs`)).md5sumCommand},{name:`sha1sum`,load:async()=>(await import(`./sha1sum-VJPNLNU6-7wFUSeyx.mjs`)).sha1sumCommand},{name:`sha256sum`,load:async()=>(await import(`./sha256sum-PI32XWXY-RLxkSiqX.mjs`)).sha256sumCommand},{name:`file`,load:async()=>(await import(`./file-ZIGAJ4YS-C1Mgh9Dx.mjs`)).fileCommand},{name:`html-to-markdown`,load:async()=>(await import(`./html-to-markdown-TFCECAGV-DYB58Aq3.mjs`)).htmlToMarkdownCommand},{name:`help`,load:async()=>(await import(`./help-VVWX7SA5-rfn2xlDJ.mjs`)).helpCommand},{name:`which`,load:async()=>(await import(`./which-XZHEH76L-CLG5qPgv.mjs`)).whichCommand},{name:`tac`,load:async()=>(await import(`./tac-SJGXQ4T2-Cp7URH3w.mjs`)).tac},{name:`hostname`,load:async()=>(await import(`./hostname-BK6HG2DE-C1nZ6rEU.mjs`)).hostname},{name:`whoami`,load:async()=>(await import(`./whoami-DGKU3D2X-DO5vmoPX.mjs`)).whoami},{name:`od`,load:async()=>(await import(`./od-VJEF2UR5-CIYaWeFb.mjs`)).od},{name:`gzip`,load:async()=>(await import(`./gzip-AQXSGOVS-ZJPD6VJq.mjs`)).gzipCommand},{name:`gunzip`,load:async()=>(await import(`./gzip-AQXSGOVS-ZJPD6VJq.mjs`)).gunzipCommand},{name:`zcat`,load:async()=>(await import(`./gzip-AQXSGOVS-ZJPD6VJq.mjs`)).zcatCommand}];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Fh.push({name:`tar`,load:async()=>(await import(`./tar-ANUBEFJY-_2-XJ8OD.mjs`)).tarCommand}),Fh.push({name:`yq`,load:async()=>(await import(`./yq-MJMAR36V-CPQTwsxW.mjs`)).yqCommand}),Fh.push({name:`xan`,load:async()=>(await import(`./xan-BXDXYEIB-BUzA9fZa.mjs`)).xanCommand}),Fh.push({name:`sqlite3`,load:async()=>(await import(`./sqlite3-56UMWEY3-htZnl7uZ.mjs`)).sqlite3Command}));var Ih=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Ih.push({name:`python3`,load:async()=>(await import(`./python3-AUFTPCU6-BS26F1oD.mjs`)).python3Command}),Ih.push({name:`python`,load:async()=>(await import(`./python3-AUFTPCU6-BS26F1oD.mjs`)).pythonCommand}));var Lh=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Lh.push({name:`js-exec`,load:async()=>(await import(`./js-exec-M6UR76J5-C3ExU6nu.mjs`)).jsExecCommand}),Lh.push({name:`node`,load:async()=>(await import(`./js-exec-M6UR76J5-C3ExU6nu.mjs`)).nodeStubCommand}));var Rh=[{name:`curl`,load:async()=>(await import(`./curl-47BFPSFW-KKVaDuOB.mjs`)).curlCommand}],zh=new Map;function Bh(e){return{name:e.name,async execute(t,n){let r=zh.get(e.name);if(r||(r=await vn.runTrustedAsync(()=>e.load()),zh.set(e.name,r)),n.coverage&&(typeof __BROWSER__>`u`||!__BROWSER__)){let{emitFlagCoverage:r}=await import(`./flag-coverage-QT4N2Z44-CirEjvTd.mjs`);r(n.coverage,e.name,t)}return r.execute(t,n)}}}function Vh(e){return(e?Fh.filter(t=>e.includes(t.name)):Fh).map(Bh)}function Hh(){return Rh.map(Bh)}function Uh(){return Ih.map(Bh)}function Wh(){return Lh.map(Bh)}function Gh(e){return`load`in e&&typeof e.load==`function`}function Kh(e){let t=null;return{name:e.name,trusted:!0,async execute(n,r){return t||=await e.load(),t.execute(n,r)}}}var qh=new TextEncoder;function Jh(e){return typeof e==`object`&&!!e&&!(e instanceof Uint8Array)&&`content`in e}var Yh=class{data=new Map;constructor(e){if(this.data.set(`/`,{type:`directory`,mode:493,mtime:new Date}),e)for(let[t,n]of Object.entries(e))typeof n==`function`?this.writeFileLazy(t,n):Jh(n)?this.writeFileSync(t,n.content,void 0,{mode:n.mode,mtime:n.mtime}):this.writeFileSync(t,n)}ensureParentDirs(e){let t=rn(e);t!==`/`&&(this.data.has(t)||(this.ensureParentDirs(t),this.data.set(t,{type:`directory`,mode:493,mtime:new Date})))}writeFileSync(e,t,n,r){k(e,`write`);let i=on(e);this.ensureParentDirs(i);let a=mn(t,pn(n));this.data.set(i,{type:`file`,content:a,mode:r?.mode??420,mtime:r?.mtime??new Date})}writeFileLazy(e,t,n){k(e,`write`);let r=on(e);this.ensureParentDirs(r),this.data.set(r,{type:`file`,lazy:t,mode:n?.mode??420,mtime:n?.mtime??new Date})}async materializeLazy(e,t){let n=await t.lazy(),r={type:`file`,content:typeof n==`string`?qh.encode(n):n,mode:t.mode,mtime:t.mtime};return this.data.set(e,r),r}async readFile(e,t){return hn(await this.readFileBuffer(e),pn(t))}async readFileBuffer(e){k(e,`open`);let t=this.resolvePathWithSymlinks(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, open '${e}'`);if(n.type!==`file`)throw Error(`EISDIR: illegal operation on a directory, read '${e}'`);if(`lazy`in n){let e=await this.materializeLazy(t,n);return e.content instanceof Uint8Array?e.content:qh.encode(e.content)}return n.content instanceof Uint8Array?n.content:qh.encode(n.content)}async writeFile(e,t,n){this.writeFileSync(e,t,n)}async appendFile(e,t,n){k(e,`append`);let r=on(e),i=this.data.get(r);if(i&&i.type===`directory`)throw Error(`EISDIR: illegal operation on a directory, write '${e}'`);let a=mn(t,pn(n));if(i?.type===`file`){let e=i;`lazy`in e&&(e=await this.materializeLazy(r,e));let t=`content`in e&&e.content instanceof Uint8Array?e.content:qh.encode(`content`in e?e.content:``),n=new Uint8Array(t.length+a.length);n.set(t),n.set(a,t.length),this.data.set(r,{type:`file`,content:n,mode:e.mode,mtime:new Date})}else this.writeFileSync(e,t,n)}async exists(e){if(e.includes(`\0`))return!1;try{let t=this.resolvePathWithSymlinks(e);return this.data.has(t)}catch{return!1}}async stat(e){k(e,`stat`);let t=this.resolvePathWithSymlinks(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, stat '${e}'`);n.type===`file`&&`lazy`in n&&(n=await this.materializeLazy(t,n));let r=0;return n.type===`file`&&`content`in n&&n.content&&(r=n.content instanceof Uint8Array?n.content.length:qh.encode(n.content).length),{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date}}async lstat(e){k(e,`lstat`);let t=this.resolveIntermediateSymlinks(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, lstat '${e}'`);if(n.type===`symlink`)return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:n.mode,size:n.target.length,mtime:n.mtime||new Date};n.type===`file`&&`lazy`in n&&(n=await this.materializeLazy(t,n));let r=0;return n.type===`file`&&`content`in n&&n.content&&(r=n.content instanceof Uint8Array?n.content.length:qh.encode(n.content).length),{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date}}resolveIntermediateSymlinks(e){let t=on(e);if(t===`/`)return`/`;let n=t.slice(1).split(`/`);if(n.length<=1)return t;let r=``,i=new Set;for(let t=0;t<n.length-1;t++){let a=n[t];r=`${r}/${a}`;let o=this.data.get(r),s=0;for(;o&&o.type===`symlink`&&s<40;){if(i.has(r))throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`);i.add(r),r=fn(r,o.target),o=this.data.get(r),s++}if(s>=40)throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`)}return`${r}/${n[n.length-1]}`}resolvePathWithSymlinks(e){let t=on(e);if(t===`/`)return`/`;let n=t.slice(1).split(`/`),r=``,i=new Set;for(let t of n){r=`${r}/${t}`;let n=this.data.get(r),a=0;for(;n&&n.type===`symlink`&&a<40;){if(i.has(r))throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`);i.add(r),r=fn(r,n.target),n=this.data.get(r),a++}if(a>=40)throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`)}return r}async mkdir(e,t){this.mkdirSync(e,t)}mkdirSync(e,t){k(e,`mkdir`);let n=on(e);if(this.data.has(n)){if(this.data.get(n)?.type===`file`)throw Error(`EEXIST: file already exists, mkdir '${e}'`);if(!t?.recursive)throw Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let r=rn(n);if(r!==`/`&&!this.data.has(r))if(t?.recursive)this.mkdirSync(r,{recursive:!0});else throw Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.data.set(n,{type:`directory`,mode:493,mtime:new Date})}async readdir(e){return(await this.readdirWithFileTypes(e)).map(e=>e.name)}async readdirWithFileTypes(e){k(e,`scandir`);let t=on(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);let r=new Set;for(;n&&n.type===`symlink`;){if(r.has(t))throw Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);r.add(t),t=fn(t,n.target),n=this.data.get(t)}if(!n)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);if(n.type!==`directory`)throw Error(`ENOTDIR: not a directory, scandir '${e}'`);let i=t===`/`?`/`:`${t}/`,a=new Map;for(let[e,n]of this.data.entries())if(e!==t&&e.startsWith(i)){let t=e.slice(i.length),r=t.split(`/`)[0];r&&!t.includes(`/`,r.length)&&!a.has(r)&&a.set(r,{name:r,isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:n.type===`symlink`})}return Array.from(a.values()).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}async rm(e,t){k(e,`rm`);let n=on(e),r=this.data.get(n);if(!r){if(t?.force)return;throw Error(`ENOENT: no such file or directory, rm '${e}'`)}if(r.type===`directory`){let r=await this.readdir(n);if(r.length>0){if(!t?.recursive)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let e of r){let r=sn(n,e);await this.rm(r,t)}}}this.data.delete(n)}async cp(e,t,n){k(e,`cp`),k(t,`cp`);let r=on(e),i=on(t),a=this.data.get(r);if(!a)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(a.type===`file`)if(this.ensureParentDirs(i),`content`in a){let e=a.content instanceof Uint8Array?new Uint8Array(a.content):a.content;this.data.set(i,{...a,content:e})}else this.data.set(i,{...a});else if(a.type===`symlink`)this.ensureParentDirs(i),this.data.set(i,{...a});else if(a.type===`directory`){if(!n?.recursive)throw Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(i,{recursive:!0});let t=await this.readdir(r);for(let e of t){let t=sn(r,e),a=sn(i,e);await this.cp(t,a,n)}}}async mv(e,t){await this.cp(e,t,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,t){return an(e,t)}async chmod(e,t){k(e,`chmod`);let n=on(e),r=this.data.get(n);if(!r)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);r.mode=t}async symlink(e,t){k(t,`symlink`);let n=on(t);if(this.data.has(n))throw Error(`EEXIST: file already exists, symlink '${t}'`);this.ensureParentDirs(n),this.data.set(n,{type:`symlink`,target:e,mode:511,mtime:new Date})}async link(e,t){k(e,`link`),k(t,`link`);let n=on(e),r=on(t),i=this.data.get(n);if(!i)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(i.type!==`file`)throw Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(r))throw Error(`EEXIST: file already exists, link '${t}'`);let a=i;`lazy`in a&&(a=await this.materializeLazy(n,a)),this.ensureParentDirs(r),this.data.set(r,{type:`file`,content:a.content,mode:a.mode,mtime:a.mtime})}async readlink(e){k(e,`readlink`);let t=on(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, readlink '${e}'`);if(n.type!==`symlink`)throw Error(`EINVAL: invalid argument, readlink '${e}'`);return n.target}async realpath(e){k(e,`realpath`);let t=this.resolvePathWithSymlinks(e);if(!this.data.has(t))throw Error(`ENOENT: no such file or directory, realpath '${e}'`);return t}async utimes(e,t,n){k(e,`utimes`);let r=on(e),i=this.resolvePathWithSymlinks(r),a=this.data.get(i);if(!a)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);a.mtime=n}};function Xh(e){let t=e;return typeof t.mkdirSync==`function`&&typeof t.writeFileSync==`function`}function Zh(e,t){e.mkdirSync(`/bin`,{recursive:!0}),e.mkdirSync(`/usr/bin`,{recursive:!0}),t&&(e.mkdirSync(`/home/user`,{recursive:!0}),e.mkdirSync(`/tmp`,{recursive:!0}))}function Qh(e){e.mkdirSync(`/dev`,{recursive:!0}),e.writeFileSync(`/dev/null`,``),e.writeFileSync(`/dev/zero`,new Uint8Array),e.writeFileSync(`/dev/stdin`,``),e.writeFileSync(`/dev/stdout`,``),e.writeFileSync(`/dev/stderr`,``)}function $h(e,t){e.mkdirSync(`/proc/self/fd`,{recursive:!0}),e.writeFileSync(`/proc/version`,`${jt}
213
213
  `),e.writeFileSync(`/proc/self/exe`,`/bin/bash`),e.writeFileSync(`/proc/self/cmdline`,`bash\0`),e.writeFileSync(`/proc/self/comm`,`bash
214
- `),e.writeFileLazy?e.writeFileLazy(`/proc/self/status`,()=>vt(t)):e.writeFileSync(`/proc/self/status`,vt(t)),e.writeFileSync(`/proc/self/fd/0`,`/dev/stdin`),e.writeFileSync(`/proc/self/fd/1`,`/dev/stdout`),e.writeFileSync(`/proc/self/fd/2`,`/dev/stderr`)}function $h(e,t,n={pid:1,ppid:0,uid:1e3,gid:1e3}){Yh(e)&&(Xh(e,t),Zh(e),Qh(e,n))}var eg=[`allexport`,`errexit`,`noglob`,`noclobber`,`noexec`,`nounset`,`pipefail`,`posix`,`verbose`,`xtrace`],tg=[`braceexpand`,`hashall`,`interactive-comments`];function ng(e){let t=[],n=[...tg.map(e=>({name:e,enabled:!0})),...eg.map(t=>({name:t,enabled:e[t]}))].sort((e,t)=>e.name.localeCompare(t.name));for(let e of n)e.enabled&&t.push(e.name);return t.join(`:`)}function rg(e){e.state.env.set(`SHELLOPTS`,ng(e.state.options))}var ig=[`dotglob`,`expand_aliases`,`extglob`,`failglob`,`globskipdots`,`globstar`,`lastpipe`,`nocaseglob`,`nocasematch`,`nullglob`,`xpg_echo`];function ag(e){let t=[];for(let n of ig)e[n]&&t.push(n);return t.join(`:`)}function og(e){e.state.env.set(`BASHOPTS`,ag(e.state.shoptOptions))}var sg=`BASH_ALIAS_`;function cg(e){return e.parts.length===1?e.parts[0].type===`Literal`:!1}function lg(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type===`Literal`?t.value:null}function ug(e,t){return e.env.get(`${sg}${t}`)}function dg(e,t,n){if(!t.name||!cg(t.name))return t;let r=lg(t.name);if(!r)return t;let i=ug(e,r);if(!i||n.has(r))return t;try{n.add(r);let a=new Zt,o=i,s=i.endsWith(` `);if(!s)for(let e of t.args){let t=pg(e);o+=` ${t}`}let c;try{c=a.parse(o)}catch(e){if(e instanceof Jt)throw e;return t}if(c.statements.length!==1||c.statements[0].pipelines.length!==1||c.statements[0].pipelines[0].commands.length!==1)return fg(t,i);let l=c.statements[0].pipelines[0].commands[0];if(l.type!==`SimpleCommand`)return fg(t,i);let u={...l,assignments:[...t.assignments,...l.assignments],redirections:[...l.redirections,...t.redirections],line:t.line};if(s&&t.args.length>0&&(u={...u,args:[...u.args,...t.args]},u.args.length>0)){let t=u.args[0];if(cg(t)){let r=lg(t);if(r&&ug(e,r)){let r={type:`SimpleCommand`,name:t,args:u.args.slice(1),assignments:[],redirections:[]},i=dg(e,r,n);i!==r&&(u={...u,name:i.name,args:[...i.args]})}}}return u}catch(e){throw n.delete(r),e}}function fg(e,t){let n=t;for(let t of e.args){let e=pg(t);n+=` ${e}`}let r=new Zt;return{type:`SimpleCommand`,name:r.parseWordFromString(`eval`,!1,!1),args:[r.parseWordFromString(`'${n.replace(/'/g,`'\\''`)}'`,!1,!1)],assignments:e.assignments,redirections:e.redirections,line:e.line}}function pg(e){let t=``;for(let n of e.parts)switch(n.type){case`Literal`:t+=n.value.replace(/([\s"'$`\\*?[\]{}()<>|&;#!])/g,`\\$1`);break;case`SingleQuoted`:t+=`'${n.value}'`;break;case`DoubleQuoted`:t+=`"${n.parts.map(e=>e.type===`Literal`?e.value:`$${e.type}`).join(``)}"`;break;case`ParameterExpansion`:t+=`\${${n.parameter}}`;break;case`CommandSubstitution`:t+=`$(...)`;break;case`ArithmeticExpansion`:t+=`$((${n.expression}))`;break;case`Glob`:t+=n.pattern;break;default:break}return t}async function mg(e,t){let n=t.parts.map(e=>e.type===`Literal`?e.value:`\0`).join(``),r=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);if(!r||!n.endsWith(`)`))return null;let i=r[1],a=[],o=!1,s=``,c=!1;for(let n of t.parts)if(n.type===`Literal`){let e=n.value;if(!o){let t=e.indexOf(`=(`);t!==-1&&(o=!0,e=e.slice(t+2))}if(o){e.endsWith(`)`)&&(e=e.slice(0,-1));let t=e.split(/(\s+)/);for(let e of t)/^\s+$/.test(e)?(s||c)&&(a.push(s),s=``,c=!1):e&&(s+=e)}}else if(o)if(n.type===`BraceExpansion`)if(/^\[.+\]=/.test(s))s+=zt({type:`Word`,parts:[n]});else{(s||c)&&(a.push(s),s=``,c=!1);let t=await tn(e,{type:`Word`,parts:[n]});a.push(...t.values)}else{(n.type===`SingleQuoted`||n.type===`DoubleQuoted`||n.type===`Escaped`)&&(c=!0);let t=await O(e,{type:`Word`,parts:[n]});s+=t}return(s||c)&&a.push(s),`${i}=(${a.map(e=>/^\[.+\]=/.test(e)?e:e===``?`''`:/[\s"'\\$`!*?[\]{}|&;<>()]/.test(e)&&!e.startsWith(`'`)&&!e.startsWith(`"`)?`'${e.replace(/'/g,`'\\''`)}'`:e).join(` `)})`}async function hg(e,t){let n=-1,r=-1,i=!1;for(let e=0;e<t.parts.length;e++){let a=t.parts[e];if(a.type===`Literal`){let t=a.value.indexOf(`+=`);if(t!==-1){let o=a.value.slice(0,t);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){n=e,r=t,i=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(o)){n=e,r=t,i=!0;break}}let o=a.value.indexOf(`=`);if(o!==-1&&(o===0||a.value[o-1]!==`+`)){let t=a.value.slice(0,o);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(t)){n=e,r=o;break}}}}if(n===-1)return null;let a=t.parts.slice(0,n),o=t.parts[n];if(o.type!==`Literal`)return null;let s=i?2:1,c=o.value.slice(0,r),l=o.value.slice(r+s),u=t.parts.slice(n+1),d=``;for(let t of a)d+=await O(e,{type:`Word`,parts:[t]});d+=c;let f={type:`Word`,parts:l===``?u:[{type:`Literal`,value:l},...u]},p=f.parts.length>0?await O(e,f):``;return`${d}${i?`+=`:`=`}${p}`}var gg=[`tar`,`yq`,`xan`,`sqlite3`,`python3`,`python`];function _g(e){return gg.includes(e)}var J=Object.freeze({stdout:``,stderr:``,exitCode:0});function Y(e=``){return{stdout:e,stderr:``,exitCode:0}}function X(e,t=1){return{stdout:``,stderr:e,exitCode:t}}function Z(e,t,n){return{stdout:e,stderr:t,exitCode:n}}function vg(e){return{stdout:``,stderr:``,exitCode:e?0:1}}function yg(e,t,n=``,r=``){throw new ot(e,t,n,r)}function bg(e){let t=e.state.fileDescriptors;if(t&&t.size>=e.limits.maxFileDescriptors)throw new ot(`too many open file descriptors (max ${e.limits.maxFileDescriptors})`,`file_descriptors`)}function xg(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new pt;return J}if(t.length>1)throw new ut(1,``,`bash: break: too many arguments
214
+ `),e.writeFileLazy?e.writeFileLazy(`/proc/self/status`,()=>vt(t)):e.writeFileSync(`/proc/self/status`,vt(t)),e.writeFileSync(`/proc/self/fd/0`,`/dev/stdin`),e.writeFileSync(`/proc/self/fd/1`,`/dev/stdout`),e.writeFileSync(`/proc/self/fd/2`,`/dev/stderr`)}function eg(e,t,n={pid:1,ppid:0,uid:1e3,gid:1e3}){Xh(e)&&(Zh(e,t),Qh(e),$h(e,n))}var tg=[`allexport`,`errexit`,`noglob`,`noclobber`,`noexec`,`nounset`,`pipefail`,`posix`,`verbose`,`xtrace`],ng=[`braceexpand`,`hashall`,`interactive-comments`];function rg(e){let t=[],n=[...ng.map(e=>({name:e,enabled:!0})),...tg.map(t=>({name:t,enabled:e[t]}))].sort((e,t)=>e.name.localeCompare(t.name));for(let e of n)e.enabled&&t.push(e.name);return t.join(`:`)}function ig(e){e.state.env.set(`SHELLOPTS`,rg(e.state.options))}var ag=[`dotglob`,`expand_aliases`,`extglob`,`failglob`,`globskipdots`,`globstar`,`lastpipe`,`nocaseglob`,`nocasematch`,`nullglob`,`xpg_echo`];function og(e){let t=[];for(let n of ag)e[n]&&t.push(n);return t.join(`:`)}function sg(e){e.state.env.set(`BASHOPTS`,og(e.state.shoptOptions))}var cg=`BASH_ALIAS_`;function lg(e){return e.parts.length===1?e.parts[0].type===`Literal`:!1}function ug(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type===`Literal`?t.value:null}function dg(e,t){return e.env.get(`${cg}${t}`)}function fg(e,t,n){if(!t.name||!lg(t.name))return t;let r=ug(t.name);if(!r)return t;let i=dg(e,r);if(!i||n.has(r))return t;try{n.add(r);let a=new Zt,o=i,s=i.endsWith(` `);if(!s)for(let e of t.args){let t=mg(e);o+=` ${t}`}let c;try{c=a.parse(o)}catch(e){if(e instanceof Jt)throw e;return t}if(c.statements.length!==1||c.statements[0].pipelines.length!==1||c.statements[0].pipelines[0].commands.length!==1)return pg(t,i);let l=c.statements[0].pipelines[0].commands[0];if(l.type!==`SimpleCommand`)return pg(t,i);let u={...l,assignments:[...t.assignments,...l.assignments],redirections:[...l.redirections,...t.redirections],line:t.line};if(s&&t.args.length>0&&(u={...u,args:[...u.args,...t.args]},u.args.length>0)){let t=u.args[0];if(lg(t)){let r=ug(t);if(r&&dg(e,r)){let r={type:`SimpleCommand`,name:t,args:u.args.slice(1),assignments:[],redirections:[]},i=fg(e,r,n);i!==r&&(u={...u,name:i.name,args:[...i.args]})}}}return u}catch(e){throw n.delete(r),e}}function pg(e,t){let n=t;for(let t of e.args){let e=mg(t);n+=` ${e}`}let r=new Zt;return{type:`SimpleCommand`,name:r.parseWordFromString(`eval`,!1,!1),args:[r.parseWordFromString(`'${n.replace(/'/g,`'\\''`)}'`,!1,!1)],assignments:e.assignments,redirections:e.redirections,line:e.line}}function mg(e){let t=``;for(let n of e.parts)switch(n.type){case`Literal`:t+=n.value.replace(/([\s"'$`\\*?[\]{}()<>|&;#!])/g,`\\$1`);break;case`SingleQuoted`:t+=`'${n.value}'`;break;case`DoubleQuoted`:t+=`"${n.parts.map(e=>e.type===`Literal`?e.value:`$${e.type}`).join(``)}"`;break;case`ParameterExpansion`:t+=`\${${n.parameter}}`;break;case`CommandSubstitution`:t+=`$(...)`;break;case`ArithmeticExpansion`:t+=`$((${n.expression}))`;break;case`Glob`:t+=n.pattern;break;default:break}return t}async function hg(e,t){let n=t.parts.map(e=>e.type===`Literal`?e.value:`\0`).join(``),r=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);if(!r||!n.endsWith(`)`))return null;let i=r[1],a=[],o=!1,s=``,c=!1;for(let n of t.parts)if(n.type===`Literal`){let e=n.value;if(!o){let t=e.indexOf(`=(`);t!==-1&&(o=!0,e=e.slice(t+2))}if(o){e.endsWith(`)`)&&(e=e.slice(0,-1));let t=e.split(/(\s+)/);for(let e of t)/^\s+$/.test(e)?(s||c)&&(a.push(s),s=``,c=!1):e&&(s+=e)}}else if(o)if(n.type===`BraceExpansion`)if(/^\[.+\]=/.test(s))s+=zt({type:`Word`,parts:[n]});else{(s||c)&&(a.push(s),s=``,c=!1);let t=await tn(e,{type:`Word`,parts:[n]});a.push(...t.values)}else{(n.type===`SingleQuoted`||n.type===`DoubleQuoted`||n.type===`Escaped`)&&(c=!0);let t=await O(e,{type:`Word`,parts:[n]});s+=t}return(s||c)&&a.push(s),`${i}=(${a.map(e=>/^\[.+\]=/.test(e)?e:e===``?`''`:/[\s"'\\$`!*?[\]{}|&;<>()]/.test(e)&&!e.startsWith(`'`)&&!e.startsWith(`"`)?`'${e.replace(/'/g,`'\\''`)}'`:e).join(` `)})`}async function gg(e,t){let n=-1,r=-1,i=!1;for(let e=0;e<t.parts.length;e++){let a=t.parts[e];if(a.type===`Literal`){let t=a.value.indexOf(`+=`);if(t!==-1){let o=a.value.slice(0,t);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){n=e,r=t,i=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(o)){n=e,r=t,i=!0;break}}let o=a.value.indexOf(`=`);if(o!==-1&&(o===0||a.value[o-1]!==`+`)){let t=a.value.slice(0,o);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(t)){n=e,r=o;break}}}}if(n===-1)return null;let a=t.parts.slice(0,n),o=t.parts[n];if(o.type!==`Literal`)return null;let s=i?2:1,c=o.value.slice(0,r),l=o.value.slice(r+s),u=t.parts.slice(n+1),d=``;for(let t of a)d+=await O(e,{type:`Word`,parts:[t]});d+=c;let f={type:`Word`,parts:l===``?u:[{type:`Literal`,value:l},...u]},p=f.parts.length>0?await O(e,f):``;return`${d}${i?`+=`:`=`}${p}`}var _g=[`tar`,`yq`,`xan`,`sqlite3`,`python3`,`python`];function vg(e){return _g.includes(e)}var J=Object.freeze({stdout:``,stderr:``,exitCode:0});function Y(e=``){return{stdout:e,stderr:``,exitCode:0}}function X(e,t=1){return{stdout:``,stderr:e,exitCode:t}}function Z(e,t,n){return{stdout:e,stderr:t,exitCode:n}}function yg(e){return{stdout:``,stderr:``,exitCode:e?0:1}}function bg(e,t,n=``,r=``){throw new ot(e,t,n,r)}function xg(e){let t=e.state.fileDescriptors;if(t&&t.size>=e.limits.maxFileDescriptors)throw new ot(`too many open file descriptors (max ${e.limits.maxFileDescriptors})`,`file_descriptors`)}function Sg(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new pt;return J}if(t.length>1)throw new ut(1,``,`bash: break: too many arguments
215
215
  `);let n=1;if(t.length>0){let e=Number.parseInt(t[0],10);if(Number.isNaN(e)||e<1)throw new ut(128,``,`bash: break: ${t[0]}: numeric argument required
216
- `);n=e}throw new tt(n)}async function Sg(e,t){let n,r=!1,i=!1,a=0;for(;a<t.length;)if(t[a]===`--`){a++;break}else if(t[a]===`-L`)i=!1,a++;else if(t[a]===`-P`)i=!0,a++;else if(t[a].startsWith(`-`)&&t[a]!==`-`)a++;else break;let o=t.slice(a);if(o.length===0||o[0]===`~`?n=e.state.env.get(`HOME`)||`/`:o[0]===`-`?(n=e.state.previousDir,r=!0):n=o[0],!n.startsWith(`/`)&&!n.startsWith(`./`)&&!n.startsWith(`../`)&&n!==`.`&&n!==`..`){let t=e.state.env.get(`CDPATH`);if(t){let i=t.split(`:`).filter(e=>e);for(let t of i){let i=t.startsWith(`/`)?`${t}/${n}`:`${e.state.cwd}/${t}/${n}`;try{if((await e.fs.stat(i)).isDirectory){n=i,r=!0;break}}catch{}}}}let s=(n.startsWith(`/`)?n:`${e.state.cwd}/${n}`).split(`/`).filter(e=>e&&e!==`.`),c=``;for(let t of s)if(t===`..`)c=c.split(`/`).slice(0,-1).join(`/`)||`/`;else{c=c?`${c}/${t}`:`/${t}`;try{if(!(await e.fs.stat(c)).isDirectory)return X(`bash: cd: ${n}: Not a directory
216
+ `);n=e}throw new tt(n)}async function Cg(e,t){let n,r=!1,i=!1,a=0;for(;a<t.length;)if(t[a]===`--`){a++;break}else if(t[a]===`-L`)i=!1,a++;else if(t[a]===`-P`)i=!0,a++;else if(t[a].startsWith(`-`)&&t[a]!==`-`)a++;else break;let o=t.slice(a);if(o.length===0||o[0]===`~`?n=e.state.env.get(`HOME`)||`/`:o[0]===`-`?(n=e.state.previousDir,r=!0):n=o[0],!n.startsWith(`/`)&&!n.startsWith(`./`)&&!n.startsWith(`../`)&&n!==`.`&&n!==`..`){let t=e.state.env.get(`CDPATH`);if(t){let i=t.split(`:`).filter(e=>e);for(let t of i){let i=t.startsWith(`/`)?`${t}/${n}`:`${e.state.cwd}/${t}/${n}`;try{if((await e.fs.stat(i)).isDirectory){n=i,r=!0;break}}catch{}}}}let s=(n.startsWith(`/`)?n:`${e.state.cwd}/${n}`).split(`/`).filter(e=>e&&e!==`.`),c=``;for(let t of s)if(t===`..`)c=c.split(`/`).slice(0,-1).join(`/`)||`/`;else{c=c?`${c}/${t}`:`/${t}`;try{if(!(await e.fs.stat(c)).isDirectory)return X(`bash: cd: ${n}: Not a directory
217
217
  `)}catch{return X(`bash: cd: ${n}: No such file or directory
218
218
  `)}}let l=c||`/`;if(i)try{l=await e.fs.realpath(l)}catch{}return e.state.previousDir=e.state.cwd,e.state.cwd=l,e.state.env.set(`PWD`,e.state.cwd),e.state.env.set(`OLDPWD`,e.state.previousDir),Y(r?`${l}
219
- `:``)}function Cg(e,t){return e.fs.resolvePath(e.state.cwd,t)}var wg=[`-e`,`-a`,`-f`,`-d`,`-r`,`-w`,`-x`,`-s`,`-L`,`-h`,`-k`,`-g`,`-u`,`-G`,`-O`,`-b`,`-c`,`-p`,`-S`,`-t`,`-N`];function Tg(e){return wg.includes(e)}async function Eg(e,t,n){let r=Cg(e,n);switch(t){case`-e`:case`-a`:return e.fs.exists(r);case`-f`:return await e.fs.exists(r)?(await e.fs.stat(r)).isFile:!1;case`-d`:return await e.fs.exists(r)?(await e.fs.stat(r)).isDirectory:!1;case`-r`:return await e.fs.exists(r)?((await e.fs.stat(r)).mode&256)!=0:!1;case`-w`:return await e.fs.exists(r)?((await e.fs.stat(r)).mode&128)!=0:!1;case`-x`:return await e.fs.exists(r)?((await e.fs.stat(r)).mode&64)!=0:!1;case`-s`:return await e.fs.exists(r)?(await e.fs.stat(r)).size>0:!1;case`-L`:case`-h`:try{return(await e.fs.lstat(r)).isSymbolicLink}catch{return!1}case`-k`:return await e.fs.exists(r)?((await e.fs.stat(r)).mode&512)!=0:!1;case`-g`:return await e.fs.exists(r)?((await e.fs.stat(r)).mode&1024)!=0:!1;case`-u`:return await e.fs.exists(r)?((await e.fs.stat(r)).mode&2048)!=0:!1;case`-G`:case`-O`:return e.fs.exists(r);case`-b`:return!1;case`-c`:return[`/dev/null`,`/dev/zero`,`/dev/random`,`/dev/urandom`,`/dev/tty`,`/dev/stdin`,`/dev/stdout`,`/dev/stderr`].includes(r);case`-p`:return!1;case`-S`:return!1;case`-t`:return!1;case`-N`:return e.fs.exists(r);default:return!1}}var Dg=[`-nt`,`-ot`,`-ef`];function Og(e){return Dg.includes(e)}async function kg(e,t,n,r){let i=Cg(e,n),a=Cg(e,r);switch(t){case`-nt`:try{let t=await e.fs.stat(i),n=await e.fs.stat(a);return t.mtime>n.mtime}catch{return!1}case`-ot`:try{let t=await e.fs.stat(i),n=await e.fs.stat(a);return t.mtime<n.mtime}catch{return!1}case`-ef`:try{return!await e.fs.exists(i)||!await e.fs.exists(a)?!1:e.fs.resolvePath(e.state.cwd,i)===e.fs.resolvePath(e.state.cwd,a)}catch{return!1}default:return!1}}var Ag=new Set([`-eq`,`-ne`,`-lt`,`-le`,`-gt`,`-ge`]);function jg(e){return Ag.has(e)}function Mg(e,t,n){switch(e){case`-eq`:return t===n;case`-ne`:return t!==n;case`-lt`:return t<n;case`-le`:return t<=n;case`-gt`:return t>n;case`-ge`:return t>=n}}function Ng(e){return e===`=`||e===`==`||e===`!=`}function Pg(e,t,n,r=!1,i=!1,a=!1){if(r){let r=Kg(t,n,i,a);return e===`!=`?!r:r}if(i){let r=t.toLowerCase()===n.toLowerCase();return e===`!=`?!r:r}let o=t===n;return e===`!=`?!o:o}var Fg=new Set([`-z`,`-n`]);function Ig(e){return Fg.has(e)}function Lg(e,t){switch(e){case`-z`:return t===``;case`-n`:return t!==``}}async function Rg(e,t){let n=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(n){let t=n[1],r=n[2];if(e.state.associativeArrays?.has(t)){let n=r;return(n.startsWith(`'`)&&n.endsWith(`'`)||n.startsWith(`"`)&&n.endsWith(`"`))&&(n=n.slice(1,-1)),n=n.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(t,n)=>e.state.env.get(n)||``),e.state.env.has(`${t}_${n}`)}let i;try{i=await Kt(e,Ft(new Zt,r).expression)}catch{if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{let t=e.state.env.get(r);i=t?Number.parseInt(t,10):0}}if(i<0){let n=Et(e,t),r=e.state.currentLine;if(n.length===0||(i=Math.max(...n)+1+i,i<0))return e.state.expansionStderr=(e.state.expansionStderr||``)+`bash: line ${r}: ${t}: bad array subscript
220
- `,!1}return e.state.env.has(`${t}_${i}`)}return e.state.env.has(t)?!0:e.state.associativeArrays?.has(t)?gt(e,t).length>0:Et(e,t).length>0}async function zg(e,t){switch(t.type){case`CondBinary`:{let n=await O(e,t.left),r=t.right.parts.length>0&&t.right.parts.every(e=>e.type===`SingleQuoted`||e.type===`DoubleQuoted`||e.type===`Escaped`&&t.operator!==`=~`),i;if(i=t.operator===`=~`?r?bt(await O(e,t.right)):await Rt(e,t.right):Ng(t.operator)&&!r?await At(e,t.right):await O(e,t.right),Ng(t.operator)){let a=e.state.shoptOptions.nocasematch;return Pg(t.operator,n,i,!r,a,!0)}if(jg(t.operator))return Mg(t.operator,await Qg(e,n),await Qg(e,i));if(Og(t.operator))return kg(e,t.operator,n,i);switch(t.operator){case`=~`:try{let t=e.state.shoptOptions.nocasematch,r=et(n_(i),t?`i`:``).match(n);if(qt(e,`BASH_REMATCH`),r)for(let t=0;t<r.length;t++)e.state.env.set(`BASH_REMATCH_${t}`,r[t]||``);return r!==null}catch{throw Error(`syntax error in regular expression`)}case`<`:return n<i;case`>`:return n>i;default:return!1}}case`CondUnary`:{let n=await O(e,t.operand);return Tg(t.operator)?Eg(e,t.operator,n):Ig(t.operator)?Lg(t.operator,n):t.operator===`-v`?await Rg(e,n):t.operator===`-o`?Zg(e,n):!1}case`CondNot`:return e.state.shoptOptions.extglob&&t.operand.type===`CondGroup`&&t.operand.expression.type===`CondWord`?`!(${await O(e,t.operand.expression.word)})`!=``:!await zg(e,t.operand);case`CondAnd`:return await zg(e,t.left)?await zg(e,t.right):!1;case`CondOr`:return await zg(e,t.left)?!0:await zg(e,t.right);case`CondGroup`:return await zg(e,t.expression);case`CondWord`:return await O(e,t.word)!==``;default:return!1}}async function Bg(e,t){if(t.length===0)return Z(``,``,1);if(t.length===1)return vg(!!t[0]);if(t.length===2){let n=t[0],r=t[1];return n===`(`?X(`test: '(' without matching ')'
221
- `,2):Tg(n)?vg(await Eg(e,n,r)):Ig(n)?vg(Lg(n,r)):n===`!`?vg(!r):n===`-v`?vg(await Rg(e,r)):n===`-o`?vg(Zg(e,r)):n===`=`||n===`==`||n===`!=`||n===`<`||n===`>`||n===`-eq`||n===`-ne`||n===`-lt`||n===`-le`||n===`-gt`||n===`-ge`||n===`-nt`||n===`-ot`||n===`-ef`?X(`test: ${n}: unary operator expected
222
- `,2):Z(``,``,1)}if(t.length===3){let n=t[0],r=t[1],i=t[2];if(Ng(r))return vg(Pg(r,n,i));if(jg(r)){let e=t_(n),t=t_(i);return!e.valid||!t.valid?Z(``,``,2):vg(Mg(r,e.value,t.value))}if(Og(r))return vg(await kg(e,r,n,i));switch(r){case`-a`:return vg(n!==``&&i!==``);case`-o`:return vg(n!==``||i!==``);case`>`:return vg(n>i);case`<`:return vg(n<i)}if(n===`!`){let t=await Bg(e,[r,i]);return Z(``,t.stderr,t.exitCode===0?1:t.exitCode===1?0:t.exitCode)}if(n===`(`&&i===`)`)return vg(r!==``)}if(t.length===4){if(t[0]===`!`){let n=await Bg(e,t.slice(1));return Z(``,n.stderr,n.exitCode===0?1:n.exitCode===1?0:n.exitCode)}if(t[0]===`(`&&t[3]===`)`)return Bg(e,[t[1],t[2]])}let n=await Vg(e,t,0);return n.pos<t.length?X(`test: too many arguments
223
- `,2):vg(n.value)}async function Vg(e,t,n){return Hg(e,t,n)}async function Hg(e,t,n){let{value:r,pos:i}=await Ug(e,t,n);for(;t[i]===`-o`;){let n=await Ug(e,t,i+1);r||=n.value,i=n.pos}return{value:r,pos:i}}async function Ug(e,t,n){let{value:r,pos:i}=await Wg(e,t,n);for(;t[i]===`-a`;){let n=await Wg(e,t,i+1);r&&=n.value,i=n.pos}return{value:r,pos:i}}async function Wg(e,t,n){if(t[n]===`!`){let{value:r,pos:i}=await Wg(e,t,n+1);return{value:!r,pos:i}}return Gg(e,t,n)}async function Gg(e,t,n){let r=t[n];if(r===`(`){let{value:r,pos:i}=await Vg(e,t,n+1);return{value:r,pos:t[i]===`)`?i+1:i}}let i=t[n+1];if(Ng(i))return{value:Pg(i,r,t[n+2]??``),pos:n+3};if(jg(i)){let e=t_(r),a=t_(t[n+2]??`0`);return!e.valid||!a.valid?{value:!1,pos:n+3}:{value:Mg(i,e.value,a.value),pos:n+3}}return Og(i)?{value:await kg(e,i,r,t[n+2]??``),pos:n+3}:Tg(r)?{value:await Eg(e,r,t[n+1]??``),pos:n+2}:Ig(r)?{value:Lg(r,t[n+1]??``),pos:n+2}:r===`-v`?{value:await Rg(e,t[n+1]??``),pos:n+2}:r===`-o`?{value:Zg(e,t[n+1]??``),pos:n+2}:{value:r!==void 0&&r!==``,pos:n+1}}function Kg(e,t,n=!1,r=!1){return et(`^${qg(t,r)}$`,n?`is`:`s`).test(e)}function qg(e,t){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(t&&(i===`@`||i===`*`||i===`+`||i===`?`||i===`!`)&&r+1<e.length&&e[r+1]===`(`){let a=Jg(e,r+1);if(a!==-1){let o=Yg(e.slice(r+2,a)),s=o.map(e=>qg(e,t)),c=s.length>0?s.join(`|`):`(?:)`;if(i===`@`)n+=`(?:${c})`;else if(i===`*`)n+=`(?:${c})*`;else if(i===`+`)n+=`(?:${c})+`;else if(i===`?`)n+=`(?:${c})?`;else if(i===`!`)if(a<e.length-1){let e=o.map(e=>Xg(e,t));if(e.every(e=>e!==null)&&e.every(t=>t===e[0])&&e[0]!==null){let t=e[0];if(t===0)n+=`(?:.+)`;else{let e=[];t>0&&e.push(`.{0,${t-1}}`),e.push(`.{${t+1},}`),e.push(`(?!(?:${c})).{${t}}`),n+=`(?:${e.join(`|`)})`}}else n+=`(?:(?!(?:${c})).)*?`}else n+=`(?!(?:${c})$).*`;r=a;continue}}if(i===`\\`)if(r+1<e.length){let t=e[r+1];/[\\^$.|+(){}[\]*?]/.test(t)?n+=`\\${t}`:n+=t,r++}else n+=`\\\\`;else if(i===`*`)n+=`.*`;else if(i===`?`)n+=`.`;else if(i===`[`){let t=e.indexOf(`]`,r+1);t===-1?n+=`\\[`:(n+=e.slice(r,t+1),r=t)}else /[\\^$.|+(){}]/.test(i)?n+=`\\${i}`:n+=i}return n}function Jg(e,t){let n=1,r=t+1;for(;r<e.length&&n>0;){let t=e[r];if(t===`\\`){r+=2;continue}if(t===`(`)n++;else if(t===`)`&&(n--,n===0))return r;r++}return-1}function Yg(e){let t=[],n=``,r=0,i=0;for(;i<e.length;){let a=e[i];if(a===`\\`){n+=a,i+1<e.length?(n+=e[i+1],i+=2):i++;continue}a===`(`?(r++,n+=a):a===`)`?(r--,n+=a):a===`|`&&r===0?(t.push(n),n=``):n+=a,i++}return t.push(n),t}function Xg(e,t){let n=0,r=0;for(;r<e.length;){let i=e[r];if(t&&(i===`@`||i===`*`||i===`+`||i===`?`||i===`!`)&&r+1<e.length&&e[r+1]===`(`){let a=Jg(e,r+1);if(a!==-1){if(i===`@`){let i=Yg(e.slice(r+2,a)).map(e=>Xg(e,t));if(i.every(e=>e!==null)&&i.every(e=>e===i[0])){n+=i[0],r=a+1;continue}return null}return null}}if(i===`*`)return null;if(i===`?`){n+=1,r++;continue}if(i===`[`){let t=e.indexOf(`]`,r+1);if(t!==-1){n+=1,r=t+1;continue}n+=1,r++;continue}if(i===`\\`){n+=1,r+=2;continue}n+=1,r++}return n}function Zg(e,t){let n=new Map([[`errexit`,()=>e.state.options.errexit===!0],[`nounset`,()=>e.state.options.nounset===!0],[`pipefail`,()=>e.state.options.pipefail===!0],[`xtrace`,()=>e.state.options.xtrace===!0],[`e`,()=>e.state.options.errexit===!0],[`u`,()=>e.state.options.nounset===!0],[`x`,()=>e.state.options.xtrace===!0]]).get(t);return n?n():!1}async function Qg(e,t){if(t=t.trim(),t===``)return 0;if(/^[+-]?(\d+#[a-zA-Z0-9@_]+|0[xX][0-9a-fA-F]+|0[0-7]+|\d+)$/.test(t))return e_(t);try{return await Kt(e,Ft(new Zt,t).expression)}catch{return e_(t)}}function $g(e,t){let n=0;for(let r of e){let e;if(r>=`0`&&r<=`9`)e=r.charCodeAt(0)-48;else if(r>=`a`&&r<=`z`)e=r.charCodeAt(0)-97+10;else if(r>=`A`&&r<=`Z`)e=r.charCodeAt(0)-65+36;else if(r===`@`)e=62;else if(r===`_`)e=63;else return NaN;if(e>=t)return NaN;n=n*t+e}return n}function e_(e){if(e=e.trim(),e===``)return 0;let t=!1;e.startsWith(`-`)?(t=!0,e=e.slice(1)):e.startsWith(`+`)&&(e=e.slice(1));let n,r=e.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(r){let e=Number.parseInt(r[1],10);n=e>=2&&e<=64?$g(r[2],e):0}else n=/^0[xX][0-9a-fA-F]+$/.test(e)?Number.parseInt(e,16):/^0[0-7]+$/.test(e)?Number.parseInt(e,8):Number.parseInt(e,10);return Number.isNaN(n)&&(n=0),t?-n:n}function t_(e){if(e=e.trim(),e===``)return{value:0,valid:!0};let t=!1;if(e.startsWith(`-`)?(t=!0,e=e.slice(1)):e.startsWith(`+`)&&(e=e.slice(1)),!/^\d+$/.test(e))return{value:0,valid:!1};let n=Number.parseInt(e,10);return Number.isNaN(n)?{value:0,valid:!1}:{value:t?-n:n,valid:!0}}function n_(e){let t=``,n=0;for(;n<e.length;)if(e[n]===`\\`&&n+1<e.length)t+=e[n]+e[n+1],n+=2;else if(e[n]===`[`){let r=r_(e,n);t+=r.converted,n=r.endIndex}else t+=e[n],n++;return t}function r_(e,t){let n=t+1,r=`[`;n<e.length&&(e[n]===`^`||e[n]===`!`)&&(r+=`^`,n++);let i=!1;n<e.length&&e[n]===`]`&&(i=!0,n++);let a=!1;n<e.length&&e[n]===`[`&&n+1<e.length&&e[n+1]!==`:`&&(a=!0,n++);let o=``,s=!1;for(;n<e.length;){let t=e[n];if(t===`]`){s=!0,n++;break}if(t===`[`&&n+1<e.length&&e[n+1]===`:`){let t=e.indexOf(`:]`,n+2);if(t!==-1){let r=e.slice(n+2,t);o+=i_(r),n=t+2;continue}}if(t===`[`&&n+1<e.length){let t=e[n+1];if(t===`.`||t===`=`){let r=`${t}]`,i=e.indexOf(r,n+2);if(i!==-1){let t=e.slice(n+2,i);o+=t,n=i+2;continue}}}if(t===`\\`&&n+1<e.length){o+=t+e[n+1],n+=2;continue}o+=t,n++}return s?(i&&(r+=`\\]`),a&&(r+=`\\[`),r+=o,r+=`]`,{converted:r,endIndex:n}):{converted:`\\[`,endIndex:t+1}}function i_(e){return new Map([[`alnum`,`a-zA-Z0-9`],[`alpha`,`a-zA-Z`],[`ascii`,`\\x00-\\x7F`],[`blank`,` \\t`],[`cntrl`,`\\x00-\\x1F\\x7F`],[`digit`,`0-9`],[`graph`,`!-~`],[`lower`,`a-z`],[`print`,` -~`],[`punct`,"!-/:-@\\[-`{-~"],[`space`,` \\t\\n\\r\\f\\v`],[`upper`,`A-Z`],[`word`,`a-zA-Z0-9_`],[`xdigit`,`0-9A-Fa-f`]]).get(e)??``}function a_(e){let t=[],n=``,r=!1,i=!1,a=!1,o=!1;for(let s of e){if(a){n+=s,a=!1,o=!0;continue}if(s===`\\`){a=!0;continue}if(s===`'`&&!i){r||(o=!0),r=!r;continue}if(s===`"`&&!r){i||(o=!0),i=!i;continue}if((s===` `||s===` `||s===`
224
- `)&&!r&&!i){o&&=(t.push(n),n=``,!1);continue}n+=s,o=!0}return o&&t.push(n),t}function o_(e){let t=[],n=0;for(;n<e.length;){for(;n<e.length&&/\s/.test(e[n]);)n++;if(n>=e.length)break;if(e[n]!==`[`){n++;continue}n++;let r=``;if(e[n]===`'`||e[n]===`"`){let t=e[n];for(n++;n<e.length&&e[n]!==t;)r+=e[n],n++;e[n]===t&&n++}else for(;n<e.length&&e[n]!==`]`&&e[n]!==`=`;)r+=e[n],n++;for(;n<e.length&&e[n]!==`]`;)n++;if(e[n]===`]`&&n++,e[n]!==`=`)continue;n++;let i=``;if(e[n]===`'`||e[n]===`"`){let t=e[n];for(n++;n<e.length&&e[n]!==t;)e[n]===`\\`&&n+1<e.length&&n++,i+=e[n],n++;e[n]===t&&n++}else for(;n<e.length&&!/\s/.test(e[n]);)i+=e[n],n++;t.push([r,i])}return t}function s_(e){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(t)return{name:t[1],isArray:!0,arrayElements:a_(t[2])};let n=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(n)return{name:n[1],isArray:!1,arrayIndex:n[2],value:n[3]};if(e.includes(`=`)){let t=e.indexOf(`=`);return{name:e.slice(0,t),isArray:!1,value:e.slice(t+1)}}return{name:e,isArray:!1}}async function c_(e,t){try{return await Kt(e,Ft(new Zt,t).expression)}catch{let e=parseInt(t,10);return Number.isNaN(e)?0:e}}async function l_(e,t,n={}){let{name:r,isArray:i,arrayElements:a,value:o,arrayIndex:s}=t,{makeReadonly:c=!1,checkReadonly:l=!0}=n;if(l){let t=yt(e,r);if(t)return t}if(i&&a){for(let t=0;t<a.length;t++)e.state.env.set(`${r}_${t}`,a[t]);e.state.env.set(`${r}__length`,String(a.length))}else if(s!==void 0&&o!==void 0){let t=await c_(e,s);e.state.env.set(`${r}_${t}`,o),t>=parseInt(e.state.env.get(`${r}__length`)??`0`,10)&&e.state.env.set(`${r}__length`,String(t+1))}else o!==void 0&&e.state.env.set(r,o);return c&&Ot(e,r),null}function u_(e,t){e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,e.state.callDepth)}function d_(e,t){return e.state.localVarDepth?.get(t)}function f_(e,t){e.state.localVarDepth?.delete(t)}function p_(e,t,n){e.state.localVarStack=e.state.localVarStack||new Map;let r=e.state.localVarStack.get(t)||[];r.push({value:n,scopeIndex:e.state.localScopes.length-1}),e.state.localVarStack.set(t,r)}function m_(e,t){let n=e.state.localVarStack?.get(t);if(!(!n||n.length===0))return n.pop()}function h_(e,t){if(e.state.localVarStack)for(let[n,r]of e.state.localVarStack.entries()){for(;r.length>0&&r[r.length-1].scopeIndex===t;)r.pop();r.length===0&&e.state.localVarStack.delete(n)}}var g_=new Set([`:`,`.`,`break`,`continue`,`eval`,`exec`,`exit`,`export`,`readonly`,`return`,`set`,`shift`,`trap`,`unset`]);function __(e){return g_.has(e)}var v_=new Set([`if`,`then`,`else`,`elif`,`fi`,`case`,`esac`,`for`,`select`,`while`,`until`,`do`,`done`,`in`,`function`,`{`,`}`,`time`,`[[`,`]]`,`!`]),y_=new Set(`:,true,false,cd,export,unset,exit,local,set,break,continue,return,eval,shift,getopts,compgen,complete,compopt,pushd,popd,dirs,source,.,read,mapfile,readarray,declare,typeset,readonly,let,command,shopt,exec,test,[,echo,printf,pwd,alias,unalias,type,hash,ulimit,umask,trap,times,wait,kill,jobs,fg,bg,disown,suspend,fc,history,help,enable,builtin,caller`.split(`,`));async function b_(e,t,n,r){try{if((await e.fs.stat(t)).isDirectory)return`bash: ${n}: Is a directory
219
+ `:``)}function wg(e,t){return e.fs.resolvePath(e.state.cwd,t)}var Tg=[`-e`,`-a`,`-f`,`-d`,`-r`,`-w`,`-x`,`-s`,`-L`,`-h`,`-k`,`-g`,`-u`,`-G`,`-O`,`-b`,`-c`,`-p`,`-S`,`-t`,`-N`];function Eg(e){return Tg.includes(e)}async function Dg(e,t,n){let r=wg(e,n);switch(t){case`-e`:case`-a`:return e.fs.exists(r);case`-f`:return await e.fs.exists(r)?(await e.fs.stat(r)).isFile:!1;case`-d`:return await e.fs.exists(r)?(await e.fs.stat(r)).isDirectory:!1;case`-r`:return await e.fs.exists(r)?((await e.fs.stat(r)).mode&256)!=0:!1;case`-w`:return await e.fs.exists(r)?((await e.fs.stat(r)).mode&128)!=0:!1;case`-x`:return await e.fs.exists(r)?((await e.fs.stat(r)).mode&64)!=0:!1;case`-s`:return await e.fs.exists(r)?(await e.fs.stat(r)).size>0:!1;case`-L`:case`-h`:try{return(await e.fs.lstat(r)).isSymbolicLink}catch{return!1}case`-k`:return await e.fs.exists(r)?((await e.fs.stat(r)).mode&512)!=0:!1;case`-g`:return await e.fs.exists(r)?((await e.fs.stat(r)).mode&1024)!=0:!1;case`-u`:return await e.fs.exists(r)?((await e.fs.stat(r)).mode&2048)!=0:!1;case`-G`:case`-O`:return e.fs.exists(r);case`-b`:return!1;case`-c`:return[`/dev/null`,`/dev/zero`,`/dev/random`,`/dev/urandom`,`/dev/tty`,`/dev/stdin`,`/dev/stdout`,`/dev/stderr`].includes(r);case`-p`:return!1;case`-S`:return!1;case`-t`:return!1;case`-N`:return e.fs.exists(r);default:return!1}}var Og=[`-nt`,`-ot`,`-ef`];function kg(e){return Og.includes(e)}async function Ag(e,t,n,r){let i=wg(e,n),a=wg(e,r);switch(t){case`-nt`:try{let t=await e.fs.stat(i),n=await e.fs.stat(a);return t.mtime>n.mtime}catch{return!1}case`-ot`:try{let t=await e.fs.stat(i),n=await e.fs.stat(a);return t.mtime<n.mtime}catch{return!1}case`-ef`:try{return!await e.fs.exists(i)||!await e.fs.exists(a)?!1:e.fs.resolvePath(e.state.cwd,i)===e.fs.resolvePath(e.state.cwd,a)}catch{return!1}default:return!1}}var jg=new Set([`-eq`,`-ne`,`-lt`,`-le`,`-gt`,`-ge`]);function Mg(e){return jg.has(e)}function Ng(e,t,n){switch(e){case`-eq`:return t===n;case`-ne`:return t!==n;case`-lt`:return t<n;case`-le`:return t<=n;case`-gt`:return t>n;case`-ge`:return t>=n}}function Pg(e){return e===`=`||e===`==`||e===`!=`}function Fg(e,t,n,r=!1,i=!1,a=!1){if(r){let r=qg(t,n,i,a);return e===`!=`?!r:r}if(i){let r=t.toLowerCase()===n.toLowerCase();return e===`!=`?!r:r}let o=t===n;return e===`!=`?!o:o}var Ig=new Set([`-z`,`-n`]);function Lg(e){return Ig.has(e)}function Rg(e,t){switch(e){case`-z`:return t===``;case`-n`:return t!==``}}async function zg(e,t){let n=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(n){let t=n[1],r=n[2];if(e.state.associativeArrays?.has(t)){let n=r;return(n.startsWith(`'`)&&n.endsWith(`'`)||n.startsWith(`"`)&&n.endsWith(`"`))&&(n=n.slice(1,-1)),n=n.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(t,n)=>e.state.env.get(n)||``),e.state.env.has(`${t}_${n}`)}let i;try{i=await Kt(e,Ft(new Zt,r).expression)}catch{if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{let t=e.state.env.get(r);i=t?Number.parseInt(t,10):0}}if(i<0){let n=Et(e,t),r=e.state.currentLine;if(n.length===0||(i=Math.max(...n)+1+i,i<0))return e.state.expansionStderr=(e.state.expansionStderr||``)+`bash: line ${r}: ${t}: bad array subscript
220
+ `,!1}return e.state.env.has(`${t}_${i}`)}return e.state.env.has(t)?!0:e.state.associativeArrays?.has(t)?gt(e,t).length>0:Et(e,t).length>0}async function Bg(e,t){switch(t.type){case`CondBinary`:{let n=await O(e,t.left),r=t.right.parts.length>0&&t.right.parts.every(e=>e.type===`SingleQuoted`||e.type===`DoubleQuoted`||e.type===`Escaped`&&t.operator!==`=~`),i;if(i=t.operator===`=~`?r?bt(await O(e,t.right)):await Rt(e,t.right):Pg(t.operator)&&!r?await At(e,t.right):await O(e,t.right),Pg(t.operator)){let a=e.state.shoptOptions.nocasematch;return Fg(t.operator,n,i,!r,a,!0)}if(Mg(t.operator))return Ng(t.operator,await $g(e,n),await $g(e,i));if(kg(t.operator))return Ag(e,t.operator,n,i);switch(t.operator){case`=~`:try{let t=e.state.shoptOptions.nocasematch,r=et(r_(i),t?`i`:``).match(n);if(qt(e,`BASH_REMATCH`),r)for(let t=0;t<r.length;t++)e.state.env.set(`BASH_REMATCH_${t}`,r[t]||``);return r!==null}catch{throw Error(`syntax error in regular expression`)}case`<`:return n<i;case`>`:return n>i;default:return!1}}case`CondUnary`:{let n=await O(e,t.operand);return Eg(t.operator)?Dg(e,t.operator,n):Lg(t.operator)?Rg(t.operator,n):t.operator===`-v`?await zg(e,n):t.operator===`-o`?Qg(e,n):!1}case`CondNot`:return e.state.shoptOptions.extglob&&t.operand.type===`CondGroup`&&t.operand.expression.type===`CondWord`?`!(${await O(e,t.operand.expression.word)})`!=``:!await Bg(e,t.operand);case`CondAnd`:return await Bg(e,t.left)?await Bg(e,t.right):!1;case`CondOr`:return await Bg(e,t.left)?!0:await Bg(e,t.right);case`CondGroup`:return await Bg(e,t.expression);case`CondWord`:return await O(e,t.word)!==``;default:return!1}}async function Vg(e,t){if(t.length===0)return Z(``,``,1);if(t.length===1)return yg(!!t[0]);if(t.length===2){let n=t[0],r=t[1];return n===`(`?X(`test: '(' without matching ')'
221
+ `,2):Eg(n)?yg(await Dg(e,n,r)):Lg(n)?yg(Rg(n,r)):n===`!`?yg(!r):n===`-v`?yg(await zg(e,r)):n===`-o`?yg(Qg(e,r)):n===`=`||n===`==`||n===`!=`||n===`<`||n===`>`||n===`-eq`||n===`-ne`||n===`-lt`||n===`-le`||n===`-gt`||n===`-ge`||n===`-nt`||n===`-ot`||n===`-ef`?X(`test: ${n}: unary operator expected
222
+ `,2):Z(``,``,1)}if(t.length===3){let n=t[0],r=t[1],i=t[2];if(Pg(r))return yg(Fg(r,n,i));if(Mg(r)){let e=n_(n),t=n_(i);return!e.valid||!t.valid?Z(``,``,2):yg(Ng(r,e.value,t.value))}if(kg(r))return yg(await Ag(e,r,n,i));switch(r){case`-a`:return yg(n!==``&&i!==``);case`-o`:return yg(n!==``||i!==``);case`>`:return yg(n>i);case`<`:return yg(n<i)}if(n===`!`){let t=await Vg(e,[r,i]);return Z(``,t.stderr,t.exitCode===0?1:t.exitCode===1?0:t.exitCode)}if(n===`(`&&i===`)`)return yg(r!==``)}if(t.length===4){if(t[0]===`!`){let n=await Vg(e,t.slice(1));return Z(``,n.stderr,n.exitCode===0?1:n.exitCode===1?0:n.exitCode)}if(t[0]===`(`&&t[3]===`)`)return Vg(e,[t[1],t[2]])}let n=await Hg(e,t,0);return n.pos<t.length?X(`test: too many arguments
223
+ `,2):yg(n.value)}async function Hg(e,t,n){return Ug(e,t,n)}async function Ug(e,t,n){let{value:r,pos:i}=await Wg(e,t,n);for(;t[i]===`-o`;){let n=await Wg(e,t,i+1);r||=n.value,i=n.pos}return{value:r,pos:i}}async function Wg(e,t,n){let{value:r,pos:i}=await Gg(e,t,n);for(;t[i]===`-a`;){let n=await Gg(e,t,i+1);r&&=n.value,i=n.pos}return{value:r,pos:i}}async function Gg(e,t,n){if(t[n]===`!`){let{value:r,pos:i}=await Gg(e,t,n+1);return{value:!r,pos:i}}return Kg(e,t,n)}async function Kg(e,t,n){let r=t[n];if(r===`(`){let{value:r,pos:i}=await Hg(e,t,n+1);return{value:r,pos:t[i]===`)`?i+1:i}}let i=t[n+1];if(Pg(i))return{value:Fg(i,r,t[n+2]??``),pos:n+3};if(Mg(i)){let e=n_(r),a=n_(t[n+2]??`0`);return!e.valid||!a.valid?{value:!1,pos:n+3}:{value:Ng(i,e.value,a.value),pos:n+3}}return kg(i)?{value:await Ag(e,i,r,t[n+2]??``),pos:n+3}:Eg(r)?{value:await Dg(e,r,t[n+1]??``),pos:n+2}:Lg(r)?{value:Rg(r,t[n+1]??``),pos:n+2}:r===`-v`?{value:await zg(e,t[n+1]??``),pos:n+2}:r===`-o`?{value:Qg(e,t[n+1]??``),pos:n+2}:{value:r!==void 0&&r!==``,pos:n+1}}function qg(e,t,n=!1,r=!1){return et(`^${Jg(t,r)}$`,n?`is`:`s`).test(e)}function Jg(e,t){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(t&&(i===`@`||i===`*`||i===`+`||i===`?`||i===`!`)&&r+1<e.length&&e[r+1]===`(`){let a=Yg(e,r+1);if(a!==-1){let o=Xg(e.slice(r+2,a)),s=o.map(e=>Jg(e,t)),c=s.length>0?s.join(`|`):`(?:)`;if(i===`@`)n+=`(?:${c})`;else if(i===`*`)n+=`(?:${c})*`;else if(i===`+`)n+=`(?:${c})+`;else if(i===`?`)n+=`(?:${c})?`;else if(i===`!`)if(a<e.length-1){let e=o.map(e=>Zg(e,t));if(e.every(e=>e!==null)&&e.every(t=>t===e[0])&&e[0]!==null){let t=e[0];if(t===0)n+=`(?:.+)`;else{let e=[];t>0&&e.push(`.{0,${t-1}}`),e.push(`.{${t+1},}`),e.push(`(?!(?:${c})).{${t}}`),n+=`(?:${e.join(`|`)})`}}else n+=`(?:(?!(?:${c})).)*?`}else n+=`(?!(?:${c})$).*`;r=a;continue}}if(i===`\\`)if(r+1<e.length){let t=e[r+1];/[\\^$.|+(){}[\]*?]/.test(t)?n+=`\\${t}`:n+=t,r++}else n+=`\\\\`;else if(i===`*`)n+=`.*`;else if(i===`?`)n+=`.`;else if(i===`[`){let t=e.indexOf(`]`,r+1);t===-1?n+=`\\[`:(n+=e.slice(r,t+1),r=t)}else /[\\^$.|+(){}]/.test(i)?n+=`\\${i}`:n+=i}return n}function Yg(e,t){let n=1,r=t+1;for(;r<e.length&&n>0;){let t=e[r];if(t===`\\`){r+=2;continue}if(t===`(`)n++;else if(t===`)`&&(n--,n===0))return r;r++}return-1}function Xg(e){let t=[],n=``,r=0,i=0;for(;i<e.length;){let a=e[i];if(a===`\\`){n+=a,i+1<e.length?(n+=e[i+1],i+=2):i++;continue}a===`(`?(r++,n+=a):a===`)`?(r--,n+=a):a===`|`&&r===0?(t.push(n),n=``):n+=a,i++}return t.push(n),t}function Zg(e,t){let n=0,r=0;for(;r<e.length;){let i=e[r];if(t&&(i===`@`||i===`*`||i===`+`||i===`?`||i===`!`)&&r+1<e.length&&e[r+1]===`(`){let a=Yg(e,r+1);if(a!==-1){if(i===`@`){let i=Xg(e.slice(r+2,a)).map(e=>Zg(e,t));if(i.every(e=>e!==null)&&i.every(e=>e===i[0])){n+=i[0],r=a+1;continue}return null}return null}}if(i===`*`)return null;if(i===`?`){n+=1,r++;continue}if(i===`[`){let t=e.indexOf(`]`,r+1);if(t!==-1){n+=1,r=t+1;continue}n+=1,r++;continue}if(i===`\\`){n+=1,r+=2;continue}n+=1,r++}return n}function Qg(e,t){let n=new Map([[`errexit`,()=>e.state.options.errexit===!0],[`nounset`,()=>e.state.options.nounset===!0],[`pipefail`,()=>e.state.options.pipefail===!0],[`xtrace`,()=>e.state.options.xtrace===!0],[`e`,()=>e.state.options.errexit===!0],[`u`,()=>e.state.options.nounset===!0],[`x`,()=>e.state.options.xtrace===!0]]).get(t);return n?n():!1}async function $g(e,t){if(t=t.trim(),t===``)return 0;if(/^[+-]?(\d+#[a-zA-Z0-9@_]+|0[xX][0-9a-fA-F]+|0[0-7]+|\d+)$/.test(t))return t_(t);try{return await Kt(e,Ft(new Zt,t).expression)}catch{return t_(t)}}function e_(e,t){let n=0;for(let r of e){let e;if(r>=`0`&&r<=`9`)e=r.charCodeAt(0)-48;else if(r>=`a`&&r<=`z`)e=r.charCodeAt(0)-97+10;else if(r>=`A`&&r<=`Z`)e=r.charCodeAt(0)-65+36;else if(r===`@`)e=62;else if(r===`_`)e=63;else return NaN;if(e>=t)return NaN;n=n*t+e}return n}function t_(e){if(e=e.trim(),e===``)return 0;let t=!1;e.startsWith(`-`)?(t=!0,e=e.slice(1)):e.startsWith(`+`)&&(e=e.slice(1));let n,r=e.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(r){let e=Number.parseInt(r[1],10);n=e>=2&&e<=64?e_(r[2],e):0}else n=/^0[xX][0-9a-fA-F]+$/.test(e)?Number.parseInt(e,16):/^0[0-7]+$/.test(e)?Number.parseInt(e,8):Number.parseInt(e,10);return Number.isNaN(n)&&(n=0),t?-n:n}function n_(e){if(e=e.trim(),e===``)return{value:0,valid:!0};let t=!1;if(e.startsWith(`-`)?(t=!0,e=e.slice(1)):e.startsWith(`+`)&&(e=e.slice(1)),!/^\d+$/.test(e))return{value:0,valid:!1};let n=Number.parseInt(e,10);return Number.isNaN(n)?{value:0,valid:!1}:{value:t?-n:n,valid:!0}}function r_(e){let t=``,n=0;for(;n<e.length;)if(e[n]===`\\`&&n+1<e.length)t+=e[n]+e[n+1],n+=2;else if(e[n]===`[`){let r=i_(e,n);t+=r.converted,n=r.endIndex}else t+=e[n],n++;return t}function i_(e,t){let n=t+1,r=`[`;n<e.length&&(e[n]===`^`||e[n]===`!`)&&(r+=`^`,n++);let i=!1;n<e.length&&e[n]===`]`&&(i=!0,n++);let a=!1;n<e.length&&e[n]===`[`&&n+1<e.length&&e[n+1]!==`:`&&(a=!0,n++);let o=``,s=!1;for(;n<e.length;){let t=e[n];if(t===`]`){s=!0,n++;break}if(t===`[`&&n+1<e.length&&e[n+1]===`:`){let t=e.indexOf(`:]`,n+2);if(t!==-1){let r=e.slice(n+2,t);o+=a_(r),n=t+2;continue}}if(t===`[`&&n+1<e.length){let t=e[n+1];if(t===`.`||t===`=`){let r=`${t}]`,i=e.indexOf(r,n+2);if(i!==-1){let t=e.slice(n+2,i);o+=t,n=i+2;continue}}}if(t===`\\`&&n+1<e.length){o+=t+e[n+1],n+=2;continue}o+=t,n++}return s?(i&&(r+=`\\]`),a&&(r+=`\\[`),r+=o,r+=`]`,{converted:r,endIndex:n}):{converted:`\\[`,endIndex:t+1}}function a_(e){return new Map([[`alnum`,`a-zA-Z0-9`],[`alpha`,`a-zA-Z`],[`ascii`,`\\x00-\\x7F`],[`blank`,` \\t`],[`cntrl`,`\\x00-\\x1F\\x7F`],[`digit`,`0-9`],[`graph`,`!-~`],[`lower`,`a-z`],[`print`,` -~`],[`punct`,"!-/:-@\\[-`{-~"],[`space`,` \\t\\n\\r\\f\\v`],[`upper`,`A-Z`],[`word`,`a-zA-Z0-9_`],[`xdigit`,`0-9A-Fa-f`]]).get(e)??``}function o_(e){let t=[],n=``,r=!1,i=!1,a=!1,o=!1;for(let s of e){if(a){n+=s,a=!1,o=!0;continue}if(s===`\\`){a=!0;continue}if(s===`'`&&!i){r||(o=!0),r=!r;continue}if(s===`"`&&!r){i||(o=!0),i=!i;continue}if((s===` `||s===` `||s===`
224
+ `)&&!r&&!i){o&&=(t.push(n),n=``,!1);continue}n+=s,o=!0}return o&&t.push(n),t}function s_(e){let t=[],n=0;for(;n<e.length;){for(;n<e.length&&/\s/.test(e[n]);)n++;if(n>=e.length)break;if(e[n]!==`[`){n++;continue}n++;let r=``;if(e[n]===`'`||e[n]===`"`){let t=e[n];for(n++;n<e.length&&e[n]!==t;)r+=e[n],n++;e[n]===t&&n++}else for(;n<e.length&&e[n]!==`]`&&e[n]!==`=`;)r+=e[n],n++;for(;n<e.length&&e[n]!==`]`;)n++;if(e[n]===`]`&&n++,e[n]!==`=`)continue;n++;let i=``;if(e[n]===`'`||e[n]===`"`){let t=e[n];for(n++;n<e.length&&e[n]!==t;)e[n]===`\\`&&n+1<e.length&&n++,i+=e[n],n++;e[n]===t&&n++}else for(;n<e.length&&!/\s/.test(e[n]);)i+=e[n],n++;t.push([r,i])}return t}function c_(e){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(t)return{name:t[1],isArray:!0,arrayElements:o_(t[2])};let n=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(n)return{name:n[1],isArray:!1,arrayIndex:n[2],value:n[3]};if(e.includes(`=`)){let t=e.indexOf(`=`);return{name:e.slice(0,t),isArray:!1,value:e.slice(t+1)}}return{name:e,isArray:!1}}async function l_(e,t){try{return await Kt(e,Ft(new Zt,t).expression)}catch{let e=parseInt(t,10);return Number.isNaN(e)?0:e}}async function u_(e,t,n={}){let{name:r,isArray:i,arrayElements:a,value:o,arrayIndex:s}=t,{makeReadonly:c=!1,checkReadonly:l=!0}=n;if(l){let t=yt(e,r);if(t)return t}if(i&&a){for(let t=0;t<a.length;t++)e.state.env.set(`${r}_${t}`,a[t]);e.state.env.set(`${r}__length`,String(a.length))}else if(s!==void 0&&o!==void 0){let t=await l_(e,s);e.state.env.set(`${r}_${t}`,o),t>=parseInt(e.state.env.get(`${r}__length`)??`0`,10)&&e.state.env.set(`${r}__length`,String(t+1))}else o!==void 0&&e.state.env.set(r,o);return c&&Ot(e,r),null}function d_(e,t){e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,e.state.callDepth)}function f_(e,t){return e.state.localVarDepth?.get(t)}function p_(e,t){e.state.localVarDepth?.delete(t)}function m_(e,t,n){e.state.localVarStack=e.state.localVarStack||new Map;let r=e.state.localVarStack.get(t)||[];r.push({value:n,scopeIndex:e.state.localScopes.length-1}),e.state.localVarStack.set(t,r)}function h_(e,t){let n=e.state.localVarStack?.get(t);if(!(!n||n.length===0))return n.pop()}function g_(e,t){if(e.state.localVarStack)for(let[n,r]of e.state.localVarStack.entries()){for(;r.length>0&&r[r.length-1].scopeIndex===t;)r.pop();r.length===0&&e.state.localVarStack.delete(n)}}var __=new Set([`:`,`.`,`break`,`continue`,`eval`,`exec`,`exit`,`export`,`readonly`,`return`,`set`,`shift`,`trap`,`unset`]);function v_(e){return __.has(e)}var y_=new Set([`if`,`then`,`else`,`elif`,`fi`,`case`,`esac`,`for`,`select`,`while`,`until`,`do`,`done`,`in`,`function`,`{`,`}`,`time`,`[[`,`]]`,`!`]),b_=new Set(`:,true,false,cd,export,unset,exit,local,set,break,continue,return,eval,shift,getopts,compgen,complete,compopt,pushd,popd,dirs,source,.,read,mapfile,readarray,declare,typeset,readonly,let,command,shopt,exec,test,[,echo,printf,pwd,alias,unalias,type,hash,ulimit,umask,trap,times,wait,kill,jobs,fg,bg,disown,suspend,fc,history,help,enable,builtin,caller`.split(`,`));async function x_(e,t,n,r){try{if((await e.fs.stat(t)).isDirectory)return`bash: ${n}: Is a directory
225
225
  `;if(r.checkNoclobber&&e.state.options.noclobber&&!r.isClobber&&n!==`/dev/null`)return`bash: ${n}: cannot overwrite existing file
226
- `}catch{}return null}function x_(e){let t=Math.min(e.length,8192);for(let n=0;n<t;n++)if(e.charCodeAt(n)>127)return`utf8`;return`binary`}function S_(e){if(!e.startsWith(`__rw__:`))return null;let t=e.slice(7),n=t.indexOf(`:`);if(n===-1)return null;let r=Number.parseInt(t.slice(0,n),10);if(Number.isNaN(r)||r<0)return null;let i=n+1,a=t.slice(i,i+r),o=i+r+1,s=t.slice(o),c=s.indexOf(`:`);if(c===-1)return null;let l=Number.parseInt(s.slice(0,c),10);return Number.isNaN(l)||l<0?null:{path:a,position:l,content:s.slice(c+1)}}async function C_(e,t){let n=new Map;for(let r=0;r<t.length;r++){let i=t[r];if(i.target.type!==`HereDoc`)if(i.operator===`>&`||i.operator===`<&`){if(Gt(e,i.target))return{targets:n,error:`bash: $@: ambiguous redirect
227
- `};n.set(r,await O(e,i.target))}else{let t=await Ht(e,i.target);if(`error`in t)return{targets:n,error:t.error};n.set(r,t.target)}}return{targets:n}}function w_(e){e.state.nextFd===void 0&&(e.state.nextFd=10);let t=e.state.nextFd,n=e.limits.maxFileDescriptors;if(t>=n)throw Error(`bash: cannot allocate file descriptor: too many open files (max ${n})`);return e.state.nextFd++,t}async function T_(e,t){for(let n of t){if(!n.fdVariable)continue;if(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),(n.operator===`>&`||n.operator===`<&`)&&n.target.type===`Word`&&await O(e,n.target)===`-`){let t=e.state.env.get(n.fdVariable);if(t!==void 0){let n=Number.parseInt(t,10);Number.isNaN(n)||e.state.fileDescriptors.delete(n)}continue}let t=w_(e);if(e.state.env.set(n.fdVariable,String(t)),n.target.type===`Word`){let r=await O(e,n.target);if(n.operator===`>&`||n.operator===`<&`){let n=Number.parseInt(r,10);if(!Number.isNaN(n)){let r=e.state.fileDescriptors.get(n);r!==void 0&&(bg(e),e.state.fileDescriptors.set(t,r));continue}}if(n.operator===`>`||n.operator===`>>`||n.operator===`>|`||n.operator===`&>`||n.operator===`&>>`){let i=e.fs.resolvePath(e.state.cwd,r);(n.operator===`>`||n.operator===`>|`||n.operator===`&>`)&&await e.fs.writeFile(i,``,`binary`),bg(e),e.state.fileDescriptors.set(t,`__file__:${i}`)}else if(n.operator===`<<<`)bg(e),e.state.fileDescriptors.set(t,`${r}
228
- `);else if(n.operator===`<`||n.operator===`<>`)try{let n=e.fs.resolvePath(e.state.cwd,r),i=await e.fs.readFile(n);bg(e),e.state.fileDescriptors.set(t,i)}catch{return Z(``,`bash: ${r}: No such file or directory
229
- `,1)}}}return null}async function E_(e,t){for(let n of t){if(n.target.type===`HereDoc`)continue;let t=n.operator===`>&`;if(n.operator!==`>`&&n.operator!==`>|`&&n.operator!==`&>`&&!t)continue;let r;if(t){if(r=await O(e,n.target),r===`-`||!Number.isNaN(Number.parseInt(r,10))||n.fd!=null)continue}else{let t=await Ht(e,n.target);if(`error`in t)return Z(``,t.error,1);r=t.target}let i=e.fs.resolvePath(e.state.cwd,r),a=n.operator===`>|`;if(i.includes(`\0`))return Z(``,`bash: ${r}: No such file or directory
226
+ `}catch{}return null}function S_(e){let t=Math.min(e.length,8192);for(let n=0;n<t;n++)if(e.charCodeAt(n)>127)return`utf8`;return`binary`}function C_(e){if(!e.startsWith(`__rw__:`))return null;let t=e.slice(7),n=t.indexOf(`:`);if(n===-1)return null;let r=Number.parseInt(t.slice(0,n),10);if(Number.isNaN(r)||r<0)return null;let i=n+1,a=t.slice(i,i+r),o=i+r+1,s=t.slice(o),c=s.indexOf(`:`);if(c===-1)return null;let l=Number.parseInt(s.slice(0,c),10);return Number.isNaN(l)||l<0?null:{path:a,position:l,content:s.slice(c+1)}}async function w_(e,t){let n=new Map;for(let r=0;r<t.length;r++){let i=t[r];if(i.target.type!==`HereDoc`)if(i.operator===`>&`||i.operator===`<&`){if(Gt(e,i.target))return{targets:n,error:`bash: $@: ambiguous redirect
227
+ `};n.set(r,await O(e,i.target))}else{let t=await Ht(e,i.target);if(`error`in t)return{targets:n,error:t.error};n.set(r,t.target)}}return{targets:n}}function T_(e){e.state.nextFd===void 0&&(e.state.nextFd=10);let t=e.state.nextFd,n=e.limits.maxFileDescriptors;if(t>=n)throw Error(`bash: cannot allocate file descriptor: too many open files (max ${n})`);return e.state.nextFd++,t}async function E_(e,t){for(let n of t){if(!n.fdVariable)continue;if(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),(n.operator===`>&`||n.operator===`<&`)&&n.target.type===`Word`&&await O(e,n.target)===`-`){let t=e.state.env.get(n.fdVariable);if(t!==void 0){let n=Number.parseInt(t,10);Number.isNaN(n)||e.state.fileDescriptors.delete(n)}continue}let t=T_(e);if(e.state.env.set(n.fdVariable,String(t)),n.target.type===`Word`){let r=await O(e,n.target);if(n.operator===`>&`||n.operator===`<&`){let n=Number.parseInt(r,10);if(!Number.isNaN(n)){let r=e.state.fileDescriptors.get(n);r!==void 0&&(xg(e),e.state.fileDescriptors.set(t,r));continue}}if(n.operator===`>`||n.operator===`>>`||n.operator===`>|`||n.operator===`&>`||n.operator===`&>>`){let i=e.fs.resolvePath(e.state.cwd,r);(n.operator===`>`||n.operator===`>|`||n.operator===`&>`)&&await e.fs.writeFile(i,``,`binary`),xg(e),e.state.fileDescriptors.set(t,`__file__:${i}`)}else if(n.operator===`<<<`)xg(e),e.state.fileDescriptors.set(t,`${r}
228
+ `);else if(n.operator===`<`||n.operator===`<>`)try{let n=e.fs.resolvePath(e.state.cwd,r),i=await e.fs.readFile(n);xg(e),e.state.fileDescriptors.set(t,i)}catch{return Z(``,`bash: ${r}: No such file or directory
229
+ `,1)}}}return null}async function D_(e,t){for(let n of t){if(n.target.type===`HereDoc`)continue;let t=n.operator===`>&`;if(n.operator!==`>`&&n.operator!==`>|`&&n.operator!==`&>`&&!t)continue;let r;if(t){if(r=await O(e,n.target),r===`-`||!Number.isNaN(Number.parseInt(r,10))||n.fd!=null)continue}else{let t=await Ht(e,n.target);if(`error`in t)return Z(``,t.error,1);r=t.target}let i=e.fs.resolvePath(e.state.cwd,r),a=n.operator===`>|`;if(i.includes(`\0`))return Z(``,`bash: ${r}: No such file or directory
230
230
  `,1);try{let t=await e.fs.stat(i);if(t.isDirectory)return Z(``,`bash: ${r}: Is a directory
231
231
  `,1);if(e.state.options.noclobber&&!a&&!t.isDirectory&&r!==`/dev/null`)return Z(``,`bash: ${r}: cannot overwrite existing file
232
232
  `,1)}catch{}if(r!==`/dev/null`&&r!==`/dev/stdout`&&r!==`/dev/stderr`&&r!==`/dev/full`&&await e.fs.writeFile(i,``,`binary`),r===`/dev/full`)return Z(``,`bash: /dev/full: No space left on device
233
- `,1)}return null}async function D_(e,t,n,r){let{stdout:i,stderr:a,exitCode:o}=t,s=t.stdoutEncoding===`binary`?()=>`binary`:e=>x_(e);for(let t=0;t<n.length;t++){let c=n[t];if(c.target.type===`HereDoc`)continue;let l,u=r?.get(t);if(u!==void 0)l=u;else if(c.operator===`>&`||c.operator===`<&`){if(Gt(e,c.target)){a+=`bash: $@: ambiguous redirect
233
+ `,1)}return null}async function O_(e,t,n,r){let{stdout:i,stderr:a,exitCode:o}=t,s=t.stdoutEncoding===`binary`?()=>`binary`:e=>S_(e);for(let t=0;t<n.length;t++){let c=n[t];if(c.target.type===`HereDoc`)continue;let l,u=r?.get(t);if(u!==void 0)l=u;else if(c.operator===`>&`||c.operator===`<&`){if(Gt(e,c.target)){a+=`bash: $@: ambiguous redirect
234
234
  `,o=1,i=``;continue}l=await O(e,c.target)}else{let t=await Ht(e,c.target);if(`error`in t){a+=t.error,o=1,i=``;continue}l=t.target}if(!c.fdVariable){if(l.includes(`\0`)){a+=`bash: ${l.replace(/\0/g,``)}: No such file or directory
235
235
  `,o=1,i=``;continue}switch(c.operator){case`>`:case`>|`:{let t=c.fd??1,n=c.operator===`>|`;if(t===1){if(l===`/dev/stdout`)break;if(l===`/dev/stderr`){a+=i,i=``;break}if(l===`/dev/full`){a+=`bash: echo: write error: No space left on device
236
- `,o=1,i=``;break}let t=e.fs.resolvePath(e.state.cwd,l),r=await b_(e,t,l,{checkNoclobber:!0,isClobber:n});if(r){a+=r,o=1,i=``;break}await e.fs.writeFile(t,i,s(i)),i=``}else if(t===2){if(l===`/dev/stderr`)break;if(l===`/dev/stdout`){i+=a,a=``;break}if(l===`/dev/full`){a+=`bash: echo: write error: No space left on device
237
- `,o=1;break}if(l===`/dev/null`)a=``;else{let t=e.fs.resolvePath(e.state.cwd,l),r=await b_(e,t,l,{checkNoclobber:!0,isClobber:n});if(r){a+=r,o=1;break}await e.fs.writeFile(t,a,x_(a)),a=``}}break}case`>>`:{let t=c.fd??1;if(t===1){if(l===`/dev/stdout`)break;if(l===`/dev/stderr`){a+=i,i=``;break}if(l===`/dev/full`){a+=`bash: echo: write error: No space left on device
238
- `,o=1,i=``;break}let t=e.fs.resolvePath(e.state.cwd,l),n=await b_(e,t,l,{});if(n){a+=n,o=1,i=``;break}await e.fs.appendFile(t,i,s(i)),i=``}else if(t===2){if(l===`/dev/stderr`)break;if(l===`/dev/stdout`){i+=a,a=``;break}if(l===`/dev/full`){a+=`bash: echo: write error: No space left on device
239
- `,o=1;break}let t=e.fs.resolvePath(e.state.cwd,l),n=await b_(e,t,l,{});if(n){a+=n,o=1;break}await e.fs.appendFile(t,a,x_(a)),a=``}break}case`>&`:case`<&`:{let t=c.fd??1;if(l===`-`)break;if(l.endsWith(`-`)){let n=l.slice(0,-1),r=Number.parseInt(n,10);if(!Number.isNaN(r)){let n=e.state.fileDescriptors?.get(r);n===void 0?r===1||r===2?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(t,`__dupout__:${r}`)):r===0?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(t,`__dupin__:${r}`)):r>=3&&(a+=`bash: ${r}: Bad file descriptor
240
- `,o=1):(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(t,n),r>=3&&e.state.fileDescriptors?.delete(r))}break}if(l===`2`||l===`&2`)t===1&&(a+=i,i=``);else if(l===`1`||l===`&1`)i+=a,a=``;else{let n=Number.parseInt(l,10);if(Number.isNaN(n)){if(c.operator===`>&`){let n=e.fs.resolvePath(e.state.cwd,l),r=await b_(e,n,l,{checkNoclobber:!0});if(r){a=r,o=1,i=``;break}if(c.fd==null){let t=i+a;await e.fs.writeFile(n,t,s(t)),i=``,a=``}else t===1?(await e.fs.writeFile(n,i,s(i)),i=``):t===2&&(await e.fs.writeFile(n,a,x_(a)),a=``)}}else{let r=e.state.fileDescriptors?.get(n);if(r?.startsWith(`__file__:`)){let n=r.slice(9);t===1?(await e.fs.appendFile(n,i,s(i)),i=``):t===2&&(await e.fs.appendFile(n,a,x_(a)),a=``)}else if(r?.startsWith(`__rw__:`)){let n=S_(r);n&&(t===1?(await e.fs.appendFile(n.path,i,s(i)),i=``):t===2&&(await e.fs.appendFile(n.path,a,x_(a)),a=``))}else if(r?.startsWith(`__dupout__:`)){let n=Number.parseInt(r.slice(11),10);if(n!==1)if(n===2)t===1&&(a+=i,i=``);else{let r=e.state.fileDescriptors?.get(n);if(r?.startsWith(`__file__:`)){let n=r.slice(9);t===1?(await e.fs.appendFile(n,i,s(i)),i=``):t===2&&(await e.fs.appendFile(n,a,x_(a)),a=``)}}}else (r?.startsWith(`__dupin__:`)||n>=3)&&(a+=`bash: ${n}: Bad file descriptor
236
+ `,o=1,i=``;break}let t=e.fs.resolvePath(e.state.cwd,l),r=await x_(e,t,l,{checkNoclobber:!0,isClobber:n});if(r){a+=r,o=1,i=``;break}await e.fs.writeFile(t,i,s(i)),i=``}else if(t===2){if(l===`/dev/stderr`)break;if(l===`/dev/stdout`){i+=a,a=``;break}if(l===`/dev/full`){a+=`bash: echo: write error: No space left on device
237
+ `,o=1;break}if(l===`/dev/null`)a=``;else{let t=e.fs.resolvePath(e.state.cwd,l),r=await x_(e,t,l,{checkNoclobber:!0,isClobber:n});if(r){a+=r,o=1;break}await e.fs.writeFile(t,a,S_(a)),a=``}}break}case`>>`:{let t=c.fd??1;if(t===1){if(l===`/dev/stdout`)break;if(l===`/dev/stderr`){a+=i,i=``;break}if(l===`/dev/full`){a+=`bash: echo: write error: No space left on device
238
+ `,o=1,i=``;break}let t=e.fs.resolvePath(e.state.cwd,l),n=await x_(e,t,l,{});if(n){a+=n,o=1,i=``;break}await e.fs.appendFile(t,i,s(i)),i=``}else if(t===2){if(l===`/dev/stderr`)break;if(l===`/dev/stdout`){i+=a,a=``;break}if(l===`/dev/full`){a+=`bash: echo: write error: No space left on device
239
+ `,o=1;break}let t=e.fs.resolvePath(e.state.cwd,l),n=await x_(e,t,l,{});if(n){a+=n,o=1;break}await e.fs.appendFile(t,a,S_(a)),a=``}break}case`>&`:case`<&`:{let t=c.fd??1;if(l===`-`)break;if(l.endsWith(`-`)){let n=l.slice(0,-1),r=Number.parseInt(n,10);if(!Number.isNaN(r)){let n=e.state.fileDescriptors?.get(r);n===void 0?r===1||r===2?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(t,`__dupout__:${r}`)):r===0?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(t,`__dupin__:${r}`)):r>=3&&(a+=`bash: ${r}: Bad file descriptor
240
+ `,o=1):(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(t,n),r>=3&&e.state.fileDescriptors?.delete(r))}break}if(l===`2`||l===`&2`)t===1&&(a+=i,i=``);else if(l===`1`||l===`&1`)i+=a,a=``;else{let n=Number.parseInt(l,10);if(Number.isNaN(n)){if(c.operator===`>&`){let n=e.fs.resolvePath(e.state.cwd,l),r=await x_(e,n,l,{checkNoclobber:!0});if(r){a=r,o=1,i=``;break}if(c.fd==null){let t=i+a;await e.fs.writeFile(n,t,s(t)),i=``,a=``}else t===1?(await e.fs.writeFile(n,i,s(i)),i=``):t===2&&(await e.fs.writeFile(n,a,S_(a)),a=``)}}else{let r=e.state.fileDescriptors?.get(n);if(r?.startsWith(`__file__:`)){let n=r.slice(9);t===1?(await e.fs.appendFile(n,i,s(i)),i=``):t===2&&(await e.fs.appendFile(n,a,S_(a)),a=``)}else if(r?.startsWith(`__rw__:`)){let n=C_(r);n&&(t===1?(await e.fs.appendFile(n.path,i,s(i)),i=``):t===2&&(await e.fs.appendFile(n.path,a,S_(a)),a=``))}else if(r?.startsWith(`__dupout__:`)){let n=Number.parseInt(r.slice(11),10);if(n!==1)if(n===2)t===1&&(a+=i,i=``);else{let r=e.state.fileDescriptors?.get(n);if(r?.startsWith(`__file__:`)){let n=r.slice(9);t===1?(await e.fs.appendFile(n,i,s(i)),i=``):t===2&&(await e.fs.appendFile(n,a,S_(a)),a=``)}}}else (r?.startsWith(`__dupin__:`)||n>=3)&&(a+=`bash: ${n}: Bad file descriptor
241
241
  `,o=1,i=``)}}break}case`&>`:{if(l===`/dev/full`){a=`bash: echo: write error: No space left on device
242
- `,o=1,i=``;break}let t=e.fs.resolvePath(e.state.cwd,l),n=await b_(e,t,l,{checkNoclobber:!0});if(n){a=n,o=1,i=``;break}let r=i+a;await e.fs.writeFile(t,r,s(r)),i=``,a=``;break}case`&>>`:{if(l===`/dev/full`){a=`bash: echo: write error: No space left on device
243
- `,o=1,i=``;break}let t=e.fs.resolvePath(e.state.cwd,l),n=await b_(e,t,l,{});if(n){a=n,o=1,i=``;break}let r=i+a;await e.fs.appendFile(t,r,s(r)),i=``,a=``;break}}}}let c=e.state.fileDescriptors?.get(1);if(c){if(c===`__dupout__:2`)a+=i,i=``;else if(c.startsWith(`__file__:`)){let t=c.slice(9);await e.fs.appendFile(t,i,s(i)),i=``}else if(c.startsWith(`__file_append__:`)){let t=c.slice(16);await e.fs.appendFile(t,i,s(i)),i=``}}let l=e.state.fileDescriptors?.get(2);if(l){if(l===`__dupout__:1`)i+=a,a=``;else if(l.startsWith(`__file__:`)){let t=l.slice(9);await e.fs.appendFile(t,a,x_(a)),a=``}else if(l.startsWith(`__file_append__:`)){let t=l.slice(16);await e.fs.appendFile(t,a,x_(a)),a=``}}return Z(i,a,o)}function O_(e,t){if(e.state.options.posix&&g_.has(t.name))throw new ut(2,``,`bash: line ${e.state.currentLine}: \`${t.name}': is a special builtin
244
- `);let n={...t,sourceFile:t.sourceFile??e.state.currentSource??`main`};return e.state.functions.set(t.name,n),J}async function k_(e,t){let n=``;for(let r of t)if((r.operator===`<<`||r.operator===`<<-`)&&r.target.type===`HereDoc`){let t=r.target,i=await O(e,t.content);t.stripTabs&&(i=i.split(`
242
+ `,o=1,i=``;break}let t=e.fs.resolvePath(e.state.cwd,l),n=await x_(e,t,l,{checkNoclobber:!0});if(n){a=n,o=1,i=``;break}let r=i+a;await e.fs.writeFile(t,r,s(r)),i=``,a=``;break}case`&>>`:{if(l===`/dev/full`){a=`bash: echo: write error: No space left on device
243
+ `,o=1,i=``;break}let t=e.fs.resolvePath(e.state.cwd,l),n=await x_(e,t,l,{});if(n){a=n,o=1,i=``;break}let r=i+a;await e.fs.appendFile(t,r,s(r)),i=``,a=``;break}}}}let c=e.state.fileDescriptors?.get(1);if(c){if(c===`__dupout__:2`)a+=i,i=``;else if(c.startsWith(`__file__:`)){let t=c.slice(9);await e.fs.appendFile(t,i,s(i)),i=``}else if(c.startsWith(`__file_append__:`)){let t=c.slice(16);await e.fs.appendFile(t,i,s(i)),i=``}}let l=e.state.fileDescriptors?.get(2);if(l){if(l===`__dupout__:1`)i+=a,a=``;else if(l.startsWith(`__file__:`)){let t=l.slice(9);await e.fs.appendFile(t,a,S_(a)),a=``}else if(l.startsWith(`__file_append__:`)){let t=l.slice(16);await e.fs.appendFile(t,a,S_(a)),a=``}}return Z(i,a,o)}function k_(e,t){if(e.state.options.posix&&__.has(t.name))throw new ut(2,``,`bash: line ${e.state.currentLine}: \`${t.name}': is a special builtin
244
+ `);let n={...t,sourceFile:t.sourceFile??e.state.currentSource??`main`};return e.state.functions.set(t.name,n),J}async function A_(e,t){let n=``;for(let r of t)if((r.operator===`<<`||r.operator===`<<-`)&&r.target.type===`HereDoc`){let t=r.target,i=await O(e,t.content);t.stripTabs&&(i=i.split(`
245
245
  `).map(e=>e.replace(/^\t+/,``)).join(`
246
246
  `)),(r.fd??0)===0&&(n=i)}else if(r.operator===`<<<`&&r.target.type===`Word`)n=`${await O(e,r.target)}
247
- `;else if(r.operator===`<`&&r.target.type===`Word`){let t=await O(e,r.target),i=e.fs.resolvePath(e.state.cwd,t);try{n=await e.fs.readFile(i)}catch{}}return n}async function A_(e,t,n,r=``,i){e.state.callDepth++,e.state.callDepth>e.limits.maxCallDepth&&(e.state.callDepth--,yg(`${t.name}: maximum recursion depth (${e.limits.maxCallDepth}) exceeded, increase executionLimits.maxCallDepth`,`recursion`)),e.state.funcNameStack||(e.state.funcNameStack=[]),e.state.callLineStack||(e.state.callLineStack=[]),e.state.sourceStack||(e.state.sourceStack=[]),e.state.funcNameStack.unshift(t.name),e.state.callLineStack.unshift(i??e.state.currentLine),e.state.sourceStack.unshift(t.sourceFile??`main`),e.state.localScopes.push(new Map),e.state.localExportedVars||(e.state.localExportedVars=[]),e.state.localExportedVars.push(new Set);let a=new Map;for(let t=0;t<n.length;t++)a.set(String(t+1),e.state.env.get(String(t+1))),e.state.env.set(String(t+1),n[t]);a.set(`@`,e.state.env.get(`@`)),a.set(`#`,e.state.env.get(`#`)),e.state.env.set(`@`,n.join(` `)),e.state.env.set(`#`,String(n.length));let o=()=>{let t=e.state.localScopes.length-1,n=e.state.localScopes.pop();if(n)for(let[t,r]of n)r===void 0?e.state.env.delete(t):e.state.env.set(t,r);if(h_(e,t),e.state.fullyUnsetLocals)for(let[n,r]of e.state.fullyUnsetLocals.entries())r===t&&e.state.fullyUnsetLocals.delete(n);if(e.state.localExportedVars&&e.state.localExportedVars.length>0){let t=e.state.localExportedVars.pop();if(t)for(let n of t)e.state.exportedVars?.delete(n)}for(let[t,n]of a)n===void 0?e.state.env.delete(t):e.state.env.set(t,n);e.state.funcNameStack?.shift(),e.state.callLineStack?.shift(),e.state.sourceStack?.shift(),e.state.callDepth--},{targets:s,error:c}=await C_(e,t.redirections);if(c)return o(),Z(``,c,1);try{let n=await k_(e,t.redirections),i=r||n,a=await e.executeCommand(t.body,i);return o(),D_(e,a,t.redirections,s)}catch(n){if(o(),n instanceof st)return D_(e,Z(n.stdout,n.stderr,n.exitCode),t.redirections,s);throw n}}var j_=[`!`,`[[`,`]]`,`case`,`do`,`done`,`elif`,`else`,`esac`,`fi`,`for`,`function`,`if`,`in`,`then`,`time`,`until`,`while`,`{`,`}`],M_=`.,:,[,alias,bg,bind,break,builtin,caller,cd,command,compgen,complete,compopt,continue,declare,dirs,disown,echo,enable,eval,exec,exit,export,false,fc,fg,getopts,hash,help,history,jobs,kill,let,local,logout,mapfile,popd,printf,pushd,pwd,read,readarray,readonly,return,set,shift,shopt,source,suspend,test,times,trap,true,type,typeset,ulimit,umask,unalias,unset,wait`.split(`,`),N_=`autocd.assoc_expand_once.cdable_vars.cdspell.checkhash.checkjobs.checkwinsize.cmdhist.compat31.compat32.compat40.compat41.compat42.compat43.compat44.complete_fullquote.direxpand.dirspell.dotglob.execfail.expand_aliases.extdebug.extglob.extquote.failglob.force_fignore.globasciiranges.globstar.gnu_errfmt.histappend.histreedit.histverify.hostcomplete.huponexit.inherit_errexit.interactive_comments.lastpipe.lithist.localvar_inherit.localvar_unset.login_shell.mailwarn.no_empty_cmd_completion.nocaseglob.nocasematch.nullglob.progcomp.progcomp_alias.promptvars.restricted_shell.shift_verbose.sourcepath.xpg_echo`.split(`.`),P_=M_;async function F_(e,t){let n=[],r=null,i=``,a=``,o=null,s=!1,c=!1,l=!1,u=null,d=null,f=null,p=[],m=[`alias`,`arrayvar`,`binding`,`builtin`,`command`,`directory`,`disabled`,`enabled`,`export`,`file`,`function`,`group`,`helptopic`,`hostname`,`job`,`keyword`,`running`,`service`,`setopt`,`shopt`,`signal`,`stopped`,`user`,`variable`];for(let e=0;e<t.length;e++){let o=t[e];if(o===`-v`)n.push(`variable`);else if(o===`-e`)n.push(`export`);else if(o===`-f`)n.push(`file`);else if(o===`-d`)n.push(`directory`);else if(o===`-k`)n.push(`keyword`);else if(o===`-A`){if(e++,e>=t.length)return X(`compgen: -A: option requires an argument
247
+ `;else if(r.operator===`<`&&r.target.type===`Word`){let t=await O(e,r.target),i=e.fs.resolvePath(e.state.cwd,t);try{n=await e.fs.readFile(i)}catch{}}return n}async function j_(e,t,n,r=``,i){e.state.callDepth++,e.state.callDepth>e.limits.maxCallDepth&&(e.state.callDepth--,bg(`${t.name}: maximum recursion depth (${e.limits.maxCallDepth}) exceeded, increase executionLimits.maxCallDepth`,`recursion`)),e.state.funcNameStack||(e.state.funcNameStack=[]),e.state.callLineStack||(e.state.callLineStack=[]),e.state.sourceStack||(e.state.sourceStack=[]),e.state.funcNameStack.unshift(t.name),e.state.callLineStack.unshift(i??e.state.currentLine),e.state.sourceStack.unshift(t.sourceFile??`main`),e.state.localScopes.push(new Map),e.state.localExportedVars||(e.state.localExportedVars=[]),e.state.localExportedVars.push(new Set);let a=new Map;for(let t=0;t<n.length;t++)a.set(String(t+1),e.state.env.get(String(t+1))),e.state.env.set(String(t+1),n[t]);a.set(`@`,e.state.env.get(`@`)),a.set(`#`,e.state.env.get(`#`)),e.state.env.set(`@`,n.join(` `)),e.state.env.set(`#`,String(n.length));let o=()=>{let t=e.state.localScopes.length-1,n=e.state.localScopes.pop();if(n)for(let[t,r]of n)r===void 0?e.state.env.delete(t):e.state.env.set(t,r);if(g_(e,t),e.state.fullyUnsetLocals)for(let[n,r]of e.state.fullyUnsetLocals.entries())r===t&&e.state.fullyUnsetLocals.delete(n);if(e.state.localExportedVars&&e.state.localExportedVars.length>0){let t=e.state.localExportedVars.pop();if(t)for(let n of t)e.state.exportedVars?.delete(n)}for(let[t,n]of a)n===void 0?e.state.env.delete(t):e.state.env.set(t,n);e.state.funcNameStack?.shift(),e.state.callLineStack?.shift(),e.state.sourceStack?.shift(),e.state.callDepth--},{targets:s,error:c}=await w_(e,t.redirections);if(c)return o(),Z(``,c,1);try{let n=await A_(e,t.redirections),i=r||n,a=await e.executeCommand(t.body,i);return o(),O_(e,a,t.redirections,s)}catch(n){if(o(),n instanceof st)return O_(e,Z(n.stdout,n.stderr,n.exitCode),t.redirections,s);throw n}}var M_=[`!`,`[[`,`]]`,`case`,`do`,`done`,`elif`,`else`,`esac`,`fi`,`for`,`function`,`if`,`in`,`then`,`time`,`until`,`while`,`{`,`}`],N_=`.,:,[,alias,bg,bind,break,builtin,caller,cd,command,compgen,complete,compopt,continue,declare,dirs,disown,echo,enable,eval,exec,exit,export,false,fc,fg,getopts,hash,help,history,jobs,kill,let,local,logout,mapfile,popd,printf,pushd,pwd,read,readarray,readonly,return,set,shift,shopt,source,suspend,test,times,trap,true,type,typeset,ulimit,umask,unalias,unset,wait`.split(`,`),P_=`autocd.assoc_expand_once.cdable_vars.cdspell.checkhash.checkjobs.checkwinsize.cmdhist.compat31.compat32.compat40.compat41.compat42.compat43.compat44.complete_fullquote.direxpand.dirspell.dotglob.execfail.expand_aliases.extdebug.extglob.extquote.failglob.force_fignore.globasciiranges.globstar.gnu_errfmt.histappend.histreedit.histverify.hostcomplete.huponexit.inherit_errexit.interactive_comments.lastpipe.lithist.localvar_inherit.localvar_unset.login_shell.mailwarn.no_empty_cmd_completion.nocaseglob.nocasematch.nullglob.progcomp.progcomp_alias.promptvars.restricted_shell.shift_verbose.sourcepath.xpg_echo`.split(`.`),F_=N_;async function I_(e,t){let n=[],r=null,i=``,a=``,o=null,s=!1,c=!1,l=!1,u=null,d=null,f=null,p=[],m=[`alias`,`arrayvar`,`binding`,`builtin`,`command`,`directory`,`disabled`,`enabled`,`export`,`file`,`function`,`group`,`helptopic`,`hostname`,`job`,`keyword`,`running`,`service`,`setopt`,`shopt`,`signal`,`stopped`,`user`,`variable`];for(let e=0;e<t.length;e++){let o=t[e];if(o===`-v`)n.push(`variable`);else if(o===`-e`)n.push(`export`);else if(o===`-f`)n.push(`file`);else if(o===`-d`)n.push(`directory`);else if(o===`-k`)n.push(`keyword`);else if(o===`-A`){if(e++,e>=t.length)return X(`compgen: -A: option requires an argument
248
248
  `,2);let r=t[e];if(!m.includes(r))return X(`compgen: ${r}: invalid action name
249
249
  `,2);n.push(r)}else if(o===`-W`){if(e++,e>=t.length)return X(`compgen: -W: option requires an argument
250
250
  `,2);r=t[e]}else if(o===`-P`){if(e++,e>=t.length)return X(`compgen: -P: option requires an argument
@@ -255,96 +255,96 @@ superseded_by: <path-to-new-canonical-article>.md
255
255
  `,2);d=t[e]}else if(o===`-C`){if(e++,e>=t.length)return X(`compgen: -C: option requires an argument
256
256
  `,2);f=t[e]}else if(o===`-X`){if(e++,e>=t.length)return X(`compgen: -X: option requires an argument
257
257
  `,2);u=t[e]}else if(o===`-G`){if(e++,e>=t.length)return X(`compgen: -G: option requires an argument
258
- `,2)}else if(o===`--`){p.push(...t.slice(e+1));break}else o.startsWith(`-`)||p.push(o)}o=p[0]??null;let h=[];if(c){let t=await W_(e,o);h.push(...t)}if(l){let t=await G_(e,o);h.push(...t)}for(let t of n)if(t===`variable`){let t=I_(e,o);h.push(...t)}else if(t===`export`){let t=L_(e,o);h.push(...t)}else if(t===`function`){let t=R_(e,o);h.push(...t)}else if(t===`builtin`){let e=z_(o);h.push(...e)}else if(t===`keyword`){let e=B_(o);h.push(...e)}else if(t===`alias`){let t=V_(e,o);h.push(...t)}else if(t===`shopt`){let e=H_(o);h.push(...e)}else if(t===`helptopic`){let e=U_(o);h.push(...e)}else if(t===`directory`){let t=await W_(e,o);h.push(...t)}else if(t===`file`){let t=await G_(e,o);h.push(...t)}else if(t===`user`){let e=K_(o);h.push(...e)}else if(t===`command`){let t=await q_(e,o);h.push(...t)}if(r!==null)try{let t=Y_(e,await J_(e,r));for(let e of t)(o===null||e.startsWith(o))&&h.push(e)}catch{return Z(``,``,1)}if(s){let t=await W_(e,o);for(let e of t)h.includes(e)||h.push(e)}let g=``;if(d!==null){let t=e.state.functions.get(d);if(t){let n=new Map;n.set(`COMP_WORDS__length`,e.state.env.get(`COMP_WORDS__length`)),e.state.env.set(`COMP_WORDS__length`,`0`),n.set(`COMP_CWORD`,e.state.env.get(`COMP_CWORD`)),e.state.env.set(`COMP_CWORD`,`-1`),n.set(`COMP_LINE`,e.state.env.get(`COMP_LINE`)),e.state.env.set(`COMP_LINE`,``),n.set(`COMP_POINT`,e.state.env.get(`COMP_POINT`)),e.state.env.set(`COMP_POINT`,`0`);let r=new Map;for(let t of e.state.env.keys())(t===`COMPREPLY`||t.startsWith(`COMPREPLY_`)||t===`COMPREPLY__length`)&&(r.set(t,e.state.env.get(t)),e.state.env.delete(t));let i=[`compgen`,p[0]??``,``];try{let a=await A_(e,t,i,``);if(a.exitCode!==0)return X_(e,n),X_(e,r),Z(``,a.stderr,1);g=a.stdout;let o=Z_(e);h.push(...o)}catch{return X_(e,n),X_(e,r),Z(``,``,1)}X_(e,n),X_(e,r)}}if(f!==null)try{let t=Dt(f),n=await e.executeScript(t);if(n.exitCode!==0)return Z(``,n.stderr,n.exitCode);if(n.stdout){let e=n.stdout.split(`
258
+ `,2)}else if(o===`--`){p.push(...t.slice(e+1));break}else o.startsWith(`-`)||p.push(o)}o=p[0]??null;let h=[];if(c){let t=await G_(e,o);h.push(...t)}if(l){let t=await K_(e,o);h.push(...t)}for(let t of n)if(t===`variable`){let t=L_(e,o);h.push(...t)}else if(t===`export`){let t=R_(e,o);h.push(...t)}else if(t===`function`){let t=z_(e,o);h.push(...t)}else if(t===`builtin`){let e=B_(o);h.push(...e)}else if(t===`keyword`){let e=V_(o);h.push(...e)}else if(t===`alias`){let t=H_(e,o);h.push(...t)}else if(t===`shopt`){let e=U_(o);h.push(...e)}else if(t===`helptopic`){let e=W_(o);h.push(...e)}else if(t===`directory`){let t=await G_(e,o);h.push(...t)}else if(t===`file`){let t=await K_(e,o);h.push(...t)}else if(t===`user`){let e=q_(o);h.push(...e)}else if(t===`command`){let t=await J_(e,o);h.push(...t)}if(r!==null)try{let t=X_(e,await Y_(e,r));for(let e of t)(o===null||e.startsWith(o))&&h.push(e)}catch{return Z(``,``,1)}if(s){let t=await G_(e,o);for(let e of t)h.includes(e)||h.push(e)}let g=``;if(d!==null){let t=e.state.functions.get(d);if(t){let n=new Map;n.set(`COMP_WORDS__length`,e.state.env.get(`COMP_WORDS__length`)),e.state.env.set(`COMP_WORDS__length`,`0`),n.set(`COMP_CWORD`,e.state.env.get(`COMP_CWORD`)),e.state.env.set(`COMP_CWORD`,`-1`),n.set(`COMP_LINE`,e.state.env.get(`COMP_LINE`)),e.state.env.set(`COMP_LINE`,``),n.set(`COMP_POINT`,e.state.env.get(`COMP_POINT`)),e.state.env.set(`COMP_POINT`,`0`);let r=new Map;for(let t of e.state.env.keys())(t===`COMPREPLY`||t.startsWith(`COMPREPLY_`)||t===`COMPREPLY__length`)&&(r.set(t,e.state.env.get(t)),e.state.env.delete(t));let i=[`compgen`,p[0]??``,``];try{let a=await j_(e,t,i,``);if(a.exitCode!==0)return Z_(e,n),Z_(e,r),Z(``,a.stderr,1);g=a.stdout;let o=Q_(e);h.push(...o)}catch{return Z_(e,n),Z_(e,r),Z(``,``,1)}Z_(e,n),Z_(e,r)}}if(f!==null)try{let t=Dt(f),n=await e.executeScript(t);if(n.exitCode!==0)return Z(``,n.stderr,n.exitCode);if(n.stdout){let e=n.stdout.split(`
259
259
  `);for(let t of e)t.length>0&&h.push(t)}}catch(e){if(e.name===`ParseException`)return X(`compgen: -C: ${e.message}
260
- `,2);throw e}let _=h;if(u!==null){let e=u.startsWith(`!`),t=e?u.slice(1):u;_=h.filter(n=>{let r=Kg(n,t,!1,!0);return e?r:!r})}if(_.length===0&&o!==null)return Z(g,``,1);let v=_.map(e=>`${i}${e}${a}`).join(`
260
+ `,2);throw e}let _=h;if(u!==null){let e=u.startsWith(`!`),t=e?u.slice(1):u;_=h.filter(n=>{let r=qg(n,t,!1,!0);return e?r:!r})}if(_.length===0&&o!==null)return Z(g,``,1);let v=_.map(e=>`${i}${e}${a}`).join(`
261
261
  `);return Y(g+(v?`${v}
262
- `:``))}function I_(e,t){let n=new Set;for(let t of e.state.env.keys()){if(t.includes(`_`)&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(t)||t.endsWith(`__length`))continue;let r=t.split(`_`)[0];/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?n.add(t):r&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)&&e.state.env.has(`${r}__length`)&&n.add(r)}let r=Array.from(n);return t!==null&&(r=r.filter(e=>e.startsWith(t))),r.sort()}function L_(e,t){let n=e.state.exportedVars??new Set,r=Array.from(n);return t!==null&&(r=r.filter(e=>e.startsWith(t))),r=r.filter(t=>t.includes(`_`)&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(t)||t.endsWith(`__length`)?!1:e.state.env.has(t)),r.sort()}function R_(e,t){let n=Array.from(e.state.functions.keys());return t!==null&&(n=n.filter(e=>e.startsWith(t))),n.sort()}function z_(e){let t=[...M_];return e!==null&&(t=t.filter(t=>t.startsWith(e))),t.sort()}function B_(e){let t=[...j_];return e!==null&&(t=t.filter(t=>t.startsWith(e))),t.sort()}function V_(e,t){let n=[];for(let t of e.state.env.keys())if(t.startsWith(`BASH_ALIAS_`)){let e=t.slice(11);n.push(e)}let r=n;return t!==null&&(r=r.filter(e=>e.startsWith(t))),r.sort()}function H_(e){let t=[...N_];return e!==null&&(t=t.filter(t=>t.startsWith(e))),t.sort()}function U_(e){let t=[...P_];return e!==null&&(t=t.filter(t=>t.startsWith(e))),t.sort()}async function W_(e,t){let n=[];try{let r=e.state.cwd,i=t??``;if(t){let n=t.lastIndexOf(`/`);if(n!==-1){let a=t.slice(0,n)||`/`;i=t.slice(n+1),r=a.startsWith(`/`)?a:`${e.state.cwd}/${a}`}}let a=await e.fs.readdir(r);for(let o of a){let a=`${r}/${o}`;try{if((await e.fs.stat(a)).isDirectory&&(!i||o.startsWith(i)))if(t?.includes(`/`)){let e=t.lastIndexOf(`/`),r=t.slice(0,e+1);n.push(r+o)}else n.push(o)}catch{}}}catch{}return n.sort()}async function G_(e,t){let n=[];try{let r=e.state.cwd,i=t??``;if(t){let n=t.lastIndexOf(`/`);if(n!==-1){let a=t.slice(0,n)||`/`;i=t.slice(n+1),r=a.startsWith(`/`)?a:`${e.state.cwd}/${a}`}}let a=await e.fs.readdir(r);for(let e of a)if(!i||e.startsWith(i))if(t?.includes(`/`)){let r=t.lastIndexOf(`/`),i=t.slice(0,r+1);n.push(i+e)}else n.push(e)}catch{}return n.sort()}function K_(e){return[`root`,`nobody`]}async function q_(e,t){let n=new Set;for(let e of M_)n.add(e);for(let t of e.state.functions.keys())n.add(t);for(let t of e.state.env.keys())t.startsWith(`BASH_ALIAS_`)&&n.add(t.slice(11));for(let e of j_)n.add(e);let r=e.state.env.get(`PATH`)??`/usr/bin:/bin`;for(let t of r.split(`:`))if(t)try{let r=await e.fs.readdir(t);for(let e of r)n.add(e)}catch{}let i=Array.from(n);return t!==null&&(i=i.filter(e=>e.startsWith(t))),i.sort()}async function J_(e,t){return await O(e,new Zt().parseWordFromString(t,!1,!1))}function Y_(e,t){let n=e.state.env.get(`IFS`)??`
263
- `;if(n.length===0)return[t];let r=new Set(n.split(``)),i=[],a=``,o=0;for(;o<t.length;){let e=t[o];if(e===`\\`&&o+1<t.length){let e=t[o+1];a+=e,o+=2}else r.has(e)?(a.length>0&&(i.push(a),a=``),o++):(a+=e,o++)}return a.length>0&&i.push(a),i}function X_(e,t){for(let[n,r]of t)r===void 0?e.state.env.delete(n):e.state.env.set(n,r)}function Z_(e){let t=[];if(e.state.env.get(`COMPREPLY__length`)!==void 0){let n=It(e,`COMPREPLY`);for(let[,e]of n)t.push(e)}else{let n=e.state.env.get(`COMPREPLY`);n!==void 0&&t.push(n)}return t}var Q_=[`bashdefault`,`default`,`dirnames`,`filenames`,`noquote`,`nosort`,`nospace`,`plusdirs`];function $_(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let n=!1,r=!1,i=!1,a,o,s,c=[],l=[],u=[];for(let e=0;e<t.length;e++){let d=t[e];if(d===`-p`)n=!0;else if(d===`-r`)r=!0;else if(d===`-D`)i=!0;else if(d===`-W`){if(e++,e>=t.length)return X(`complete: -W: option requires an argument
262
+ `:``))}function L_(e,t){let n=new Set;for(let t of e.state.env.keys()){if(t.includes(`_`)&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(t)||t.endsWith(`__length`))continue;let r=t.split(`_`)[0];/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?n.add(t):r&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)&&e.state.env.has(`${r}__length`)&&n.add(r)}let r=Array.from(n);return t!==null&&(r=r.filter(e=>e.startsWith(t))),r.sort()}function R_(e,t){let n=e.state.exportedVars??new Set,r=Array.from(n);return t!==null&&(r=r.filter(e=>e.startsWith(t))),r=r.filter(t=>t.includes(`_`)&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(t)||t.endsWith(`__length`)?!1:e.state.env.has(t)),r.sort()}function z_(e,t){let n=Array.from(e.state.functions.keys());return t!==null&&(n=n.filter(e=>e.startsWith(t))),n.sort()}function B_(e){let t=[...N_];return e!==null&&(t=t.filter(t=>t.startsWith(e))),t.sort()}function V_(e){let t=[...M_];return e!==null&&(t=t.filter(t=>t.startsWith(e))),t.sort()}function H_(e,t){let n=[];for(let t of e.state.env.keys())if(t.startsWith(`BASH_ALIAS_`)){let e=t.slice(11);n.push(e)}let r=n;return t!==null&&(r=r.filter(e=>e.startsWith(t))),r.sort()}function U_(e){let t=[...P_];return e!==null&&(t=t.filter(t=>t.startsWith(e))),t.sort()}function W_(e){let t=[...F_];return e!==null&&(t=t.filter(t=>t.startsWith(e))),t.sort()}async function G_(e,t){let n=[];try{let r=e.state.cwd,i=t??``;if(t){let n=t.lastIndexOf(`/`);if(n!==-1){let a=t.slice(0,n)||`/`;i=t.slice(n+1),r=a.startsWith(`/`)?a:`${e.state.cwd}/${a}`}}let a=await e.fs.readdir(r);for(let o of a){let a=`${r}/${o}`;try{if((await e.fs.stat(a)).isDirectory&&(!i||o.startsWith(i)))if(t?.includes(`/`)){let e=t.lastIndexOf(`/`),r=t.slice(0,e+1);n.push(r+o)}else n.push(o)}catch{}}}catch{}return n.sort()}async function K_(e,t){let n=[];try{let r=e.state.cwd,i=t??``;if(t){let n=t.lastIndexOf(`/`);if(n!==-1){let a=t.slice(0,n)||`/`;i=t.slice(n+1),r=a.startsWith(`/`)?a:`${e.state.cwd}/${a}`}}let a=await e.fs.readdir(r);for(let e of a)if(!i||e.startsWith(i))if(t?.includes(`/`)){let r=t.lastIndexOf(`/`),i=t.slice(0,r+1);n.push(i+e)}else n.push(e)}catch{}return n.sort()}function q_(e){return[`root`,`nobody`]}async function J_(e,t){let n=new Set;for(let e of N_)n.add(e);for(let t of e.state.functions.keys())n.add(t);for(let t of e.state.env.keys())t.startsWith(`BASH_ALIAS_`)&&n.add(t.slice(11));for(let e of M_)n.add(e);let r=e.state.env.get(`PATH`)??`/usr/bin:/bin`;for(let t of r.split(`:`))if(t)try{let r=await e.fs.readdir(t);for(let e of r)n.add(e)}catch{}let i=Array.from(n);return t!==null&&(i=i.filter(e=>e.startsWith(t))),i.sort()}async function Y_(e,t){return await O(e,new Zt().parseWordFromString(t,!1,!1))}function X_(e,t){let n=e.state.env.get(`IFS`)??`
263
+ `;if(n.length===0)return[t];let r=new Set(n.split(``)),i=[],a=``,o=0;for(;o<t.length;){let e=t[o];if(e===`\\`&&o+1<t.length){let e=t[o+1];a+=e,o+=2}else r.has(e)?(a.length>0&&(i.push(a),a=``),o++):(a+=e,o++)}return a.length>0&&i.push(a),i}function Z_(e,t){for(let[n,r]of t)r===void 0?e.state.env.delete(n):e.state.env.set(n,r)}function Q_(e){let t=[];if(e.state.env.get(`COMPREPLY__length`)!==void 0){let n=It(e,`COMPREPLY`);for(let[,e]of n)t.push(e)}else{let n=e.state.env.get(`COMPREPLY`);n!==void 0&&t.push(n)}return t}var $_=[`bashdefault`,`default`,`dirnames`,`filenames`,`noquote`,`nosort`,`nospace`,`plusdirs`];function ev(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let n=!1,r=!1,i=!1,a,o,s,c=[],l=[],u=[];for(let e=0;e<t.length;e++){let d=t[e];if(d===`-p`)n=!0;else if(d===`-r`)r=!0;else if(d===`-D`)i=!0;else if(d===`-W`){if(e++,e>=t.length)return X(`complete: -W: option requires an argument
264
264
  `,2);a=t[e]}else if(d===`-F`){if(e++,e>=t.length)return X(`complete: -F: option requires an argument
265
265
  `,2);o=t[e]}else if(d===`-o`){if(e++,e>=t.length)return X(`complete: -o: option requires an argument
266
- `,2);let n=t[e];if(!Q_.includes(n))return X(`complete: ${n}: invalid option name
266
+ `,2);let n=t[e];if(!$_.includes(n))return X(`complete: ${n}: invalid option name
267
267
  `,2);c.push(n)}else if(d===`-A`){if(e++,e>=t.length)return X(`complete: -A: option requires an argument
268
268
  `,2);l.push(t[e])}else if(d===`-C`){if(e++,e>=t.length)return X(`complete: -C: option requires an argument
269
269
  `,2);s=t[e]}else if(d===`-G`){if(e++,e>=t.length)return X(`complete: -G: option requires an argument
270
270
  `,2)}else if(d===`-P`){if(e++,e>=t.length)return X(`complete: -P: option requires an argument
271
271
  `,2)}else if(d===`-S`){if(e++,e>=t.length)return X(`complete: -S: option requires an argument
272
272
  `,2)}else if(d===`-X`){if(e++,e>=t.length)return X(`complete: -X: option requires an argument
273
- `,2)}else if(d===`--`){u.push(...t.slice(e+1));break}else d.startsWith(`-`)||u.push(d)}if(r){if(u.length===0)return e.state.completionSpecs.clear(),Y(``);for(let t of u)e.state.completionSpecs.delete(t);return Y(``)}if(n)return u.length===0?ev(e):ev(e,u);if(t.length===0||u.length===0&&!a&&!o&&!s&&c.length===0&&l.length===0&&!i)return ev(e);if(o&&u.length===0&&!i)return X(`complete: -F: option requires a command name
274
- `,2);if(i){let t={isDefault:!0};return a!==void 0&&(t.wordlist=a),o!==void 0&&(t.function=o),s!==void 0&&(t.command=s),c.length>0&&(t.options=c),l.length>0&&(t.actions=l),e.state.completionSpecs.set(`__default__`,t),Y(``)}for(let t of u){let n=Object.create(null);a!==void 0&&(n.wordlist=a),o!==void 0&&(n.function=o),s!==void 0&&(n.command=s),c.length>0&&(n.options=c),l.length>0&&(n.actions=l),e.state.completionSpecs.set(t,n)}return Y(``)}function ev(e,t){let n=e.state.completionSpecs;if(!n||n.size===0){if(t&&t.length>0){let e=``;for(let n of t)e+=`complete: ${n}: no completion specification
273
+ `,2)}else if(d===`--`){u.push(...t.slice(e+1));break}else d.startsWith(`-`)||u.push(d)}if(r){if(u.length===0)return e.state.completionSpecs.clear(),Y(``);for(let t of u)e.state.completionSpecs.delete(t);return Y(``)}if(n)return u.length===0?tv(e):tv(e,u);if(t.length===0||u.length===0&&!a&&!o&&!s&&c.length===0&&l.length===0&&!i)return tv(e);if(o&&u.length===0&&!i)return X(`complete: -F: option requires a command name
274
+ `,2);if(i){let t={isDefault:!0};return a!==void 0&&(t.wordlist=a),o!==void 0&&(t.function=o),s!==void 0&&(t.command=s),c.length>0&&(t.options=c),l.length>0&&(t.actions=l),e.state.completionSpecs.set(`__default__`,t),Y(``)}for(let t of u){let n=Object.create(null);a!==void 0&&(n.wordlist=a),o!==void 0&&(n.function=o),s!==void 0&&(n.command=s),c.length>0&&(n.options=c),l.length>0&&(n.actions=l),e.state.completionSpecs.set(t,n)}return Y(``)}function tv(e,t){let n=e.state.completionSpecs;if(!n||n.size===0){if(t&&t.length>0){let e=``;for(let n of t)e+=`complete: ${n}: no completion specification
275
275
  `;return Z(``,e,1)}return Y(``)}let r=[],i=t||Array.from(n.keys());for(let e of i){if(e===`__default__`)continue;let i=n.get(e);if(!i){if(t)return Z(r.join(`
276
276
  `)+(r.length>0?`
277
277
  `:``),`complete: ${e}: no completion specification
278
278
  `,1);continue}let a=`complete`;if(i.options)for(let e of i.options)a+=` -o ${e}`;if(i.actions)for(let e of i.actions)a+=` -A ${e}`;i.wordlist!==void 0&&(i.wordlist.includes(` `)||i.wordlist.includes(`'`)?a+=` -W '${i.wordlist}'`:a+=` -W ${i.wordlist}`),i.function!==void 0&&(a+=` -F ${i.function}`),i.isDefault&&(a+=` -D`),a+=` ${e}`,r.push(a)}return r.length===0?Y(``):Y(`${r.join(`
279
279
  `)}
280
- `)}var tv=[`bashdefault`,`default`,`dirnames`,`filenames`,`noquote`,`nosort`,`nospace`,`plusdirs`];function nv(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let n=!1,r=!1,i=[],a=[],o=[];for(let e=0;e<t.length;e++){let s=t[e];if(s===`-D`)n=!0;else if(s===`-E`)r=!0;else if(s===`-o`){if(e++,e>=t.length)return X(`compopt: -o: option requires an argument
281
- `,2);let n=t[e];if(!tv.includes(n))return X(`compopt: ${n}: invalid option name
280
+ `)}var nv=[`bashdefault`,`default`,`dirnames`,`filenames`,`noquote`,`nosort`,`nospace`,`plusdirs`];function rv(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let n=!1,r=!1,i=[],a=[],o=[];for(let e=0;e<t.length;e++){let s=t[e];if(s===`-D`)n=!0;else if(s===`-E`)r=!0;else if(s===`-o`){if(e++,e>=t.length)return X(`compopt: -o: option requires an argument
281
+ `,2);let n=t[e];if(!nv.includes(n))return X(`compopt: ${n}: invalid option name
282
282
  `,2);i.push(n)}else if(s===`+o`){if(e++,e>=t.length)return X(`compopt: +o: option requires an argument
283
- `,2);let n=t[e];if(!tv.includes(n))return X(`compopt: ${n}: invalid option name
283
+ `,2);let n=t[e];if(!nv.includes(n))return X(`compopt: ${n}: invalid option name
284
284
  `,2);a.push(n)}else if(s===`--`){o.push(...t.slice(e+1));break}else !s.startsWith(`-`)&&!s.startsWith(`+`)&&o.push(s)}if(n){let t=e.state.completionSpecs.get(`__default__`)??{isDefault:!0},n=new Set(t.options??[]);for(let e of i)n.add(e);for(let e of a)n.delete(e);return t.options=n.size>0?Array.from(n):void 0,e.state.completionSpecs.set(`__default__`,t),Y(``)}if(r){let t=e.state.completionSpecs.get(`__empty__`)??{},n=new Set(t.options??[]);for(let e of i)n.add(e);for(let e of a)n.delete(e);return t.options=n.size>0?Array.from(n):void 0,e.state.completionSpecs.set(`__empty__`,t),Y(``)}if(o.length>0){for(let t of o){let n=e.state.completionSpecs.get(t)??{},r=new Set(n.options??[]);for(let e of i)r.add(e);for(let e of a)r.delete(e);n.options=r.size>0?Array.from(r):void 0,e.state.completionSpecs.set(t,n)}return Y(``)}return X(`compopt: not currently executing completion function
285
- `,1)}function rv(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new pt;return J}if(t.length>1)throw new ut(1,``,`bash: continue: too many arguments
285
+ `,1)}function iv(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new pt;return J}if(t.length>1)throw new ut(1,``,`bash: continue: too many arguments
286
286
  `);let n=1;if(t.length>0){let e=Number.parseInt(t[0],10);if(Number.isNaN(e)||e<1)throw new ut(1,``,`bash: continue: ${t[0]}: numeric argument required
287
- `);n=e}throw new ft(n)}function iv(e,t){let n=e.state.env.get(`HOME`)||`/home/user`;return t.split(`:`).map(e=>e===`~`?n:e===`~root`?`/root`:e.startsWith(`~/`)?n+e.slice(1):e.startsWith(`~root/`)?`/root${e.slice(5)}`:e).join(`:`)}function av(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!0}return!1}function ov(e){let t=`$'`;for(let n=0;n<e.length;n++){let r=e[n],i=e.charCodeAt(n);i===7?t+=`\\a`:i===8?t+=`\\b`:i===9?t+=`\\t`:i===10?t+=`\\n`:i===11?t+=`\\v`:i===12?t+=`\\f`:i===13?t+=`\\r`:i===27?t+=`\\e`:i===39?t+=`\\'`:i===92?t+=`\\\\`:i<32||i===127?t+=`\\${i.toString(8).padStart(3,`0`)}`:t+=r}return t+=`'`,t}function sv(e){return av(e)?ov(e):/^[a-zA-Z0-9_/.:\-@%+,=]*$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function cv(e){return av(e)?ov(e):`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function lv(e){return av(e)?ov(e):`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function uv(e,t){let n=``;return e.state.integerVars?.has(t)&&(n+=`i`),e.state.lowercaseVars?.has(t)&&(n+=`l`),Pt(e,t)&&(n+=`n`),e.state.readonlyVars?.has(t)&&(n+=`r`),e.state.uppercaseVars?.has(t)&&(n+=`u`),e.state.exportedVars?.has(t)&&(n+=`x`),n===``?`--`:`-${n}`}function dv(e){return e===``?`''`:/[\s'\\]/.test(e)?`'${e.replace(/'/g,`'\\''`)}'`:e}function fv(e,t){let n=``,r=``,i=!1;for(let a of t){let t=uv(e,a);if(e.state.associativeArrays?.has(a)){let t=gt(e,a);if(t.length===0)n+=`declare -A ${a}=()
288
- `;else{let r=t.map(t=>`['${t}']=${dv(e.state.env.get(`${a}_${t}`)??``)}`);n+=`declare -A ${a}=(${r.join(` `)})
289
- `}continue}let o=Et(e,a);if(o.length>0){let t=o.map(t=>`[${t}]=${cv(e.state.env.get(`${a}_${t}`)??``)}`);n+=`declare -a ${a}=(${t.join(` `)})
287
+ `);n=e}throw new ft(n)}function av(e,t){let n=e.state.env.get(`HOME`)||`/home/user`;return t.split(`:`).map(e=>e===`~`?n:e===`~root`?`/root`:e.startsWith(`~/`)?n+e.slice(1):e.startsWith(`~root/`)?`/root${e.slice(5)}`:e).join(`:`)}function ov(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!0}return!1}function sv(e){let t=`$'`;for(let n=0;n<e.length;n++){let r=e[n],i=e.charCodeAt(n);i===7?t+=`\\a`:i===8?t+=`\\b`:i===9?t+=`\\t`:i===10?t+=`\\n`:i===11?t+=`\\v`:i===12?t+=`\\f`:i===13?t+=`\\r`:i===27?t+=`\\e`:i===39?t+=`\\'`:i===92?t+=`\\\\`:i<32||i===127?t+=`\\${i.toString(8).padStart(3,`0`)}`:t+=r}return t+=`'`,t}function cv(e){return ov(e)?sv(e):/^[a-zA-Z0-9_/.:\-@%+,=]*$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function lv(e){return ov(e)?sv(e):`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function uv(e){return ov(e)?sv(e):`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function dv(e,t){let n=``;return e.state.integerVars?.has(t)&&(n+=`i`),e.state.lowercaseVars?.has(t)&&(n+=`l`),Pt(e,t)&&(n+=`n`),e.state.readonlyVars?.has(t)&&(n+=`r`),e.state.uppercaseVars?.has(t)&&(n+=`u`),e.state.exportedVars?.has(t)&&(n+=`x`),n===``?`--`:`-${n}`}function fv(e){return e===``?`''`:/[\s'\\]/.test(e)?`'${e.replace(/'/g,`'\\''`)}'`:e}function pv(e,t){let n=``,r=``,i=!1;for(let a of t){let t=dv(e,a);if(e.state.associativeArrays?.has(a)){let t=gt(e,a);if(t.length===0)n+=`declare -A ${a}=()
288
+ `;else{let r=t.map(t=>`['${t}']=${fv(e.state.env.get(`${a}_${t}`)??``)}`);n+=`declare -A ${a}=(${r.join(` `)})
289
+ `}continue}let o=Et(e,a);if(o.length>0){let t=o.map(t=>`[${t}]=${lv(e.state.env.get(`${a}_${t}`)??``)}`);n+=`declare -a ${a}=(${t.join(` `)})
290
290
  `;continue}if(e.state.env.has(`${a}__length`)){n+=`declare -a ${a}=()
291
- `;continue}let s=e.state.env.get(a);if(s!==void 0)n+=`declare ${t} ${a}=${lv(s)}
291
+ `;continue}let s=e.state.env.get(a);if(s!==void 0)n+=`declare ${t} ${a}=${uv(s)}
292
292
  `;else{let o=e.state.declaredVars?.has(a),s=e.state.localVarDepth?.has(a);o||s?n+=`declare ${t} ${a}
293
293
  `:(r+=`bash: declare: ${a}: not found
294
- `,i=!0)}}return Z(n,r,i?1:0)}function pv(e,t){let{filterExport:n,filterReadonly:r,filterNameref:i,filterIndexedArray:a,filterAssocArray:o}=t,s=n||r||i||a||o,c=``,l=new Set;for(let t of e.state.env.keys()){if(t.startsWith(`BASH_`))continue;if(t.endsWith(`__length`)){let e=t.slice(0,-8);l.add(e);continue}let n=t.lastIndexOf(`_`);if(n>0){let r=t.slice(0,n),i=t.slice(n+1);if(/^\d+$/.test(i)||e.state.associativeArrays?.has(r)){l.add(r);continue}}l.add(t)}if(e.state.localVarDepth)for(let t of e.state.localVarDepth.keys())l.add(t);if(e.state.associativeArrays)for(let t of e.state.associativeArrays)l.add(t);let u=Array.from(l).sort();for(let t of u){let l=uv(e,t),u=e.state.associativeArrays?.has(t),d=Et(e,t),f=!u&&(d.length>0||e.state.env.has(`${t}__length`));if(s&&(o&&!u||a&&!f||n&&!e.state.exportedVars?.has(t)||r&&!e.state.readonlyVars?.has(t)||i&&!Pt(e,t)))continue;if(u){let n=gt(e,t);if(n.length===0)c+=`declare -A ${t}=()
295
- `;else{let r=n.map(n=>`['${n}']=${dv(e.state.env.get(`${t}_${n}`)??``)}`);c+=`declare -A ${t}=(${r.join(` `)})
296
- `}continue}if(d.length>0){let n=d.map(n=>`[${n}]=${cv(e.state.env.get(`${t}_${n}`)??``)}`);c+=`declare -a ${t}=(${n.join(` `)})
294
+ `,i=!0)}}return Z(n,r,i?1:0)}function mv(e,t){let{filterExport:n,filterReadonly:r,filterNameref:i,filterIndexedArray:a,filterAssocArray:o}=t,s=n||r||i||a||o,c=``,l=new Set;for(let t of e.state.env.keys()){if(t.startsWith(`BASH_`))continue;if(t.endsWith(`__length`)){let e=t.slice(0,-8);l.add(e);continue}let n=t.lastIndexOf(`_`);if(n>0){let r=t.slice(0,n),i=t.slice(n+1);if(/^\d+$/.test(i)||e.state.associativeArrays?.has(r)){l.add(r);continue}}l.add(t)}if(e.state.localVarDepth)for(let t of e.state.localVarDepth.keys())l.add(t);if(e.state.associativeArrays)for(let t of e.state.associativeArrays)l.add(t);let u=Array.from(l).sort();for(let t of u){let l=dv(e,t),u=e.state.associativeArrays?.has(t),d=Et(e,t),f=!u&&(d.length>0||e.state.env.has(`${t}__length`));if(s&&(o&&!u||a&&!f||n&&!e.state.exportedVars?.has(t)||r&&!e.state.readonlyVars?.has(t)||i&&!Pt(e,t)))continue;if(u){let n=gt(e,t);if(n.length===0)c+=`declare -A ${t}=()
295
+ `;else{let r=n.map(n=>`['${n}']=${fv(e.state.env.get(`${t}_${n}`)??``)}`);c+=`declare -A ${t}=(${r.join(` `)})
296
+ `}continue}if(d.length>0){let n=d.map(n=>`[${n}]=${lv(e.state.env.get(`${t}_${n}`)??``)}`);c+=`declare -a ${t}=(${n.join(` `)})
297
297
  `;continue}if(e.state.env.has(`${t}__length`)){c+=`declare -a ${t}=()
298
- `;continue}let p=e.state.env.get(t);p!==void 0&&(c+=`declare ${l} ${t}=${lv(p)}
299
- `)}return Y(c)}function mv(e){let t=``,n=Array.from(e.state.associativeArrays??[]).sort();for(let r of n){let n=gt(e,r);if(n.length===0)t+=`declare -A ${r}=()
300
- `;else{let i=n.map(t=>`['${t}']=${dv(e.state.env.get(`${r}_${t}`)??``)}`);t+=`declare -A ${r}=(${i.join(` `)})
301
- `}}return Y(t)}function hv(e){let t=``,n=new Set;for(let t of e.state.env.keys()){if(t.startsWith(`BASH_`))continue;if(t.endsWith(`__length`)){let r=t.slice(0,-8);e.state.associativeArrays?.has(r)||n.add(r);continue}let r=t.lastIndexOf(`_`);if(r>0){let i=t.slice(0,r),a=t.slice(r+1);/^\d+$/.test(a)&&(e.state.associativeArrays?.has(i)||n.add(i))}}let r=Array.from(n).sort();for(let n of r){let r=Et(e,n);if(r.length===0)t+=`declare -a ${n}=()
302
- `;else{let i=r.map(t=>`[${t}]=${cv(e.state.env.get(`${n}_${t}`)??``)}`);t+=`declare -a ${n}=(${i.join(` `)})
303
- `}}return Y(t)}function gv(e){let t=``,n=new Set;for(let t of e.state.env.keys()){if(t.startsWith(`BASH_`))continue;if(t.endsWith(`__length`)){let e=t.slice(0,-8);n.add(e);continue}let r=t.lastIndexOf(`_`);if(r>0){let i=t.slice(0,r),a=t.slice(r+1);if(/^\d+$/.test(a)||e.state.associativeArrays?.has(i)){n.add(i);continue}}n.add(t)}let r=Array.from(n).sort();for(let n of r){if(e.state.associativeArrays?.has(n)||Et(e,n).length>0||e.state.env.has(`${n}__length`))continue;let r=e.state.env.get(n);r!==void 0&&(t+=`${n}=${sv(r)}
304
- `)}return Y(t)}function _v(e,t){e.state.integerVars??=new Set,e.state.integerVars.add(t)}function vv(e,t){return e.state.integerVars?.has(t)??!1}function yv(e,t){e.state.lowercaseVars??=new Set,e.state.lowercaseVars.add(t),e.state.uppercaseVars?.delete(t)}function bv(e,t){return e.state.lowercaseVars?.has(t)??!1}function xv(e,t){e.state.uppercaseVars??=new Set,e.state.uppercaseVars.add(t),e.state.lowercaseVars?.delete(t)}function Sv(e,t){return e.state.uppercaseVars?.has(t)??!1}function Cv(e,t,n){return bv(e,t)?n.toLowerCase():Sv(e,t)?n.toUpperCase():n}async function wv(e,t){try{let n=await Kt(e,Ft(new Zt,t).expression);return String(n)}catch{return`0`}}function Tv(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return null;let n=t[0],r=n.length;if(e[r]!==`[`)return null;let i=0,a=r+1;for(;r<e.length;r++)if(e[r]===`[`)i++;else if(e[r]===`]`&&(i--,i===0))break;if(i!==0)return null;let o=e.slice(a,r);return r++,e[r]===`=`?(r++,{name:n,indexExpr:o,value:e.slice(r)}):null}async function Ev(e,t){let n=!1,r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=!1,d=!1,f=!1,p=!1,m=!1,h=!1,g=!1,_=[];for(let e=0;e<t.length;e++){let v=t[e];if(v===`-a`)n=!0;else if(v===`-A`)r=!0;else if(v===`-r`)i=!0;else if(v===`-x`)a=!0;else if(v===`-p`)o=!0;else if(v===`-n`)s=!0;else if(v===`+n`)c=!0;else if(v===`+a`)l=!0;else if(v===`+x`)u=!0;else if(v===`--`){_.push(...t.slice(e+1));break}else if(v.startsWith(`+`)){for(let e of v.slice(1))if(e===`n`)c=!0;else if(e===`a`)l=!0;else if(e===`x`)u=!0;else if(e!==`r`&&e!==`i`&&!(e===`f`||e===`F`))return Z(``,`bash: typeset: +${e}: invalid option
298
+ `;continue}let p=e.state.env.get(t);p!==void 0&&(c+=`declare ${l} ${t}=${uv(p)}
299
+ `)}return Y(c)}function hv(e){let t=``,n=Array.from(e.state.associativeArrays??[]).sort();for(let r of n){let n=gt(e,r);if(n.length===0)t+=`declare -A ${r}=()
300
+ `;else{let i=n.map(t=>`['${t}']=${fv(e.state.env.get(`${r}_${t}`)??``)}`);t+=`declare -A ${r}=(${i.join(` `)})
301
+ `}}return Y(t)}function gv(e){let t=``,n=new Set;for(let t of e.state.env.keys()){if(t.startsWith(`BASH_`))continue;if(t.endsWith(`__length`)){let r=t.slice(0,-8);e.state.associativeArrays?.has(r)||n.add(r);continue}let r=t.lastIndexOf(`_`);if(r>0){let i=t.slice(0,r),a=t.slice(r+1);/^\d+$/.test(a)&&(e.state.associativeArrays?.has(i)||n.add(i))}}let r=Array.from(n).sort();for(let n of r){let r=Et(e,n);if(r.length===0)t+=`declare -a ${n}=()
302
+ `;else{let i=r.map(t=>`[${t}]=${lv(e.state.env.get(`${n}_${t}`)??``)}`);t+=`declare -a ${n}=(${i.join(` `)})
303
+ `}}return Y(t)}function _v(e){let t=``,n=new Set;for(let t of e.state.env.keys()){if(t.startsWith(`BASH_`))continue;if(t.endsWith(`__length`)){let e=t.slice(0,-8);n.add(e);continue}let r=t.lastIndexOf(`_`);if(r>0){let i=t.slice(0,r),a=t.slice(r+1);if(/^\d+$/.test(a)||e.state.associativeArrays?.has(i)){n.add(i);continue}}n.add(t)}let r=Array.from(n).sort();for(let n of r){if(e.state.associativeArrays?.has(n)||Et(e,n).length>0||e.state.env.has(`${n}__length`))continue;let r=e.state.env.get(n);r!==void 0&&(t+=`${n}=${cv(r)}
304
+ `)}return Y(t)}function vv(e,t){e.state.integerVars??=new Set,e.state.integerVars.add(t)}function yv(e,t){return e.state.integerVars?.has(t)??!1}function bv(e,t){e.state.lowercaseVars??=new Set,e.state.lowercaseVars.add(t),e.state.uppercaseVars?.delete(t)}function xv(e,t){return e.state.lowercaseVars?.has(t)??!1}function Sv(e,t){e.state.uppercaseVars??=new Set,e.state.uppercaseVars.add(t),e.state.lowercaseVars?.delete(t)}function Cv(e,t){return e.state.uppercaseVars?.has(t)??!1}function wv(e,t,n){return xv(e,t)?n.toLowerCase():Cv(e,t)?n.toUpperCase():n}async function Tv(e,t){try{let n=await Kt(e,Ft(new Zt,t).expression);return String(n)}catch{return`0`}}function Ev(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return null;let n=t[0],r=n.length;if(e[r]!==`[`)return null;let i=0,a=r+1;for(;r<e.length;r++)if(e[r]===`[`)i++;else if(e[r]===`]`&&(i--,i===0))break;if(i!==0)return null;let o=e.slice(a,r);return r++,e[r]===`=`?(r++,{name:n,indexExpr:o,value:e.slice(r)}):null}async function Dv(e,t){let n=!1,r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=!1,d=!1,f=!1,p=!1,m=!1,h=!1,g=!1,_=[];for(let e=0;e<t.length;e++){let v=t[e];if(v===`-a`)n=!0;else if(v===`-A`)r=!0;else if(v===`-r`)i=!0;else if(v===`-x`)a=!0;else if(v===`-p`)o=!0;else if(v===`-n`)s=!0;else if(v===`+n`)c=!0;else if(v===`+a`)l=!0;else if(v===`+x`)u=!0;else if(v===`--`){_.push(...t.slice(e+1));break}else if(v.startsWith(`+`)){for(let e of v.slice(1))if(e===`n`)c=!0;else if(e===`a`)l=!0;else if(e===`x`)u=!0;else if(e!==`r`&&e!==`i`&&!(e===`f`||e===`F`))return Z(``,`bash: typeset: +${e}: invalid option
305
305
  `,2)}else if(v===`-i`)d=!0;else if(v===`-l`)f=!0;else if(v===`-u`)p=!0;else if(v===`-f`)m=!0;else if(v===`-F`)h=!0;else if(v===`-g`)g=!0;else if(v.startsWith(`-`))for(let e of v.slice(1))if(e===`a`)n=!0;else if(e===`A`)r=!0;else if(e===`r`)i=!0;else if(e===`x`)a=!0;else if(e===`p`)o=!0;else if(e===`n`)s=!0;else if(e===`i`)d=!0;else if(e===`l`)f=!0;else if(e===`u`)p=!0;else if(e===`f`)m=!0;else if(e===`F`)h=!0;else if(e===`g`)g=!0;else return Z(``,`bash: typeset: -${e}: invalid option
306
- `,2);else _.push(v)}let v=e.state.localScopes.length>0&&!g,y=t=>{if(!v)return;let n=e.state.localScopes[e.state.localScopes.length-1];n.has(t)||n.set(t,e.state.env.get(t))},b=t=>{if(!v)return;let n=e.state.localScopes[e.state.localScopes.length-1];n.has(t)||n.set(t,e.state.env.get(t));let r=`${t}_`;for(let t of e.state.env.keys())t.startsWith(r)&&!t.includes(`__`)&&(n.has(t)||n.set(t,e.state.env.get(t)));let i=`${t}__length`;e.state.env.has(i)&&!n.has(i)&&n.set(i,e.state.env.get(i))},x=t=>{v&&u_(e,t)};if(h){if(_.length===0){let t=Array.from(e.state.functions.keys()).sort(),n=``;for(let e of t)n+=`declare -f ${e}
306
+ `,2);else _.push(v)}let v=e.state.localScopes.length>0&&!g,y=t=>{if(!v)return;let n=e.state.localScopes[e.state.localScopes.length-1];n.has(t)||n.set(t,e.state.env.get(t))},b=t=>{if(!v)return;let n=e.state.localScopes[e.state.localScopes.length-1];n.has(t)||n.set(t,e.state.env.get(t));let r=`${t}_`;for(let t of e.state.env.keys())t.startsWith(r)&&!t.includes(`__`)&&(n.has(t)||n.set(t,e.state.env.get(t)));let i=`${t}__length`;e.state.env.has(i)&&!n.has(i)&&n.set(i,e.state.env.get(i))},x=t=>{v&&d_(e,t)};if(h){if(_.length===0){let t=Array.from(e.state.functions.keys()).sort(),n=``;for(let e of t)n+=`declare -f ${e}
307
307
  `;return Y(n)}let t=!0,n=``;for(let r of _)e.state.functions.has(r)?n+=`${r}
308
308
  `:t=!1;return Z(n,``,t?0:1)}if(m){if(_.length===0){let t=``,n=Array.from(e.state.functions.keys()).sort();for(let e of n)t+=`${e} ()
309
309
  {
310
310
  # function body
311
311
  }
312
- `;return Y(t)}let t=!0;for(let n of _)e.state.functions.has(n)||(t=!1);return Z(``,``,t?0:1)}if(o&&_.length>0)return fv(e,_);if(o&&_.length===0)return pv(e,{filterExport:a,filterReadonly:i,filterNameref:s,filterIndexedArray:n,filterAssocArray:r});if(_.length===0&&r&&!o)return mv(e);if(_.length===0&&n&&!o)return hv(e);if(_.length===0&&!o)return gv(e);let S=``,ee=0;for(let t of _){let o=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(o&&!l){let t=o[1],s=o[2];if(r&&Et(e,t).length>0){S+=`bash: declare: ${t}: cannot convert indexed to associative array
312
+ `;return Y(t)}let t=!0;for(let n of _)e.state.functions.has(n)||(t=!1);return Z(``,``,t?0:1)}if(o&&_.length>0)return pv(e,_);if(o&&_.length===0)return mv(e,{filterExport:a,filterReadonly:i,filterNameref:s,filterIndexedArray:n,filterAssocArray:r});if(_.length===0&&r&&!o)return hv(e);if(_.length===0&&n&&!o)return gv(e);if(_.length===0&&!o)return _v(e);let S=``,ee=0;for(let t of _){let o=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(o&&!l){let t=o[1],s=o[2];if(r&&Et(e,t).length>0){S+=`bash: declare: ${t}: cannot convert indexed to associative array
313
313
  `,ee=1;continue}if((n||!r&&!n)&&e.state.associativeArrays?.has(t)){S+=`bash: declare: ${t}: cannot convert associative to indexed array
314
- `,ee=1;continue}if(b(t),r&&(e.state.associativeArrays??=new Set,e.state.associativeArrays.add(t)),qt(e,t),e.state.env.delete(t),e.state.env.delete(`${t}__length`),r&&s.includes(`[`)){let n=o_(s);for(let[r,i]of n){let n=iv(e,i);e.state.env.set(`${t}_${r}`,n)}}else if(r){let n=a_(s);for(let r=0;r<n.length;r+=2){let i=n[r],a=r+1<n.length?iv(e,n[r+1]):``;e.state.env.set(`${t}_${i}`,a)}}else{let n=a_(s);if(n.some(e=>/^\[[^\]]+\]=/.test(e))){let r=0;for(let i of n){let n=i.match(/^\[([^\]]+)\]=(.*)$/);if(n){let i=n[1],a=n[2],o=iv(e,a),s;if(/^-?\d+$/.test(i))s=Number.parseInt(i,10);else try{s=await Kt(e,Ft(new Zt,i).expression)}catch{s=0}e.state.env.set(`${t}_${s}`,o),r=s+1}else{let n=iv(e,i);e.state.env.set(`${t}_${r}`,n),r++}}}else{for(let r=0;r<n.length;r++)e.state.env.set(`${t}_${r}`,n[r]);e.state.env.set(`${t}__length`,String(n.length))}}x(t),i&&Ot(e,t),a&&Tt(e,t);continue}if(c&&(Ct(e,t.includes(`=`)?t.slice(0,t.indexOf(`=`)):t),!t.includes(`=`))||u&&(Vt(e,t.includes(`=`)?t.slice(0,t.indexOf(`=`)):t),!t.includes(`=`)))continue;let m=Tv(t);if(m){let{name:t,indexExpr:n,value:r}=m,o=yt(e,t);if(o)return o;b(t);let s;try{s=await Kt(e,Ft(new Zt,n).expression)}catch{let e=parseInt(n,10);s=Number.isNaN(e)?0:e}e.state.env.set(`${t}_${s}`,r);let c=parseInt(e.state.env.get(`${t}__length`)??`0`,10);s>=c&&e.state.env.set(`${t}__length`,String(s+1)),x(t),i&&Ot(e,t),a&&Tt(e,t);continue}let h=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(h&&!l){let t=h[1],n=h[2],r=yt(e,t);if(r)return r;b(t);let o=a_(n);if(e.state.associativeArrays?.has(t)){let r=o_(n);for(let[n,i]of r){let r=iv(e,i);e.state.env.set(`${t}_${n}`,r)}}else{let n=Et(e,t),r=0,i=e.state.env.get(t);n.length===0&&i!==void 0?(e.state.env.set(`${t}_0`,i),e.state.env.delete(t),r=1):n.length>0&&(r=Math.max(...n)+1);for(let n=0;n<o.length;n++)e.state.env.set(`${t}_${r+n}`,iv(e,o[n]));let a=r+o.length;e.state.env.set(`${t}__length`,String(a))}x(t),i&&Ot(e,t),a&&Tt(e,t);continue}let g=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(g){let t=g[1],n=iv(e,g[2]),r=yt(e,t);if(r)return r;y(t),d&&_v(e,t),f&&yv(e,t),p&&xv(e,t);let o=Et(e,t).length>0||e.state.associativeArrays?.has(t);if(vv(e,t)){let r=e.state.env.get(t)??`0`,i=parseInt(r,10)||0,a=parseInt(await wv(e,n),10)||0;n=String(i+a),e.state.env.set(t,n)}else if(o){n=Cv(e,t,n);let r=`${t}_0`,i=e.state.env.get(r)??``;e.state.env.set(r,i+n)}else{n=Cv(e,t,n);let r=e.state.env.get(t)??``;e.state.env.set(t,r+n)}x(t),i&&Ot(e,t),a&&Tt(e,t),e.state.options.allexport&&!u&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(t));continue}if(t.includes(`=`)){let n=t.indexOf(`=`),r=t.slice(0,n),o=t.slice(n+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)){S+=`bash: typeset: \`${r}': not a valid identifier
314
+ `,ee=1;continue}if(b(t),r&&(e.state.associativeArrays??=new Set,e.state.associativeArrays.add(t)),qt(e,t),e.state.env.delete(t),e.state.env.delete(`${t}__length`),r&&s.includes(`[`)){let n=s_(s);for(let[r,i]of n){let n=av(e,i);e.state.env.set(`${t}_${r}`,n)}}else if(r){let n=o_(s);for(let r=0;r<n.length;r+=2){let i=n[r],a=r+1<n.length?av(e,n[r+1]):``;e.state.env.set(`${t}_${i}`,a)}}else{let n=o_(s);if(n.some(e=>/^\[[^\]]+\]=/.test(e))){let r=0;for(let i of n){let n=i.match(/^\[([^\]]+)\]=(.*)$/);if(n){let i=n[1],a=n[2],o=av(e,a),s;if(/^-?\d+$/.test(i))s=Number.parseInt(i,10);else try{s=await Kt(e,Ft(new Zt,i).expression)}catch{s=0}e.state.env.set(`${t}_${s}`,o),r=s+1}else{let n=av(e,i);e.state.env.set(`${t}_${r}`,n),r++}}}else{for(let r=0;r<n.length;r++)e.state.env.set(`${t}_${r}`,n[r]);e.state.env.set(`${t}__length`,String(n.length))}}x(t),i&&Ot(e,t),a&&Tt(e,t);continue}if(c&&(Ct(e,t.includes(`=`)?t.slice(0,t.indexOf(`=`)):t),!t.includes(`=`))||u&&(Vt(e,t.includes(`=`)?t.slice(0,t.indexOf(`=`)):t),!t.includes(`=`)))continue;let m=Ev(t);if(m){let{name:t,indexExpr:n,value:r}=m,o=yt(e,t);if(o)return o;b(t);let s;try{s=await Kt(e,Ft(new Zt,n).expression)}catch{let e=parseInt(n,10);s=Number.isNaN(e)?0:e}e.state.env.set(`${t}_${s}`,r);let c=parseInt(e.state.env.get(`${t}__length`)??`0`,10);s>=c&&e.state.env.set(`${t}__length`,String(s+1)),x(t),i&&Ot(e,t),a&&Tt(e,t);continue}let h=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(h&&!l){let t=h[1],n=h[2],r=yt(e,t);if(r)return r;b(t);let o=o_(n);if(e.state.associativeArrays?.has(t)){let r=s_(n);for(let[n,i]of r){let r=av(e,i);e.state.env.set(`${t}_${n}`,r)}}else{let n=Et(e,t),r=0,i=e.state.env.get(t);n.length===0&&i!==void 0?(e.state.env.set(`${t}_0`,i),e.state.env.delete(t),r=1):n.length>0&&(r=Math.max(...n)+1);for(let n=0;n<o.length;n++)e.state.env.set(`${t}_${r+n}`,av(e,o[n]));let a=r+o.length;e.state.env.set(`${t}__length`,String(a))}x(t),i&&Ot(e,t),a&&Tt(e,t);continue}let g=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(g){let t=g[1],n=av(e,g[2]),r=yt(e,t);if(r)return r;y(t),d&&vv(e,t),f&&bv(e,t),p&&Sv(e,t);let o=Et(e,t).length>0||e.state.associativeArrays?.has(t);if(yv(e,t)){let r=e.state.env.get(t)??`0`,i=parseInt(r,10)||0,a=parseInt(await Tv(e,n),10)||0;n=String(i+a),e.state.env.set(t,n)}else if(o){n=wv(e,t,n);let r=`${t}_0`,i=e.state.env.get(r)??``;e.state.env.set(r,i+n)}else{n=wv(e,t,n);let r=e.state.env.get(t)??``;e.state.env.set(t,r+n)}x(t),i&&Ot(e,t),a&&Tt(e,t),e.state.options.allexport&&!u&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(t));continue}if(t.includes(`=`)){let n=t.indexOf(`=`),r=t.slice(0,n),o=t.slice(n+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)){S+=`bash: typeset: \`${r}': not a valid identifier
315
315
  `,ee=1;continue}let c=yt(e,r);if(c)return c;if(y(r),s){if(o!==``&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(o)){S+=`bash: declare: \`${o}': invalid variable name for name reference
316
- `,ee=1;continue}e.state.env.set(r,o),en(e,r),o!==``&&wt(e,o)&&Nt(e,r),x(r),i&&Ot(e,r),a&&Tt(e,r);continue}if(d&&_v(e,r),f&&yv(e,r),p&&xv(e,r),vv(e,r)&&(o=await wv(e,o)),o=Cv(e,r,o),Pt(e,r)){let t=Bt(e,r);t&&t!==r?e.state.env.set(t,o):e.state.env.set(r,o)}else e.state.env.set(r,o);x(r),i&&Ot(e,r),a&&Tt(e,r),e.state.options.allexport&&!u&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(r))}else{let o=t;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){S+=`bash: typeset: \`${o}': not a valid identifier
317
- `,ee=1;continue}if(n||r?b(o):y(o),s){en(e,o);let t=e.state.env.get(o);t!==void 0&&t!==``&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(t)?Wt(e,o):t&&wt(e,t)&&Nt(e,o),x(o),i&&Ot(e,o),a&&Tt(e,o);continue}if(d&&_v(e,o),f&&yv(e,o),p&&xv(e,o),r){if(Et(e,o).length>0){S+=`bash: declare: ${o}: cannot convert indexed to associative array
318
- `,ee=1;continue}e.state.associativeArrays??=new Set,e.state.associativeArrays.add(o)}let c=Array.from(e.state.env.keys()).some(e=>e.startsWith(`${o}_`)&&!e.startsWith(`${o}__length`));!e.state.env.has(o)&&!c&&(n||r?e.state.env.set(`${o}__length`,`0`):(e.state.declaredVars??=new Set,e.state.declaredVars.add(o))),x(o),i&&Ot(e,o),a&&Tt(e,o)}}return Z(``,S,ee)}async function Dv(e,t){let n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r!==`-a`&&r!==`-A`&&r!==`-p`)if(r===`--`){n.push(...t.slice(e+1));break}else r.startsWith(`-`)||n.push(r)}if(n.length===0){let t=``,n=Array.from(e.state.readonlyVars||[]).sort();for(let r of n){let n=e.state.env.get(r);if(n!==void 0){let e=n.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`);t+=`declare -r ${r}="${e}"
319
- `}}return Y(t)}for(let t of n){let n=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(n){let t=n[1],r=n[2],i=yt(e,t);if(i)return i;let a=a_(r);if(e.state.associativeArrays?.has(t)){let n=o_(r);for(let[r,i]of n){let n=iv(e,i);e.state.env.set(`${t}_${r}`,n)}}else{let n=Et(e,t),r=0,i=e.state.env.get(t);n.length===0&&i!==void 0?(e.state.env.set(`${t}_0`,i),e.state.env.delete(t),r=1):n.length>0&&(r=Math.max(...n)+1);for(let n=0;n<a.length;n++)e.state.env.set(`${t}_${r+n}`,iv(e,a[n]));let o=r+a.length;e.state.env.set(`${t}__length`,String(o))}Ot(e,t);continue}let r=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(r){let t=r[1],n=iv(e,r[2]),i=yt(e,t);if(i)return i;let a=e.state.env.get(t)??``;e.state.env.set(t,a+n),Ot(e,t);continue}let i=s_(t);if(i.value===void 0&&!i.isArray){Ot(e,i.name);continue}let a=await l_(e,i,{makeReadonly:!0});if(a)return a}return J}function Ov(e){return e.state.directoryStack??=[],e.state.directoryStack}function kv(e,t){return t&&e===t?`~`:t&&e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function Av(e){let t=e.split(`/`).filter(e=>e&&e!==`.`),n=[];for(let e of t)e===`..`?n.pop():n.push(e);return`/${n.join(`/`)}`}async function jv(e,t){let n=Ov(e),r;for(let e=0;e<t.length;e++){let n=t[e];if(n===`--`){if(e+1<t.length){if(r!==void 0)return X(`bash: pushd: too many arguments
316
+ `,ee=1;continue}e.state.env.set(r,o),en(e,r),o!==``&&wt(e,o)&&Nt(e,r),x(r),i&&Ot(e,r),a&&Tt(e,r);continue}if(d&&vv(e,r),f&&bv(e,r),p&&Sv(e,r),yv(e,r)&&(o=await Tv(e,o)),o=wv(e,r,o),Pt(e,r)){let t=Bt(e,r);t&&t!==r?e.state.env.set(t,o):e.state.env.set(r,o)}else e.state.env.set(r,o);x(r),i&&Ot(e,r),a&&Tt(e,r),e.state.options.allexport&&!u&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(r))}else{let o=t;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){S+=`bash: typeset: \`${o}': not a valid identifier
317
+ `,ee=1;continue}if(n||r?b(o):y(o),s){en(e,o);let t=e.state.env.get(o);t!==void 0&&t!==``&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(t)?Wt(e,o):t&&wt(e,t)&&Nt(e,o),x(o),i&&Ot(e,o),a&&Tt(e,o);continue}if(d&&vv(e,o),f&&bv(e,o),p&&Sv(e,o),r){if(Et(e,o).length>0){S+=`bash: declare: ${o}: cannot convert indexed to associative array
318
+ `,ee=1;continue}e.state.associativeArrays??=new Set,e.state.associativeArrays.add(o)}let c=Array.from(e.state.env.keys()).some(e=>e.startsWith(`${o}_`)&&!e.startsWith(`${o}__length`));!e.state.env.has(o)&&!c&&(n||r?e.state.env.set(`${o}__length`,`0`):(e.state.declaredVars??=new Set,e.state.declaredVars.add(o))),x(o),i&&Ot(e,o),a&&Tt(e,o)}}return Z(``,S,ee)}async function Ov(e,t){let n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r!==`-a`&&r!==`-A`&&r!==`-p`)if(r===`--`){n.push(...t.slice(e+1));break}else r.startsWith(`-`)||n.push(r)}if(n.length===0){let t=``,n=Array.from(e.state.readonlyVars||[]).sort();for(let r of n){let n=e.state.env.get(r);if(n!==void 0){let e=n.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`);t+=`declare -r ${r}="${e}"
319
+ `}}return Y(t)}for(let t of n){let n=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(n){let t=n[1],r=n[2],i=yt(e,t);if(i)return i;let a=o_(r);if(e.state.associativeArrays?.has(t)){let n=s_(r);for(let[r,i]of n){let n=av(e,i);e.state.env.set(`${t}_${r}`,n)}}else{let n=Et(e,t),r=0,i=e.state.env.get(t);n.length===0&&i!==void 0?(e.state.env.set(`${t}_0`,i),e.state.env.delete(t),r=1):n.length>0&&(r=Math.max(...n)+1);for(let n=0;n<a.length;n++)e.state.env.set(`${t}_${r+n}`,av(e,a[n]));let o=r+a.length;e.state.env.set(`${t}__length`,String(o))}Ot(e,t);continue}let r=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(r){let t=r[1],n=av(e,r[2]),i=yt(e,t);if(i)return i;let a=e.state.env.get(t)??``;e.state.env.set(t,a+n),Ot(e,t);continue}let i=c_(t);if(i.value===void 0&&!i.isArray){Ot(e,i.name);continue}let a=await u_(e,i,{makeReadonly:!0});if(a)return a}return J}function kv(e){return e.state.directoryStack??=[],e.state.directoryStack}function Av(e,t){return t&&e===t?`~`:t&&e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function jv(e){let t=e.split(`/`).filter(e=>e&&e!==`.`),n=[];for(let e of t)e===`..`?n.pop():n.push(e);return`/${n.join(`/`)}`}async function Mv(e,t){let n=kv(e),r;for(let e=0;e<t.length;e++){let n=t[e];if(n===`--`){if(e+1<t.length){if(r!==void 0)return X(`bash: pushd: too many arguments
320
320
  `,2);r=t[e+1],e++}}else{if(n.startsWith(`-`)&&n!==`-`)return X(`bash: pushd: ${n}: invalid option
321
321
  `,2);if(r!==void 0)return X(`bash: pushd: too many arguments
322
322
  `,2);r=n}}if(r===void 0){if(n.length<2)return X(`bash: pushd: no other directory
323
- `,1);let e=n[0];n[0]=n[1],n[1]=e,r=n[0]}let i;if(r.startsWith(`/`))i=r;else if(r===`..`){let t=e.state.cwd.split(`/`).filter(e=>e);t.pop(),i=`/${t.join(`/`)}`}else i=r===`.`?e.state.cwd:r.startsWith(`~`)?(e.state.env.get(`HOME`)||`/`)+r.slice(1):`${e.state.cwd}/${r}`;i=Av(i);try{if(!(await e.fs.stat(i)).isDirectory)return X(`bash: pushd: ${r}: Not a directory
323
+ `,1);let e=n[0];n[0]=n[1],n[1]=e,r=n[0]}let i;if(r.startsWith(`/`))i=r;else if(r===`..`){let t=e.state.cwd.split(`/`).filter(e=>e);t.pop(),i=`/${t.join(`/`)}`}else i=r===`.`?e.state.cwd:r.startsWith(`~`)?(e.state.env.get(`HOME`)||`/`)+r.slice(1):`${e.state.cwd}/${r}`;i=jv(i);try{if(!(await e.fs.stat(i)).isDirectory)return X(`bash: pushd: ${r}: Not a directory
324
324
  `,1)}catch{return X(`bash: pushd: ${r}: No such file or directory
325
- `,1)}n.unshift(e.state.cwd),e.state.previousDir=e.state.cwd,e.state.cwd=i,e.state.env.set(`PWD`,i),e.state.env.set(`OLDPWD`,e.state.previousDir);let a=e.state.env.get(`HOME`)||``;return Y(`${[i,...n].map(e=>kv(e,a)).join(` `)}
326
- `)}function Mv(e,t){let n=Ov(e);for(let e of t)if(e!==`--`)return e.startsWith(`-`)&&e!==`-`?X(`bash: popd: ${e}: invalid option
325
+ `,1)}n.unshift(e.state.cwd),e.state.previousDir=e.state.cwd,e.state.cwd=i,e.state.env.set(`PWD`,i),e.state.env.set(`OLDPWD`,e.state.previousDir);let a=e.state.env.get(`HOME`)||``;return Y(`${[i,...n].map(e=>Av(e,a)).join(` `)}
326
+ `)}function Nv(e,t){let n=kv(e);for(let e of t)if(e!==`--`)return e.startsWith(`-`)&&e!==`-`?X(`bash: popd: ${e}: invalid option
327
327
  `,2):X(`bash: popd: too many arguments
328
328
  `,2);if(n.length===0)return X(`bash: popd: directory stack empty
329
329
  `,1);let r=n.shift();if(!r)return X(`bash: popd: directory stack empty
330
- `,1);e.state.previousDir=e.state.cwd,e.state.cwd=r,e.state.env.set(`PWD`,r),e.state.env.set(`OLDPWD`,e.state.previousDir);let i=e.state.env.get(`HOME`)||``;return Y(`${[r,...n].map(e=>kv(e,i)).join(` `)}
331
- `)}function Nv(e,t){let n=Ov(e),r=!1,i=!1,a=!1,o=!1;for(let e of t)if(e!==`--`)if(e.startsWith(`-`))for(let t of e.slice(1))if(t===`c`)r=!0;else if(t===`l`)i=!0;else if(t===`p`)a=!0;else if(t===`v`)a=!0,o=!0;else return X(`bash: dirs: -${t}: invalid option
330
+ `,1);e.state.previousDir=e.state.cwd,e.state.cwd=r,e.state.env.set(`PWD`,r),e.state.env.set(`OLDPWD`,e.state.previousDir);let i=e.state.env.get(`HOME`)||``;return Y(`${[r,...n].map(e=>Av(e,i)).join(` `)}
331
+ `)}function Pv(e,t){let n=kv(e),r=!1,i=!1,a=!1,o=!1;for(let e of t)if(e!==`--`)if(e.startsWith(`-`))for(let t of e.slice(1))if(t===`c`)r=!0;else if(t===`l`)i=!0;else if(t===`p`)a=!0;else if(t===`v`)a=!0,o=!0;else return X(`bash: dirs: -${t}: invalid option
332
332
  `,2);else return X(`bash: dirs: too many arguments
333
- `,1);if(r)return e.state.directoryStack=[],J;let s=[e.state.cwd,...n],c=e.state.env.get(`HOME`)||``,l;return o?(l=s.map((e,t)=>` ${t} ${i?e:kv(e,c)}`).join(`
333
+ `,1);if(r)return e.state.directoryStack=[],J;let s=[e.state.cwd,...n],c=e.state.env.get(`HOME`)||``,l;return o?(l=s.map((e,t)=>` ${t} ${i?e:Av(e,c)}`).join(`
334
334
  `),l+=`
335
- `):l=a?s.map(e=>i?e:kv(e,c)).join(`
335
+ `):l=a?s.map(e=>i?e:Av(e,c)).join(`
336
336
  `)+`
337
- `:s.map(e=>i?e:kv(e,c)).join(` `)+`
338
- `,Y(l)}async function Pv(e,t,n){let r=t;if(r.length>0){let e=r[0];if(e===`--`)r=r.slice(1);else if(e.startsWith(`-`)&&e!==`-`&&e.length>1)return X(`bash: eval: ${e}: invalid option
337
+ `:s.map(e=>i?e:Av(e,c)).join(` `)+`
338
+ `,Y(l)}async function Fv(e,t,n){let r=t;if(r.length>0){let e=r[0];if(e===`--`)r=r.slice(1);else if(e.startsWith(`-`)&&e!==`-`&&e.length>1)return X(`bash: eval: ${e}: invalid option
339
339
  eval: usage: eval [arg ...]
340
340
  `,2)}if(r.length===0)return J;let i=r.join(` `);if(i.trim()===``)return J;let a=e.state.groupStdin,o=n??e.state.groupStdin;o!==void 0&&(e.state.groupStdin=o);try{let t=Dt(i);return await e.executeScript(t)}catch(e){if(e instanceof tt||e instanceof ft||e instanceof st||e instanceof ut)throw e;if(e.name===`ParseException`)return X(`bash: eval: ${e.message}
341
- `);throw e}finally{e.state.groupStdin=a}}function Fv(e,t){let n,r=``;if(t.length===0)n=e.state.lastExitCode;else{let e=t[0],i=Number.parseInt(e,10);e===``||Number.isNaN(i)||!/^-?\d+$/.test(e)?(r=`bash: exit: ${e}: numeric argument required
342
- `,n=2):n=(i%256+256)%256}throw new ut(n,``,r)}function Iv(e,t){let n=!1,r=[];for(let e of t)e===`-n`?n=!0:e===`-p`||e===`--`||r.push(e);if(r.length===0&&!n){let t=``,n=e.state.exportedVars??new Set,r=Array.from(n).sort();for(let n of r){let r=e.state.env.get(n);if(r!==void 0){let e=r.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`);t+=`declare -x ${n}="${e}"
343
- `}}return Y(t)}if(n){for(let t of r){let n,r;if(t.includes(`=`)){let i=t.indexOf(`=`);n=t.slice(0,i),r=iv(e,t.slice(i+1)),e.state.env.set(n,r)}else n=t;Vt(e,n)}return J}let i=``,a=0;for(let t of r){let n,r,o=!1,s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(s)n=s[1],r=iv(e,s[2]),o=!0;else if(t.includes(`=`)){let i=t.indexOf(`=`);n=t.slice(0,i),r=iv(e,t.slice(i+1))}else n=t;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)){i+=`bash: export: \`${t}': not a valid identifier
344
- `,a=1;continue}if(r!==void 0)if(o){let t=e.state.env.get(n)??``;e.state.env.set(n,t+r)}else e.state.env.set(n,r);else e.state.env.has(n)||e.state.env.set(n,``);Tt(e,n)}return Z(``,i,a)}function Lv(e,t){if(t.length<2)return X(`bash: getopts: usage: getopts optstring name [arg ...]
345
- `);let n=t[0],r=t[1],i=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r),a=n.startsWith(`:`),o=a?n.slice(1):n,s;if(t.length>2)s=t.slice(2);else{let t=Number.parseInt(e.state.env.get(`#`)||`0`,10);s=[];for(let n=1;n<=t;n++)s.push(e.state.env.get(String(n))||``)}let c=Number.parseInt(e.state.env.get(`OPTIND`)||`1`,10);c<1&&(c=1);let l=Number.parseInt(e.state.env.get(`__GETOPTS_CHARINDEX`)||`0`,10);if(e.state.env.set(`OPTARG`,``),c>s.length)return i||e.state.env.set(r,`?`),e.state.env.set(`OPTIND`,String(s.length+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),{exitCode:i?2:1,stdout:``,stderr:``};let u=s[c-1];if(!u||u===`-`||!u.startsWith(`-`))return i||e.state.env.set(r,`?`),{exitCode:i?2:1,stdout:``,stderr:``};if(u===`--`)return e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),i||e.state.env.set(r,`?`),{exitCode:i?2:1,stdout:``,stderr:``};let d=l===0?1:l,f=u[d];if(!f)return e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),Lv(e,t);let p=o.indexOf(f);if(p===-1){let t=``;return a?e.state.env.set(`OPTARG`,f):t=`bash: illegal option -- ${f}
341
+ `);throw e}finally{e.state.groupStdin=a}}function Iv(e,t){let n,r=``;if(t.length===0)n=e.state.lastExitCode;else{let e=t[0],i=Number.parseInt(e,10);e===``||Number.isNaN(i)||!/^-?\d+$/.test(e)?(r=`bash: exit: ${e}: numeric argument required
342
+ `,n=2):n=(i%256+256)%256}throw new ut(n,``,r)}function Lv(e,t){let n=!1,r=[];for(let e of t)e===`-n`?n=!0:e===`-p`||e===`--`||r.push(e);if(r.length===0&&!n){let t=``,n=e.state.exportedVars??new Set,r=Array.from(n).sort();for(let n of r){let r=e.state.env.get(n);if(r!==void 0){let e=r.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`);t+=`declare -x ${n}="${e}"
343
+ `}}return Y(t)}if(n){for(let t of r){let n,r;if(t.includes(`=`)){let i=t.indexOf(`=`);n=t.slice(0,i),r=av(e,t.slice(i+1)),e.state.env.set(n,r)}else n=t;Vt(e,n)}return J}let i=``,a=0;for(let t of r){let n,r,o=!1,s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(s)n=s[1],r=av(e,s[2]),o=!0;else if(t.includes(`=`)){let i=t.indexOf(`=`);n=t.slice(0,i),r=av(e,t.slice(i+1))}else n=t;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)){i+=`bash: export: \`${t}': not a valid identifier
344
+ `,a=1;continue}if(r!==void 0)if(o){let t=e.state.env.get(n)??``;e.state.env.set(n,t+r)}else e.state.env.set(n,r);else e.state.env.has(n)||e.state.env.set(n,``);Tt(e,n)}return Z(``,i,a)}function Rv(e,t){if(t.length<2)return X(`bash: getopts: usage: getopts optstring name [arg ...]
345
+ `);let n=t[0],r=t[1],i=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r),a=n.startsWith(`:`),o=a?n.slice(1):n,s;if(t.length>2)s=t.slice(2);else{let t=Number.parseInt(e.state.env.get(`#`)||`0`,10);s=[];for(let n=1;n<=t;n++)s.push(e.state.env.get(String(n))||``)}let c=Number.parseInt(e.state.env.get(`OPTIND`)||`1`,10);c<1&&(c=1);let l=Number.parseInt(e.state.env.get(`__GETOPTS_CHARINDEX`)||`0`,10);if(e.state.env.set(`OPTARG`,``),c>s.length)return i||e.state.env.set(r,`?`),e.state.env.set(`OPTIND`,String(s.length+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),{exitCode:i?2:1,stdout:``,stderr:``};let u=s[c-1];if(!u||u===`-`||!u.startsWith(`-`))return i||e.state.env.set(r,`?`),{exitCode:i?2:1,stdout:``,stderr:``};if(u===`--`)return e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),i||e.state.env.set(r,`?`),{exitCode:i?2:1,stdout:``,stderr:``};let d=l===0?1:l,f=u[d];if(!f)return e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),Rv(e,t);let p=o.indexOf(f);if(p===-1){let t=``;return a?e.state.env.set(`OPTARG`,f):t=`bash: illegal option -- ${f}
346
346
  `,i||e.state.env.set(r,`?`),d+1<u.length?(e.state.env.set(`__GETOPTS_CHARINDEX`,String(d+1)),e.state.env.set(`OPTIND`,String(c))):(e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`)),{exitCode:i?2:0,stdout:``,stderr:t}}if(p+1<o.length&&o[p+1]===`:`)if(d+1<u.length)e.state.env.set(`OPTARG`,u.slice(d+1)),e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`);else{if(c>=s.length){let t=``;return a?(e.state.env.set(`OPTARG`,f),i||e.state.env.set(r,`:`)):(t=`bash: option requires an argument -- ${f}
347
- `,i||e.state.env.set(r,`?`)),e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),{exitCode:i?2:0,stdout:``,stderr:t}}e.state.env.set(`OPTARG`,s[c]),e.state.env.set(`OPTIND`,String(c+2)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`)}else d+1<u.length?(e.state.env.set(`__GETOPTS_CHARINDEX`,String(d+1)),e.state.env.set(`OPTIND`,String(c))):(e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`));return i||e.state.env.set(r,f),{exitCode:i?2:0,stdout:``,stderr:``}}async function Rv(e,t){e.state.hashTable||(e.state.hashTable=new Map);let n=!1,r=!1,i=!1,a=!1,o=!1,s=``,c=[],l=0;for(;l<t.length;){let e=t[l];if(e===`--`){l++,c.push(...t.slice(l));break}if(e===`-r`)n=!0,l++;else if(e===`-d`)r=!0,l++;else if(e===`-l`)i=!0,l++;else if(e===`-t`)o=!0,l++;else if(e===`-p`){if(a=!0,l++,l>=t.length)return X(`bash: hash: -p: option requires an argument
347
+ `,i||e.state.env.set(r,`?`)),e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),{exitCode:i?2:0,stdout:``,stderr:t}}e.state.env.set(`OPTARG`,s[c]),e.state.env.set(`OPTIND`,String(c+2)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`)}else d+1<u.length?(e.state.env.set(`__GETOPTS_CHARINDEX`,String(d+1)),e.state.env.set(`OPTIND`,String(c))):(e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`));return i||e.state.env.set(r,f),{exitCode:i?2:0,stdout:``,stderr:``}}async function zv(e,t){e.state.hashTable||(e.state.hashTable=new Map);let n=!1,r=!1,i=!1,a=!1,o=!1,s=``,c=[],l=0;for(;l<t.length;){let e=t[l];if(e===`--`){l++,c.push(...t.slice(l));break}if(e===`-r`)n=!0,l++;else if(e===`-d`)r=!0,l++;else if(e===`-l`)i=!0,l++;else if(e===`-t`)o=!0,l++;else if(e===`-p`){if(a=!0,l++,l>=t.length)return X(`bash: hash: -p: option requires an argument
348
348
  `,1);s=t[l],l++}else if(e.startsWith(`-`)&&e.length>1){for(let t of e.slice(1))if(t===`r`)n=!0;else if(t===`d`)r=!0;else if(t===`l`)i=!0;else if(t===`t`)o=!0;else return X(t===`p`?`bash: hash: -p: option requires an argument
349
349
  `:`bash: hash: -${t}: invalid option
350
350
  `,1);l++}else c.push(e),l++}if(n)return e.state.hashTable.clear(),J;if(r){if(c.length===0)return X(`bash: hash: -d: option requires an argument
@@ -360,7 +360,7 @@ eval: usage: eval [arg ...]
360
360
  `;for(let[,n]of e.state.hashTable)t+=` 1 ${n}
361
361
  `}return Y(t)}let u=!1,d=``,f=(e.state.env.get(`PATH`)||`/usr/bin:/bin`).split(`:`);for(let t of c){if(t.includes(`/`)){d+=`bash: hash: ${t}: cannot use / in name
362
362
  `,u=!0;continue}let n=!1;for(let r of f){if(!r)continue;let i=`${r}/${t}`;if(await e.fs.exists(i)){e.state.hashTable.set(t,i),n=!0;break}}n||(d+=`bash: hash: ${t}: not found
363
- `,u=!0)}return u?X(d,1):J}var zv=new Map([[`:`,[`: [arguments]`,`Null command.
363
+ `,u=!0)}return u?X(d,1):J}var Bv=new Map([[`:`,[`: [arguments]`,`Null command.
364
364
  No effect; the command does nothing.
365
365
  Exit Status:
366
366
  Always succeeds.`]],[`.`,[`. filename [arguments]`,`Execute commands from a file in the current shell.
@@ -707,33 +707,33 @@ eval: usage: eval [arg ...]
707
707
  job specification, and reports its termination status.
708
708
  Exit Status:
709
709
  Returns the status of the last ID; fails if ID is invalid or an invalid
710
- option is given.`]]]),Bv=[...zv.keys()].sort();function Vv(e,t){let n=!1,r=[],i=0;for(;i<t.length;){let e=t[i];if(e===`--`){for(i++;i<t.length;)r.push(t[i]),i++;break}if(e.startsWith(`-`)&&e.length>1){for(let t=1;t<e.length;t++){let r=e[t];if(r===`s`)n=!0;else return X(`bash: help: -${r}: invalid option
711
- `,2)}i++}else r.push(e),i++}if(r.length===0)return Uv();let a=``,o=!1,s=``;for(let e of r){let t=Hv(e);if(t.length===0){s+=`bash: help: no help topics match \`${e}'. Try \`help help' or \`man -k ${e}' or \`info ${e}'.
712
- `,o=!0;continue}for(let e of t){let t=zv.get(e);if(!t)continue;let[r,i]=t;n?a+=`${e}: ${r}
710
+ option is given.`]]]),Vv=[...Bv.keys()].sort();function Hv(e,t){let n=!1,r=[],i=0;for(;i<t.length;){let e=t[i];if(e===`--`){for(i++;i<t.length;)r.push(t[i]),i++;break}if(e.startsWith(`-`)&&e.length>1){for(let t=1;t<e.length;t++){let r=e[t];if(r===`s`)n=!0;else return X(`bash: help: -${r}: invalid option
711
+ `,2)}i++}else r.push(e),i++}if(r.length===0)return Wv();let a=``,o=!1,s=``;for(let e of r){let t=Uv(e);if(t.length===0){s+=`bash: help: no help topics match \`${e}'. Try \`help help' or \`man -k ${e}' or \`info ${e}'.
712
+ `,o=!0;continue}for(let e of t){let t=Bv.get(e);if(!t)continue;let[r,i]=t;n?a+=`${e}: ${r}
713
713
  `:a+=`${e}: ${r}
714
714
  ${i}
715
- `}}return{exitCode:o?1:0,stdout:a,stderr:s}}function Hv(e){let t=et(`^${e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`).replace(/\?/g,`.`)}$`);return Bv.filter(e=>t.test(e))}function Uv(){let e=[];e.push(`just-bash shell builtins`),e.push("These shell commands are defined internally. Type `help' to see this list."),e.push("Type `help name' to find out more about the function `name'."),e.push(``);let t=Bv.slice(),n=Math.ceil(t.length/2);for(let r=0;r<n;r++){let i=t[r]||``,a=t[r+n]||``,o=i.padEnd(36);e.push(a?`${o}${a}`:i)}return Y(`${e.join(`
715
+ `}}return{exitCode:o?1:0,stdout:a,stderr:s}}function Uv(e){let t=et(`^${e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`).replace(/\?/g,`.`)}$`);return Vv.filter(e=>t.test(e))}function Wv(){let e=[];e.push(`just-bash shell builtins`),e.push("These shell commands are defined internally. Type `help' to see this list."),e.push("Type `help name' to find out more about the function `name'."),e.push(``);let t=Vv.slice(),n=Math.ceil(t.length/2);for(let r=0;r<n;r++){let i=t[r]||``,a=t[r+n]||``,o=i.padEnd(36);e.push(a?`${o}${a}`:i)}return Y(`${e.join(`
716
716
  `)}
717
- `)}function Wv(e){let t=[],n=``,r=0;for(let i of e){for(let e of i)e===`(`?r++:e===`)`&&r--;n?n+=` ${i}`:n=i,r===0&&(t.push(n),n=``)}return n&&t.push(n),t}async function Gv(e,t){if(t.length===0)return X(`bash: let: expression expected
718
- `);let n=Wv(t),r=0;for(let t of n)try{let n=Dt(`(( ${t} ))`).statements[0];if(n&&n.pipelines.length>0&&n.pipelines[0].commands.length>0){let t=n.pipelines[0].commands[0];t.type===`ArithmeticCommand`&&(r=await Kt(e,t.expression.expression))}}catch(e){return X(`bash: let: ${t}: ${e.message}
719
- `)}return Z(``,``,r===0?1:0)}async function Kv(e,t){if(e.state.localScopes.length===0)return X(`bash: local: can only be used in a function
717
+ `)}function Gv(e){let t=[],n=``,r=0;for(let i of e){for(let e of i)e===`(`?r++:e===`)`&&r--;n?n+=` ${i}`:n=i,r===0&&(t.push(n),n=``)}return n&&t.push(n),t}async function Kv(e,t){if(t.length===0)return X(`bash: let: expression expected
718
+ `);let n=Gv(t),r=0;for(let t of n)try{let n=Dt(`(( ${t} ))`).statements[0];if(n&&n.pipelines.length>0&&n.pipelines[0].commands.length>0){let t=n.pipelines[0].commands[0];t.type===`ArithmeticCommand`&&(r=await Kt(e,t.expression.expression))}}catch(e){return X(`bash: let: ${t}: ${e.message}
719
+ `)}return Z(``,``,r===0?1:0)}async function qv(e,t){if(e.state.localScopes.length===0)return X(`bash: local: can only be used in a function
720
720
  `);let n=e.state.localScopes[e.state.localScopes.length-1],r=``,i=0,a=!1,o=!1,s=[];for(let e of t)if(e===`-n`)a=!0;else if(e===`-a`)o=!0;else if(e!==`-p`)if(e.startsWith(`-`)&&!e.includes(`=`))for(let t of e.slice(1))t===`n`?a=!0:t===`a`&&(o=!0);else s.push(e);if(s.length===0){let t=``,r=Array.from(n.keys()).filter(e=>!e.includes(`_`)||!e.match(/_\d+$/)).filter(e=>!e.includes(`__length`)).sort();for(let n of r){let r=e.state.env.get(n);r!==void 0&&(t+=`${n}=${r}
721
721
  `)}return Z(t,``,0)}for(let t of s){let s,c,l=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(l){s=l[1];let o=l[2];if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)){r+=`bash: local: \`${t}': not a valid identifier
722
- `,i=1;continue}if(yt(e,s,`bash`),!n.has(s)){n.set(s,e.state.env.get(s));let t=`${s}_`;for(let r of e.state.env.keys())r.startsWith(t)&&!r.includes(`__`)&&(n.has(r)||n.set(r,e.state.env.get(r)))}let c=`${s}_`;for(let t of e.state.env.keys())t.startsWith(c)&&!t.includes(`__`)&&e.state.env.delete(t);let u=a_(o);for(let t=0;t<u.length;t++)e.state.env.set(`${s}_${t}`,u[t]);e.state.env.set(`${s}__length`,String(u.length)),u_(e,s),a&&en(e,s);continue}let u=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(u){s=u[1];let t=u[2];if(yt(e,s,`bash`),!n.has(s)){n.set(s,e.state.env.get(s));let t=`${s}_`;for(let r of e.state.env.keys())r.startsWith(t)&&!r.includes(`__`)&&(n.has(r)||n.set(r,e.state.env.get(r)));let r=`${s}__length`;e.state.env.has(r)&&!n.has(r)&&n.set(r,e.state.env.get(r))}let r=a_(t),i=Et(e,s),o=0,c=e.state.env.get(s);i.length===0&&c!==void 0?(e.state.env.set(`${s}_0`,c),e.state.env.delete(s),o=1):i.length>0&&(o=Math.max(...i)+1);for(let t=0;t<r.length;t++)e.state.env.set(`${s}_${o+t}`,iv(e,r[t]));let l=o+r.length;e.state.env.set(`${s}__length`,String(l)),u_(e,s),a&&en(e,s);continue}let d=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(d){s=d[1];let t=iv(e,d[2]);yt(e,s,`bash`),n.has(s)||n.set(s,e.state.env.get(s));let r=e.state.env.get(s)??``;e.state.env.set(s,r+t),u_(e,s),a&&en(e,s);continue}let f=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(f){s=f[1];let t=f[2],r=iv(e,f[3]);if(yt(e,s,`bash`),!n.has(s)){n.set(s,e.state.env.get(s));let t=`${s}_`;for(let r of e.state.env.keys())r.startsWith(t)&&!r.includes(`__`)&&(n.has(r)||n.set(r,e.state.env.get(r)));let r=`${s}__length`;e.state.env.has(r)&&!n.has(r)&&n.set(r,e.state.env.get(r))}let i;try{i=await Kt(e,Ft(new Zt,t).expression)}catch{let e=parseInt(t,10);i=Number.isNaN(e)?0:e}e.state.env.set(`${s}_${i}`,r);let o=parseInt(e.state.env.get(`${s}__length`)??`0`,10);i>=o&&e.state.env.set(`${s}__length`,String(i+1)),u_(e,s),a&&en(e,s);continue}if(t.includes(`=`)){let n=t.indexOf(`=`);s=t.slice(0,n),c=iv(e,t.slice(n+1))}else s=t;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)){r+=`bash: local: \`${t}': not a valid identifier
723
- `,i=1;continue}let p=n.has(s);if(c!==void 0){let t=e.state.env.get(s);if(e.state.tempEnvBindings){let n=e.state.accessedTempEnvVars?.has(s),r=e.state.mutatedTempEnvVars?.has(s);if(!n&&!r)for(let n=e.state.tempEnvBindings.length-1;n>=0;n--){let r=e.state.tempEnvBindings[n];if(r.has(s)){t=r.get(s);break}}}p_(e,s,t)}if(!p){let t=e.state.env.get(s);if(e.state.tempEnvBindings)for(let n=e.state.tempEnvBindings.length-1;n>=0;n--){let r=e.state.tempEnvBindings[n];if(r.has(s)){t=r.get(s);break}}if(n.set(s,t),o){let t=`${s}_`;for(let r of e.state.env.keys())r.startsWith(t)&&!r.includes(`__`)&&(n.has(r)||n.set(r,e.state.env.get(r)));let r=`${s}__length`;e.state.env.has(r)&&!n.has(r)&&n.set(r,e.state.env.get(r))}}if(o&&c===void 0){let t=`${s}_`;for(let n of e.state.env.keys())n.startsWith(t)&&!n.includes(`__`)&&e.state.env.delete(n);e.state.env.set(`${s}__length`,`0`)}else if(c!==void 0){if(yt(e,s,`bash`),a&&c!==``&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(c)){r+=`bash: local: \`${c}': invalid variable name for name reference
724
- `,i=1;continue}e.state.env.set(s,c),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(s))}else{let t=e.state.tempEnvBindings?.some(e=>e.has(s));!p&&!t&&e.state.env.delete(s)}u_(e,s),a&&en(e,s)}return Z(``,r,i)}function qv(e,t,n){let r=`
722
+ `,i=1;continue}if(yt(e,s,`bash`),!n.has(s)){n.set(s,e.state.env.get(s));let t=`${s}_`;for(let r of e.state.env.keys())r.startsWith(t)&&!r.includes(`__`)&&(n.has(r)||n.set(r,e.state.env.get(r)))}let c=`${s}_`;for(let t of e.state.env.keys())t.startsWith(c)&&!t.includes(`__`)&&e.state.env.delete(t);let u=o_(o);for(let t=0;t<u.length;t++)e.state.env.set(`${s}_${t}`,u[t]);e.state.env.set(`${s}__length`,String(u.length)),d_(e,s),a&&en(e,s);continue}let u=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(u){s=u[1];let t=u[2];if(yt(e,s,`bash`),!n.has(s)){n.set(s,e.state.env.get(s));let t=`${s}_`;for(let r of e.state.env.keys())r.startsWith(t)&&!r.includes(`__`)&&(n.has(r)||n.set(r,e.state.env.get(r)));let r=`${s}__length`;e.state.env.has(r)&&!n.has(r)&&n.set(r,e.state.env.get(r))}let r=o_(t),i=Et(e,s),o=0,c=e.state.env.get(s);i.length===0&&c!==void 0?(e.state.env.set(`${s}_0`,c),e.state.env.delete(s),o=1):i.length>0&&(o=Math.max(...i)+1);for(let t=0;t<r.length;t++)e.state.env.set(`${s}_${o+t}`,av(e,r[t]));let l=o+r.length;e.state.env.set(`${s}__length`,String(l)),d_(e,s),a&&en(e,s);continue}let d=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(d){s=d[1];let t=av(e,d[2]);yt(e,s,`bash`),n.has(s)||n.set(s,e.state.env.get(s));let r=e.state.env.get(s)??``;e.state.env.set(s,r+t),d_(e,s),a&&en(e,s);continue}let f=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(f){s=f[1];let t=f[2],r=av(e,f[3]);if(yt(e,s,`bash`),!n.has(s)){n.set(s,e.state.env.get(s));let t=`${s}_`;for(let r of e.state.env.keys())r.startsWith(t)&&!r.includes(`__`)&&(n.has(r)||n.set(r,e.state.env.get(r)));let r=`${s}__length`;e.state.env.has(r)&&!n.has(r)&&n.set(r,e.state.env.get(r))}let i;try{i=await Kt(e,Ft(new Zt,t).expression)}catch{let e=parseInt(t,10);i=Number.isNaN(e)?0:e}e.state.env.set(`${s}_${i}`,r);let o=parseInt(e.state.env.get(`${s}__length`)??`0`,10);i>=o&&e.state.env.set(`${s}__length`,String(i+1)),d_(e,s),a&&en(e,s);continue}if(t.includes(`=`)){let n=t.indexOf(`=`);s=t.slice(0,n),c=av(e,t.slice(n+1))}else s=t;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)){r+=`bash: local: \`${t}': not a valid identifier
723
+ `,i=1;continue}let p=n.has(s);if(c!==void 0){let t=e.state.env.get(s);if(e.state.tempEnvBindings){let n=e.state.accessedTempEnvVars?.has(s),r=e.state.mutatedTempEnvVars?.has(s);if(!n&&!r)for(let n=e.state.tempEnvBindings.length-1;n>=0;n--){let r=e.state.tempEnvBindings[n];if(r.has(s)){t=r.get(s);break}}}m_(e,s,t)}if(!p){let t=e.state.env.get(s);if(e.state.tempEnvBindings)for(let n=e.state.tempEnvBindings.length-1;n>=0;n--){let r=e.state.tempEnvBindings[n];if(r.has(s)){t=r.get(s);break}}if(n.set(s,t),o){let t=`${s}_`;for(let r of e.state.env.keys())r.startsWith(t)&&!r.includes(`__`)&&(n.has(r)||n.set(r,e.state.env.get(r)));let r=`${s}__length`;e.state.env.has(r)&&!n.has(r)&&n.set(r,e.state.env.get(r))}}if(o&&c===void 0){let t=`${s}_`;for(let n of e.state.env.keys())n.startsWith(t)&&!n.includes(`__`)&&e.state.env.delete(n);e.state.env.set(`${s}__length`,`0`)}else if(c!==void 0){if(yt(e,s,`bash`),a&&c!==``&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(c)){r+=`bash: local: \`${c}': invalid variable name for name reference
724
+ `,i=1;continue}e.state.env.set(s,c),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(s))}else{let t=e.state.tempEnvBindings?.some(e=>e.has(s));!p&&!t&&e.state.env.delete(s)}d_(e,s),a&&en(e,s)}return Z(``,r,i)}function Jv(e,t,n){let r=`
725
725
  `,i=0,a=0,o=0,s=!1,c=`MAPFILE`,l=0;for(;l<t.length;){let e=t[l];e===`-d`&&l+1<t.length?(r=t[l+1]===``?`\0`:t[l+1]||`
726
726
  `,l+=2):e===`-n`&&l+1<t.length?(i=Number.parseInt(t[l+1],10)||0,l+=2):e===`-O`&&l+1<t.length?(a=Number.parseInt(t[l+1],10)||0,l+=2):e===`-s`&&l+1<t.length?(o=Number.parseInt(t[l+1],10)||0,l+=2):e===`-t`?(s=!0,l++):e===`-u`||e===`-C`||e===`-c`?l+=2:(e.startsWith(`-`)||(c=e),l++)}let u=n;!u&&e.state.groupStdin!==void 0&&(u=e.state.groupStdin);let d=[],f=u,p=0,m=0,h=e.limits?.maxArrayElements??1e5;for(;f.length>0;){let e=f.indexOf(r);if(e===-1){if(f.length>0){if(m<o)m++;else if(i===0||p<i){if(a+p>=h)return Z(``,`mapfile: array element limit exceeded (${h})
727
727
  `,1);let e=f,t=e.indexOf(`\0`);t!==-1&&(e=e.substring(0,t)),d.push(e),p++}}break}let t=f.substring(0,e),n=t.indexOf(`\0`);if(n!==-1&&(t=t.substring(0,n)),!s&&r!==`\0`&&(t+=r),f=f.substring(e+r.length),m<o){m++;continue}if(i>0&&p>=i)break;if(a+p>=h)return Z(``,`mapfile: array element limit exceeded (${h})
728
- `,1);d.push(t),p++}a===0&&qt(e,c);for(let t=0;t<d.length;t++)e.state.env.set(`${c}_${a+t}`,d[t]);let g=parseInt(e.state.env.get(`${c}__length`)||`0`,10),_=a+d.length;return e.state.env.set(`${c}__length`,String(Math.max(g,_))),e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=``),Z(``,``,0)}function Jv(e){if(!e.startsWith(`__rw__:`))return null;let t=e.slice(7),n=t.indexOf(`:`);if(n===-1)return null;let r=Number.parseInt(t.slice(0,n),10);if(Number.isNaN(r)||r<0)return null;let i=n+1,a=t.slice(i,i+r),o=i+r+1,s=t.slice(o),c=s.indexOf(`:`);if(c===-1)return null;let l=Number.parseInt(s.slice(0,c),10);return Number.isNaN(l)||l<0?null:{path:a,position:l,content:s.slice(c+1)}}function Yv(e,t,n){return`__rw__:${e.length}:${e}:${t}:${n}`}function Xv(e,t,n,r=-1){let i=!1,a=`
729
- `,o=-1,s=-1,c=null,l=-1,u=-1,d=[],f=0,p=!1,m=(e,n)=>{let r=1;for(;r<e.length;){let d=e[r];if(d===`r`)i=!0,r++;else if(d===`s`)r++;else{if(d===`d`)return r+1<e.length?(a=e.substring(r+1),{nextArgIndex:n+1}):n+1<t.length?(a=t[n+1],{nextArgIndex:n+2}):{nextArgIndex:n+1};if(d===`n`){if(r+1<e.length){let t=e.substring(r+1);return o=Number.parseInt(t,10),(Number.isNaN(o)||o<0)&&(p=!0,o=0),{nextArgIndex:n+1}}else if(n+1<t.length)return o=Number.parseInt(t[n+1],10),(Number.isNaN(o)||o<0)&&(p=!0,o=0),{nextArgIndex:n+2};return{nextArgIndex:n+1}}else if(d===`N`){if(r+1<e.length){let t=e.substring(r+1);return s=Number.parseInt(t,10),(Number.isNaN(s)||s<0)&&(p=!0,s=0),{nextArgIndex:n+1}}else if(n+1<t.length)return s=Number.parseInt(t[n+1],10),(Number.isNaN(s)||s<0)&&(p=!0,s=0),{nextArgIndex:n+2};return{nextArgIndex:n+1}}else{if(d===`a`)return r+1<e.length?(c=e.substring(r+1),{nextArgIndex:n+1}):n+1<t.length?(c=t[n+1],{nextArgIndex:n+2}):{nextArgIndex:n+1};if(d===`p`)return r+1<e.length?(e.substring(r+1),{nextArgIndex:n+1}):n+1<t.length?(t[n+1],{nextArgIndex:n+2}):{nextArgIndex:n+1};if(d===`u`){if(r+1<e.length){let t=e.substring(r+1);return l=Number.parseInt(t,10),Number.isNaN(l)||l<0?{nextArgIndex:-2}:{nextArgIndex:n+1}}else if(n+1<t.length)return l=Number.parseInt(t[n+1],10),Number.isNaN(l)||l<0?{nextArgIndex:-2}:{nextArgIndex:n+2};return{nextArgIndex:n+1}}else if(d===`t`){if(r+1<e.length){let t=e.substring(r+1);return u=Number.parseFloat(t),Number.isNaN(u)&&(u=0),{nextArgIndex:n+1}}else if(n+1<t.length)return u=Number.parseFloat(t[n+1]),Number.isNaN(u)&&(u=0),{nextArgIndex:n+2};return{nextArgIndex:n+1}}else if(d===`e`||d===`i`||d===`P`){if(d===`i`&&n+1<t.length)return{nextArgIndex:n+2};r++}else r++}}}return{nextArgIndex:n+1}};for(;f<t.length;){let e=t[f];if(e.startsWith(`-`)&&e.length>1&&e!==`--`){let t=m(e,f);if(t.nextArgIndex===-1)return{stdout:``,stderr:``,exitCode:2};if(t.nextArgIndex===-2)return{stdout:``,stderr:``,exitCode:1};f=t.nextArgIndex}else if(e===`--`)for(f++;f<t.length;)d.push(t[f]),f++;else d.push(e),f++}if(p)return Z(``,``,1);if(d.length===0&&c===null&&d.push(`REPLY`),u===0){if(c)qt(e,c);else{for(let t of d)e.state.env.set(t,``);d.length===0&&e.state.env.set(`REPLY`,``)}return Z(``,``,0)}if(u<0&&u!==-1)return Z(``,``,1);let h=n;l>=0?h=e.state.fileDescriptors&&e.state.fileDescriptors.get(l)||``:!h&&e.state.groupStdin!==void 0&&(h=e.state.groupStdin);let g=a===``?`\0`:a,_=``,v=0,y=!0,b=t=>{if(l>=0&&e.state.fileDescriptors)e.state.fileDescriptors.set(l,h.substring(t));else if(r>=0&&e.state.fileDescriptors){let n=e.state.fileDescriptors.get(r);if(n?.startsWith(`__rw__:`)){let i=Jv(n);if(i){let n=i.position+t;e.state.fileDescriptors.set(r,Yv(i.path,n,i.content))}}}else e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=h.substring(t))};if(s>=0){let t=Math.min(s,h.length);_=h.substring(0,t),v=t,y=t>=s,b(v);let n=d[0]||`REPLY`;e.state.env.set(n,_);for(let t=1;t<d.length;t++)e.state.env.set(d[t],``);return Z(``,``,y?0:1)}else if(o>=0){let e=0,t=0,n=!1;for(;t<h.length&&e<o;){let r=h[t];if(r===g){v=t+1,n=!0;break}if(!i&&r===`\\`&&t+1<h.length){let n=h[t+1];if(n===g&&g===`
728
+ `,1);d.push(t),p++}a===0&&qt(e,c);for(let t=0;t<d.length;t++)e.state.env.set(`${c}_${a+t}`,d[t]);let g=parseInt(e.state.env.get(`${c}__length`)||`0`,10),_=a+d.length;return e.state.env.set(`${c}__length`,String(Math.max(g,_))),e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=``),Z(``,``,0)}function Yv(e){if(!e.startsWith(`__rw__:`))return null;let t=e.slice(7),n=t.indexOf(`:`);if(n===-1)return null;let r=Number.parseInt(t.slice(0,n),10);if(Number.isNaN(r)||r<0)return null;let i=n+1,a=t.slice(i,i+r),o=i+r+1,s=t.slice(o),c=s.indexOf(`:`);if(c===-1)return null;let l=Number.parseInt(s.slice(0,c),10);return Number.isNaN(l)||l<0?null:{path:a,position:l,content:s.slice(c+1)}}function Xv(e,t,n){return`__rw__:${e.length}:${e}:${t}:${n}`}function Zv(e,t,n,r=-1){let i=!1,a=`
729
+ `,o=-1,s=-1,c=null,l=-1,u=-1,d=[],f=0,p=!1,m=(e,n)=>{let r=1;for(;r<e.length;){let d=e[r];if(d===`r`)i=!0,r++;else if(d===`s`)r++;else{if(d===`d`)return r+1<e.length?(a=e.substring(r+1),{nextArgIndex:n+1}):n+1<t.length?(a=t[n+1],{nextArgIndex:n+2}):{nextArgIndex:n+1};if(d===`n`){if(r+1<e.length){let t=e.substring(r+1);return o=Number.parseInt(t,10),(Number.isNaN(o)||o<0)&&(p=!0,o=0),{nextArgIndex:n+1}}else if(n+1<t.length)return o=Number.parseInt(t[n+1],10),(Number.isNaN(o)||o<0)&&(p=!0,o=0),{nextArgIndex:n+2};return{nextArgIndex:n+1}}else if(d===`N`){if(r+1<e.length){let t=e.substring(r+1);return s=Number.parseInt(t,10),(Number.isNaN(s)||s<0)&&(p=!0,s=0),{nextArgIndex:n+1}}else if(n+1<t.length)return s=Number.parseInt(t[n+1],10),(Number.isNaN(s)||s<0)&&(p=!0,s=0),{nextArgIndex:n+2};return{nextArgIndex:n+1}}else{if(d===`a`)return r+1<e.length?(c=e.substring(r+1),{nextArgIndex:n+1}):n+1<t.length?(c=t[n+1],{nextArgIndex:n+2}):{nextArgIndex:n+1};if(d===`p`)return r+1<e.length?(e.substring(r+1),{nextArgIndex:n+1}):n+1<t.length?(t[n+1],{nextArgIndex:n+2}):{nextArgIndex:n+1};if(d===`u`){if(r+1<e.length){let t=e.substring(r+1);return l=Number.parseInt(t,10),Number.isNaN(l)||l<0?{nextArgIndex:-2}:{nextArgIndex:n+1}}else if(n+1<t.length)return l=Number.parseInt(t[n+1],10),Number.isNaN(l)||l<0?{nextArgIndex:-2}:{nextArgIndex:n+2};return{nextArgIndex:n+1}}else if(d===`t`){if(r+1<e.length){let t=e.substring(r+1);return u=Number.parseFloat(t),Number.isNaN(u)&&(u=0),{nextArgIndex:n+1}}else if(n+1<t.length)return u=Number.parseFloat(t[n+1]),Number.isNaN(u)&&(u=0),{nextArgIndex:n+2};return{nextArgIndex:n+1}}else if(d===`e`||d===`i`||d===`P`){if(d===`i`&&n+1<t.length)return{nextArgIndex:n+2};r++}else r++}}}return{nextArgIndex:n+1}};for(;f<t.length;){let e=t[f];if(e.startsWith(`-`)&&e.length>1&&e!==`--`){let t=m(e,f);if(t.nextArgIndex===-1)return{stdout:``,stderr:``,exitCode:2};if(t.nextArgIndex===-2)return{stdout:``,stderr:``,exitCode:1};f=t.nextArgIndex}else if(e===`--`)for(f++;f<t.length;)d.push(t[f]),f++;else d.push(e),f++}if(p)return Z(``,``,1);if(d.length===0&&c===null&&d.push(`REPLY`),u===0){if(c)qt(e,c);else{for(let t of d)e.state.env.set(t,``);d.length===0&&e.state.env.set(`REPLY`,``)}return Z(``,``,0)}if(u<0&&u!==-1)return Z(``,``,1);let h=n;l>=0?h=e.state.fileDescriptors&&e.state.fileDescriptors.get(l)||``:!h&&e.state.groupStdin!==void 0&&(h=e.state.groupStdin);let g=a===``?`\0`:a,_=``,v=0,y=!0,b=t=>{if(l>=0&&e.state.fileDescriptors)e.state.fileDescriptors.set(l,h.substring(t));else if(r>=0&&e.state.fileDescriptors){let n=e.state.fileDescriptors.get(r);if(n?.startsWith(`__rw__:`)){let i=Yv(n);if(i){let n=i.position+t;e.state.fileDescriptors.set(r,Xv(i.path,n,i.content))}}}else e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=h.substring(t))};if(s>=0){let t=Math.min(s,h.length);_=h.substring(0,t),v=t,y=t>=s,b(v);let n=d[0]||`REPLY`;e.state.env.set(n,_);for(let t=1;t<d.length;t++)e.state.env.set(d[t],``);return Z(``,``,y?0:1)}else if(o>=0){let e=0,t=0,n=!1;for(;t<h.length&&e<o;){let r=h[t];if(r===g){v=t+1,n=!0;break}if(!i&&r===`\\`&&t+1<h.length){let n=h[t+1];if(n===g&&g===`
730
730
  `){t+=2,v=t;continue}if(n===g){t+=2,e++,_+=n,v=t;continue}_+=n,t+=2,e++,v=t}else _+=r,t++,e++,v=t}y=e>=o||n,b(v)}else{v=0;let t=0;for(;t<h.length;){let e=h[t];if(e===g){v=t+g.length,y=!0;break}if(!i&&e===`\\`&&t+1<h.length){let n=h[t+1];if(n===`
731
731
  `){t+=2;continue}if(n===g){_+=n,t+=2;continue}_+=e,_+=n,t+=2;continue}_+=e,t++}if(t>=h.length&&(y=!1,v=t,_.length===0&&h.length===0)){for(let t of d)e.state.env.set(t,``);return c&&qt(e,c),Z(``,``,1)}b(v)}g===`
732
732
  `&&_.endsWith(`
733
733
  `)&&(_=_.slice(0,-1));let x=e=>i?e:e.replace(/\\(.)/g,`$1`);if(d.length===1&&d[0]===`REPLY`)return e.state.env.set(`REPLY`,x(_)),Z(``,``,y?0:1);let S=Lt(e.state.env);if(c){let{words:t}=$t(_,S,void 0,i),n=e.limits?.maxArrayElements??1e5;if(t.length>n)return Z(``,`read: array element limit exceeded (${n})
734
- `,1);qt(e,c);for(let n=0;n<t.length;n++)e.state.env.set(`${c}_${n}`,x(t[n]));return Z(``,``,y?0:1)}let ee=d.length,{words:te,wordStarts:ne}=$t(_,S,ee,i);for(let t=0;t<d.length;t++){let n=d[t];if(t<d.length-1)e.state.env.set(n,x(te[t]??``));else if(t<ne.length){let r=_.substring(ne[t]);r=Mt(r,S,i),r=x(r),e.state.env.set(n,r)}else e.state.env.set(n,``)}return Z(``,``,y?0:1)}function Zv(e,t){if(e.state.callDepth===0&&e.state.sourceDepth===0)return X(`bash: return: can only \`return' from a function or sourced script
734
+ `,1);qt(e,c);for(let n=0;n<t.length;n++)e.state.env.set(`${c}_${n}`,x(t[n]));return Z(``,``,y?0:1)}let ee=d.length,{words:te,wordStarts:ne}=$t(_,S,ee,i);for(let t=0;t<d.length;t++){let n=d[t];if(t<d.length-1)e.state.env.set(n,x(te[t]??``));else if(t<ne.length){let r=_.substring(ne[t]);r=Mt(r,S,i),r=x(r),e.state.env.set(n,r)}else e.state.env.set(n,``)}return Z(``,``,y?0:1)}function Qv(e,t){if(e.state.callDepth===0&&e.state.sourceDepth===0)return X(`bash: return: can only \`return' from a function or sourced script
735
735
  `);let n=e.state.lastExitCode;if(t.length>0){let e=t[0],r=Number.parseInt(e,10);if(e===``||Number.isNaN(r)||!/^-?\d+$/.test(e))return X(`bash: return: ${e}: numeric argument required
736
- `,2);n=(r%256+256)%256}throw new st(n)}var Qv=`set: usage: set [-eux] [+eux] [-o option] [+o option]
736
+ `,2);n=(r%256+256)%256}throw new st(n)}var $v=`set: usage: set [-eux] [+eux] [-o option] [+o option]
737
737
  Options:
738
738
  -e Exit immediately if a command exits with non-zero status
739
739
  +e Disable -e
@@ -749,57 +749,57 @@ Options:
749
749
  +o pipefail Disable pipefail
750
750
  -o xtrace Same as -x
751
751
  +o xtrace Disable xtrace
752
- `,$v=new Map([[`e`,`errexit`],[`u`,`nounset`],[`x`,`xtrace`],[`v`,`verbose`],[`f`,`noglob`],[`C`,`noclobber`],[`a`,`allexport`],[`n`,`noexec`],[`h`,null],[`b`,null],[`m`,null],[`B`,null],[`H`,null],[`P`,null],[`T`,null],[`E`,null],[`p`,null]]),ey=new Map([[`errexit`,`errexit`],[`pipefail`,`pipefail`],[`nounset`,`nounset`],[`xtrace`,`xtrace`],[`verbose`,`verbose`],[`noclobber`,`noclobber`],[`noglob`,`noglob`],[`allexport`,`allexport`],[`noexec`,`noexec`],[`posix`,`posix`],[`vi`,`vi`],[`emacs`,`emacs`],[`notify`,null],[`monitor`,null],[`braceexpand`,null],[`histexpand`,null],[`physical`,null],[`functrace`,null],[`errtrace`,null],[`privileged`,null],[`hashall`,null],[`ignoreeof`,null],[`interactive-comments`,null],[`keyword`,null],[`onecmd`,null]]),ty=[`errexit`,`nounset`,`pipefail`,`verbose`,`xtrace`,`posix`,`allexport`,`noclobber`,`noglob`,`noexec`,`vi`,`emacs`],ny=[`braceexpand`,`errtrace`,`functrace`,`hashall`,`histexpand`,`history`,`ignoreeof`,`interactive-comments`,`keyword`,`monitor`,`nolog`,`notify`,`onecmd`,`physical`,`privileged`];function ry(e,t,n){t!==null&&(n&&(t===`vi`?e.state.options.emacs=!1:t===`emacs`&&(e.state.options.vi=!1)),e.state.options[t]=n,rg(e))}function iy(e,t){return t+1<e.length&&!e[t+1].startsWith(`-`)&&!e[t+1].startsWith(`+`)}function ay(e,t){let n=Et(e,t);return n.length===0?`${t}=()`:`${t}=(${n.map(n=>`[${n}]=${cv(e.state.env.get(`${t}_${n}`)??``)}`).join(` `)})`}function oy(e){return/^[a-zA-Z0-9_]+$/.test(e)?e:`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function sy(e,t){let n=gt(e,t);return n.length===0?`${t}=()`:`${t}=(${n.map(n=>{let r=e.state.env.get(`${t}_${n}`)??``;return`[${oy(n)}]=${cv(r)}`}).join(` `)} )`}function cy(e){let t=new Set,n=e.state.associativeArrays??new Set;for(let r of e.state.env.keys()){let e=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(e){let r=e[1];n.has(r)||t.add(r)}}return t}function ly(e){return e.state.associativeArrays??new Set}function uy(e,t){if(t.includes(`--help`))return Y(Qv);if(t.length===0){let t=cy(e),n=ly(e),r=e=>{for(let t of n){let n=`${t}_`;if(e!==`${t}__length`&&e.startsWith(n)){if(e.slice(n.length).startsWith(`_length`))continue;return!0}}return!1},i=[];for(let[a,o]of e.state.env){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)||t.has(a)||n.has(a))continue;let e=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(e&&t.has(e[1]))continue;let s=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)__length$/);s&&t.has(s[1])||r(a)||s&&n.has(s[1])||i.push([a,o])}let a=[];for(let[e,t]of i.sort(([e],[t])=>e<t?-1:e>t?1:0))a.push(`${e}=${sv(t)}`);for(let n of[...t].sort((e,t)=>e<t?-1:e>t?1:0))a.push(ay(e,n));for(let t of[...n].sort((e,t)=>e<t?-1:e>t?1:0))a.push(sy(e,t));return a.sort((e,t)=>{let n=e.split(`=`)[0],r=t.split(`=`)[0];return n<r?-1:n>r?1:0}),Y(a.length>0?`${a.join(`
752
+ `,ey=new Map([[`e`,`errexit`],[`u`,`nounset`],[`x`,`xtrace`],[`v`,`verbose`],[`f`,`noglob`],[`C`,`noclobber`],[`a`,`allexport`],[`n`,`noexec`],[`h`,null],[`b`,null],[`m`,null],[`B`,null],[`H`,null],[`P`,null],[`T`,null],[`E`,null],[`p`,null]]),ty=new Map([[`errexit`,`errexit`],[`pipefail`,`pipefail`],[`nounset`,`nounset`],[`xtrace`,`xtrace`],[`verbose`,`verbose`],[`noclobber`,`noclobber`],[`noglob`,`noglob`],[`allexport`,`allexport`],[`noexec`,`noexec`],[`posix`,`posix`],[`vi`,`vi`],[`emacs`,`emacs`],[`notify`,null],[`monitor`,null],[`braceexpand`,null],[`histexpand`,null],[`physical`,null],[`functrace`,null],[`errtrace`,null],[`privileged`,null],[`hashall`,null],[`ignoreeof`,null],[`interactive-comments`,null],[`keyword`,null],[`onecmd`,null]]),ny=[`errexit`,`nounset`,`pipefail`,`verbose`,`xtrace`,`posix`,`allexport`,`noclobber`,`noglob`,`noexec`,`vi`,`emacs`],ry=[`braceexpand`,`errtrace`,`functrace`,`hashall`,`histexpand`,`history`,`ignoreeof`,`interactive-comments`,`keyword`,`monitor`,`nolog`,`notify`,`onecmd`,`physical`,`privileged`];function iy(e,t,n){t!==null&&(n&&(t===`vi`?e.state.options.emacs=!1:t===`emacs`&&(e.state.options.vi=!1)),e.state.options[t]=n,ig(e))}function ay(e,t){return t+1<e.length&&!e[t+1].startsWith(`-`)&&!e[t+1].startsWith(`+`)}function oy(e,t){let n=Et(e,t);return n.length===0?`${t}=()`:`${t}=(${n.map(n=>`[${n}]=${lv(e.state.env.get(`${t}_${n}`)??``)}`).join(` `)})`}function sy(e){return/^[a-zA-Z0-9_]+$/.test(e)?e:`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function cy(e,t){let n=gt(e,t);return n.length===0?`${t}=()`:`${t}=(${n.map(n=>{let r=e.state.env.get(`${t}_${n}`)??``;return`[${sy(n)}]=${lv(r)}`}).join(` `)} )`}function ly(e){let t=new Set,n=e.state.associativeArrays??new Set;for(let r of e.state.env.keys()){let e=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(e){let r=e[1];n.has(r)||t.add(r)}}return t}function uy(e){return e.state.associativeArrays??new Set}function dy(e,t){if(t.includes(`--help`))return Y($v);if(t.length===0){let t=ly(e),n=uy(e),r=e=>{for(let t of n){let n=`${t}_`;if(e!==`${t}__length`&&e.startsWith(n)){if(e.slice(n.length).startsWith(`_length`))continue;return!0}}return!1},i=[];for(let[a,o]of e.state.env){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)||t.has(a)||n.has(a))continue;let e=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(e&&t.has(e[1]))continue;let s=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)__length$/);s&&t.has(s[1])||r(a)||s&&n.has(s[1])||i.push([a,o])}let a=[];for(let[e,t]of i.sort(([e],[t])=>e<t?-1:e>t?1:0))a.push(`${e}=${cv(t)}`);for(let n of[...t].sort((e,t)=>e<t?-1:e>t?1:0))a.push(oy(e,n));for(let t of[...n].sort((e,t)=>e<t?-1:e>t?1:0))a.push(cy(e,t));return a.sort((e,t)=>{let n=e.split(`=`)[0],r=t.split(`=`)[0];return n<r?-1:n>r?1:0}),Y(a.length>0?`${a.join(`
753
753
  `)}
754
- `:``)}let n=0;for(;n<t.length;){let r=t[n];if((r===`-o`||r===`+o`)&&iy(t,n)){let i=t[n+1];if(!ey.has(i)){let t=`bash: set: ${i}: invalid option name
755
- ${Qv}`;if(e.state.options.posix)throw new lt(1,``,t);return X(t)}ry(e,ey.get(i)??null,r===`-o`),n+=2;continue}if(r===`-o`){let t=ty.map(t=>`${t.padEnd(16)}${e.state.options[t]?`on`:`off`}`),n=ny.map(e=>`${e.padEnd(16)}off`);return Y(`${[...t,...n].sort().join(`
754
+ `:``)}let n=0;for(;n<t.length;){let r=t[n];if((r===`-o`||r===`+o`)&&ay(t,n)){let i=t[n+1];if(!ty.has(i)){let t=`bash: set: ${i}: invalid option name
755
+ ${$v}`;if(e.state.options.posix)throw new lt(1,``,t);return X(t)}iy(e,ty.get(i)??null,r===`-o`),n+=2;continue}if(r===`-o`){let t=ny.map(t=>`${t.padEnd(16)}${e.state.options[t]?`on`:`off`}`),n=ry.map(e=>`${e.padEnd(16)}off`);return Y(`${[...t,...n].sort().join(`
756
756
  `)}
757
- `)}if(r===`+o`){let t=ty.map(t=>`set ${e.state.options[t]?`-o`:`+o`} ${t}`),n=ny.map(e=>`set +o ${e}`);return Y(`${[...t,...n].sort().join(`
757
+ `)}if(r===`+o`){let t=ny.map(t=>`set ${e.state.options[t]?`-o`:`+o`} ${t}`),n=ry.map(e=>`set +o ${e}`);return Y(`${[...t,...n].sort().join(`
758
758
  `)}
759
- `)}if(r.length>1&&(r[0]===`-`||r[0]===`+`)&&r[1]!==`-`){let t=r[0]===`-`;for(let n=1;n<r.length;n++){let i=r[n];if(!$v.has(i)){let t=`bash: set: ${r[0]}${i}: invalid option
760
- ${Qv}`;if(e.state.options.posix)throw new lt(1,``,t);return X(t)}ry(e,$v.get(i)??null,t)}n++;continue}if(r===`--`)return dy(e,t.slice(n+1)),J;if(r===`-`){if(e.state.options.xtrace=!1,e.state.options.verbose=!1,rg(e),n+1<t.length)return dy(e,t.slice(n+1)),J;n++;continue}if(r===`+`){n++;continue}if(r.startsWith(`-`)||r.startsWith(`+`)){let t=`bash: set: ${r}: invalid option
761
- ${Qv}`;if(e.state.options.posix)throw new lt(1,``,t);return X(t)}return dy(e,t.slice(n)),J}return J}function dy(e,t){let n=1;for(;e.state.env.has(String(n));)e.state.env.delete(String(n)),n++;for(let n=0;n<t.length;n++)e.state.env.set(String(n+1),t[n]);e.state.env.set(`#`,String(t.length)),e.state.env.set(`@`,t.join(` `)),e.state.env.set(`*`,t.join(` `))}function fy(e,t){let n=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<0){let n=`bash: shift: ${t[0]}: numeric argument required
759
+ `)}if(r.length>1&&(r[0]===`-`||r[0]===`+`)&&r[1]!==`-`){let t=r[0]===`-`;for(let n=1;n<r.length;n++){let i=r[n];if(!ey.has(i)){let t=`bash: set: ${r[0]}${i}: invalid option
760
+ ${$v}`;if(e.state.options.posix)throw new lt(1,``,t);return X(t)}iy(e,ey.get(i)??null,t)}n++;continue}if(r===`--`)return fy(e,t.slice(n+1)),J;if(r===`-`){if(e.state.options.xtrace=!1,e.state.options.verbose=!1,ig(e),n+1<t.length)return fy(e,t.slice(n+1)),J;n++;continue}if(r===`+`){n++;continue}if(r.startsWith(`-`)||r.startsWith(`+`)){let t=`bash: set: ${r}: invalid option
761
+ ${$v}`;if(e.state.options.posix)throw new lt(1,``,t);return X(t)}return fy(e,t.slice(n)),J}return J}function fy(e,t){let n=1;for(;e.state.env.has(String(n));)e.state.env.delete(String(n)),n++;for(let n=0;n<t.length;n++)e.state.env.set(String(n+1),t[n]);e.state.env.set(`#`,String(t.length)),e.state.env.set(`@`,t.join(` `)),e.state.env.set(`*`,t.join(` `))}function py(e,t){let n=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<0){let n=`bash: shift: ${t[0]}: numeric argument required
762
762
  `;if(e.state.options.posix)throw new lt(1,``,n);return X(n)}n=r}let r=Number.parseInt(e.state.env.get(`#`)||`0`,10);if(n>r){let t=`bash: shift: shift count out of range
763
- `;if(e.state.options.posix)throw new lt(1,``,t);return X(t)}if(n===0)return J;let i=[];for(let t=1;t<=r;t++)i.push(e.state.env.get(String(t))||``);let a=i.slice(n);for(let t=1;t<=r;t++)e.state.env.delete(String(t));for(let t=0;t<a.length;t++)e.state.env.set(String(t+1),a[t]);return e.state.env.set(`#`,String(a.length)),e.state.env.set(`@`,a.join(` `)),J}async function py(e,t){let n=t;if(n.length>0&&n[0]===`--`&&(n=n.slice(1)),n.length===0)return Z(``,`bash: source: filename argument required
763
+ `;if(e.state.options.posix)throw new lt(1,``,t);return X(t)}if(n===0)return J;let i=[];for(let t=1;t<=r;t++)i.push(e.state.env.get(String(t))||``);let a=i.slice(n);for(let t=1;t<=r;t++)e.state.env.delete(String(t));for(let t=0;t<a.length;t++)e.state.env.set(String(t+1),a[t]);return e.state.env.set(`#`,String(a.length)),e.state.env.set(`@`,a.join(` `)),J}async function my(e,t){let n=t;if(n.length>0&&n[0]===`--`&&(n=n.slice(1)),n.length===0)return Z(``,`bash: source: filename argument required
764
764
  `,2);let r=n[0],i=null;if(r.includes(`/`)){let t=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(t)}catch{}}else{let t=(e.state.env.get(`PATH`)||``).split(`:`).filter(e=>e);for(let n of t){let t=e.fs.resolvePath(e.state.cwd,`${n}/${r}`);try{if((await e.fs.stat(t)).isDirectory)continue;i=await e.fs.readFile(t);break}catch{}}if(i===null){let t=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(t)}catch{}}}if(i===null)return X(`bash: ${r}: No such file or directory
765
765
  `);let a=new Map;if(n.length>1){for(let t=1;t<=9;t++)a.set(String(t),e.state.env.get(String(t)));a.set(`#`,e.state.env.get(`#`)),a.set(`@`,e.state.env.get(`@`));let t=n.slice(1);e.state.env.set(`#`,String(t.length)),e.state.env.set(`@`,t.join(` `));for(let n=0;n<t.length&&n<9;n++)e.state.env.set(String(n+1),t[n]);for(let n=t.length+1;n<=9;n++)e.state.env.delete(String(n))}let o=e.state.currentSource,s=()=>{if(e.state.sourceDepth--,e.state.currentSource=o,n.length>1)for(let[t,n]of a)n===void 0?e.state.env.delete(t):e.state.env.set(t,n)};if(e.state.sourceDepth++,e.state.sourceDepth>e.limits.maxSourceDepth)throw e.state.sourceDepth--,new ot(`source: maximum nesting depth (${e.limits.maxSourceDepth}) exceeded, increase executionLimits.maxSourceDepth`,`recursion`);e.state.currentSource=r;try{let t=Dt(i),n=await e.executeScript(t);return s(),n}catch(e){if(s(),e instanceof ut)throw e;if(e instanceof st)return Z(e.stdout,e.stderr,e.exitCode);if(e.name===`ParseException`)return X(`bash: ${r}: ${e.message}
766
- `);throw e}}function my(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function hy(e){return e.startsWith(`'`)&&e.endsWith(`'`)||e.startsWith(`"`)&&e.endsWith(`"`)}async function gy(e,t){if(hy(t))return null;try{return await Kt(e,Ft(new Zt,t).expression)}catch{let e=parseInt(t,10);return Number.isNaN(e)?0:e}}function _y(e,t){if(e.state.localVarStack?.has(t)){let n=m_(e,t);if(n){n.value===void 0?e.state.env.delete(t):e.state.env.set(t,n.value);let r=e.state.localVarStack?.get(t);if(!r||r.length===0)f_(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,n.scopeIndex),vy(e,t);else{let n=r[r.length-1];e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,n.scopeIndex+1)}return!0}return e.state.env.delete(t),f_(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,0),!0}for(let n=e.state.localScopes.length-1;n>=0;n--){let r=e.state.localScopes[n];if(r.has(t)){let i=r.get(t);i===void 0?e.state.env.delete(t):e.state.env.set(t,i),r.delete(t);let a=!1;for(let r=n-1;r>=0;r--)if(e.state.localScopes[r].has(t)){e.state.localVarDepth&&e.state.localVarDepth.set(t,r+1),a=!0;break}return a||f_(e,t),!0}}return!1}function vy(e,t){if(!e.state.tempEnvBindings||e.state.tempEnvBindings.length===0)return!1;for(let n=e.state.tempEnvBindings.length-1;n>=0;n--){let r=e.state.tempEnvBindings[n];if(r.has(t)){let n=r.get(t);return n===void 0?e.state.env.delete(t):e.state.env.set(t,n),r.delete(t),!0}}return!1}async function yy(e,t){if(t.startsWith(`'`)&&t.endsWith(`'`))return t.slice(1,-1);if(t.startsWith(`"`)&&t.endsWith(`"`)){let n=t.slice(1,-1);return O(e,new Zt().parseWordFromString(n,!0,!1))}return t.includes(`$`)?O(e,new Zt().parseWordFromString(t,!1,!1)):t}async function by(e,t){let n=`both`,r=``,i=0;for(let a of t){if(a===`-v`){n=`variable`;continue}if(a===`-f`){n=`function`;continue}if(n===`function`){e.state.functions.delete(a);continue}if(n===`variable`){let t=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(t){let n=t[1],a=t[2];if(a===`@`||a===`*`){let t=It(e,n);for(let[r]of t)e.state.env.delete(`${n}_${r}`);e.state.env.delete(n);continue}let o=e.state.associativeArrays?.has(n);if(o){let t=await yy(e,a);e.state.env.delete(`${n}_${t}`);continue}let s=Qt(e,n),c=e.state.declaredVars?.has(n);if((e.state.env.has(n)||c)&&!s&&!o){r+=`bash: unset: ${n}: not an array variable
767
- `,i=1;continue}let l=await gy(e,a);if(l===null&&s){r+=`bash: unset: ${a}: not a valid identifier
766
+ `);throw e}}function hy(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function gy(e){return e.startsWith(`'`)&&e.endsWith(`'`)||e.startsWith(`"`)&&e.endsWith(`"`)}async function _y(e,t){if(gy(t))return null;try{return await Kt(e,Ft(new Zt,t).expression)}catch{let e=parseInt(t,10);return Number.isNaN(e)?0:e}}function vy(e,t){if(e.state.localVarStack?.has(t)){let n=h_(e,t);if(n){n.value===void 0?e.state.env.delete(t):e.state.env.set(t,n.value);let r=e.state.localVarStack?.get(t);if(!r||r.length===0)p_(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,n.scopeIndex),yy(e,t);else{let n=r[r.length-1];e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,n.scopeIndex+1)}return!0}return e.state.env.delete(t),p_(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,0),!0}for(let n=e.state.localScopes.length-1;n>=0;n--){let r=e.state.localScopes[n];if(r.has(t)){let i=r.get(t);i===void 0?e.state.env.delete(t):e.state.env.set(t,i),r.delete(t);let a=!1;for(let r=n-1;r>=0;r--)if(e.state.localScopes[r].has(t)){e.state.localVarDepth&&e.state.localVarDepth.set(t,r+1),a=!0;break}return a||p_(e,t),!0}}return!1}function yy(e,t){if(!e.state.tempEnvBindings||e.state.tempEnvBindings.length===0)return!1;for(let n=e.state.tempEnvBindings.length-1;n>=0;n--){let r=e.state.tempEnvBindings[n];if(r.has(t)){let n=r.get(t);return n===void 0?e.state.env.delete(t):e.state.env.set(t,n),r.delete(t),!0}}return!1}async function by(e,t){if(t.startsWith(`'`)&&t.endsWith(`'`))return t.slice(1,-1);if(t.startsWith(`"`)&&t.endsWith(`"`)){let n=t.slice(1,-1);return O(e,new Zt().parseWordFromString(n,!0,!1))}return t.includes(`$`)?O(e,new Zt().parseWordFromString(t,!1,!1)):t}async function xy(e,t){let n=`both`,r=``,i=0;for(let a of t){if(a===`-v`){n=`variable`;continue}if(a===`-f`){n=`function`;continue}if(n===`function`){e.state.functions.delete(a);continue}if(n===`variable`){let t=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(t){let n=t[1],a=t[2];if(a===`@`||a===`*`){let t=It(e,n);for(let[r]of t)e.state.env.delete(`${n}_${r}`);e.state.env.delete(n);continue}let o=e.state.associativeArrays?.has(n);if(o){let t=await by(e,a);e.state.env.delete(`${n}_${t}`);continue}let s=Qt(e,n),c=e.state.declaredVars?.has(n);if((e.state.env.has(n)||c)&&!s&&!o){r+=`bash: unset: ${n}: not an array variable
767
+ `,i=1;continue}let l=await _y(e,a);if(l===null&&s){r+=`bash: unset: ${a}: not a valid identifier
768
768
  `,i=1;continue}if(l===null)continue;if(l<0){let t=It(e,n),a=t.length,o=e.state.currentLine;if(a===0){r+=`bash: line ${o}: unset: [${l}]: bad array subscript
769
769
  `,i=1;continue}let s=a+l;if(s<0){r+=`bash: line ${o}: unset: [${l}]: bad array subscript
770
- `,i=1;continue}let c=t[s][0];e.state.env.delete(`${n}_${c}`);continue}e.state.env.delete(`${n}_${l}`);continue}if(!my(a)){r+=`bash: unset: \`${a}': not a valid identifier
770
+ `,i=1;continue}let c=t[s][0];e.state.env.delete(`${n}_${c}`);continue}e.state.env.delete(`${n}_${l}`);continue}if(!hy(a)){r+=`bash: unset: \`${a}': not a valid identifier
771
771
  `,i=1;continue}let n=a;if(Pt(e,a)){let t=Bt(e,a);t&&t!==a&&(n=t)}if(_t(e,n)){r+=`bash: unset: ${n}: cannot unset: readonly variable
772
- `,i=1;continue}let o=d_(e,n);if(o!==void 0&&o!==e.state.callDepth)_y(e,n);else if(e.state.fullyUnsetLocals?.has(n))e.state.env.delete(n);else if(o!==void 0){let t=e.state.accessedTempEnvVars?.has(n),r=e.state.mutatedTempEnvVars?.has(n);if((t||r)&&e.state.localVarStack?.has(n)){let t=m_(e,n);t?t.value===void 0?e.state.env.delete(n):e.state.env.set(n,t.value):e.state.env.delete(n)}else e.state.env.delete(n)}else vy(e,n)||e.state.env.delete(n);e.state.exportedVars?.delete(n);continue}let t=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(t){let n=t[1],a=t[2];if(a===`@`||a===`*`){let t=It(e,n);for(let[r]of t)e.state.env.delete(`${n}_${r}`);e.state.env.delete(n);continue}let o=e.state.associativeArrays?.has(n);if(o){let t=await yy(e,a);e.state.env.delete(`${n}_${t}`);continue}let s=Qt(e,n);if(e.state.env.has(n)&&!s&&!o){r+=`bash: unset: ${n}: not an array variable
773
- `,i=1;continue}let c=await gy(e,a);if(c===null&&s){r+=`bash: unset: ${a}: not a valid identifier
772
+ `,i=1;continue}let o=f_(e,n);if(o!==void 0&&o!==e.state.callDepth)vy(e,n);else if(e.state.fullyUnsetLocals?.has(n))e.state.env.delete(n);else if(o!==void 0){let t=e.state.accessedTempEnvVars?.has(n),r=e.state.mutatedTempEnvVars?.has(n);if((t||r)&&e.state.localVarStack?.has(n)){let t=h_(e,n);t?t.value===void 0?e.state.env.delete(n):e.state.env.set(n,t.value):e.state.env.delete(n)}else e.state.env.delete(n)}else yy(e,n)||e.state.env.delete(n);e.state.exportedVars?.delete(n);continue}let t=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(t){let n=t[1],a=t[2];if(a===`@`||a===`*`){let t=It(e,n);for(let[r]of t)e.state.env.delete(`${n}_${r}`);e.state.env.delete(n);continue}let o=e.state.associativeArrays?.has(n);if(o){let t=await by(e,a);e.state.env.delete(`${n}_${t}`);continue}let s=Qt(e,n);if(e.state.env.has(n)&&!s&&!o){r+=`bash: unset: ${n}: not an array variable
773
+ `,i=1;continue}let c=await _y(e,a);if(c===null&&s){r+=`bash: unset: ${a}: not a valid identifier
774
774
  `,i=1;continue}if(c===null)continue;if(c<0){let t=It(e,n),a=t.length,o=e.state.currentLine;if(a===0){r+=`bash: line ${o}: unset: [${c}]: bad array subscript
775
775
  `,i=1;continue}let s=a+c;if(s<0){r+=`bash: line ${o}: unset: [${c}]: bad array subscript
776
- `,i=1;continue}let l=t[s][0];e.state.env.delete(`${n}_${l}`);continue}e.state.env.delete(`${n}_${c}`);continue}if(!my(a)){r+=`bash: unset: \`${a}': not a valid identifier
776
+ `,i=1;continue}let l=t[s][0];e.state.env.delete(`${n}_${l}`);continue}e.state.env.delete(`${n}_${c}`);continue}if(!hy(a)){r+=`bash: unset: \`${a}': not a valid identifier
777
777
  `,i=1;continue}let o=a;if(Pt(e,a)){let t=Bt(e,a);t&&t!==a&&(o=t)}if(_t(e,o)){r+=`bash: unset: ${o}: cannot unset: readonly variable
778
- `,i=1;continue}let s=d_(e,o);if(s!==void 0&&s!==e.state.callDepth)_y(e,o);else if(e.state.fullyUnsetLocals?.has(o))e.state.env.delete(o);else if(s!==void 0){let t=e.state.accessedTempEnvVars?.has(o),n=e.state.mutatedTempEnvVars?.has(o);if((t||n)&&e.state.localVarStack?.has(o)){let t=m_(e,o);t?t.value===void 0?e.state.env.delete(o):e.state.env.set(o,t.value):e.state.env.delete(o)}else e.state.env.delete(o)}else vy(e,o)||e.state.env.delete(o);e.state.exportedVars?.delete(o),e.state.functions.delete(a)}return Z(``,r,i)}var xy=[`extglob`,`dotglob`,`nullglob`,`failglob`,`globstar`,`globskipdots`,`nocaseglob`,`nocasematch`,`expand_aliases`,`lastpipe`,`xpg_echo`],Sy=`autocd.cdable_vars.cdspell.checkhash.checkjobs.checkwinsize.cmdhist.compat31.compat32.compat40.compat41.compat42.compat43.compat44.complete_fullquote.direxpand.dirspell.execfail.extdebug.extquote.force_fignore.globasciiranges.gnu_errfmt.histappend.histreedit.histverify.hostcomplete.huponexit.inherit_errexit.interactive_comments.lithist.localvar_inherit.localvar_unset.login_shell.mailwarn.no_empty_cmd_completion.progcomp.progcomp_alias.promptvars.restricted_shell.shift_verbose.sourcepath`.split(`.`);function Cy(e){return xy.includes(e)}function wy(e){return Sy.includes(e)}function Ty(e,t){let n=!1,r=!1,i=!1,a=!1,o=!1,s=[],c=0;for(;c<t.length;){let e=t[c];if(e===`--`){c++;break}if(e.startsWith(`-`)&&e.length>1){for(let t=1;t<e.length;t++){let s=e[t];switch(s){case`s`:n=!0;break;case`u`:r=!0;break;case`p`:i=!0;break;case`q`:a=!0;break;case`o`:o=!0;break;default:return{exitCode:2,stdout:``,stderr:`shopt: -${s}: invalid option
779
- `}}}c++}else break}for(;c<t.length;)s.push(t[c]),c++;if(o)return Ey(e,s,n,r,i,a);if(n&&r)return{exitCode:1,stdout:``,stderr:`shopt: cannot set and unset shell options simultaneously
780
- `};if(s.length===0){if(n||r){let t=[];for(let a of xy){let o=e.state.shoptOptions[a];n&&o?t.push(i?`shopt -s ${a}`:`${a} on`):r&&!o&&t.push(i?`shopt -u ${a}`:`${a} off`)}return{exitCode:0,stdout:t.length>0?`${t.join(`
778
+ `,i=1;continue}let s=f_(e,o);if(s!==void 0&&s!==e.state.callDepth)vy(e,o);else if(e.state.fullyUnsetLocals?.has(o))e.state.env.delete(o);else if(s!==void 0){let t=e.state.accessedTempEnvVars?.has(o),n=e.state.mutatedTempEnvVars?.has(o);if((t||n)&&e.state.localVarStack?.has(o)){let t=h_(e,o);t?t.value===void 0?e.state.env.delete(o):e.state.env.set(o,t.value):e.state.env.delete(o)}else e.state.env.delete(o)}else yy(e,o)||e.state.env.delete(o);e.state.exportedVars?.delete(o),e.state.functions.delete(a)}return Z(``,r,i)}var Sy=[`extglob`,`dotglob`,`nullglob`,`failglob`,`globstar`,`globskipdots`,`nocaseglob`,`nocasematch`,`expand_aliases`,`lastpipe`,`xpg_echo`],Cy=`autocd.cdable_vars.cdspell.checkhash.checkjobs.checkwinsize.cmdhist.compat31.compat32.compat40.compat41.compat42.compat43.compat44.complete_fullquote.direxpand.dirspell.execfail.extdebug.extquote.force_fignore.globasciiranges.gnu_errfmt.histappend.histreedit.histverify.hostcomplete.huponexit.inherit_errexit.interactive_comments.lithist.localvar_inherit.localvar_unset.login_shell.mailwarn.no_empty_cmd_completion.progcomp.progcomp_alias.promptvars.restricted_shell.shift_verbose.sourcepath`.split(`.`);function wy(e){return Sy.includes(e)}function Ty(e){return Cy.includes(e)}function Ey(e,t){let n=!1,r=!1,i=!1,a=!1,o=!1,s=[],c=0;for(;c<t.length;){let e=t[c];if(e===`--`){c++;break}if(e.startsWith(`-`)&&e.length>1){for(let t=1;t<e.length;t++){let s=e[t];switch(s){case`s`:n=!0;break;case`u`:r=!0;break;case`p`:i=!0;break;case`q`:a=!0;break;case`o`:o=!0;break;default:return{exitCode:2,stdout:``,stderr:`shopt: -${s}: invalid option
779
+ `}}}c++}else break}for(;c<t.length;)s.push(t[c]),c++;if(o)return Dy(e,s,n,r,i,a);if(n&&r)return{exitCode:1,stdout:``,stderr:`shopt: cannot set and unset shell options simultaneously
780
+ `};if(s.length===0){if(n||r){let t=[];for(let a of Sy){let o=e.state.shoptOptions[a];n&&o?t.push(i?`shopt -s ${a}`:`${a} on`):r&&!o&&t.push(i?`shopt -u ${a}`:`${a} off`)}return{exitCode:0,stdout:t.length>0?`${t.join(`
781
781
  `)}
782
- `:``,stderr:``}}let t=[];for(let n of xy){let r=e.state.shoptOptions[n];t.push(i?`shopt ${r?`-s`:`-u`} ${n}`:`${n} ${r?`on`:`off`}`)}return{exitCode:0,stdout:`${t.join(`
782
+ `:``,stderr:``}}let t=[];for(let n of Sy){let r=e.state.shoptOptions[n];t.push(i?`shopt ${r?`-s`:`-u`} ${n}`:`${n} ${r?`on`:`off`}`)}return{exitCode:0,stdout:`${t.join(`
783
783
  `)}
784
- `,stderr:``}}let l=!1,u=``,d=[];for(let t of s){if(!Cy(t)&&!wy(t)){u+=`shopt: ${t}: invalid shell option name
785
- `,l=!0;continue}if(n)Cy(t)&&(e.state.shoptOptions[t]=!0,og(e));else if(r)Cy(t)&&(e.state.shoptOptions[t]=!1,og(e));else if(Cy(t)){let n=e.state.shoptOptions[t];a?n||(l=!0):i?(d.push(`shopt ${n?`-s`:`-u`} ${t}`),n||(l=!0)):(d.push(`${t} ${n?`on`:`off`}`),n||(l=!0))}else a?l=!0:i?(d.push(`shopt -u ${t}`),l=!0):(d.push(`${t} off`),l=!0)}return{exitCode:l?1:0,stdout:d.length>0?`${d.join(`
784
+ `,stderr:``}}let l=!1,u=``,d=[];for(let t of s){if(!wy(t)&&!Ty(t)){u+=`shopt: ${t}: invalid shell option name
785
+ `,l=!0;continue}if(n)wy(t)&&(e.state.shoptOptions[t]=!0,sg(e));else if(r)wy(t)&&(e.state.shoptOptions[t]=!1,sg(e));else if(wy(t)){let n=e.state.shoptOptions[t];a?n||(l=!0):i?(d.push(`shopt ${n?`-s`:`-u`} ${t}`),n||(l=!0)):(d.push(`${t} ${n?`on`:`off`}`),n||(l=!0))}else a?l=!0:i?(d.push(`shopt -u ${t}`),l=!0):(d.push(`${t} off`),l=!0)}return{exitCode:l?1:0,stdout:d.length>0?`${d.join(`
786
786
  `)}
787
- `:``,stderr:u}}function Ey(e,t,n,r,i,a){let o=new Map([[`errexit`,`errexit`],[`pipefail`,`pipefail`],[`nounset`,`nounset`],[`xtrace`,`xtrace`],[`verbose`,`verbose`],[`posix`,`posix`],[`allexport`,`allexport`],[`noclobber`,`noclobber`],[`noglob`,`noglob`],[`noexec`,`noexec`],[`vi`,`vi`],[`emacs`,`emacs`]]),s=[`braceexpand`,`errtrace`,`functrace`,`hashall`,`histexpand`,`history`,`ignoreeof`,`interactive-comments`,`keyword`,`monitor`,`nolog`,`notify`,`onecmd`,`physical`,`privileged`],c=[...o.keys(),...s].sort();if(t.length===0){let t=[];for(let a of c){let c=s.includes(a),l=o.get(a),u=c||!l?!1:e.state.options[l];n&&!u||r&&u||t.push(i?`set ${u?`-o`:`+o`} ${a}`:`${a} ${u?`on`:`off`}`)}return{exitCode:0,stdout:t.length>0?`${t.join(`
787
+ `:``,stderr:u}}function Dy(e,t,n,r,i,a){let o=new Map([[`errexit`,`errexit`],[`pipefail`,`pipefail`],[`nounset`,`nounset`],[`xtrace`,`xtrace`],[`verbose`,`verbose`],[`posix`,`posix`],[`allexport`,`allexport`],[`noclobber`,`noclobber`],[`noglob`,`noglob`],[`noexec`,`noexec`],[`vi`,`vi`],[`emacs`,`emacs`]]),s=[`braceexpand`,`errtrace`,`functrace`,`hashall`,`histexpand`,`history`,`ignoreeof`,`interactive-comments`,`keyword`,`monitor`,`nolog`,`notify`,`onecmd`,`physical`,`privileged`],c=[...o.keys(),...s].sort();if(t.length===0){let t=[];for(let a of c){let c=s.includes(a),l=o.get(a),u=c||!l?!1:e.state.options[l];n&&!u||r&&u||t.push(i?`set ${u?`-o`:`+o`} ${a}`:`${a} ${u?`on`:`off`}`)}return{exitCode:0,stdout:t.length>0?`${t.join(`
788
788
  `)}
789
789
  `:``,stderr:``}}let l=!1,u=``,d=[];for(let c of t){let t=o.has(c),f=s.includes(c);if(!t&&!f){u+=`shopt: ${c}: invalid option name
790
- `,l=!0;continue}if(f){n||r||(a?l=!0:i?(d.push(`set +o ${c}`),l=!0):(d.push(`${c} off`),l=!0));continue}let p=o.get(c);if(p)if(n)p===`vi`?e.state.options.emacs=!1:p===`emacs`&&(e.state.options.vi=!1),e.state.options[p]=!0,rg(e);else if(r)e.state.options[p]=!1,rg(e);else{let t=e.state.options[p];a?t||(l=!0):i?(d.push(`set ${t?`-o`:`+o`} ${c}`),t||(l=!0)):(d.push(`${c} ${t?`on`:`off`}`),t||(l=!0))}}return{exitCode:l?1:0,stdout:d.length>0?`${d.join(`
790
+ `,l=!0;continue}if(f){n||r||(a?l=!0:i?(d.push(`set +o ${c}`),l=!0):(d.push(`${c} off`),l=!0));continue}let p=o.get(c);if(p)if(n)p===`vi`?e.state.options.emacs=!1:p===`emacs`&&(e.state.options.vi=!1),e.state.options[p]=!0,ig(e);else if(r)e.state.options[p]=!1,ig(e);else{let t=e.state.options[p];a?t||(l=!0):i?(d.push(`set ${t?`-o`:`+o`} ${c}`),t||(l=!0)):(d.push(`${c} ${t?`on`:`off`}`),t||(l=!0))}}return{exitCode:l?1:0,stdout:d.length>0?`${d.join(`
791
791
  `)}
792
- `:``,stderr:u}}async function Dy(e,t,n){if(t.includes(`/`)){let n=e.fs.resolvePath(e.state.cwd,t);if(!await e.fs.exists(n))return{error:`not_found`,path:n};let r=n.split(`/`).pop()||t,i=e.commands.get(r);try{let t=await e.fs.stat(n);return t.isDirectory?{error:`permission_denied`,path:n}:i?{cmd:i,path:n}:t.mode&73?{script:!0,path:n}:{error:`permission_denied`,path:n}}catch{return{error:`not_found`,path:n}}}if(!n&&e.state.hashTable){let n=e.state.hashTable.get(t);if(n)if(await e.fs.exists(n)){let r=e.commands.get(t);if(r)return{cmd:r,path:n};try{let t=await e.fs.stat(n);if(!t.isDirectory&&t.mode&73)return{script:!0,path:n}}catch{}}else e.state.hashTable.delete(t)}let r=(n??e.state.env.get(`PATH`)??`/usr/bin:/bin`).split(`:`);for(let n of r){if(!n)continue;let r=`${n.startsWith(`/`)?n:e.fs.resolvePath(e.state.cwd,n)}/${t}`;if(await e.fs.exists(r))try{let i=await e.fs.stat(r);if(i.isDirectory)continue;let a=(i.mode&73)!=0,o=e.commands.get(t),s=n===`/bin`||n===`/usr/bin`;if(o&&s)return{cmd:o,path:r};if(a&&(o&&!s||!o))return{script:!0,path:r}}catch{}}if(!await e.fs.exists(`/usr/bin`)){let n=e.commands.get(t);if(n)return{cmd:n,path:`/usr/bin/${t}`}}return null}async function Oy(e,t){let n=[];if(t.includes(`/`)){let r=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(r))try{let i=await e.fs.stat(r);i.isDirectory||i.mode&73&&n.push(t)}catch{}return n}let r=(e.state.env.get(`PATH`)||`/usr/bin:/bin`).split(`:`);for(let i of r){if(!i)continue;let r=`${i.startsWith(`/`)?i:e.fs.resolvePath(e.state.cwd,i)}/${t}`;if(await e.fs.exists(r)){try{if((await e.fs.stat(r)).isDirectory)continue}catch{continue}n.push(i.startsWith(`/`)?r:`${i}/${t}`)}}return n}function ky(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function Q(e,t,n,r){return((...i)=>{Tn(t,n,`${r} call`);let a=e(...i);return ky(a)?a.then(e=>(Tn(t,n,`${r} post-await`),e),e=>{throw Tn(t,n,`${r} post-await`),e}):(Tn(t,n,`${r} return`),a)})}function Ay(e,t,n){let r={readFile:Q(e.readFile.bind(e),t,n,`fs.readFile`),readFileBuffer:Q(e.readFileBuffer.bind(e),t,n,`fs.readFileBuffer`),writeFile:Q(e.writeFile.bind(e),t,n,`fs.writeFile`),appendFile:Q(e.appendFile.bind(e),t,n,`fs.appendFile`),exists:Q(e.exists.bind(e),t,n,`fs.exists`),stat:Q(e.stat.bind(e),t,n,`fs.stat`),mkdir:Q(e.mkdir.bind(e),t,n,`fs.mkdir`),readdir:Q(e.readdir.bind(e),t,n,`fs.readdir`),rm:Q(e.rm.bind(e),t,n,`fs.rm`),cp:Q(e.cp.bind(e),t,n,`fs.cp`),mv:Q(e.mv.bind(e),t,n,`fs.mv`),resolvePath:Q(e.resolvePath.bind(e),t,n,`fs.resolvePath`),getAllPaths:Q(e.getAllPaths.bind(e),t,n,`fs.getAllPaths`),chmod:Q(e.chmod.bind(e),t,n,`fs.chmod`),symlink:Q(e.symlink.bind(e),t,n,`fs.symlink`),link:Q(e.link.bind(e),t,n,`fs.link`),readlink:Q(e.readlink.bind(e),t,n,`fs.readlink`),lstat:Q(e.lstat.bind(e),t,n,`fs.lstat`),realpath:Q(e.realpath.bind(e),t,n,`fs.realpath`),utimes:Q(e.utimes.bind(e),t,n,`fs.utimes`)};return e.readdirWithFileTypes&&(r.readdirWithFileTypes=Q(e.readdirWithFileTypes.bind(e),t,n,`fs.readdirWithFileTypes`)),r}function jy(e,t){if(!e.requireDefenseContext)return e;let n=`command:${t}`,r={...e,fs:Ay(e.fs,e.requireDefenseContext,n)};return e.exec&&(r.exec=Q(e.exec,e.requireDefenseContext,n,`exec`)),e.fetch&&(r.fetch=Q(e.fetch,e.requireDefenseContext,n,`fetch`)),e.sleep&&(r.sleep=Q(e.sleep,e.requireDefenseContext,n,`sleep`)),e.getRegisteredCommands&&(r.getRegisteredCommands=Q(e.getRegisteredCommands,e.requireDefenseContext,n,`getRegisteredCommands`)),r}async function My(e,t,n,r){let i=!1,a=!1,o=!1,s=!1,c=!1,l=[];for(let e of t)if(e.startsWith(`-`)&&e.length>1)for(let t of e.slice(1))t===`t`?i=!0:t===`p`?a=!0:t===`P`?o=!0:t===`a`?s=!0:t===`f`&&(c=!0);else l.push(e);let u=``,d=``,f=0,p=!1,m=!1;for(let t of l){let l=!1;if(o){if(s){let e=await r(t);if(e.length>0){for(let t of e)u+=`${t}
792
+ `:``,stderr:u}}async function Oy(e,t,n){if(t.includes(`/`)){let n=e.fs.resolvePath(e.state.cwd,t);if(!await e.fs.exists(n))return{error:`not_found`,path:n};let r=n.split(`/`).pop()||t,i=e.commands.get(r);try{let t=await e.fs.stat(n);return t.isDirectory?{error:`permission_denied`,path:n}:i?{cmd:i,path:n}:t.mode&73?{script:!0,path:n}:{error:`permission_denied`,path:n}}catch{return{error:`not_found`,path:n}}}if(!n&&e.state.hashTable){let n=e.state.hashTable.get(t);if(n)if(await e.fs.exists(n)){let r=e.commands.get(t);if(r)return{cmd:r,path:n};try{let t=await e.fs.stat(n);if(!t.isDirectory&&t.mode&73)return{script:!0,path:n}}catch{}}else e.state.hashTable.delete(t)}let r=(n??e.state.env.get(`PATH`)??`/usr/bin:/bin`).split(`:`);for(let n of r){if(!n)continue;let r=`${n.startsWith(`/`)?n:e.fs.resolvePath(e.state.cwd,n)}/${t}`;if(await e.fs.exists(r))try{let i=await e.fs.stat(r);if(i.isDirectory)continue;let a=(i.mode&73)!=0,o=e.commands.get(t),s=n===`/bin`||n===`/usr/bin`;if(o&&s)return{cmd:o,path:r};if(a&&(o&&!s||!o))return{script:!0,path:r}}catch{}}if(!await e.fs.exists(`/usr/bin`)){let n=e.commands.get(t);if(n)return{cmd:n,path:`/usr/bin/${t}`}}return null}async function ky(e,t){let n=[];if(t.includes(`/`)){let r=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(r))try{let i=await e.fs.stat(r);i.isDirectory||i.mode&73&&n.push(t)}catch{}return n}let r=(e.state.env.get(`PATH`)||`/usr/bin:/bin`).split(`:`);for(let i of r){if(!i)continue;let r=`${i.startsWith(`/`)?i:e.fs.resolvePath(e.state.cwd,i)}/${t}`;if(await e.fs.exists(r)){try{if((await e.fs.stat(r)).isDirectory)continue}catch{continue}n.push(i.startsWith(`/`)?r:`${i}/${t}`)}}return n}function Ay(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function Q(e,t,n,r){return((...i)=>{Tn(t,n,`${r} call`);let a=e(...i);return Ay(a)?a.then(e=>(Tn(t,n,`${r} post-await`),e),e=>{throw Tn(t,n,`${r} post-await`),e}):(Tn(t,n,`${r} return`),a)})}function jy(e,t,n){let r={readFile:Q(e.readFile.bind(e),t,n,`fs.readFile`),readFileBuffer:Q(e.readFileBuffer.bind(e),t,n,`fs.readFileBuffer`),writeFile:Q(e.writeFile.bind(e),t,n,`fs.writeFile`),appendFile:Q(e.appendFile.bind(e),t,n,`fs.appendFile`),exists:Q(e.exists.bind(e),t,n,`fs.exists`),stat:Q(e.stat.bind(e),t,n,`fs.stat`),mkdir:Q(e.mkdir.bind(e),t,n,`fs.mkdir`),readdir:Q(e.readdir.bind(e),t,n,`fs.readdir`),rm:Q(e.rm.bind(e),t,n,`fs.rm`),cp:Q(e.cp.bind(e),t,n,`fs.cp`),mv:Q(e.mv.bind(e),t,n,`fs.mv`),resolvePath:Q(e.resolvePath.bind(e),t,n,`fs.resolvePath`),getAllPaths:Q(e.getAllPaths.bind(e),t,n,`fs.getAllPaths`),chmod:Q(e.chmod.bind(e),t,n,`fs.chmod`),symlink:Q(e.symlink.bind(e),t,n,`fs.symlink`),link:Q(e.link.bind(e),t,n,`fs.link`),readlink:Q(e.readlink.bind(e),t,n,`fs.readlink`),lstat:Q(e.lstat.bind(e),t,n,`fs.lstat`),realpath:Q(e.realpath.bind(e),t,n,`fs.realpath`),utimes:Q(e.utimes.bind(e),t,n,`fs.utimes`)};return e.readdirWithFileTypes&&(r.readdirWithFileTypes=Q(e.readdirWithFileTypes.bind(e),t,n,`fs.readdirWithFileTypes`)),r}function My(e,t){if(!e.requireDefenseContext)return e;let n=`command:${t}`,r={...e,fs:jy(e.fs,e.requireDefenseContext,n)};return e.exec&&(r.exec=Q(e.exec,e.requireDefenseContext,n,`exec`)),e.fetch&&(r.fetch=Q(e.fetch,e.requireDefenseContext,n,`fetch`)),e.sleep&&(r.sleep=Q(e.sleep,e.requireDefenseContext,n,`sleep`)),e.getRegisteredCommands&&(r.getRegisteredCommands=Q(e.getRegisteredCommands,e.requireDefenseContext,n,`getRegisteredCommands`)),r}async function Ny(e,t,n,r){let i=!1,a=!1,o=!1,s=!1,c=!1,l=[];for(let e of t)if(e.startsWith(`-`)&&e.length>1)for(let t of e.slice(1))t===`t`?i=!0:t===`p`?a=!0:t===`P`?o=!0:t===`a`?s=!0:t===`f`&&(c=!0);else l.push(e);let u=``,d=``,f=0,p=!1,m=!1;for(let t of l){let l=!1;if(o){if(s){let e=await r(t);if(e.length>0){for(let t of e)u+=`${t}
793
793
  `;p=!0,l=!0}}else{let e=await n(t);e&&(u+=`${e}
794
794
  `,p=!0,l=!0)}l||(m=!0);continue}let f=!c&&e.state.functions.has(t);if(s&&f){if(!a)if(i)u+=`function
795
- `;else{let n=e.state.functions.get(t),r=n?Ny(t,n):`${t} is a function
795
+ `;else{let n=e.state.functions.get(t),r=n?Py(t,n):`${t} is a function
796
796
  `;u+=r}l=!0}let h=e.state.env.get(`BASH_ALIAS_${t}`);if(!(h!==void 0&&(s||!l)&&(a||(i?u+=`alias
797
797
  `:u+=`${t} is aliased to \`${h}'
798
- `),l=!0,!s)||v_.has(t)&&(s||!l)&&(a||(i?u+=`keyword
798
+ `),l=!0,!s)||y_.has(t)&&(s||!l)&&(a||(i?u+=`keyword
799
799
  `:u+=`${t} is a shell keyword
800
800
  `),l=!0,!s))){if(!s&&f&&!l){if(!a)if(i)u+=`function
801
- `;else{let n=e.state.functions.get(t),r=n?Ny(t,n):`${t} is a function
802
- `;u+=r}l=!0;continue}if(!(y_.has(t)&&(s||!l)&&(a||(i?u+=`builtin
801
+ `;else{let n=e.state.functions.get(t),r=n?Py(t,n):`${t} is a function
802
+ `;u+=r}l=!0;continue}if(!(b_.has(t)&&(s||!l)&&(a||(i?u+=`builtin
803
803
  `:u+=`${t} is a shell builtin
804
804
  `),l=!0,!s))){if(s){let e=await r(t);for(let n of e)a?u+=`${n}
805
805
  `:i?u+=`file
@@ -808,16 +808,16 @@ ${Qv}`;if(e.state.options.posix)throw new lt(1,``,t);return X(t)}return dy(e,t.s
808
808
  `:i?u+=`file
809
809
  `:u+=`${t} is ${e}
810
810
  `,p=!0,l=!0)}if(!l&&(m=!0,!i&&!a)){let n=!0;if(t.includes(`/`)){let r=e.fs.resolvePath(e.state.cwd,t);await e.fs.exists(r)&&(n=!1)}n&&(d+=`bash: type: ${t}: not found
811
- `)}}}}return f=a?m&&!p?1:0:m?1:0,Z(u,d,f)}function Ny(e,t){let n;return n=t.body.type===`Group`?t.body.body.map(e=>Py(e)).join(`; `):Py(t.body),`${e} is a function
811
+ `)}}}}return f=a?m&&!p?1:0:m?1:0,Z(u,d,f)}function Py(e,t){let n;return n=t.body.type===`Group`?t.body.body.map(e=>Fy(e)).join(`; `):Fy(t.body),`${e} is a function
812
812
  ${e} ()
813
813
  {
814
814
  ${n}
815
815
  }
816
- `}function Py(e){if(Array.isArray(e))return e.map(e=>Py(e)).join(`; `);if(e.type===`Statement`){let t=[];for(let n=0;n<e.pipelines.length;n++){let r=e.pipelines[n];t.push(Fy(r)),e.operators[n]&&t.push(e.operators[n])}return t.join(` `)}if(e.type===`SimpleCommand`){let t=e,n=[];t.name&&n.push(Iy(t.name));for(let e of t.args)n.push(Iy(e));return n.join(` `)}return e.type===`Group`?`{ ${e.body.map(e=>Py(e)).join(`; `)}; }`:`...`}function Fy(e){let t=e.commands.map(e=>Py(e));return(e.negated?`! `:``)+t.join(` | `)}function Iy(e){let t=``;for(let n of e.parts)n.type===`Literal`?t+=n.value:n.type===`DoubleQuoted`?t+=`"${n.parts.map(e=>Ly(e)).join(``)}"`:n.type===`SingleQuoted`?t+=`'${n.value}'`:t+=Ly(n);return t}function Ly(e){let t=e;return t.type===`Literal`?t.value??``:t.type===`Variable`?`$${t.name}`:``}async function Ry(e,t,n,r){let i=``,a=``,o=0;for(let n of t){if(!n){o=1;continue}let t=e.state.env.get(`BASH_ALIAS_${n}`);if(t!==void 0)r?i+=`${n} is an alias for "${t}"
816
+ `}function Fy(e){if(Array.isArray(e))return e.map(e=>Fy(e)).join(`; `);if(e.type===`Statement`){let t=[];for(let n=0;n<e.pipelines.length;n++){let r=e.pipelines[n];t.push(Iy(r)),e.operators[n]&&t.push(e.operators[n])}return t.join(` `)}if(e.type===`SimpleCommand`){let t=e,n=[];t.name&&n.push(Ly(t.name));for(let e of t.args)n.push(Ly(e));return n.join(` `)}return e.type===`Group`?`{ ${e.body.map(e=>Fy(e)).join(`; `)}; }`:`...`}function Iy(e){let t=e.commands.map(e=>Fy(e));return(e.negated?`! `:``)+t.join(` | `)}function Ly(e){let t=``;for(let n of e.parts)n.type===`Literal`?t+=n.value:n.type===`DoubleQuoted`?t+=`"${n.parts.map(e=>Ry(e)).join(``)}"`:n.type===`SingleQuoted`?t+=`'${n.value}'`:t+=Ry(n);return t}function Ry(e){let t=e;return t.type===`Literal`?t.value??``:t.type===`Variable`?`$${t.name}`:``}async function zy(e,t,n,r){let i=``,a=``,o=0;for(let n of t){if(!n){o=1;continue}let t=e.state.env.get(`BASH_ALIAS_${n}`);if(t!==void 0)r?i+=`${n} is an alias for "${t}"
817
817
  `:i+=`alias ${n}='${t}'
818
- `;else if(v_.has(n))r?i+=`${n} is a shell keyword
818
+ `;else if(y_.has(n))r?i+=`${n} is a shell keyword
819
819
  `:i+=`${n}
820
- `;else if(y_.has(n))r?i+=`${n} is a shell builtin
820
+ `;else if(b_.has(n))r?i+=`${n} is a shell builtin
821
821
  `:i+=`${n}
822
822
  `;else if(e.state.functions.has(n))r?i+=`${n} is a function
823
823
  `:i+=`${n}
@@ -827,111 +827,111 @@ ${e} ()
827
827
  `),o=1)}else if(e.commands.has(n)){let t=(e.state.env.get(`PATH`)??`/usr/bin:/bin`).split(`:`),a=null;for(let r of t){if(!r)continue;let t=`${r}/${n}`;try{let n=await e.fs.stat(t);if(!n.isDirectory&&n.mode&73){a=t;break}}catch{}}a||=`/usr/bin/${n}`,r?i+=`${n} is ${a}
828
828
  `:i+=`${a}
829
829
  `}else r&&(a+=`${n}: not found
830
- `),o=1}return Z(i,a,o)}async function zy(e,t){if(t.includes(`/`)){let n=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(n)){try{let t=await e.fs.stat(n);if(t.isDirectory||!(t.mode&73))return null}catch{return null}return t}return null}let n=(e.state.env.get(`PATH`)??`/usr/bin:/bin`).split(`:`);for(let r of n){if(!r)continue;let n=`${r.startsWith(`/`)?r:e.fs.resolvePath(e.state.cwd,r)}/${t}`;if(await e.fs.exists(n)){try{if((await e.fs.stat(n)).isDirectory)continue}catch{continue}return`${r}/${t}`}}if(e.commands.has(t)){for(let e of n)if(e===`/usr/bin`||e===`/bin`)return`${e}/${t}`;return`/usr/bin/${t}`}return null}async function By(e,t,n,r,i,a,o,s){let{ctx:c,runCommand:l}=e;if(c.coverage&&y_.has(t)&&c.coverage.hit(`bash:builtin:${t}`),t===`export`)return Iv(c,n);if(t===`unset`)return by(c,n);if(t===`exit`)return Fv(c,n);if(t===`local`)return Kv(c,n);if(t===`set`)return uy(c,n);if(t===`break`)return xg(c,n);if(t===`continue`)return rv(c,n);if(t===`return`)return Zv(c,n);if(t===`eval`&&c.state.options.posix)return Pv(c,n,i);if(t===`shift`)return fy(c,n);if(t===`getopts`)return Lv(c,n);if(t===`compgen`)return F_(c,n);if(t===`complete`)return $_(c,n);if(t===`compopt`)return nv(c,n);if(t===`pushd`)return await jv(c,n);if(t===`popd`)return Mv(c,n);if(t===`dirs`)return Nv(c,n);if(t===`source`||t===`.`)return py(c,n);if(t===`read`)return Xv(c,n,i,s);if(t===`mapfile`||t===`readarray`)return qv(c,n,i);if(t===`declare`||t===`typeset`)return Ev(c,n);if(t===`readonly`)return Dv(c,n);if(!a){let e=c.state.functions.get(t);if(e)return A_(c,e,n,i)}if(t===`eval`)return Pv(c,n,i);if(t===`cd`)return await Sg(c,n);if(t===`:`||t===`true`)return J;if(t===`false`)return vg(!1);if(t===`let`)return Gv(c,n);if(t===`command`)return Vy(e,n,i);if(t===`builtin`)return Hy(e,n,i);if(t===`shopt`)return Ty(c,n);if(t===`exec`){if(n.length===0)return J;let[e,...t]=n;return l(e,t,[],i,!1,!1,-1)}if(t===`wait`)return J;if(t===`type`)return await My(c,n,e=>zy(c,e),e=>Oy(c,e));if(t===`hash`)return Rv(c,n);if(t===`help`)return Vv(c,n);if(t===`[`||t===`test`){let e=n;if(t===`[`){if(n[n.length-1]!==`]`)return X(`[: missing \`]'
831
- `,2);e=n.slice(0,-1)}return Bg(c,e)}return null}async function Vy(e,t,n){let{ctx:r,runCommand:i}=e;if(t.length===0)return J;let a=!1,o=!1,s=!1,c=t;for(;c.length>0&&c[0].startsWith(`-`);){let e=c[0];if(e===`--`){c=c.slice(1);break}for(let t of e.slice(1))t===`p`?a=!0:t===`V`?o=!0:t===`v`&&(s=!0);c=c.slice(1)}if(c.length===0)return J;if(s||o)return await Ry(r,c,s,o);let[l,...u]=c;return i(l,u,[],n,!0,a,-1)}async function Hy(e,t,n){let{runCommand:r}=e;if(t.length===0)return J;let i=t;if(i[0]===`--`&&(i=i.slice(1),i.length===0))return J;let a=i[0];if(!y_.has(a))return X(`bash: builtin: ${a}: not a shell builtin
832
- `);let[,...o]=i;return r(a,o,[],n,!0,!1,-1)}async function Uy(e,t,n,r,i){let{ctx:a,buildExportedEnv:o,executeUserScript:s}=e,c=await Dy(a,t,i?`/usr/bin:/bin`:void 0);if(!c)return _g(t)?X(`bash: ${t}: command not available in browser environments. Exclude '${t}' from your commands or use the Node.js bundle.
830
+ `),o=1}return Z(i,a,o)}async function By(e,t){if(t.includes(`/`)){let n=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(n)){try{let t=await e.fs.stat(n);if(t.isDirectory||!(t.mode&73))return null}catch{return null}return t}return null}let n=(e.state.env.get(`PATH`)??`/usr/bin:/bin`).split(`:`);for(let r of n){if(!r)continue;let n=`${r.startsWith(`/`)?r:e.fs.resolvePath(e.state.cwd,r)}/${t}`;if(await e.fs.exists(n)){try{if((await e.fs.stat(n)).isDirectory)continue}catch{continue}return`${r}/${t}`}}if(e.commands.has(t)){for(let e of n)if(e===`/usr/bin`||e===`/bin`)return`${e}/${t}`;return`/usr/bin/${t}`}return null}async function Vy(e,t,n,r,i,a,o,s){let{ctx:c,runCommand:l}=e;if(c.coverage&&b_.has(t)&&c.coverage.hit(`bash:builtin:${t}`),t===`export`)return Lv(c,n);if(t===`unset`)return xy(c,n);if(t===`exit`)return Iv(c,n);if(t===`local`)return qv(c,n);if(t===`set`)return dy(c,n);if(t===`break`)return Sg(c,n);if(t===`continue`)return iv(c,n);if(t===`return`)return Qv(c,n);if(t===`eval`&&c.state.options.posix)return Fv(c,n,i);if(t===`shift`)return py(c,n);if(t===`getopts`)return Rv(c,n);if(t===`compgen`)return I_(c,n);if(t===`complete`)return ev(c,n);if(t===`compopt`)return rv(c,n);if(t===`pushd`)return await Mv(c,n);if(t===`popd`)return Nv(c,n);if(t===`dirs`)return Pv(c,n);if(t===`source`||t===`.`)return my(c,n);if(t===`read`)return Zv(c,n,i,s);if(t===`mapfile`||t===`readarray`)return Jv(c,n,i);if(t===`declare`||t===`typeset`)return Dv(c,n);if(t===`readonly`)return Ov(c,n);if(!a){let e=c.state.functions.get(t);if(e)return j_(c,e,n,i)}if(t===`eval`)return Fv(c,n,i);if(t===`cd`)return await Cg(c,n);if(t===`:`||t===`true`)return J;if(t===`false`)return yg(!1);if(t===`let`)return Kv(c,n);if(t===`command`)return Hy(e,n,i);if(t===`builtin`)return Uy(e,n,i);if(t===`shopt`)return Ey(c,n);if(t===`exec`){if(n.length===0)return J;let[e,...t]=n;return l(e,t,[],i,!1,!1,-1)}if(t===`wait`)return J;if(t===`type`)return await Ny(c,n,e=>By(c,e),e=>ky(c,e));if(t===`hash`)return zv(c,n);if(t===`help`)return Hv(c,n);if(t===`[`||t===`test`){let e=n;if(t===`[`){if(n[n.length-1]!==`]`)return X(`[: missing \`]'
831
+ `,2);e=n.slice(0,-1)}return Vg(c,e)}return null}async function Hy(e,t,n){let{ctx:r,runCommand:i}=e;if(t.length===0)return J;let a=!1,o=!1,s=!1,c=t;for(;c.length>0&&c[0].startsWith(`-`);){let e=c[0];if(e===`--`){c=c.slice(1);break}for(let t of e.slice(1))t===`p`?a=!0:t===`V`?o=!0:t===`v`&&(s=!0);c=c.slice(1)}if(c.length===0)return J;if(s||o)return await zy(r,c,s,o);let[l,...u]=c;return i(l,u,[],n,!0,a,-1)}async function Uy(e,t,n){let{runCommand:r}=e;if(t.length===0)return J;let i=t;if(i[0]===`--`&&(i=i.slice(1),i.length===0))return J;let a=i[0];if(!b_.has(a))return X(`bash: builtin: ${a}: not a shell builtin
832
+ `);let[,...o]=i;return r(a,o,[],n,!0,!1,-1)}async function Wy(e,t,n,r,i){let{ctx:a,buildExportedEnv:o,executeUserScript:s}=e,c=await Oy(a,t,i?`/usr/bin:/bin`:void 0);if(!c)return vg(t)?X(`bash: ${t}: command not available in browser environments. Exclude '${t}' from your commands or use the Node.js bundle.
833
833
  `,127):X(`bash: ${t}: command not found
834
834
  `,127);if(`error`in c)return c.error===`permission_denied`?X(`bash: ${t}: Permission denied
835
835
  `,126):X(`bash: ${t}: No such file or directory
836
- `,127);if(`script`in c)return t.includes(`/`)||(a.state.hashTable||(a.state.hashTable=new Map),a.state.hashTable.set(t,c.path)),await s(c.path,n,r);let{cmd:l,path:u}=c;t.includes(`/`)||(a.state.hashTable||(a.state.hashTable=new Map),a.state.hashTable.set(t,u));let d=r||a.state.groupStdin||``,f=o(),p=jy({fs:a.fs,cwd:a.state.cwd,env:a.state.env,exportedEnv:f,stdin:d,limits:a.limits,exec:a.execFn,fetch:a.fetch,getRegisteredCommands:()=>Array.from(a.commands.keys()),sleep:a.sleep,trace:a.trace,fileDescriptors:a.state.fileDescriptors,xpgEcho:a.state.shoptOptions.xpg_echo,coverage:a.coverage,signal:a.state.signal,requireDefenseContext:a.requireDefenseContext,jsBootstrapCode:a.jsBootstrapCode},t);try{let e=()=>wn(a.requireDefenseContext,`command`,`${t} execution`,()=>l.execute(n,p));return l.trusted?await vn.runTrustedAsync(()=>e()):await e()}catch(e){if(e instanceof ot||e instanceof _n)throw e;return X(`${t}: ${En(Dn(e))}
837
- `)}}async function Wy(e,t){let n=e.state.inCondition;e.state.inCondition=!0;let r=``,i=``,a=0;try{for(let n of t){let t=await e.executeStatement(n);r+=t.stdout,i+=t.stderr,a=t.exitCode}}finally{e.state.inCondition=n}return{stdout:r,stderr:i,exitCode:a}}function Gy(e,t,n,r){if(e instanceof tt)return t+=e.stdout,n+=e.stderr,e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=n,{action:`rethrow`,stdout:t,stderr:n,error:e}):{action:`break`,stdout:t,stderr:n};if(e instanceof ft)return t+=e.stdout,n+=e.stderr,e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=n,{action:`rethrow`,stdout:t,stderr:n,error:e}):{action:`continue`,stdout:t,stderr:n};if(e instanceof st||e instanceof dt||e instanceof ut||e instanceof ot)return e.prependOutput(t,n),{action:`rethrow`,stdout:t,stderr:n,error:e};let i=Dn(e);return{action:`error`,stdout:t,stderr:`${n}${i}
838
- `,exitCode:1}}async function Ky(e,t,n=``,r=``){let i=n,a=r,o=0;try{for(let n of t){let t=await e.executeStatement(n);i+=t.stdout,a+=t.stderr,o=t.exitCode}}catch(e){if(ct(e)||e instanceof dt||e instanceof ut||e instanceof ot||e instanceof pt)throw e.prependOutput(i,a),e;return{stdout:i,stderr:`${a}${Dn(e)}
839
- `,exitCode:1}}return{stdout:i,stderr:a,exitCode:o}}async function qy(e,t){let n=``,r=``;for(let i of t.clauses){let t=await Wy(e,i.condition);if(n+=t.stdout,r+=t.stderr,t.exitCode===0)return Ky(e,i.body,n,r)}return t.elseBody?Ky(e,t.elseBody,n,r):Z(n,r,0)}async function Jy(e,t){let n=await E_(e,t.redirections);if(n)return n;let r=``,i=``,a=0,o=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t.variable))return X(`bash: \`${t.variable}': not a valid identifier
840
- `);let s=[];if(t.words===null)s=(e.state.env.get(`@`)||``).split(` `).filter(Boolean);else if(t.words.length===0)s=[];else try{for(let n of t.words){let t=await tn(e,n);s.push(...t.values)}}catch(e){if(e instanceof nt)return{stdout:``,stderr:e.stderr,exitCode:1};throw e}e.state.loopDepth++;try{for(let n of s){o++,o>e.limits.maxLoopIterations&&yg(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,r,i),e.state.env.set(t.variable,n);try{for(let n of t.body){let t=await e.executeStatement(n);r+=t.stdout,i+=t.stderr,a=t.exitCode}}catch(n){let a=Gy(n,r,i,e.state.loopDepth);if(r=a.stdout,i=a.stderr,a.action===`break`)break;if(a.action===`continue`)continue;if(a.action===`error`)return D_(e,Z(r,i,a.exitCode??1),t.redirections);throw a.error}}}finally{e.state.loopDepth--}return D_(e,Z(r,i,a),t.redirections)}async function Yy(e,t){let n=await E_(e,t.redirections);if(n)return n;let r=t.line;r!==void 0&&(e.state.currentLine=r);let i=``,a=``,o=0,s=0;t.init&&await Kt(e,t.init.expression),e.state.loopDepth++;try{for(;s++,s>e.limits.maxLoopIterations&&yg(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,i,a),!(t.condition&&(r!==void 0&&(e.state.currentLine=r),await Kt(e,t.condition.expression)===0));){try{for(let n of t.body){let t=await e.executeStatement(n);i+=t.stdout,a+=t.stderr,o=t.exitCode}}catch(n){let r=Gy(n,i,a,e.state.loopDepth);if(i=r.stdout,a=r.stderr,r.action===`break`)break;if(r.action===`continue`){t.update&&await Kt(e,t.update.expression);continue}if(r.action===`error`)return D_(e,Z(i,a,r.exitCode??1),t.redirections);throw r.error}t.update&&await Kt(e,t.update.expression)}}finally{e.state.loopDepth--}return D_(e,Z(i,a,o),t.redirections)}async function Xy(e,t,n=``){let r=``,i=``,a=0,o=0,s=n;for(let n of t.redirections)if((n.operator===`<<`||n.operator===`<<-`)&&n.target.type===`HereDoc`){let t=n.target,r=await O(e,t.content);t.stripTabs&&(r=r.split(`
836
+ `,127);if(`script`in c)return t.includes(`/`)||(a.state.hashTable||(a.state.hashTable=new Map),a.state.hashTable.set(t,c.path)),await s(c.path,n,r);let{cmd:l,path:u}=c;t.includes(`/`)||(a.state.hashTable||(a.state.hashTable=new Map),a.state.hashTable.set(t,u));let d=r||a.state.groupStdin||``,f=o(),p=My({fs:a.fs,cwd:a.state.cwd,env:a.state.env,exportedEnv:f,stdin:d,limits:a.limits,exec:a.execFn,fetch:a.fetch,getRegisteredCommands:()=>Array.from(a.commands.keys()),sleep:a.sleep,trace:a.trace,fileDescriptors:a.state.fileDescriptors,xpgEcho:a.state.shoptOptions.xpg_echo,coverage:a.coverage,signal:a.state.signal,requireDefenseContext:a.requireDefenseContext,jsBootstrapCode:a.jsBootstrapCode},t);try{let e=()=>wn(a.requireDefenseContext,`command`,`${t} execution`,()=>l.execute(n,p));return l.trusted?await vn.runTrustedAsync(()=>e()):await e()}catch(e){if(e instanceof ot||e instanceof _n)throw e;return X(`${t}: ${En(Dn(e))}
837
+ `)}}async function Gy(e,t){let n=e.state.inCondition;e.state.inCondition=!0;let r=``,i=``,a=0;try{for(let n of t){let t=await e.executeStatement(n);r+=t.stdout,i+=t.stderr,a=t.exitCode}}finally{e.state.inCondition=n}return{stdout:r,stderr:i,exitCode:a}}function Ky(e,t,n,r){if(e instanceof tt)return t+=e.stdout,n+=e.stderr,e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=n,{action:`rethrow`,stdout:t,stderr:n,error:e}):{action:`break`,stdout:t,stderr:n};if(e instanceof ft)return t+=e.stdout,n+=e.stderr,e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=n,{action:`rethrow`,stdout:t,stderr:n,error:e}):{action:`continue`,stdout:t,stderr:n};if(e instanceof st||e instanceof dt||e instanceof ut||e instanceof ot)return e.prependOutput(t,n),{action:`rethrow`,stdout:t,stderr:n,error:e};let i=Dn(e);return{action:`error`,stdout:t,stderr:`${n}${i}
838
+ `,exitCode:1}}async function qy(e,t,n=``,r=``){let i=n,a=r,o=0;try{for(let n of t){let t=await e.executeStatement(n);i+=t.stdout,a+=t.stderr,o=t.exitCode}}catch(e){if(ct(e)||e instanceof dt||e instanceof ut||e instanceof ot||e instanceof pt)throw e.prependOutput(i,a),e;return{stdout:i,stderr:`${a}${Dn(e)}
839
+ `,exitCode:1}}return{stdout:i,stderr:a,exitCode:o}}async function Jy(e,t){let n=``,r=``;for(let i of t.clauses){let t=await Gy(e,i.condition);if(n+=t.stdout,r+=t.stderr,t.exitCode===0)return qy(e,i.body,n,r)}return t.elseBody?qy(e,t.elseBody,n,r):Z(n,r,0)}async function Yy(e,t){let n=await D_(e,t.redirections);if(n)return n;let r=``,i=``,a=0,o=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t.variable))return X(`bash: \`${t.variable}': not a valid identifier
840
+ `);let s=[];if(t.words===null)s=(e.state.env.get(`@`)||``).split(` `).filter(Boolean);else if(t.words.length===0)s=[];else try{for(let n of t.words){let t=await tn(e,n);s.push(...t.values)}}catch(e){if(e instanceof nt)return{stdout:``,stderr:e.stderr,exitCode:1};throw e}e.state.loopDepth++;try{for(let n of s){o++,o>e.limits.maxLoopIterations&&bg(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,r,i),e.state.env.set(t.variable,n);try{for(let n of t.body){let t=await e.executeStatement(n);r+=t.stdout,i+=t.stderr,a=t.exitCode}}catch(n){let a=Ky(n,r,i,e.state.loopDepth);if(r=a.stdout,i=a.stderr,a.action===`break`)break;if(a.action===`continue`)continue;if(a.action===`error`)return O_(e,Z(r,i,a.exitCode??1),t.redirections);throw a.error}}}finally{e.state.loopDepth--}return O_(e,Z(r,i,a),t.redirections)}async function Xy(e,t){let n=await D_(e,t.redirections);if(n)return n;let r=t.line;r!==void 0&&(e.state.currentLine=r);let i=``,a=``,o=0,s=0;t.init&&await Kt(e,t.init.expression),e.state.loopDepth++;try{for(;s++,s>e.limits.maxLoopIterations&&bg(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,i,a),!(t.condition&&(r!==void 0&&(e.state.currentLine=r),await Kt(e,t.condition.expression)===0));){try{for(let n of t.body){let t=await e.executeStatement(n);i+=t.stdout,a+=t.stderr,o=t.exitCode}}catch(n){let r=Ky(n,i,a,e.state.loopDepth);if(i=r.stdout,a=r.stderr,r.action===`break`)break;if(r.action===`continue`){t.update&&await Kt(e,t.update.expression);continue}if(r.action===`error`)return O_(e,Z(i,a,r.exitCode??1),t.redirections);throw r.error}t.update&&await Kt(e,t.update.expression)}}finally{e.state.loopDepth--}return O_(e,Z(i,a,o),t.redirections)}async function Zy(e,t,n=``){let r=``,i=``,a=0,o=0,s=n;for(let n of t.redirections)if((n.operator===`<<`||n.operator===`<<-`)&&n.target.type===`HereDoc`){let t=n.target,r=await O(e,t.content);t.stripTabs&&(r=r.split(`
841
841
  `).map(e=>e.replace(/^\t+/,``)).join(`
842
842
  `)),s=r}else if(n.operator===`<<<`&&n.target.type===`Word`)s=`${await O(e,n.target)}
843
843
  `;else if(n.operator===`<`&&n.target.type===`Word`)try{let t=await O(e,n.target),r=e.fs.resolvePath(e.state.cwd,t);s=await e.fs.readFile(r)}catch{return X(`bash: ${await O(e,n.target)}: No such file or directory
844
- `)}let c=e.state.groupStdin;s&&(e.state.groupStdin=s),e.state.loopDepth++;try{for(;;){o++,o>e.limits.maxLoopIterations&&yg(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,r,i);let n=0,s=!1,c=!1,l=e.state.inCondition;e.state.inCondition=!0;try{for(let a of t.condition){let t=await e.executeStatement(a);r+=t.stdout,i+=t.stderr,n=t.exitCode}}catch(t){if(t instanceof tt){if(r+=t.stdout,i+=t.stderr,t.levels>1&&e.state.loopDepth>1)throw t.levels--,t.stdout=r,t.stderr=i,e.state.inCondition=l,t;s=!0}else if(t instanceof ft){if(r+=t.stdout,i+=t.stderr,t.levels>1&&e.state.loopDepth>1)throw t.levels--,t.stdout=r,t.stderr=i,e.state.inCondition=l,t;c=!0}else throw e.state.inCondition=l,t}finally{e.state.inCondition=l}if(s)break;if(!c){if(n!==0)break;try{for(let n of t.body){let t=await e.executeStatement(n);r+=t.stdout,i+=t.stderr,a=t.exitCode}}catch(t){let n=Gy(t,r,i,e.state.loopDepth);if(r=n.stdout,i=n.stderr,n.action===`break`)break;if(n.action===`continue`)continue;if(n.action===`error`)return Z(r,i,n.exitCode??1);throw n.error}}}}finally{e.state.loopDepth--,e.state.groupStdin=c}return Z(r,i,a)}async function Zy(e,t){let n=``,r=``,i=0,a=0;e.state.loopDepth++;try{for(;;){a++,a>e.limits.maxLoopIterations&&yg(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,n,r);let o=await Wy(e,t.condition);if(n+=o.stdout,r+=o.stderr,o.exitCode===0)break;try{for(let a of t.body){let t=await e.executeStatement(a);n+=t.stdout,r+=t.stderr,i=t.exitCode}}catch(t){let i=Gy(t,n,r,e.state.loopDepth);if(n=i.stdout,r=i.stderr,i.action===`break`)break;if(i.action===`continue`)continue;if(i.action===`error`)return Z(n,r,i.exitCode??1);throw i.error}}}finally{e.state.loopDepth--}return Z(n,r,i)}async function Qy(e,t){let n=await E_(e,t.redirections);if(n)return n;let r=``,i=``,a=0,o=await O(e,t.word),s=!1;for(let n=0;n<t.items.length;n++){let c=t.items[n],l=s;if(!s)for(let t of c.patterns){let n=await O(e,t);Yt(t)&&(n=kt(n));let r=e.state.shoptOptions.nocasematch,i=e.state.shoptOptions.extglob;if(Kg(o,n,r,i)){l=!0;break}}if(l){let t=await Ky(e,c.body,r,i);if(r=t.stdout,i=t.stderr,a=t.exitCode,c.terminator===`;;`)break;s=c.terminator===`;&`}else s=!1}return D_(e,Z(r,i,a),t.redirections)}function $y(e,t){if(e.parts.length!==1)return!1;let n=e.parts[0];return n.type===`Literal`?t.includes(n.value):!1}function eb(e){if(!e.startsWith(`__rw__:`))return null;let t=e.slice(7),n=t.indexOf(`:`);if(n===-1)return null;let r=Number.parseInt(t.slice(0,n),10);if(Number.isNaN(r)||r<0)return null;let i=n+1,a=t.slice(i,i+r),o=i+r+1,s=t.slice(o),c=s.indexOf(`:`);if(c===-1)return null;let l=Number.parseInt(s.slice(0,c),10);return Number.isNaN(l)||l<0?null:{path:a,position:l,content:s.slice(c+1)}}var tb=`+ `;async function nb(e){let t=e.state.env.get(`PS4`);if(t===void 0)return tb;if(t===``)return``;try{return await O(e,new Zt().parseWordFromString(t,!1,!1))}catch{return e.state.expansionStderr=`${e.state.expansionStderr||``}bash: ${t}: bad substitution
845
- `,t||tb}}function rb(e){return e.map(e=>ib(e)).join(` `)}function ib(e){if(e===``)return`''`;if(!/[\s'"\\$`!*?[\]{}|&;<>()~#\n\t]/.test(e))return e;let t=/[\x00-\x1f\x7f]/.test(e),n=e.includes(`
844
+ `)}let c=e.state.groupStdin;s&&(e.state.groupStdin=s),e.state.loopDepth++;try{for(;;){o++,o>e.limits.maxLoopIterations&&bg(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,r,i);let n=0,s=!1,c=!1,l=e.state.inCondition;e.state.inCondition=!0;try{for(let a of t.condition){let t=await e.executeStatement(a);r+=t.stdout,i+=t.stderr,n=t.exitCode}}catch(t){if(t instanceof tt){if(r+=t.stdout,i+=t.stderr,t.levels>1&&e.state.loopDepth>1)throw t.levels--,t.stdout=r,t.stderr=i,e.state.inCondition=l,t;s=!0}else if(t instanceof ft){if(r+=t.stdout,i+=t.stderr,t.levels>1&&e.state.loopDepth>1)throw t.levels--,t.stdout=r,t.stderr=i,e.state.inCondition=l,t;c=!0}else throw e.state.inCondition=l,t}finally{e.state.inCondition=l}if(s)break;if(!c){if(n!==0)break;try{for(let n of t.body){let t=await e.executeStatement(n);r+=t.stdout,i+=t.stderr,a=t.exitCode}}catch(t){let n=Ky(t,r,i,e.state.loopDepth);if(r=n.stdout,i=n.stderr,n.action===`break`)break;if(n.action===`continue`)continue;if(n.action===`error`)return Z(r,i,n.exitCode??1);throw n.error}}}}finally{e.state.loopDepth--,e.state.groupStdin=c}return Z(r,i,a)}async function Qy(e,t){let n=``,r=``,i=0,a=0;e.state.loopDepth++;try{for(;;){a++,a>e.limits.maxLoopIterations&&bg(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,n,r);let o=await Gy(e,t.condition);if(n+=o.stdout,r+=o.stderr,o.exitCode===0)break;try{for(let a of t.body){let t=await e.executeStatement(a);n+=t.stdout,r+=t.stderr,i=t.exitCode}}catch(t){let i=Ky(t,n,r,e.state.loopDepth);if(n=i.stdout,r=i.stderr,i.action===`break`)break;if(i.action===`continue`)continue;if(i.action===`error`)return Z(n,r,i.exitCode??1);throw i.error}}}finally{e.state.loopDepth--}return Z(n,r,i)}async function $y(e,t){let n=await D_(e,t.redirections);if(n)return n;let r=``,i=``,a=0,o=await O(e,t.word),s=!1;for(let n=0;n<t.items.length;n++){let c=t.items[n],l=s;if(!s)for(let t of c.patterns){let n=await O(e,t);Yt(t)&&(n=kt(n));let r=e.state.shoptOptions.nocasematch,i=e.state.shoptOptions.extglob;if(qg(o,n,r,i)){l=!0;break}}if(l){let t=await qy(e,c.body,r,i);if(r=t.stdout,i=t.stderr,a=t.exitCode,c.terminator===`;;`)break;s=c.terminator===`;&`}else s=!1}return O_(e,Z(r,i,a),t.redirections)}function eb(e,t){if(e.parts.length!==1)return!1;let n=e.parts[0];return n.type===`Literal`?t.includes(n.value):!1}function tb(e){if(!e.startsWith(`__rw__:`))return null;let t=e.slice(7),n=t.indexOf(`:`);if(n===-1)return null;let r=Number.parseInt(t.slice(0,n),10);if(Number.isNaN(r)||r<0)return null;let i=n+1,a=t.slice(i,i+r),o=i+r+1,s=t.slice(o),c=s.indexOf(`:`);if(c===-1)return null;let l=Number.parseInt(s.slice(0,c),10);return Number.isNaN(l)||l<0?null:{path:a,position:l,content:s.slice(c+1)}}var nb=`+ `;async function rb(e){let t=e.state.env.get(`PS4`);if(t===void 0)return nb;if(t===``)return``;try{return await O(e,new Zt().parseWordFromString(t,!1,!1))}catch{return e.state.expansionStderr=`${e.state.expansionStderr||``}bash: ${t}: bad substitution
845
+ `,t||nb}}function ib(e){return e.map(e=>ab(e)).join(` `)}function ab(e){if(e===``)return`''`;if(!/[\s'"\\$`!*?[\]{}|&;<>()~#\n\t]/.test(e))return e;let t=/[\x00-\x1f\x7f]/.test(e),n=e.includes(`
846
846
  `),r=e.includes(` `),i=e.includes(`\\`),a=e.includes(`'`);if(t||n||r||i){let t=``;for(let n of e){let e=n.charCodeAt(0);n===`
847
- `?t+=`\\n`:n===` `?t+=`\\t`:n===`\\`?t+=`\\\\`:n===`'`?t+=`'`:n===`"`?t+=`"`:e<32||e===127?e<256?t+=`\\x${e.toString(16).padStart(2,`0`)}`:t+=`\\u${e.toString(16).padStart(4,`0`)}`:t+=n}return`$'${t}'`}return a?`"${e.replace(/([\\$`"])/g,`\\$1`)}"`:`'${e}'`}async function ab(e,t,n){return e.state.options.xtrace?`${await nb(e)}${rb([t,...n])}
848
- `:``}async function ob(e,t,n){return e.state.options.xtrace?`${await nb(e)}${t}=${n}
849
- `:``}async function sb(e,t,n){let r=t.timed?gn():0,i=``,a=J,o=0,s=[],c=``,l=t.commands.length>1,u=e.state.lastArg;for(let r=0;r<t.commands.length;r++){let u=t.commands[r],d=r===t.commands.length-1,f=r===0;l&&(e.state.lastArg=``,f||(e.state.groupStdin=void 0));let p=l&&(!d||!e.state.shoptOptions.lastpipe)?new Map(e.state.env):null,m;try{m=await n(u,i)}catch(n){if(n instanceof ht)m={stdout:n.stdout,stderr:n.stderr,exitCode:1};else if(n instanceof ut&&t.commands.length>1)m={stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode};else if(n instanceof dt&&t.commands.length>1)m={stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode};else throw p&&(e.state.env=p),n}p&&(e.state.env=p),s.push(m.exitCode),m.exitCode!==0&&(o=m.exitCode),d?a=m:(t.pipeStderr?.[r]??!1?i=m.stderr+m.stdout:(i=m.stdout,c+=m.stderr),a={stdout:``,stderr:``,exitCode:m.exitCode})}if(c&&(a={...a,stderr:c+a.stderr}),t.commands.length>1||t.commands.length===1&&t.commands[0].type===`SimpleCommand`){for(let t of e.state.env.keys())t.startsWith(`PIPESTATUS_`)&&e.state.env.delete(t);for(let t=0;t<s.length;t++)e.state.env.set(`PIPESTATUS_${t}`,String(s[t]));e.state.env.set(`PIPESTATUS__length`,String(s.length))}if(e.state.options.pipefail&&o!==0&&(a={...a,exitCode:o}),t.negated&&(a={...a,exitCode:a.exitCode===0?1:0}),t.timed){let e=(gn()-r)/1e3,n=Math.floor(e/60),i=e%60,o;o=t.timePosix?`real ${e.toFixed(2)}
847
+ `?t+=`\\n`:n===` `?t+=`\\t`:n===`\\`?t+=`\\\\`:n===`'`?t+=`'`:n===`"`?t+=`"`:e<32||e===127?e<256?t+=`\\x${e.toString(16).padStart(2,`0`)}`:t+=`\\u${e.toString(16).padStart(4,`0`)}`:t+=n}return`$'${t}'`}return a?`"${e.replace(/([\\$`"])/g,`\\$1`)}"`:`'${e}'`}async function ob(e,t,n){return e.state.options.xtrace?`${await rb(e)}${ib([t,...n])}
848
+ `:``}async function sb(e,t,n){return e.state.options.xtrace?`${await rb(e)}${t}=${n}
849
+ `:``}async function cb(e,t,n){let r=t.timed?gn():0,i=``,a=J,o=0,s=[],c=``,l=t.commands.length>1,u=e.state.lastArg;for(let r=0;r<t.commands.length;r++){let u=t.commands[r],d=r===t.commands.length-1,f=r===0;l&&(e.state.lastArg=``,f||(e.state.groupStdin=void 0));let p=l&&(!d||!e.state.shoptOptions.lastpipe)?new Map(e.state.env):null,m;try{m=await n(u,i)}catch(n){if(n instanceof ht)m={stdout:n.stdout,stderr:n.stderr,exitCode:1};else if(n instanceof ut&&t.commands.length>1)m={stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode};else if(n instanceof dt&&t.commands.length>1)m={stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode};else throw p&&(e.state.env=p),n}p&&(e.state.env=p),s.push(m.exitCode),m.exitCode!==0&&(o=m.exitCode),d?a=m:(t.pipeStderr?.[r]??!1?i=m.stderr+m.stdout:(i=m.stdout,c+=m.stderr),a={stdout:``,stderr:``,exitCode:m.exitCode})}if(c&&(a={...a,stderr:c+a.stderr}),t.commands.length>1||t.commands.length===1&&t.commands[0].type===`SimpleCommand`){for(let t of e.state.env.keys())t.startsWith(`PIPESTATUS_`)&&e.state.env.delete(t);for(let t=0;t<s.length;t++)e.state.env.set(`PIPESTATUS_${t}`,String(s[t]));e.state.env.set(`PIPESTATUS__length`,String(s.length))}if(e.state.options.pipefail&&o!==0&&(a={...a,exitCode:o}),t.negated&&(a={...a,exitCode:a.exitCode===0?1:0}),t.timed){let e=(gn()-r)/1e3,n=Math.floor(e/60),i=e%60,o;o=t.timePosix?`real ${e.toFixed(2)}
850
850
  user 0.00
851
851
  sys 0.00
852
852
  `:`
853
853
  real ${`${n}m${i.toFixed(3)}s`}
854
854
  user 0m0.000s
855
855
  sys 0m0.000s
856
- `,a={...a,stderr:a.stderr+o}}return l&&!e.state.shoptOptions.lastpipe&&(e.state.lastArg=u),a}async function cb(e,t){let n=new Map,r=``;for(let i of t.assignments){let a=i.name;if(i.array){let o=await lb(e,t,a,i.array,i.append,n);if(o.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:o.error};if(r+=o.xtraceOutput,o.continueToNext)continue}let o=i.value?await O(e,i.value):``;if(a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:Z(``,`bash: ${a}: bad array subscript
857
- `,1)};let s=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let a=await mb(e,t,s[1],s[2],o,i.append,n);if(a.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:a.error};if(a.continueToNext)continue}let c=await _b(e,t,a,o,i.append,n);if(c.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:c.error};r+=c.xtraceOutput,c.continueToNext}return{continueToNext:!1,xtraceOutput:r,tempAssignments:n}}async function lb(e,t,n,r,i,a){let o=``;if(/\[.+\]$/.test(n))return{continueToNext:!1,xtraceOutput:``,error:Z(``,`bash: ${n}: cannot assign list to array member
856
+ `,a={...a,stderr:a.stderr+o}}return l&&!e.state.shoptOptions.lastpipe&&(e.state.lastArg=u),a}async function lb(e,t){let n=new Map,r=``;for(let i of t.assignments){let a=i.name;if(i.array){let o=await ub(e,t,a,i.array,i.append,n);if(o.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:o.error};if(r+=o.xtraceOutput,o.continueToNext)continue}let o=i.value?await O(e,i.value):``;if(a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:Z(``,`bash: ${a}: bad array subscript
857
+ `,1)};let s=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let a=await hb(e,t,s[1],s[2],o,i.append,n);if(a.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:a.error};if(a.continueToNext)continue}let c=await vb(e,t,a,o,i.append,n);if(c.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:c.error};r+=c.xtraceOutput,c.continueToNext}return{continueToNext:!1,xtraceOutput:r,tempAssignments:n}}async function ub(e,t,n,r,i,a){let o=``;if(/\[.+\]$/.test(n))return{continueToNext:!1,xtraceOutput:``,error:Z(``,`bash: ${n}: cannot assign list to array member
858
858
  `,1)};if(Pt(e,n)){let t=Ut(e,n);if(t===void 0||t===``)throw new ut(1,``,``);let r=Bt(e,n);if(r&&/^[a-zA-Z_][a-zA-Z0-9_]*\[@\]$/.test(r))return{continueToNext:!1,xtraceOutput:``,error:Z(``,`bash: ${n}: cannot assign list to array member
859
859
  `,1)}}if(_t(e,n)){if(t.name)return o+=`bash: ${n}: readonly variable
860
- `,{continueToNext:!0,xtraceOutput:o};let r=yt(e,n);if(r)return{continueToNext:!1,xtraceOutput:``,error:r}}let s=e.state.associativeArrays?.has(n),c=ub(r),l=()=>{let t=`${n}_`;for(let n of e.state.env.keys())n.startsWith(t)&&!n.includes(`__`)&&e.state.env.delete(n);e.state.env.delete(n)};if(s&&c?await db(e,t,n,r,i,l,e=>{o+=e}):c?await fb(e,n,r,i,l):await pb(e,n,r,i,l),t.name){a.set(n,e.state.env.get(n));let t=`(${r.map(e=>zt(e)).join(` `)})`;e.state.env.set(n,t)}return{continueToNext:!0,xtraceOutput:o}}function ub(e){return e.some(e=>{if(e.parts.length>=2){let t=e.parts[0],n=e.parts[1];if(t.type!==`Glob`||!t.pattern.startsWith(`[`))return!1;if(t.pattern===`[`&&(n.type===`DoubleQuoted`||n.type===`SingleQuoted`)){if(e.parts.length<3)return!1;let t=e.parts[2];return t.type===`Literal`?t.value.startsWith(`]=`)||t.value.startsWith(`]+=`):!1}return n.type===`Literal`?n.value.startsWith(`]`)?n.value.startsWith(`]=`)||n.value.startsWith(`]+=`):t.pattern.endsWith(`]`)?n.value.startsWith(`=`)||n.value.startsWith(`+=`):!1:!1}return!1})}async function db(e,t,n,r,i,a,o){let s=[];for(let t of r){let n=Xt(t);if(n){let{key:t,valueParts:r,append:i}=n,a;a=r.length>0?await O(e,{type:`Word`,parts:r}):``,a=iv(e,a),s.push({type:`keyed`,key:t,value:a,append:i})}else{let n=await O(e,t);s.push({type:`invalid`,expandedValue:n})}}i||a();for(let r of s)if(r.type===`keyed`)if(r.append){let t=e.state.env.get(`${n}_${r.key}`)??``;e.state.env.set(`${n}_${r.key}`,t+r.value)}else e.state.env.set(`${n}_${r.key}`,r.value);else o(`bash: line ${t.line??e.state.currentLine??1}: ${n}: ${r.expandedValue}: must use subscript when assigning associative array
861
- `)}async function fb(e,t,n,r,i){let a=[];for(let t of n){let n=Xt(t);if(n){let{key:t,valueParts:r,append:i}=n,o;o=r.length>0?await O(e,{type:`Word`,parts:r}):``,o=iv(e,o),a.push({type:`keyed`,indexExpr:t,value:o,append:i})}else{let n=await tn(e,t);a.push({type:`non-keyed`,values:n.values})}}r||i();let o=0;for(let n of a)if(n.type===`keyed`){let r;try{r=await Kt(e,Ft(new Zt,n.indexExpr).expression,!1)}catch{if(/^-?\d+$/.test(n.indexExpr))r=Number.parseInt(n.indexExpr,10);else{let t=e.state.env.get(n.indexExpr);r=t?Number.parseInt(t,10):0,Number.isNaN(r)&&(r=0)}}if(n.append){let i=e.state.env.get(`${t}_${r}`)??``;e.state.env.set(`${t}_${r}`,i+n.value)}else e.state.env.set(`${t}_${r}`,n.value);o=r+1}else for(let r of n.values)e.state.env.set(`${t}_${o++}`,r)}async function pb(e,t,n,r,i){let a=[];for(let t of n){let n=await tn(e,t);a.push(...n.values)}let o=0;if(r){let n=It(e,t);if(n.length>0)o=Math.max(...n.map(([e])=>typeof e==`number`?e:0))+1;else{let n=e.state.env.get(t);n!==void 0&&(e.state.env.set(`${t}_0`,n),e.state.env.delete(t),o=1)}}else i();for(let n=0;n<a.length;n++)e.state.env.set(`${t}_${o+n}`,a[n]);r||e.state.env.set(`${t}__length`,String(a.length))}async function mb(e,t,n,r,i,a,o){let s=n;if(Pt(e,n)){let t=Bt(e,n);if(t&&t!==n){if(t.includes(`[`))return{continueToNext:!1,xtraceOutput:``,error:Z(``,`bash: \`${t}': not a valid identifier
862
- `,1)};s=t}}if(_t(e,s)){if(t.name)return{continueToNext:!0,xtraceOutput:``};let n=yt(e,s);if(n)return{continueToNext:!1,xtraceOutput:``,error:n}}let c=e.state.associativeArrays?.has(s),l;if(c)l=await hb(e,s,r);else{let t=await gb(e,s,r);if(t.error)return{continueToNext:!1,xtraceOutput:``,error:t.error};l=`${s}_${t.index}`}let u=a?(e.state.env.get(l)||``)+i:i;if(t.name)o.set(l,e.state.env.get(l)),e.state.env.set(l,u);else{let t=d_(e,s);if(t!==void 0&&t===e.state.callDepth&&e.state.localScopes.length>0){let t=e.state.localScopes[e.state.localScopes.length-1];t.has(l)||t.set(l,e.state.env.get(l))}e.state.env.set(l,u)}return{continueToNext:!0,xtraceOutput:``}}async function hb(e,t,n){let r;if(n.startsWith(`'`)&&n.endsWith(`'`))r=n.slice(1,-1);else if(n.startsWith(`"`)&&n.endsWith(`"`)){let t=n.slice(1,-1);r=await O(e,new Zt().parseWordFromString(t,!0,!1))}else r=n.includes(`$`)?await O(e,new Zt().parseWordFromString(n,!1,!1)):n;return`${t}_${r}`}async function gb(e,t,n){let r=n;n.startsWith(`"`)&&n.endsWith(`"`)&&n.length>=2&&(r=n.slice(1,-1));let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{i=await Kt(e,Ft(new Zt,r).expression,!1)}catch(t){if(t instanceof it){let r=`bash: line ${e.state.currentLine}: ${n}: ${t.message}
860
+ `,{continueToNext:!0,xtraceOutput:o};let r=yt(e,n);if(r)return{continueToNext:!1,xtraceOutput:``,error:r}}let s=e.state.associativeArrays?.has(n),c=db(r),l=()=>{let t=`${n}_`;for(let n of e.state.env.keys())n.startsWith(t)&&!n.includes(`__`)&&e.state.env.delete(n);e.state.env.delete(n)};if(s&&c?await fb(e,t,n,r,i,l,e=>{o+=e}):c?await pb(e,n,r,i,l):await mb(e,n,r,i,l),t.name){a.set(n,e.state.env.get(n));let t=`(${r.map(e=>zt(e)).join(` `)})`;e.state.env.set(n,t)}return{continueToNext:!0,xtraceOutput:o}}function db(e){return e.some(e=>{if(e.parts.length>=2){let t=e.parts[0],n=e.parts[1];if(t.type!==`Glob`||!t.pattern.startsWith(`[`))return!1;if(t.pattern===`[`&&(n.type===`DoubleQuoted`||n.type===`SingleQuoted`)){if(e.parts.length<3)return!1;let t=e.parts[2];return t.type===`Literal`?t.value.startsWith(`]=`)||t.value.startsWith(`]+=`):!1}return n.type===`Literal`?n.value.startsWith(`]`)?n.value.startsWith(`]=`)||n.value.startsWith(`]+=`):t.pattern.endsWith(`]`)?n.value.startsWith(`=`)||n.value.startsWith(`+=`):!1:!1}return!1})}async function fb(e,t,n,r,i,a,o){let s=[];for(let t of r){let n=Xt(t);if(n){let{key:t,valueParts:r,append:i}=n,a;a=r.length>0?await O(e,{type:`Word`,parts:r}):``,a=av(e,a),s.push({type:`keyed`,key:t,value:a,append:i})}else{let n=await O(e,t);s.push({type:`invalid`,expandedValue:n})}}i||a();for(let r of s)if(r.type===`keyed`)if(r.append){let t=e.state.env.get(`${n}_${r.key}`)??``;e.state.env.set(`${n}_${r.key}`,t+r.value)}else e.state.env.set(`${n}_${r.key}`,r.value);else o(`bash: line ${t.line??e.state.currentLine??1}: ${n}: ${r.expandedValue}: must use subscript when assigning associative array
861
+ `)}async function pb(e,t,n,r,i){let a=[];for(let t of n){let n=Xt(t);if(n){let{key:t,valueParts:r,append:i}=n,o;o=r.length>0?await O(e,{type:`Word`,parts:r}):``,o=av(e,o),a.push({type:`keyed`,indexExpr:t,value:o,append:i})}else{let n=await tn(e,t);a.push({type:`non-keyed`,values:n.values})}}r||i();let o=0;for(let n of a)if(n.type===`keyed`){let r;try{r=await Kt(e,Ft(new Zt,n.indexExpr).expression,!1)}catch{if(/^-?\d+$/.test(n.indexExpr))r=Number.parseInt(n.indexExpr,10);else{let t=e.state.env.get(n.indexExpr);r=t?Number.parseInt(t,10):0,Number.isNaN(r)&&(r=0)}}if(n.append){let i=e.state.env.get(`${t}_${r}`)??``;e.state.env.set(`${t}_${r}`,i+n.value)}else e.state.env.set(`${t}_${r}`,n.value);o=r+1}else for(let r of n.values)e.state.env.set(`${t}_${o++}`,r)}async function mb(e,t,n,r,i){let a=[];for(let t of n){let n=await tn(e,t);a.push(...n.values)}let o=0;if(r){let n=It(e,t);if(n.length>0)o=Math.max(...n.map(([e])=>typeof e==`number`?e:0))+1;else{let n=e.state.env.get(t);n!==void 0&&(e.state.env.set(`${t}_0`,n),e.state.env.delete(t),o=1)}}else i();for(let n=0;n<a.length;n++)e.state.env.set(`${t}_${o+n}`,a[n]);r||e.state.env.set(`${t}__length`,String(a.length))}async function hb(e,t,n,r,i,a,o){let s=n;if(Pt(e,n)){let t=Bt(e,n);if(t&&t!==n){if(t.includes(`[`))return{continueToNext:!1,xtraceOutput:``,error:Z(``,`bash: \`${t}': not a valid identifier
862
+ `,1)};s=t}}if(_t(e,s)){if(t.name)return{continueToNext:!0,xtraceOutput:``};let n=yt(e,s);if(n)return{continueToNext:!1,xtraceOutput:``,error:n}}let c=e.state.associativeArrays?.has(s),l;if(c)l=await gb(e,s,r);else{let t=await _b(e,s,r);if(t.error)return{continueToNext:!1,xtraceOutput:``,error:t.error};l=`${s}_${t.index}`}let u=a?(e.state.env.get(l)||``)+i:i;if(t.name)o.set(l,e.state.env.get(l)),e.state.env.set(l,u);else{let t=f_(e,s);if(t!==void 0&&t===e.state.callDepth&&e.state.localScopes.length>0){let t=e.state.localScopes[e.state.localScopes.length-1];t.has(l)||t.set(l,e.state.env.get(l))}e.state.env.set(l,u)}return{continueToNext:!0,xtraceOutput:``}}async function gb(e,t,n){let r;if(n.startsWith(`'`)&&n.endsWith(`'`))r=n.slice(1,-1);else if(n.startsWith(`"`)&&n.endsWith(`"`)){let t=n.slice(1,-1);r=await O(e,new Zt().parseWordFromString(t,!0,!1))}else r=n.includes(`$`)?await O(e,new Zt().parseWordFromString(n,!1,!1)):n;return`${t}_${r}`}async function _b(e,t,n){let r=n;n.startsWith(`"`)&&n.endsWith(`"`)&&n.length>=2&&(r=n.slice(1,-1));let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{i=await Kt(e,Ft(new Zt,r).expression,!1)}catch(t){if(t instanceof it){let r=`bash: line ${e.state.currentLine}: ${n}: ${t.message}
863
863
  `;if(t.fatal)throw new ut(1,``,r);return{index:0,error:Z(``,r,1)}}let r=e.state.env.get(n);i=r?Number.parseInt(r,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let r=It(e,t);if(r.length===0){let r=e.state.currentLine;return{index:0,error:Z(``,`bash: line ${r}: ${t}[${n}]: bad array subscript
864
864
  `,1)}}if(i=Math.max(...r.map(([e])=>typeof e==`number`?e:0))+1+i,i<0){let r=e.state.currentLine;return{index:0,error:Z(``,`bash: line ${r}: ${t}[${n}]: bad array subscript
865
- `,1)}}}return{index:i}}async function _b(e,t,n,r,i,a){let o=``,s=n,c=null;if(Pt(e,n)){let t=St(e,n,r);if(t===void 0)return{continueToNext:!1,xtraceOutput:``,error:Z(``,`bash: ${n}: circular name reference
865
+ `,1)}}}return{index:i}}async function vb(e,t,n,r,i,a){let o=``,s=n,c=null;if(Pt(e,n)){let t=St(e,n,r);if(t===void 0)return{continueToNext:!1,xtraceOutput:``,error:Z(``,`bash: ${n}: circular name reference
866
866
  `,1)};if(t===null)return{continueToNext:!0,xtraceOutput:``};s=t;let i=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);i&&(c={arrayName:i[1],subscriptExpr:i[2]},s=i[1])}if(_t(e,s)){if(t.name)return o+=`bash: ${s}: readonly variable
867
- `,{continueToNext:!0,xtraceOutput:o};let n=yt(e,s);if(n)return{continueToNext:!1,xtraceOutput:``,error:n}}let l;if(vv(e,s))try{let t=new Zt;if(i){let n=Ft(t,`(${e.state.env.get(s)||`0`}) + (${r})`);l=String(await Kt(e,n.expression))}else{let n=Ft(t,r);l=String(await Kt(e,n.expression))}}catch{l=`0`}else{let{isArray:t}=await import(`./expansion-ENLSRCXJ-CE4BVBhZ.mjs`),n=t(e,s)?`${s}_0`:s;l=i?(e.state.env.get(n)||``)+r:r}l=Cv(e,s,l),o+=await ob(e,s,l);let u=s;if(c)u=await vb(e,c);else{let{isArray:t}=await import(`./expansion-ENLSRCXJ-CE4BVBhZ.mjs`);t(e,s)&&(u=`${s}_0`)}return t.name?(a.set(u,e.state.env.get(u)),e.state.env.set(u,l)):(e.state.env.set(u,l),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(s)),e.state.tempEnvBindings?.some(e=>e.has(s))&&(e.state.mutatedTempEnvVars=e.state.mutatedTempEnvVars||new Set,e.state.mutatedTempEnvVars.add(s))),{continueToNext:!1,xtraceOutput:o}}async function vb(e,t){let{arrayName:n,subscriptExpr:r}=t;if(e.state.associativeArrays?.has(n))return hb(e,n,r);let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{i=await Kt(e,Ft(new Zt,r).expression,!1)}catch{let t=e.state.env.get(r);i=t?Number.parseInt(t,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let t=It(e,n);t.length>0&&(i=Math.max(...t.map(e=>e[0]))+1+i)}return`${n}_${i}`}async function yb(e,t,n,r){let i=await E_(e,t.redirections);if(i)return i;let a=new Map(e.state.env),o=e.state.cwd,s={...e.state.options},c=new Map(e.state.functions),l=e.state.localScopes,u=e.state.localVarStack,d=e.state.localVarDepth,f=e.state.fullyUnsetLocals;if(e.state.localScopes=l.map(e=>new Map(e)),u){e.state.localVarStack=new Map;for(let[t,n]of u.entries())e.state.localVarStack.set(t,n.map(e=>({...e})))}d&&(e.state.localVarDepth=new Map(d)),f&&(e.state.fullyUnsetLocals=new Map(f));let p=e.state.loopDepth,m=e.state.parentHasLoopContext;e.state.parentHasLoopContext=p>0,e.state.loopDepth=0;let h=e.state.lastArg,g=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let _=e.state.groupStdin;n&&(e.state.groupStdin=n);let v=``,y=``,b=0,x=()=>{e.state.env=a,e.state.cwd=o,e.state.options=s,e.state.functions=c,e.state.localScopes=l,e.state.localVarStack=u,e.state.localVarDepth=d,e.state.fullyUnsetLocals=f,e.state.loopDepth=p,e.state.parentHasLoopContext=m,e.state.groupStdin=_,e.state.bashPid=g,e.state.lastArg=h};try{for(let e of t.body){let t=await r(e);v+=t.stdout,y+=t.stderr,b=t.exitCode}}catch(n){if(x(),n instanceof ot)throw n;return n instanceof pt||n instanceof tt||n instanceof ft?(v+=n.stdout,y+=n.stderr,D_(e,Z(v,y,0),t.redirections)):n instanceof ut||n instanceof st?(v+=n.stdout,y+=n.stderr,D_(e,Z(v,y,n.exitCode),t.redirections)):n instanceof dt?D_(e,Z(v+n.stdout,y+n.stderr,n.exitCode),t.redirections):D_(e,Z(v,`${y}${Dn(n)}
868
- `,1),t.redirections)}return x(),D_(e,Z(v,y,b),t.redirections)}async function bb(e,t,n,r){let i=``,a=``,o=0,s=await T_(e,t.redirections);if(s)return s;let c=n;for(let n of t.redirections)if((n.operator===`<<`||n.operator===`<<-`)&&n.target.type===`HereDoc`){let t=n.target,r=await O(e,t.content);t.stripTabs&&(r=r.split(`
867
+ `,{continueToNext:!0,xtraceOutput:o};let n=yt(e,s);if(n)return{continueToNext:!1,xtraceOutput:``,error:n}}let l;if(yv(e,s))try{let t=new Zt;if(i){let n=Ft(t,`(${e.state.env.get(s)||`0`}) + (${r})`);l=String(await Kt(e,n.expression))}else{let n=Ft(t,r);l=String(await Kt(e,n.expression))}}catch{l=`0`}else{let{isArray:t}=await import(`./expansion-ENLSRCXJ-CE4BVBhZ.mjs`),n=t(e,s)?`${s}_0`:s;l=i?(e.state.env.get(n)||``)+r:r}l=wv(e,s,l),o+=await sb(e,s,l);let u=s;if(c)u=await yb(e,c);else{let{isArray:t}=await import(`./expansion-ENLSRCXJ-CE4BVBhZ.mjs`);t(e,s)&&(u=`${s}_0`)}return t.name?(a.set(u,e.state.env.get(u)),e.state.env.set(u,l)):(e.state.env.set(u,l),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(s)),e.state.tempEnvBindings?.some(e=>e.has(s))&&(e.state.mutatedTempEnvVars=e.state.mutatedTempEnvVars||new Set,e.state.mutatedTempEnvVars.add(s))),{continueToNext:!1,xtraceOutput:o}}async function yb(e,t){let{arrayName:n,subscriptExpr:r}=t;if(e.state.associativeArrays?.has(n))return gb(e,n,r);let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{i=await Kt(e,Ft(new Zt,r).expression,!1)}catch{let t=e.state.env.get(r);i=t?Number.parseInt(t,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let t=It(e,n);t.length>0&&(i=Math.max(...t.map(e=>e[0]))+1+i)}return`${n}_${i}`}async function bb(e,t,n,r){let i=await D_(e,t.redirections);if(i)return i;let a=new Map(e.state.env),o=e.state.cwd,s={...e.state.options},c=new Map(e.state.functions),l=e.state.localScopes,u=e.state.localVarStack,d=e.state.localVarDepth,f=e.state.fullyUnsetLocals;if(e.state.localScopes=l.map(e=>new Map(e)),u){e.state.localVarStack=new Map;for(let[t,n]of u.entries())e.state.localVarStack.set(t,n.map(e=>({...e})))}d&&(e.state.localVarDepth=new Map(d)),f&&(e.state.fullyUnsetLocals=new Map(f));let p=e.state.loopDepth,m=e.state.parentHasLoopContext;e.state.parentHasLoopContext=p>0,e.state.loopDepth=0;let h=e.state.lastArg,g=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let _=e.state.groupStdin;n&&(e.state.groupStdin=n);let v=``,y=``,b=0,x=()=>{e.state.env=a,e.state.cwd=o,e.state.options=s,e.state.functions=c,e.state.localScopes=l,e.state.localVarStack=u,e.state.localVarDepth=d,e.state.fullyUnsetLocals=f,e.state.loopDepth=p,e.state.parentHasLoopContext=m,e.state.groupStdin=_,e.state.bashPid=g,e.state.lastArg=h};try{for(let e of t.body){let t=await r(e);v+=t.stdout,y+=t.stderr,b=t.exitCode}}catch(n){if(x(),n instanceof ot)throw n;return n instanceof pt||n instanceof tt||n instanceof ft?(v+=n.stdout,y+=n.stderr,O_(e,Z(v,y,0),t.redirections)):n instanceof ut||n instanceof st?(v+=n.stdout,y+=n.stderr,O_(e,Z(v,y,n.exitCode),t.redirections)):n instanceof dt?O_(e,Z(v+n.stdout,y+n.stderr,n.exitCode),t.redirections):O_(e,Z(v,`${y}${Dn(n)}
868
+ `,1),t.redirections)}return x(),O_(e,Z(v,y,b),t.redirections)}async function xb(e,t,n,r){let i=``,a=``,o=0,s=await E_(e,t.redirections);if(s)return s;let c=n;for(let n of t.redirections)if((n.operator===`<<`||n.operator===`<<-`)&&n.target.type===`HereDoc`){let t=n.target,r=await O(e,t.content);t.stripTabs&&(r=r.split(`
869
869
  `).map(e=>e.replace(/^\t+/,``)).join(`
870
- `));let i=n.fd??0;i===0?c=r:(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),bg(e),e.state.fileDescriptors.set(i,r))}else if(n.operator===`<<<`&&n.target.type===`Word`)c=`${await O(e,n.target)}
870
+ `));let i=n.fd??0;i===0?c=r:(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),xg(e),e.state.fileDescriptors.set(i,r))}else if(n.operator===`<<<`&&n.target.type===`Word`)c=`${await O(e,n.target)}
871
871
  `;else if(n.operator===`<`&&n.target.type===`Word`)try{let t=await O(e,n.target),r=e.fs.resolvePath(e.state.cwd,t);c=await e.fs.readFile(r)}catch{return Z(``,`bash: ${await O(e,n.target)}: No such file or directory
872
872
  `,1)}let l=e.state.groupStdin;c&&(e.state.groupStdin=c);try{for(let e of t.body){let t=await r(e);i+=t.stdout,a+=t.stderr,o=t.exitCode}}catch(t){if(e.state.groupStdin=l,t instanceof ot)throw t;if(ct(t)||t instanceof dt||t instanceof ut)throw t.prependOutput(i,a),t;return Z(i,`${a}${Dn(t)}
873
- `,1)}return e.state.groupStdin=l,D_(e,Z(i,a,o),t.redirections)}async function xb(e,t,n,r,i){let a;try{a=await e.fs.readFile(t)}catch{return X(`bash: ${t}: No such file or directory
873
+ `,1)}return e.state.groupStdin=l,O_(e,Z(i,a,o),t.redirections)}async function Sb(e,t,n,r,i){let a;try{a=await e.fs.readFile(t)}catch{return X(`bash: ${t}: No such file or directory
874
874
  `,127)}if(a.startsWith(`#!`)){let e=a.indexOf(`
875
875
  `);e!==-1&&(a=a.slice(e+1))}let o=new Map(e.state.env),s=e.state.cwd,c={...e.state.options},l=e.state.loopDepth,u=e.state.parentHasLoopContext,d=e.state.lastArg,f=e.state.bashPid,p=e.state.groupStdin,m=e.state.currentSource;e.state.parentHasLoopContext=l>0,e.state.loopDepth=0,e.state.bashPid=e.state.nextVirtualPid++,r&&(e.state.groupStdin=r),e.state.currentSource=t,e.state.env.set(`0`,t),e.state.env.set(`#`,String(n.length)),e.state.env.set(`@`,n.join(` `)),e.state.env.set(`*`,n.join(` `));for(let t=0;t<n.length&&t<9;t++)e.state.env.set(String(t+1),n[t]);for(let t=n.length+1;t<=9;t++)e.state.env.delete(String(t));let h=()=>{e.state.env=o,e.state.cwd=s,e.state.options=c,e.state.loopDepth=l,e.state.parentHasLoopContext=u,e.state.lastArg=d,e.state.bashPid=f,e.state.groupStdin=p,e.state.currentSource=m};try{let e=await i(new Zt().parse(a));return h(),e}catch(e){if(h(),e instanceof ut||e instanceof ot)throw e;if(e.name===`ParseException`)return X(`bash: ${t}: ${e.message}
876
- `);throw e}}var Sb=class{ctx;constructor(e,t){this.ctx={state:t,fs:e.fs,commands:e.commands,limits:e.limits,execFn:e.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:e.fetch,sleep:e.sleep,trace:e.trace,coverage:e.coverage,requireDefenseContext:e.requireDefenseContext??!1,jsBootstrapCode:e.jsBootstrapCode}}assertDefenseContext(e){if(!this.ctx.requireDefenseContext||vn.isInSandboxedContext())return;let t=`interpreter ${e} attempted outside defense context`;throw new _n(t,{timestamp:Date.now(),type:`missing_defense_context`,message:t,path:`DefenseInDepthBox.context`,stack:Error().stack,executionId:vn.getCurrentExecutionId()})}buildExportedEnv(){let e=this.ctx.state.exportedVars,t=this.ctx.state.tempExportedVars,n=new Set;if(e)for(let t of e)n.add(t);if(t)for(let e of t)n.add(e);if(n.size===0)return Object.create(null);let r=Object.create(null);for(let e of n){let t=this.ctx.state.env.get(e);t!==void 0&&(r[e]=t)}return r}async executeScript(e){this.assertDefenseContext(`execution`);let t=``,n=``,r=0,i=this.ctx.limits.maxOutputSize,a=(e,r)=>{t.length+n.length+e.length+r.length>i&&yg(`total output size exceeded (>${i} bytes), increase executionLimits.maxOutputSize`,`output_size`),t+=e,n+=r};for(let i of e.statements)try{let e=await this.executeStatement(i);a(e.stdout,e.stderr),r=e.exitCode,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r))}catch(e){if(e instanceof ut)throw e.prependOutput(t,n),e;if(e instanceof lt)return a(e.stdout,e.stderr),r=e.exitCode,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r)),{stdout:t,stderr:n,exitCode:r,env:Sn(this.ctx.state.env)};if(e instanceof ot)throw e;if(e instanceof dt)return a(e.stdout,e.stderr),r=e.exitCode,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r)),{stdout:t,stderr:n,exitCode:r,env:Sn(this.ctx.state.env)};if(e instanceof at||e instanceof ht)return a(e.stdout,e.stderr),r=1,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r)),{stdout:t,stderr:n,exitCode:r,env:Sn(this.ctx.state.env)};if(e instanceof it){a(e.stdout,e.stderr),r=1,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r));continue}if(e instanceof rt){a(e.stdout,e.stderr),r=1,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r));continue}if(e instanceof tt||e instanceof ft){if(this.ctx.state.loopDepth>0)throw e.prependOutput(t,n),e;a(e.stdout,e.stderr);continue}throw e instanceof st&&e.prependOutput(t,n),e}return{stdout:t,stderr:n,exitCode:r,env:Sn(this.ctx.state.env)}}async executeUserScript(e,t,n=``){return xb(this.ctx,e,t,n,e=>this.executeScript(e))}async executeStatement(e){if(this.assertDefenseContext(`statement`),this.ctx.state.signal?.aborted)throw new mt;if(this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&yg(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,`commands`),e.deferredError)throw new Jt(e.deferredError.message,e.line??1,1);if(this.ctx.state.options.noexec)return J;this.ctx.state.errexitSafe=!1;let t=``,n=``;this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&e.sourceText&&(n+=`${e.sourceText}
877
- `);let r=0,i=-1,a=!1;for(let o=0;o<e.pipelines.length;o++){let s=e.pipelines[o],c=o>0?e.operators[o-1]:null;if(c===`&&`&&r!==0||c===`||`&&r===0)continue;let l=await this.executePipeline(s);t+=l.stdout,n+=l.stderr,r=l.exitCode,i=o,a=s.negated,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r))}let o=i<e.pipelines.length-1,s=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=o||a||s,this.ctx.state.options.errexit&&r!==0&&i===e.pipelines.length-1&&!a&&!this.ctx.state.inCondition&&!s)throw new dt(r,t,n);return Z(t,n,r)}async executePipeline(e){return sb(this.ctx,e,(e,t)=>this.executeCommand(e,t))}async executeCommand(e,t){switch(this.assertDefenseContext(`command`),this.ctx.coverage?.hit(`bash:cmd:${e.type}`),e.type){case`SimpleCommand`:return this.executeSimpleCommand(e,t);case`If`:return qy(this.ctx,e);case`For`:return Jy(this.ctx,e);case`CStyleFor`:return Yy(this.ctx,e);case`While`:return Xy(this.ctx,e,t);case`Until`:return Zy(this.ctx,e);case`Case`:return Qy(this.ctx,e);case`Subshell`:return this.executeSubshell(e,t);case`Group`:return this.executeGroup(e,t);case`FunctionDef`:return O_(this.ctx,e);case`ArithmeticCommand`:return this.executeArithmeticCommand(e);case`ConditionalCommand`:return this.executeConditionalCommand(e);default:return J}}async executeSimpleCommand(e,t){try{return await this.executeSimpleCommandInner(e,t)}catch(e){if(e instanceof nt)return X(e.stderr);throw e}}async executeSimpleCommandInner(e,t){if(e.line!==void 0&&(this.ctx.state.currentLine=e.line),this.ctx.state.shoptOptions.expand_aliases&&e.name){let t=e,n=100;for(;n>0;){let e=this.expandAlias(t);if(e===t)break;t=e,n--}this.aliasExpansionStack.clear(),t!==e&&(e=t)}this.ctx.state.expansionStderr=``;let n=await cb(this.ctx,e);if(n.error)return n.error;let r=n.tempAssignments,i=n.xtraceOutput;if(!e.name){if(e.redirections.length>0){let t=await E_(this.ctx,e.redirections);if(t)return t;let n=Z(``,i,0);return D_(this.ctx,n,e.redirections)}this.ctx.state.lastArg=``;let t=(this.ctx.state.expansionStderr||``)+i;return this.ctx.state.expansionStderr=``,Z(``,t,this.ctx.state.lastExitCode)}let a=e.name&&$y(e.name,[`local`,`declare`,`typeset`,`export`,`readonly`]),o=Array.from(r.keys());if(o.length>0&&!a){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let e of o)this.ctx.state.tempExportedVars.add(e)}let s=await T_(this.ctx,e.redirections);if(s){for(let[e,t]of r)t===void 0?this.ctx.state.env.delete(e):this.ctx.state.env.set(e,t);return s}let c=-1;for(let n of e.redirections){if((n.operator===`<<`||n.operator===`<<-`)&&n.target.type===`HereDoc`){let e=n.target,r=await O(this.ctx,e.content);e.stripTabs&&(r=r.split(`
876
+ `);throw e}}var Cb=class{ctx;constructor(e,t){this.ctx={state:t,fs:e.fs,commands:e.commands,limits:e.limits,execFn:e.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:e.fetch,sleep:e.sleep,trace:e.trace,coverage:e.coverage,requireDefenseContext:e.requireDefenseContext??!1,jsBootstrapCode:e.jsBootstrapCode}}assertDefenseContext(e){if(!this.ctx.requireDefenseContext||vn.isInSandboxedContext())return;let t=`interpreter ${e} attempted outside defense context`;throw new _n(t,{timestamp:Date.now(),type:`missing_defense_context`,message:t,path:`DefenseInDepthBox.context`,stack:Error().stack,executionId:vn.getCurrentExecutionId()})}buildExportedEnv(){let e=this.ctx.state.exportedVars,t=this.ctx.state.tempExportedVars,n=new Set;if(e)for(let t of e)n.add(t);if(t)for(let e of t)n.add(e);if(n.size===0)return Object.create(null);let r=Object.create(null);for(let e of n){let t=this.ctx.state.env.get(e);t!==void 0&&(r[e]=t)}return r}async executeScript(e){this.assertDefenseContext(`execution`);let t=``,n=``,r=0,i=this.ctx.limits.maxOutputSize,a=(e,r)=>{t.length+n.length+e.length+r.length>i&&bg(`total output size exceeded (>${i} bytes), increase executionLimits.maxOutputSize`,`output_size`),t+=e,n+=r};for(let i of e.statements)try{let e=await this.executeStatement(i);a(e.stdout,e.stderr),r=e.exitCode,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r))}catch(e){if(e instanceof ut)throw e.prependOutput(t,n),e;if(e instanceof lt)return a(e.stdout,e.stderr),r=e.exitCode,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r)),{stdout:t,stderr:n,exitCode:r,env:Sn(this.ctx.state.env)};if(e instanceof ot)throw e;if(e instanceof dt)return a(e.stdout,e.stderr),r=e.exitCode,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r)),{stdout:t,stderr:n,exitCode:r,env:Sn(this.ctx.state.env)};if(e instanceof at||e instanceof ht)return a(e.stdout,e.stderr),r=1,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r)),{stdout:t,stderr:n,exitCode:r,env:Sn(this.ctx.state.env)};if(e instanceof it){a(e.stdout,e.stderr),r=1,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r));continue}if(e instanceof rt){a(e.stdout,e.stderr),r=1,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r));continue}if(e instanceof tt||e instanceof ft){if(this.ctx.state.loopDepth>0)throw e.prependOutput(t,n),e;a(e.stdout,e.stderr);continue}throw e instanceof st&&e.prependOutput(t,n),e}return{stdout:t,stderr:n,exitCode:r,env:Sn(this.ctx.state.env)}}async executeUserScript(e,t,n=``){return Sb(this.ctx,e,t,n,e=>this.executeScript(e))}async executeStatement(e){if(this.assertDefenseContext(`statement`),this.ctx.state.signal?.aborted)throw new mt;if(this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&bg(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,`commands`),e.deferredError)throw new Jt(e.deferredError.message,e.line??1,1);if(this.ctx.state.options.noexec)return J;this.ctx.state.errexitSafe=!1;let t=``,n=``;this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&e.sourceText&&(n+=`${e.sourceText}
877
+ `);let r=0,i=-1,a=!1;for(let o=0;o<e.pipelines.length;o++){let s=e.pipelines[o],c=o>0?e.operators[o-1]:null;if(c===`&&`&&r!==0||c===`||`&&r===0)continue;let l=await this.executePipeline(s);t+=l.stdout,n+=l.stderr,r=l.exitCode,i=o,a=s.negated,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r))}let o=i<e.pipelines.length-1,s=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=o||a||s,this.ctx.state.options.errexit&&r!==0&&i===e.pipelines.length-1&&!a&&!this.ctx.state.inCondition&&!s)throw new dt(r,t,n);return Z(t,n,r)}async executePipeline(e){return cb(this.ctx,e,(e,t)=>this.executeCommand(e,t))}async executeCommand(e,t){switch(this.assertDefenseContext(`command`),this.ctx.coverage?.hit(`bash:cmd:${e.type}`),e.type){case`SimpleCommand`:return this.executeSimpleCommand(e,t);case`If`:return Jy(this.ctx,e);case`For`:return Yy(this.ctx,e);case`CStyleFor`:return Xy(this.ctx,e);case`While`:return Zy(this.ctx,e,t);case`Until`:return Qy(this.ctx,e);case`Case`:return $y(this.ctx,e);case`Subshell`:return this.executeSubshell(e,t);case`Group`:return this.executeGroup(e,t);case`FunctionDef`:return k_(this.ctx,e);case`ArithmeticCommand`:return this.executeArithmeticCommand(e);case`ConditionalCommand`:return this.executeConditionalCommand(e);default:return J}}async executeSimpleCommand(e,t){try{return await this.executeSimpleCommandInner(e,t)}catch(e){if(e instanceof nt)return X(e.stderr);throw e}}async executeSimpleCommandInner(e,t){if(e.line!==void 0&&(this.ctx.state.currentLine=e.line),this.ctx.state.shoptOptions.expand_aliases&&e.name){let t=e,n=100;for(;n>0;){let e=this.expandAlias(t);if(e===t)break;t=e,n--}this.aliasExpansionStack.clear(),t!==e&&(e=t)}this.ctx.state.expansionStderr=``;let n=await lb(this.ctx,e);if(n.error)return n.error;let r=n.tempAssignments,i=n.xtraceOutput;if(!e.name){if(e.redirections.length>0){let t=await D_(this.ctx,e.redirections);if(t)return t;let n=Z(``,i,0);return O_(this.ctx,n,e.redirections)}this.ctx.state.lastArg=``;let t=(this.ctx.state.expansionStderr||``)+i;return this.ctx.state.expansionStderr=``,Z(``,t,this.ctx.state.lastExitCode)}let a=e.name&&eb(e.name,[`local`,`declare`,`typeset`,`export`,`readonly`]),o=Array.from(r.keys());if(o.length>0&&!a){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let e of o)this.ctx.state.tempExportedVars.add(e)}let s=await E_(this.ctx,e.redirections);if(s){for(let[e,t]of r)t===void 0?this.ctx.state.env.delete(e):this.ctx.state.env.set(e,t);return s}let c=-1;for(let n of e.redirections){if((n.operator===`<<`||n.operator===`<<-`)&&n.target.type===`HereDoc`){let e=n.target,r=await O(this.ctx,e.content);e.stripTabs&&(r=r.split(`
878
878
  `).map(e=>e.replace(/^\t+/,``)).join(`
879
- `));let i=n.fd??0;i===0?t=r:(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),bg(this.ctx),this.ctx.state.fileDescriptors.set(i,r));continue}if(n.operator===`<<<`&&n.target.type===`Word`){t=`${await O(this.ctx,n.target)}
879
+ `));let i=n.fd??0;i===0?t=r:(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),xg(this.ctx),this.ctx.state.fileDescriptors.set(i,r));continue}if(n.operator===`<<<`&&n.target.type===`Word`){t=`${await O(this.ctx,n.target)}
880
880
  `;continue}if(n.operator===`<`&&n.target.type===`Word`)try{let e=await O(this.ctx,n.target),r=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);t=await this.ctx.fs.readFile(r)}catch{let e=await O(this.ctx,n.target);for(let[e,t]of r)t===void 0?this.ctx.state.env.delete(e):this.ctx.state.env.set(e,t);return X(`bash: ${e}: No such file or directory
881
- `)}if(n.operator===`<&`&&n.target.type===`Word`){let e=await O(this.ctx,n.target),r=Number.parseInt(e,10);if(!Number.isNaN(r)&&this.ctx.state.fileDescriptors){let e=this.ctx.state.fileDescriptors.get(r);if(e!==void 0)if(e.startsWith(`__rw__:`)){let n=eb(e);n&&(t=n.content.slice(n.position),c=r)}else e.startsWith(`__file__:`)||e.startsWith(`__file_append__:`)||(t=e)}}}let l=await O(this.ctx,e.name),u=[],d=[];if($y(e.name,[`local`,`declare`,`typeset`,`export`,`readonly`])&&(l===`local`||l===`declare`||l===`typeset`||l===`export`||l===`readonly`))for(let t of e.args){let e=await mg(this.ctx,t);if(e)u.push(e),d.push(!0);else{let e=await hg(this.ctx,t);if(e!==null)u.push(e),d.push(!0);else{let e=await tn(this.ctx,t);for(let t of e.values)u.push(t),d.push(e.quoted)}}}else for(let t of e.args){let e=await tn(this.ctx,t);for(let t of e.values)u.push(t),d.push(e.quoted)}if(!l){if(e.name.parts.every(e=>e.type===`CommandSubstitution`||e.type===`ParameterExpansion`||e.type===`ArithmeticExpansion`)){if(u.length>0){let e=u.shift();return d.shift(),await this.runCommand(e,u,d,t,!1,!1,c)}return Z(``,``,this.ctx.state.lastExitCode)}return X(`bash: : command not found
882
- `,127)}if(l===`exec`&&(u.length===0||u[0]===`--`)){for(let t of e.redirections){if(t.target.type===`HereDoc`||t.fdVariable)continue;let e=await O(this.ctx,t.target),n=t.fd??(t.operator===`<`||t.operator===`<>`?0:1);switch(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),t.operator){case`>`:case`>|`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);await this.ctx.fs.writeFile(t,``,`utf8`),bg(this.ctx),this.ctx.state.fileDescriptors.set(n,`__file__:${t}`);break}case`>>`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);bg(this.ctx),this.ctx.state.fileDescriptors.set(n,`__file_append__:${t}`);break}case`<`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);try{let e=await this.ctx.fs.readFile(t);bg(this.ctx),this.ctx.state.fileDescriptors.set(n,e)}catch{return X(`bash: ${e}: No such file or directory
883
- `)}break}case`<>`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);try{let e=await this.ctx.fs.readFile(t);bg(this.ctx),this.ctx.state.fileDescriptors.set(n,`__rw__:${t.length}:${t}:0:${e}`)}catch{await this.ctx.fs.writeFile(t,``,`utf8`),bg(this.ctx),this.ctx.state.fileDescriptors.set(n,`__rw__:${t.length}:${t}:0:`)}break}case`>&`:if(e===`-`)this.ctx.state.fileDescriptors.delete(n);else if(e.endsWith(`-`)){let t=e.slice(0,-1),r=Number.parseInt(t,10);if(!Number.isNaN(r)){let e=this.ctx.state.fileDescriptors.get(r);e===void 0?this.ctx.state.fileDescriptors.set(n,`__dupout__:${r}`):this.ctx.state.fileDescriptors.set(n,e),this.ctx.state.fileDescriptors.delete(r)}}else{let t=Number.parseInt(e,10);Number.isNaN(t)||(bg(this.ctx),this.ctx.state.fileDescriptors.set(n,`__dupout__:${t}`))}break;case`<&`:if(e===`-`)this.ctx.state.fileDescriptors.delete(n);else if(e.endsWith(`-`)){let t=e.slice(0,-1),r=Number.parseInt(t,10);if(!Number.isNaN(r)){let e=this.ctx.state.fileDescriptors.get(r);e===void 0?this.ctx.state.fileDescriptors.set(n,`__dupin__:${r}`):this.ctx.state.fileDescriptors.set(n,e),this.ctx.state.fileDescriptors.delete(r)}}else{let t=Number.parseInt(e,10);Number.isNaN(t)||(bg(this.ctx),this.ctx.state.fileDescriptors.set(n,`__dupin__:${t}`))}break}}for(let[e,t]of r)t===void 0?this.ctx.state.env.delete(e):this.ctx.state.env.set(e,t);if(this.ctx.state.tempExportedVars)for(let e of r.keys())this.ctx.state.tempExportedVars.delete(e);return J}if(this.ctx.state.extraArgs){u.push(...this.ctx.state.extraArgs);for(let e=0;e<this.ctx.state.extraArgs.length;e++)d.push(!0);this.ctx.state.extraArgs=void 0}let f=await ab(this.ctx,l,u);r.size>0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(r)));let p,m=null;try{p=await this.runCommand(l,u,d,t,!1,!1,c)}catch(e){if(e instanceof tt||e instanceof ft)m=e,p=J;else throw e}let h=i+f;if(h&&(p={...p,stderr:h+p.stderr}),p=await D_(this.ctx,p,e.redirections),m)throw m;if(u.length>0){let e=u[u.length-1];if((l===`declare`||l===`local`||l===`typeset`)&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test(e)){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);t&&(e=t[1])}this.ctx.state.lastArg=e}else this.ctx.state.lastArg=l;let g=__(l)&&l!==`unset`&&l!==`eval`;if(!this.ctx.state.options.posix||!g)for(let[e,t]of r)this.ctx.state.fullyUnsetLocals?.has(e)||(t===void 0?this.ctx.state.env.delete(e):this.ctx.state.env.set(e,t));if(this.ctx.state.tempExportedVars)for(let e of r.keys())this.ctx.state.tempExportedVars.delete(e);return r.size>0&&this.ctx.state.tempEnvBindings&&this.ctx.state.tempEnvBindings.pop(),this.ctx.state.expansionStderr&&(p={...p,stderr:this.ctx.state.expansionStderr+p.stderr},this.ctx.state.expansionStderr=``),p}async runCommand(e,t,n,r,i=!1,a=!1,o=-1){let s={ctx:this.ctx,runCommand:(e,t,n,r,i,a,o)=>this.runCommand(e,t,n,r,i,a,o),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(e,t,n)=>this.executeUserScript(e,t,n)},c=await By(s,e,t,n,r,i,a,o);return c===null?Uy(s,e,t,r,a):c}aliasExpansionStack=new Set;expandAlias(e){return dg(this.ctx.state,e,this.aliasExpansionStack)}async findCommandInPath(e){return Oy(this.ctx,e)}async executeSubshell(e,t=``){return yb(this.ctx,e,t,e=>this.executeStatement(e))}async executeGroup(e,t=``){return bb(this.ctx,e,t,e=>this.executeStatement(e))}async executeArithmeticCommand(e){e.line!==void 0&&(this.ctx.state.currentLine=e.line);let t=await E_(this.ctx,e.redirections);if(t)return t;try{let t=vg(await Kt(this.ctx,e.expression.expression)!==0);return this.ctx.state.expansionStderr&&(t={...t,stderr:this.ctx.state.expansionStderr+t.stderr},this.ctx.state.expansionStderr=``),D_(this.ctx,t,e.redirections)}catch(t){let n=X(`bash: arithmetic expression: ${t.message}
884
- `);return D_(this.ctx,n,e.redirections)}}async executeConditionalCommand(e){e.line!==void 0&&(this.ctx.state.currentLine=e.line);let t=await E_(this.ctx,e.redirections);if(t)return t;try{let t=vg(await zg(this.ctx,e.expression));return this.ctx.state.expansionStderr&&(t={...t,stderr:this.ctx.state.expansionStderr+t.stderr},this.ctx.state.expansionStderr=``),D_(this.ctx,t,e.redirections)}catch(t){let n=t instanceof it?1:2,r=X(`bash: conditional expression: ${t.message}
885
- `,n);return D_(this.ctx,r,e.redirections)}}},Cb={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3,maxPythonTimeoutMs:1e4,maxJsTimeoutMs:1e4,maxGlobOperations:1e5,maxStringLength:10485760,maxArrayElements:1e5,maxHeredocSize:10485760,maxSubstitutionDepth:50,maxBraceExpansionResults:1e4,maxOutputSize:10485760,maxFileDescriptors:1024,maxSourceDepth:100};function wb(e){return e?{maxCallDepth:e.maxCallDepth??Cb.maxCallDepth,maxCommandCount:e.maxCommandCount??Cb.maxCommandCount,maxLoopIterations:e.maxLoopIterations??Cb.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??Cb.maxAwkIterations,maxSedIterations:e.maxSedIterations??Cb.maxSedIterations,maxJqIterations:e.maxJqIterations??Cb.maxJqIterations,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??Cb.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??Cb.maxPythonTimeoutMs,maxJsTimeoutMs:e.maxJsTimeoutMs??Cb.maxJsTimeoutMs,maxGlobOperations:e.maxGlobOperations??Cb.maxGlobOperations,maxStringLength:e.maxStringLength??Cb.maxStringLength,maxArrayElements:e.maxArrayElements??Cb.maxArrayElements,maxHeredocSize:e.maxHeredocSize??Cb.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??Cb.maxSubstitutionDepth,maxBraceExpansionResults:e.maxBraceExpansionResults??Cb.maxBraceExpansionResults,maxOutputSize:e.maxOutputSize??Cb.maxOutputSize,maxFileDescriptors:e.maxFileDescriptors??Cb.maxFileDescriptors,maxSourceDepth:e.maxSourceDepth??Cb.maxSourceDepth}:{...Cb}}function Tb(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function Eb(e){let t=Tb(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}function Db(e){if(e.includes(`\\`))return!0;let t=e.toLowerCase();return t.includes(`%2f`)||t.includes(`%5c`)}function Ob(e,t){return t===`/`||t===``?!0:t.endsWith(`/`)?e.startsWith(t):e===t||e.startsWith(`${t}/`)}function kb(e,t){let n=Tb(e);if(!n)return!1;let r=Eb(t);return!r||n.origin!==r.origin||r.pathPrefix!==`/`&&r.pathPrefix!==``&&Db(n.pathname)?!1:Ob(n.pathname,r.pathPrefix)}function Ab(e){return typeof e==`string`?e:e.url}function jb(e,t){return!t||t.length===0?!1:t.some(t=>kb(e,Ab(t)))}function Mb(e){let t=Nb(e);if(t===`localhost`||t.endsWith(`.localhost`))return!0;let n=Fb(t);if(n)return Lb(n);let r=Ib(t);return r?Rb(r):!1}function Nb(e){let t=e.trim().toLowerCase();return t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1):t}function Pb(e){if(!e)return null;let t=10,n=e;if(n.startsWith(`0x`)||n.startsWith(`0X`)?(t=16,n=n.slice(2)):n.length>1&&n.startsWith(`0`)&&(t=8),!n||t===16&&!/^[0-9a-fA-F]+$/.test(n)||t===10&&!/^\d+$/.test(n)||t===8&&!/^[0-7]+$/.test(n))return null;let r=Number.parseInt(n,t);return!Number.isFinite(r)||r<0?null:r}function Fb(e){let t=e.split(`.`);if(t.length===0||t.length>4)return null;let n=t.map(e=>Pb(e));if(n.some(e=>e===null))return null;let r=n;if(t.length===1){let e=r[0];return e>4294967295?null:[e>>>24&255,e>>>16&255,e>>>8&255,e&255]}if(t.length===2){let[e,t]=r;return e>255||t>16777215?null:[e,t>>>16&255,t>>>8&255,t&255]}if(t.length===3){let[e,t,n]=r;return e>255||t>255||n>65535?null:[e,t,n>>>8&255,n&255]}let[i,a,o,s]=r;return i>255||a>255||o>255||s>255?null:[i,a,o,s]}function Ib(e){let t=e,n=null;if(t.includes(`.`)){let e=t.lastIndexOf(`:`);if(e<0)return null;let r=Fb(t.slice(e+1));if(!r)return null;n=r,t=t.slice(0,e)}let r=t.includes(`::`)?t.split(`::`).length-1:0;if(r>1)return null;let[i,a]=t.split(`::`),o=i?i.split(`:`).filter(Boolean):[],s=a?a.split(`:`).filter(Boolean):[],c=e=>/^[0-9a-f]{1,4}$/i.test(e)?Number.parseInt(e,16):null,l=o.map(c),u=s.map(c);if(l.some(e=>e===null)||u.some(e=>e===null))return null;let d=n?2:0,f=l.length+u.length+d,p=0;if(r===1){if(p=8-f,p<0)return null}else if(f!==8)return null;let m=[...l,...Array(p).fill(0),...u];return n&&(m.push(n[0]<<8|n[1]),m.push(n[2]<<8|n[3])),m.length===8?m:null}function Lb(e){let[t,n]=e;return t===127||t===10||t===172&&n>=16&&n<=31||t===192&&n===168||t===169&&n===254||t===0||t===100&&n>=64&&n<=127||t===198&&(n===18||n===19)||t===192&&n===0&&e[2]===0||t===192&&n===0&&e[2]===2||t===198&&n===51&&e[2]===100||t===203&&n===0&&e[2]===113||t>=240}function Rb(e){return e.every(e=>e===0)||e.slice(0,7).every(e=>e===0)&&e[7]===1||(e[0]&65472)==65152||(e[0]&65024)==64512?!0:e[0]===0&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===65535?Lb([e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255]):e[0]===8193&&e[1]===3512?!0:e[0]===100&&e[1]===65435&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===0?Lb([e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255]):e[0]===100&&e[1]===65435&&e[2]===1?!0:e[0]===8194?Lb([e[1]>>>8&255,e[1]&255,e[2]>>>8&255,e[2]&255]):!1}function zb(e){let t=[];for(let n of e){if(typeof n!=`string`&&(typeof n!=`object`||!n||!(`url`in n)||typeof n.url!=`string`)){t.push(`Invalid allow-list entry: must be a string URL or an object with a "url" string property`);continue}let e=Ab(n);if(!Tb(e)){t.push(`Invalid URL in allow-list: "${e}" - must be a valid URL with scheme and host (e.g., "https://example.com")`);continue}let r=new URL(e);if(r.protocol!==`http:`&&r.protocol!==`https:`){t.push(`Only http and https URLs are allowed in allow-list: "${e}"`);continue}if(!r.hostname){t.push(`Allow-list entry must include a hostname: "${e}"`);continue}if(r.pathname!==`/`&&r.pathname!==``&&Db(r.pathname)){t.push(`Allow-list entry contains ambiguous path separators: "${e}"`);continue}(r.search||r.hash)&&t.push(`Query strings and fragments are ignored in allow-list entries: "${e}"`)}return t}var Bb=class extends Error{constructor(e,t){super(`Network access denied: ${t??`URL not in allow-list`}: ${e}`),this.name=`NetworkAccessDeniedError`}},Vb=class extends Error{constructor(e){super(`Too many redirects (max: ${e})`),this.name=`TooManyRedirectsError`}},Hb=class extends Error{constructor(e){super(`Redirect target not in allow-list: ${e}`),this.name=`RedirectNotAllowedError`}},Ub=class extends Error{constructor(e,t){super(`HTTP method '${e}' not allowed. Allowed methods: ${t.join(`, `)}`),this.name=`MethodNotAllowedError`}},Wb=class extends Error{constructor(e){super(`Response body too large (max: ${e} bytes)`),this.name=`ResponseTooLargeError`}};function Gb(e){return new Promise((t,n)=>{hr(e,{all:!0},(e,r)=>{e?n(e):t(r)})})}var Kb=20,qb=3e4,Jb=10485760,Yb=[`GET`,`HEAD`],Xb=new Set([`GET`,`HEAD`,`OPTIONS`]),Zb=new Set([301,302,303,307,308]);function Qb(e){let t=e.allowedUrlPrefixes??[];if(!e.dangerouslyAllowFullInternetAccess){let e=zb(t);if(e.length>0)throw Error(`Invalid network allow-list:
881
+ `)}if(n.operator===`<&`&&n.target.type===`Word`){let e=await O(this.ctx,n.target),r=Number.parseInt(e,10);if(!Number.isNaN(r)&&this.ctx.state.fileDescriptors){let e=this.ctx.state.fileDescriptors.get(r);if(e!==void 0)if(e.startsWith(`__rw__:`)){let n=tb(e);n&&(t=n.content.slice(n.position),c=r)}else e.startsWith(`__file__:`)||e.startsWith(`__file_append__:`)||(t=e)}}}let l=await O(this.ctx,e.name),u=[],d=[];if(eb(e.name,[`local`,`declare`,`typeset`,`export`,`readonly`])&&(l===`local`||l===`declare`||l===`typeset`||l===`export`||l===`readonly`))for(let t of e.args){let e=await hg(this.ctx,t);if(e)u.push(e),d.push(!0);else{let e=await gg(this.ctx,t);if(e!==null)u.push(e),d.push(!0);else{let e=await tn(this.ctx,t);for(let t of e.values)u.push(t),d.push(e.quoted)}}}else for(let t of e.args){let e=await tn(this.ctx,t);for(let t of e.values)u.push(t),d.push(e.quoted)}if(!l){if(e.name.parts.every(e=>e.type===`CommandSubstitution`||e.type===`ParameterExpansion`||e.type===`ArithmeticExpansion`)){if(u.length>0){let e=u.shift();return d.shift(),await this.runCommand(e,u,d,t,!1,!1,c)}return Z(``,``,this.ctx.state.lastExitCode)}return X(`bash: : command not found
882
+ `,127)}if(l===`exec`&&(u.length===0||u[0]===`--`)){for(let t of e.redirections){if(t.target.type===`HereDoc`||t.fdVariable)continue;let e=await O(this.ctx,t.target),n=t.fd??(t.operator===`<`||t.operator===`<>`?0:1);switch(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),t.operator){case`>`:case`>|`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);await this.ctx.fs.writeFile(t,``,`utf8`),xg(this.ctx),this.ctx.state.fileDescriptors.set(n,`__file__:${t}`);break}case`>>`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);xg(this.ctx),this.ctx.state.fileDescriptors.set(n,`__file_append__:${t}`);break}case`<`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);try{let e=await this.ctx.fs.readFile(t);xg(this.ctx),this.ctx.state.fileDescriptors.set(n,e)}catch{return X(`bash: ${e}: No such file or directory
883
+ `)}break}case`<>`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);try{let e=await this.ctx.fs.readFile(t);xg(this.ctx),this.ctx.state.fileDescriptors.set(n,`__rw__:${t.length}:${t}:0:${e}`)}catch{await this.ctx.fs.writeFile(t,``,`utf8`),xg(this.ctx),this.ctx.state.fileDescriptors.set(n,`__rw__:${t.length}:${t}:0:`)}break}case`>&`:if(e===`-`)this.ctx.state.fileDescriptors.delete(n);else if(e.endsWith(`-`)){let t=e.slice(0,-1),r=Number.parseInt(t,10);if(!Number.isNaN(r)){let e=this.ctx.state.fileDescriptors.get(r);e===void 0?this.ctx.state.fileDescriptors.set(n,`__dupout__:${r}`):this.ctx.state.fileDescriptors.set(n,e),this.ctx.state.fileDescriptors.delete(r)}}else{let t=Number.parseInt(e,10);Number.isNaN(t)||(xg(this.ctx),this.ctx.state.fileDescriptors.set(n,`__dupout__:${t}`))}break;case`<&`:if(e===`-`)this.ctx.state.fileDescriptors.delete(n);else if(e.endsWith(`-`)){let t=e.slice(0,-1),r=Number.parseInt(t,10);if(!Number.isNaN(r)){let e=this.ctx.state.fileDescriptors.get(r);e===void 0?this.ctx.state.fileDescriptors.set(n,`__dupin__:${r}`):this.ctx.state.fileDescriptors.set(n,e),this.ctx.state.fileDescriptors.delete(r)}}else{let t=Number.parseInt(e,10);Number.isNaN(t)||(xg(this.ctx),this.ctx.state.fileDescriptors.set(n,`__dupin__:${t}`))}break}}for(let[e,t]of r)t===void 0?this.ctx.state.env.delete(e):this.ctx.state.env.set(e,t);if(this.ctx.state.tempExportedVars)for(let e of r.keys())this.ctx.state.tempExportedVars.delete(e);return J}if(this.ctx.state.extraArgs){u.push(...this.ctx.state.extraArgs);for(let e=0;e<this.ctx.state.extraArgs.length;e++)d.push(!0);this.ctx.state.extraArgs=void 0}let f=await ob(this.ctx,l,u);r.size>0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(r)));let p,m=null;try{p=await this.runCommand(l,u,d,t,!1,!1,c)}catch(e){if(e instanceof tt||e instanceof ft)m=e,p=J;else throw e}let h=i+f;if(h&&(p={...p,stderr:h+p.stderr}),p=await O_(this.ctx,p,e.redirections),m)throw m;if(u.length>0){let e=u[u.length-1];if((l===`declare`||l===`local`||l===`typeset`)&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test(e)){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);t&&(e=t[1])}this.ctx.state.lastArg=e}else this.ctx.state.lastArg=l;let g=v_(l)&&l!==`unset`&&l!==`eval`;if(!this.ctx.state.options.posix||!g)for(let[e,t]of r)this.ctx.state.fullyUnsetLocals?.has(e)||(t===void 0?this.ctx.state.env.delete(e):this.ctx.state.env.set(e,t));if(this.ctx.state.tempExportedVars)for(let e of r.keys())this.ctx.state.tempExportedVars.delete(e);return r.size>0&&this.ctx.state.tempEnvBindings&&this.ctx.state.tempEnvBindings.pop(),this.ctx.state.expansionStderr&&(p={...p,stderr:this.ctx.state.expansionStderr+p.stderr},this.ctx.state.expansionStderr=``),p}async runCommand(e,t,n,r,i=!1,a=!1,o=-1){let s={ctx:this.ctx,runCommand:(e,t,n,r,i,a,o)=>this.runCommand(e,t,n,r,i,a,o),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(e,t,n)=>this.executeUserScript(e,t,n)},c=await Vy(s,e,t,n,r,i,a,o);return c===null?Wy(s,e,t,r,a):c}aliasExpansionStack=new Set;expandAlias(e){return fg(this.ctx.state,e,this.aliasExpansionStack)}async findCommandInPath(e){return ky(this.ctx,e)}async executeSubshell(e,t=``){return bb(this.ctx,e,t,e=>this.executeStatement(e))}async executeGroup(e,t=``){return xb(this.ctx,e,t,e=>this.executeStatement(e))}async executeArithmeticCommand(e){e.line!==void 0&&(this.ctx.state.currentLine=e.line);let t=await D_(this.ctx,e.redirections);if(t)return t;try{let t=yg(await Kt(this.ctx,e.expression.expression)!==0);return this.ctx.state.expansionStderr&&(t={...t,stderr:this.ctx.state.expansionStderr+t.stderr},this.ctx.state.expansionStderr=``),O_(this.ctx,t,e.redirections)}catch(t){let n=X(`bash: arithmetic expression: ${t.message}
884
+ `);return O_(this.ctx,n,e.redirections)}}async executeConditionalCommand(e){e.line!==void 0&&(this.ctx.state.currentLine=e.line);let t=await D_(this.ctx,e.redirections);if(t)return t;try{let t=yg(await Bg(this.ctx,e.expression));return this.ctx.state.expansionStderr&&(t={...t,stderr:this.ctx.state.expansionStderr+t.stderr},this.ctx.state.expansionStderr=``),O_(this.ctx,t,e.redirections)}catch(t){let n=t instanceof it?1:2,r=X(`bash: conditional expression: ${t.message}
885
+ `,n);return O_(this.ctx,r,e.redirections)}}},wb={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3,maxPythonTimeoutMs:1e4,maxJsTimeoutMs:1e4,maxGlobOperations:1e5,maxStringLength:10485760,maxArrayElements:1e5,maxHeredocSize:10485760,maxSubstitutionDepth:50,maxBraceExpansionResults:1e4,maxOutputSize:10485760,maxFileDescriptors:1024,maxSourceDepth:100};function Tb(e){return e?{maxCallDepth:e.maxCallDepth??wb.maxCallDepth,maxCommandCount:e.maxCommandCount??wb.maxCommandCount,maxLoopIterations:e.maxLoopIterations??wb.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??wb.maxAwkIterations,maxSedIterations:e.maxSedIterations??wb.maxSedIterations,maxJqIterations:e.maxJqIterations??wb.maxJqIterations,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??wb.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??wb.maxPythonTimeoutMs,maxJsTimeoutMs:e.maxJsTimeoutMs??wb.maxJsTimeoutMs,maxGlobOperations:e.maxGlobOperations??wb.maxGlobOperations,maxStringLength:e.maxStringLength??wb.maxStringLength,maxArrayElements:e.maxArrayElements??wb.maxArrayElements,maxHeredocSize:e.maxHeredocSize??wb.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??wb.maxSubstitutionDepth,maxBraceExpansionResults:e.maxBraceExpansionResults??wb.maxBraceExpansionResults,maxOutputSize:e.maxOutputSize??wb.maxOutputSize,maxFileDescriptors:e.maxFileDescriptors??wb.maxFileDescriptors,maxSourceDepth:e.maxSourceDepth??wb.maxSourceDepth}:{...wb}}function Eb(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function Db(e){let t=Eb(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}function Ob(e){if(e.includes(`\\`))return!0;let t=e.toLowerCase();return t.includes(`%2f`)||t.includes(`%5c`)}function kb(e,t){return t===`/`||t===``?!0:t.endsWith(`/`)?e.startsWith(t):e===t||e.startsWith(`${t}/`)}function Ab(e,t){let n=Eb(e);if(!n)return!1;let r=Db(t);return!r||n.origin!==r.origin||r.pathPrefix!==`/`&&r.pathPrefix!==``&&Ob(n.pathname)?!1:kb(n.pathname,r.pathPrefix)}function jb(e){return typeof e==`string`?e:e.url}function Mb(e,t){return!t||t.length===0?!1:t.some(t=>Ab(e,jb(t)))}function Nb(e){let t=Pb(e);if(t===`localhost`||t.endsWith(`.localhost`))return!0;let n=Ib(t);if(n)return Rb(n);let r=Lb(t);return r?zb(r):!1}function Pb(e){let t=e.trim().toLowerCase();return t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1):t}function Fb(e){if(!e)return null;let t=10,n=e;if(n.startsWith(`0x`)||n.startsWith(`0X`)?(t=16,n=n.slice(2)):n.length>1&&n.startsWith(`0`)&&(t=8),!n||t===16&&!/^[0-9a-fA-F]+$/.test(n)||t===10&&!/^\d+$/.test(n)||t===8&&!/^[0-7]+$/.test(n))return null;let r=Number.parseInt(n,t);return!Number.isFinite(r)||r<0?null:r}function Ib(e){let t=e.split(`.`);if(t.length===0||t.length>4)return null;let n=t.map(e=>Fb(e));if(n.some(e=>e===null))return null;let r=n;if(t.length===1){let e=r[0];return e>4294967295?null:[e>>>24&255,e>>>16&255,e>>>8&255,e&255]}if(t.length===2){let[e,t]=r;return e>255||t>16777215?null:[e,t>>>16&255,t>>>8&255,t&255]}if(t.length===3){let[e,t,n]=r;return e>255||t>255||n>65535?null:[e,t,n>>>8&255,n&255]}let[i,a,o,s]=r;return i>255||a>255||o>255||s>255?null:[i,a,o,s]}function Lb(e){let t=e,n=null;if(t.includes(`.`)){let e=t.lastIndexOf(`:`);if(e<0)return null;let r=Ib(t.slice(e+1));if(!r)return null;n=r,t=t.slice(0,e)}let r=t.includes(`::`)?t.split(`::`).length-1:0;if(r>1)return null;let[i,a]=t.split(`::`),o=i?i.split(`:`).filter(Boolean):[],s=a?a.split(`:`).filter(Boolean):[],c=e=>/^[0-9a-f]{1,4}$/i.test(e)?Number.parseInt(e,16):null,l=o.map(c),u=s.map(c);if(l.some(e=>e===null)||u.some(e=>e===null))return null;let d=n?2:0,f=l.length+u.length+d,p=0;if(r===1){if(p=8-f,p<0)return null}else if(f!==8)return null;let m=[...l,...Array(p).fill(0),...u];return n&&(m.push(n[0]<<8|n[1]),m.push(n[2]<<8|n[3])),m.length===8?m:null}function Rb(e){let[t,n]=e;return t===127||t===10||t===172&&n>=16&&n<=31||t===192&&n===168||t===169&&n===254||t===0||t===100&&n>=64&&n<=127||t===198&&(n===18||n===19)||t===192&&n===0&&e[2]===0||t===192&&n===0&&e[2]===2||t===198&&n===51&&e[2]===100||t===203&&n===0&&e[2]===113||t>=240}function zb(e){return e.every(e=>e===0)||e.slice(0,7).every(e=>e===0)&&e[7]===1||(e[0]&65472)==65152||(e[0]&65024)==64512?!0:e[0]===0&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===65535?Rb([e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255]):e[0]===8193&&e[1]===3512?!0:e[0]===100&&e[1]===65435&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===0?Rb([e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255]):e[0]===100&&e[1]===65435&&e[2]===1?!0:e[0]===8194?Rb([e[1]>>>8&255,e[1]&255,e[2]>>>8&255,e[2]&255]):!1}function Bb(e){let t=[];for(let n of e){if(typeof n!=`string`&&(typeof n!=`object`||!n||!(`url`in n)||typeof n.url!=`string`)){t.push(`Invalid allow-list entry: must be a string URL or an object with a "url" string property`);continue}let e=jb(n);if(!Eb(e)){t.push(`Invalid URL in allow-list: "${e}" - must be a valid URL with scheme and host (e.g., "https://example.com")`);continue}let r=new URL(e);if(r.protocol!==`http:`&&r.protocol!==`https:`){t.push(`Only http and https URLs are allowed in allow-list: "${e}"`);continue}if(!r.hostname){t.push(`Allow-list entry must include a hostname: "${e}"`);continue}if(r.pathname!==`/`&&r.pathname!==``&&Ob(r.pathname)){t.push(`Allow-list entry contains ambiguous path separators: "${e}"`);continue}(r.search||r.hash)&&t.push(`Query strings and fragments are ignored in allow-list entries: "${e}"`)}return t}var Vb=class extends Error{constructor(e,t){super(`Network access denied: ${t??`URL not in allow-list`}: ${e}`),this.name=`NetworkAccessDeniedError`}},Hb=class extends Error{constructor(e){super(`Too many redirects (max: ${e})`),this.name=`TooManyRedirectsError`}},Ub=class extends Error{constructor(e){super(`Redirect target not in allow-list: ${e}`),this.name=`RedirectNotAllowedError`}},Wb=class extends Error{constructor(e,t){super(`HTTP method '${e}' not allowed. Allowed methods: ${t.join(`, `)}`),this.name=`MethodNotAllowedError`}},Gb=class extends Error{constructor(e){super(`Response body too large (max: ${e} bytes)`),this.name=`ResponseTooLargeError`}};function Kb(e){return new Promise((t,n)=>{hr(e,{all:!0},(e,r)=>{e?n(e):t(r)})})}var qb=20,Jb=3e4,Yb=10485760,Xb=[`GET`,`HEAD`],Zb=new Set([`GET`,`HEAD`,`OPTIONS`]),Qb=new Set([301,302,303,307,308]);function $b(e){let t=e.allowedUrlPrefixes??[];if(!e.dangerouslyAllowFullInternetAccess){let e=Bb(t);if(e.length>0)throw Error(`Invalid network allow-list:
886
886
  ${e.join(`
887
- `)}`)}let n=[];for(let e of t)typeof e==`object`&&e.transform&&e.transform.length>0&&n.push(e);function r(e){if(n.length===0)return null;let t=null;for(let r of n)if(kb(e,r.url)&&r.transform){t||=new Headers;for(let e of r.transform)for(let[n,r]of Object.entries(e.headers))t.set(n,r)}return t}let i=e.maxRedirects??Kb,a=e.timeoutMs??qb,o=e.maxResponseSize??Jb,s=e.dangerouslyAllowFullInternetAccess?[`GET`,`HEAD`,`POST`,`PUT`,`DELETE`,`PATCH`,`OPTIONS`]:e.allowedMethods??Yb,c=e.denyPrivateRanges??(typeof process<`u`&&process.env?.NODE_ENV===`production`),l=e._dnsResolve??Gb;async function u(n){if(!e.dangerouslyAllowFullInternetAccess&&!jb(n,t))throw new Bb(n);if(c)try{let e=new URL(n);if(Mb(e.hostname))throw new Bb(n,`private/loopback IP address blocked`);let t=e.hostname;if(/[a-zA-Z]/.test(t))try{let e=await l(t);for(let{address:t}of e)if(Mb(t))throw new Bb(n,`hostname resolves to private/loopback IP address`)}catch(e){if(e instanceof Bb)throw e;let t=e?.code;if(!(t===`ENOTFOUND`||t===`ENODATA`))throw new Bb(n,`DNS resolution failed for private IP check`)}}catch(e){if(e instanceof Bb)throw e}}function d(t){if(e.dangerouslyAllowFullInternetAccess)return;let n=t.toUpperCase();if(!s.includes(n))throw new Ub(n,s)}async function f(e,t={}){let n=t.method?.toUpperCase()??`GET`;await u(e),d(n);let s=e,c=0,l=t.followRedirects??!0,f=t.timeoutMs===void 0?a:Math.min(t.timeoutMs,a);for(;;){let e=new AbortController,a=bn(()=>e.abort(),f);try{let a=await vn.runTrustedAsync(()=>{let i=r(s),a={method:n,headers:$b(t.headers,i),signal:e.signal,redirect:`manual`};return t.body&&!Xb.has(n)&&(a.body=t.body),fetch(s,a)});if(Zb.has(a.status)&&l){let e=a.headers.get(`location`);if(!e)return await ex(a,s,o);let t=new URL(e,s).href;try{await u(t)}catch{throw new Hb(t)}if(c++,c>i)throw new Vb(i);s=t;continue}return await ex(a,s,o)}finally{yn(a)}}}return f}function $b(e,t){if(!e&&!t)return;if(!t)return e;let n=(e instanceof Headers,new Headers(e));for(let[e,r]of t)n.set(e,r);return n}async function ex(e,t,n){let r=Object.create(null);if(e.headers.forEach((e,t)=>{r[t.toLowerCase()]=e}),n>0){let t=e.headers.get(`content-length`);if(t){let e=parseInt(t,10);if(!Number.isNaN(e)&&e>n)throw new Wb(n)}}let i;if(n>0&&e.body){let t=e.body.getReader(),r=[],a=0;for(;;){let{done:e,value:i}=await t.read();if(e)break;if(i){if(a+=i.byteLength,a>n)throw t.cancel(),new Wb(n);r.push(i)}}i=new Uint8Array(a);let o=0;for(let e of r)i.set(e,o),o+=e.byteLength}else{let t=await e.arrayBuffer();if(n>0&&t.byteLength>n)throw new Wb(n);i=new Uint8Array(t)}return{status:e.status,statusText:e.statusText,headers:r,body:i,url:t}}function tx(e){return nx(e)}function nx(e){return e.statements.map(rx).join(`
888
- `)}function rx(e){let t=[];for(let n=0;n<e.pipelines.length;n++)t.push(ix(e.pipelines[n])),n<e.operators.length&&t.push(e.operators[n]);let n=t.join(` `);return e.background&&(n+=` &`),n}function ix(e){let t=[];e.timed&&t.push(e.timePosix?`time -p`:`time`),e.negated&&t.push(`!`);let n=[];for(let t=0;t<e.commands.length;t++)if(n.push(ax(e.commands[t])),t<e.commands.length-1){let r=e.pipeStderr?.[t];n.push(r?`|&`:`|`)}return(t.length>0?`${t.join(` `)} `:``)+n.join(` `)}function ax(e){switch(e.type){case`SimpleCommand`:return ox(e);case`If`:return Cx(e);case`For`:return wx(e);case`CStyleFor`:return Tx(e);case`While`:return Ex(e);case`Until`:return Dx(e);case`Case`:return Ox(e);case`Subshell`:return Ax(e);case`Group`:return jx(e);case`ArithmeticCommand`:return Mx(e);case`ConditionalCommand`:return Nx(e);case`FunctionDef`:return Px(e);default:throw Error(`Unsupported command type: ${e.type}`)}}function ox(e){let t=[];for(let n of e.assignments)t.push(sx(n));e.name&&t.push(cx(e.name));for(let n of e.args)t.push(cx(n));for(let n of e.redirections)t.push(bx(n));return t.join(` `)}function sx(e){let t=e.append?`+=`:`=`;if(e.array){let n=e.array.map(cx).join(` `);return`${e.name}${t}(${n})`}return e.value?`${e.name}${t}${cx(e.value)}`:`${e.name}${t}`}function cx(e){return e.parts.map(e=>ux(e,!1)).join(``)}function lx(e){return e.parts.map(e=>ux(e,!0)).join(``)}function ux(e,t){switch(e.type){case`Literal`:return t?fx(e.value):dx(e.value);case`SingleQuoted`:return`'${e.value}'`;case`DoubleQuoted`:return`"${e.parts.map(e=>ux(e,!0)).join(``)}"`;case`Escaped`:return`\\${e.value}`;case`ParameterExpansion`:return hx(e);case`CommandSubstitution`:return e.legacy?`\`${nx(e.body)}\``:`$(${nx(e.body)})`;case`ArithmeticExpansion`:return`$((${$(e.expression.expression)}))`;case`ProcessSubstitution`:return e.direction===`input`?`<(${nx(e.body)})`:`>(${nx(e.body)})`;case`BraceExpansion`:return vx(e);case`TildeExpansion`:return e.user===null?`~`:`~${e.user}`;case`Glob`:return e.pattern;default:throw Error(`Unsupported word part type: ${e.type}`)}}function dx(e){return e.replace(/[\s\\'"`!|&;()<>{}[\]*?~#]/g,`\\$&`)}function fx(e){return e.replace(/[$`"\\]/g,`\\$&`)}function px(e,t){return e.parts.map(e=>mx(e,t)).join(``)}function mx(e,t){switch(e.type){case`Literal`:return t?e.value:e.value.replace(/[$`]/g,`\\$&`);case`Escaped`:return`\\${e.value}`;case`ParameterExpansion`:return hx(e);case`CommandSubstitution`:return e.legacy?`\`${nx(e.body)}\``:`$(${nx(e.body)})`;case`ArithmeticExpansion`:return`$((${$(e.expression.expression)}))`;default:return ux(e,!1)}}function hx(e){return e.operation?`\${${_x(e.parameter,e.operation)}}`:gx(e.parameter)?`\${${e.parameter}}`:`$${e.parameter}`}function gx(e){return!(/^[?#@*$!\-0-9]$/.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e))}function _x(e,t){switch(t.type){case`Length`:return`#${e}`;case`LengthSliceError`:return`#${e}:`;case`BadSubstitution`:return t.text;case`DefaultValue`:return`${e}${t.checkEmpty?`:`:``}-${lx(t.word)}`;case`AssignDefault`:return`${e}${t.checkEmpty?`:`:``}=${lx(t.word)}`;case`ErrorIfUnset`:return`${e}${t.checkEmpty?`:`:``}?${t.word?lx(t.word):``}`;case`UseAlternative`:return`${e}${t.checkEmpty?`:`:``}+${lx(t.word)}`;case`Substring`:{let n=$(t.offset.expression);return t.length?`${e}:${n}:${$(t.length.expression)}`:`${e}:${n}`}case`PatternRemoval`:{let n=t.side===`prefix`?`#`:`%`;return`${e}${t.greedy?`${n}${n}`:n}${lx(t.pattern)}`}case`PatternReplacement`:{let n=`/`;t.all?n=`//`:t.anchor===`start`?n=`/#`:t.anchor===`end`&&(n=`/%`);let r=t.replacement?`/${lx(t.replacement)}`:``;return`${e}${n}${lx(t.pattern)}${r}`}case`CaseModification`:{let n=t.direction===`upper`?`^`:`,`;return`${e}${t.all?`${n}${n}`:n}${t.pattern?lx(t.pattern):``}`}case`Transform`:return`${e}@${t.operator}`;case`Indirection`:return t.innerOp?`!${_x(e,t.innerOp)}`:`!${e}`;case`ArrayKeys`:return`!${t.array}[${t.star?`*`:`@`}]`;case`VarNamePrefix`:return`!${t.prefix}${t.star?`*`:`@`}`;default:throw Error(`Unsupported parameter operation type: ${t.type}`)}}function vx(e){return`{${e.items.map(yx).join(`,`)}}`}function yx(e){if(e.type===`Word`)return cx(e.word);let t=e.startStr??String(e.start),n=e.endStr??String(e.end);return e.step===void 0?`${t}..${n}`:`${t}..${n}..${e.step}`}function bx(e){let t=e.fdVariable?`{${e.fdVariable}}`:e.fd===null?``:String(e.fd);if(e.operator===`<<`||e.operator===`<<-`){let n=e.target,r=n.quoted?`'${n.delimiter}'`:n.delimiter,i=px(n.content,n.quoted);return`${t}${e.operator}${r}
889
- ${i}${n.delimiter}`}return e.operator===`<<<`?`${t}<<< ${cx(e.target)}`:e.operator===`&>`||e.operator===`&>>`?`${e.operator} ${cx(e.target)}`:`${t}${e.operator} ${cx(e.target)}`}function xx(e){return e.length===0?``:` ${e.map(bx).join(` `)}`}function Sx(e){return e.map(rx).join(`
890
- `)}function Cx(e){let t=[];for(let n=0;n<e.clauses.length;n++){let r=e.clauses[n],i=n===0?`if`:`elif`;t.push(`${i} ${Sx(r.condition)}; then
891
- ${Sx(r.body)}`)}return e.elseBody&&t.push(`else
892
- ${Sx(e.elseBody)}`),`${t.join(`
887
+ `)}`)}let n=[];for(let e of t)typeof e==`object`&&e.transform&&e.transform.length>0&&n.push(e);function r(e){if(n.length===0)return null;let t=null;for(let r of n)if(Ab(e,r.url)&&r.transform){t||=new Headers;for(let e of r.transform)for(let[n,r]of Object.entries(e.headers))t.set(n,r)}return t}let i=e.maxRedirects??qb,a=e.timeoutMs??Jb,o=e.maxResponseSize??Yb,s=e.dangerouslyAllowFullInternetAccess?[`GET`,`HEAD`,`POST`,`PUT`,`DELETE`,`PATCH`,`OPTIONS`]:e.allowedMethods??Xb,c=e.denyPrivateRanges??(typeof process<`u`&&process.env?.NODE_ENV===`production`),l=e._dnsResolve??Kb;async function u(n){if(!e.dangerouslyAllowFullInternetAccess&&!Mb(n,t))throw new Vb(n);if(c)try{let e=new URL(n);if(Nb(e.hostname))throw new Vb(n,`private/loopback IP address blocked`);let t=e.hostname;if(/[a-zA-Z]/.test(t))try{let e=await l(t);for(let{address:t}of e)if(Nb(t))throw new Vb(n,`hostname resolves to private/loopback IP address`)}catch(e){if(e instanceof Vb)throw e;let t=e?.code;if(!(t===`ENOTFOUND`||t===`ENODATA`))throw new Vb(n,`DNS resolution failed for private IP check`)}}catch(e){if(e instanceof Vb)throw e}}function d(t){if(e.dangerouslyAllowFullInternetAccess)return;let n=t.toUpperCase();if(!s.includes(n))throw new Wb(n,s)}async function f(e,t={}){let n=t.method?.toUpperCase()??`GET`;await u(e),d(n);let s=e,c=0,l=t.followRedirects??!0,f=t.timeoutMs===void 0?a:Math.min(t.timeoutMs,a);for(;;){let e=new AbortController,a=bn(()=>e.abort(),f);try{let a=await vn.runTrustedAsync(()=>{let i=r(s),a={method:n,headers:ex(t.headers,i),signal:e.signal,redirect:`manual`};return t.body&&!Zb.has(n)&&(a.body=t.body),fetch(s,a)});if(Qb.has(a.status)&&l){let e=a.headers.get(`location`);if(!e)return await tx(a,s,o);let t=new URL(e,s).href;try{await u(t)}catch{throw new Ub(t)}if(c++,c>i)throw new Hb(i);s=t;continue}return await tx(a,s,o)}finally{yn(a)}}}return f}function ex(e,t){if(!e&&!t)return;if(!t)return e;let n=(e instanceof Headers,new Headers(e));for(let[e,r]of t)n.set(e,r);return n}async function tx(e,t,n){let r=Object.create(null);if(e.headers.forEach((e,t)=>{r[t.toLowerCase()]=e}),n>0){let t=e.headers.get(`content-length`);if(t){let e=parseInt(t,10);if(!Number.isNaN(e)&&e>n)throw new Gb(n)}}let i;if(n>0&&e.body){let t=e.body.getReader(),r=[],a=0;for(;;){let{done:e,value:i}=await t.read();if(e)break;if(i){if(a+=i.byteLength,a>n)throw t.cancel(),new Gb(n);r.push(i)}}i=new Uint8Array(a);let o=0;for(let e of r)i.set(e,o),o+=e.byteLength}else{let t=await e.arrayBuffer();if(n>0&&t.byteLength>n)throw new Gb(n);i=new Uint8Array(t)}return{status:e.status,statusText:e.statusText,headers:r,body:i,url:t}}function nx(e){return rx(e)}function rx(e){return e.statements.map(ix).join(`
888
+ `)}function ix(e){let t=[];for(let n=0;n<e.pipelines.length;n++)t.push(ax(e.pipelines[n])),n<e.operators.length&&t.push(e.operators[n]);let n=t.join(` `);return e.background&&(n+=` &`),n}function ax(e){let t=[];e.timed&&t.push(e.timePosix?`time -p`:`time`),e.negated&&t.push(`!`);let n=[];for(let t=0;t<e.commands.length;t++)if(n.push(ox(e.commands[t])),t<e.commands.length-1){let r=e.pipeStderr?.[t];n.push(r?`|&`:`|`)}return(t.length>0?`${t.join(` `)} `:``)+n.join(` `)}function ox(e){switch(e.type){case`SimpleCommand`:return sx(e);case`If`:return wx(e);case`For`:return Tx(e);case`CStyleFor`:return Ex(e);case`While`:return Dx(e);case`Until`:return Ox(e);case`Case`:return kx(e);case`Subshell`:return jx(e);case`Group`:return Mx(e);case`ArithmeticCommand`:return Nx(e);case`ConditionalCommand`:return Px(e);case`FunctionDef`:return Fx(e);default:throw Error(`Unsupported command type: ${e.type}`)}}function sx(e){let t=[];for(let n of e.assignments)t.push(cx(n));e.name&&t.push(lx(e.name));for(let n of e.args)t.push(lx(n));for(let n of e.redirections)t.push(xx(n));return t.join(` `)}function cx(e){let t=e.append?`+=`:`=`;if(e.array){let n=e.array.map(lx).join(` `);return`${e.name}${t}(${n})`}return e.value?`${e.name}${t}${lx(e.value)}`:`${e.name}${t}`}function lx(e){return e.parts.map(e=>dx(e,!1)).join(``)}function ux(e){return e.parts.map(e=>dx(e,!0)).join(``)}function dx(e,t){switch(e.type){case`Literal`:return t?px(e.value):fx(e.value);case`SingleQuoted`:return`'${e.value}'`;case`DoubleQuoted`:return`"${e.parts.map(e=>dx(e,!0)).join(``)}"`;case`Escaped`:return`\\${e.value}`;case`ParameterExpansion`:return gx(e);case`CommandSubstitution`:return e.legacy?`\`${rx(e.body)}\``:`$(${rx(e.body)})`;case`ArithmeticExpansion`:return`$((${$(e.expression.expression)}))`;case`ProcessSubstitution`:return e.direction===`input`?`<(${rx(e.body)})`:`>(${rx(e.body)})`;case`BraceExpansion`:return yx(e);case`TildeExpansion`:return e.user===null?`~`:`~${e.user}`;case`Glob`:return e.pattern;default:throw Error(`Unsupported word part type: ${e.type}`)}}function fx(e){return e.replace(/[\s\\'"`!|&;()<>{}[\]*?~#]/g,`\\$&`)}function px(e){return e.replace(/[$`"\\]/g,`\\$&`)}function mx(e,t){return e.parts.map(e=>hx(e,t)).join(``)}function hx(e,t){switch(e.type){case`Literal`:return t?e.value:e.value.replace(/[$`]/g,`\\$&`);case`Escaped`:return`\\${e.value}`;case`ParameterExpansion`:return gx(e);case`CommandSubstitution`:return e.legacy?`\`${rx(e.body)}\``:`$(${rx(e.body)})`;case`ArithmeticExpansion`:return`$((${$(e.expression.expression)}))`;default:return dx(e,!1)}}function gx(e){return e.operation?`\${${vx(e.parameter,e.operation)}}`:_x(e.parameter)?`\${${e.parameter}}`:`$${e.parameter}`}function _x(e){return!(/^[?#@*$!\-0-9]$/.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e))}function vx(e,t){switch(t.type){case`Length`:return`#${e}`;case`LengthSliceError`:return`#${e}:`;case`BadSubstitution`:return t.text;case`DefaultValue`:return`${e}${t.checkEmpty?`:`:``}-${ux(t.word)}`;case`AssignDefault`:return`${e}${t.checkEmpty?`:`:``}=${ux(t.word)}`;case`ErrorIfUnset`:return`${e}${t.checkEmpty?`:`:``}?${t.word?ux(t.word):``}`;case`UseAlternative`:return`${e}${t.checkEmpty?`:`:``}+${ux(t.word)}`;case`Substring`:{let n=$(t.offset.expression);return t.length?`${e}:${n}:${$(t.length.expression)}`:`${e}:${n}`}case`PatternRemoval`:{let n=t.side===`prefix`?`#`:`%`;return`${e}${t.greedy?`${n}${n}`:n}${ux(t.pattern)}`}case`PatternReplacement`:{let n=`/`;t.all?n=`//`:t.anchor===`start`?n=`/#`:t.anchor===`end`&&(n=`/%`);let r=t.replacement?`/${ux(t.replacement)}`:``;return`${e}${n}${ux(t.pattern)}${r}`}case`CaseModification`:{let n=t.direction===`upper`?`^`:`,`;return`${e}${t.all?`${n}${n}`:n}${t.pattern?ux(t.pattern):``}`}case`Transform`:return`${e}@${t.operator}`;case`Indirection`:return t.innerOp?`!${vx(e,t.innerOp)}`:`!${e}`;case`ArrayKeys`:return`!${t.array}[${t.star?`*`:`@`}]`;case`VarNamePrefix`:return`!${t.prefix}${t.star?`*`:`@`}`;default:throw Error(`Unsupported parameter operation type: ${t.type}`)}}function yx(e){return`{${e.items.map(bx).join(`,`)}}`}function bx(e){if(e.type===`Word`)return lx(e.word);let t=e.startStr??String(e.start),n=e.endStr??String(e.end);return e.step===void 0?`${t}..${n}`:`${t}..${n}..${e.step}`}function xx(e){let t=e.fdVariable?`{${e.fdVariable}}`:e.fd===null?``:String(e.fd);if(e.operator===`<<`||e.operator===`<<-`){let n=e.target,r=n.quoted?`'${n.delimiter}'`:n.delimiter,i=mx(n.content,n.quoted);return`${t}${e.operator}${r}
889
+ ${i}${n.delimiter}`}return e.operator===`<<<`?`${t}<<< ${lx(e.target)}`:e.operator===`&>`||e.operator===`&>>`?`${e.operator} ${lx(e.target)}`:`${t}${e.operator} ${lx(e.target)}`}function Sx(e){return e.length===0?``:` ${e.map(xx).join(` `)}`}function Cx(e){return e.map(ix).join(`
890
+ `)}function wx(e){let t=[];for(let n=0;n<e.clauses.length;n++){let r=e.clauses[n],i=n===0?`if`:`elif`;t.push(`${i} ${Cx(r.condition)}; then
891
+ ${Cx(r.body)}`)}return e.elseBody&&t.push(`else
892
+ ${Cx(e.elseBody)}`),`${t.join(`
893
893
  `)}
894
- fi${xx(e.redirections)}`}function wx(e){let t;if(e.words===null)t=`for ${e.variable}`;else{let n=e.words.map(cx).join(` `);t=`for ${e.variable} in ${n}`}return`${t}; do
895
- ${Sx(e.body)}
896
- done${xx(e.redirections)}`}function Tx(e){return`for ((${e.init?$(e.init.expression):``}; ${e.condition?$(e.condition.expression):``}; ${e.update?$(e.update.expression):``})); do
897
- ${Sx(e.body)}
898
- done${xx(e.redirections)}`}function Ex(e){return`while ${Sx(e.condition)}; do
899
- ${Sx(e.body)}
900
- done${xx(e.redirections)}`}function Dx(e){return`until ${Sx(e.condition)}; do
901
- ${Sx(e.body)}
902
- done${xx(e.redirections)}`}function Ox(e){let t=e.items.map(kx).join(`
903
- `);return`case ${cx(e.word)} in
894
+ fi${Sx(e.redirections)}`}function Tx(e){let t;if(e.words===null)t=`for ${e.variable}`;else{let n=e.words.map(lx).join(` `);t=`for ${e.variable} in ${n}`}return`${t}; do
895
+ ${Cx(e.body)}
896
+ done${Sx(e.redirections)}`}function Ex(e){return`for ((${e.init?$(e.init.expression):``}; ${e.condition?$(e.condition.expression):``}; ${e.update?$(e.update.expression):``})); do
897
+ ${Cx(e.body)}
898
+ done${Sx(e.redirections)}`}function Dx(e){return`while ${Cx(e.condition)}; do
899
+ ${Cx(e.body)}
900
+ done${Sx(e.redirections)}`}function Ox(e){return`until ${Cx(e.condition)}; do
901
+ ${Cx(e.body)}
902
+ done${Sx(e.redirections)}`}function kx(e){let t=e.items.map(Ax).join(`
903
+ `);return`case ${lx(e.word)} in
904
904
  ${t}
905
- esac${xx(e.redirections)}`}function kx(e){let t=e.patterns.map(cx).join(` | `),n=Sx(e.body);return n?`${t})
905
+ esac${Sx(e.redirections)}`}function Ax(e){let t=e.patterns.map(lx).join(` | `),n=Cx(e.body);return n?`${t})
906
906
  ${n}
907
907
  ${e.terminator}`:`${t})
908
- ${e.terminator}`}function Ax(e){return`(${Sx(e.body)})${xx(e.redirections)}`}function jx(e){return`{ ${Sx(e.body)}; }${xx(e.redirections)}`}function Mx(e){return`((${$(e.expression.expression)}))${xx(e.redirections)}`}function Nx(e){return`[[ ${Fx(e.expression)} ]]${xx(e.redirections)}`}function Px(e){let t=ax(e.body);return`${e.name}() ${t}${xx(e.redirections)}`}function $(e){switch(e.type){case`ArithNumber`:return String(e.value);case`ArithVariable`:return e.hasDollarPrefix?`$${e.name}`:e.name;case`ArithSpecialVar`:return`$${e.name}`;case`ArithBinary`:return`${$(e.left)} ${e.operator} ${$(e.right)}`;case`ArithUnary`:return e.prefix?`${e.operator}${$(e.operand)}`:`${$(e.operand)}${e.operator}`;case`ArithTernary`:return`${$(e.condition)} ? ${$(e.consequent)} : ${$(e.alternate)}`;case`ArithAssignment`:return`${e.subscript?`${e.variable}[${$(e.subscript)}]`:e.stringKey===void 0?e.variable:`${e.variable}[${e.stringKey}]`} ${e.operator} ${$(e.value)}`;case`ArithDynamicAssignment`:return`${e.subscript?`${$(e.target)}[${$(e.subscript)}]`:$(e.target)} ${e.operator} ${$(e.value)}`;case`ArithDynamicElement`:return`${$(e.nameExpr)}[${$(e.subscript)}]`;case`ArithGroup`:return`(${$(e.expression)})`;case`ArithNested`:return`$((${$(e.expression)}))`;case`ArithCommandSubst`:return`$(${e.command})`;case`ArithBracedExpansion`:return`\${${e.content}}`;case`ArithArrayElement`:return e.stringKey===void 0?e.index?`${e.array}[${$(e.index)}]`:e.array:`${e.array}[${e.stringKey}]`;case`ArithDynamicBase`:return`\${${e.baseExpr}}#${e.value}`;case`ArithDynamicNumber`:return`\${${e.prefix}}${e.suffix}`;case`ArithConcat`:return e.parts.map($).join(``);case`ArithDoubleSubscript`:return`${e.array}[${$(e.index)}]`;case`ArithNumberSubscript`:return`${e.number}[${e.errorToken}]`;case`ArithSyntaxError`:return e.errorToken;case`ArithSingleQuote`:return`'${e.content}'`;default:throw Error(`Unsupported arithmetic expression type: ${e.type}`)}}function Fx(e){switch(e.type){case`CondBinary`:return`${cx(e.left)} ${e.operator} ${cx(e.right)}`;case`CondUnary`:return`${e.operator} ${cx(e.operand)}`;case`CondNot`:return`! ${Fx(e.operand)}`;case`CondAnd`:return`${Fx(e.left)} && ${Fx(e.right)}`;case`CondOr`:return`${Fx(e.left)} || ${Fx(e.right)}`;case`CondGroup`:return`( ${Fx(e.expression)} )`;case`CondWord`:return cx(e.word);default:throw Error(`Unsupported conditional expression type: ${e.type}`)}}var Ix=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;jsBootstrapCode;transformPlugins=[];state;constructor(e={}){let t=e.fs??new Jh(e.files);this.fs=t,this.useDefaultLayout=!e.cwd&&!e.files;let n=e.cwd||(this.useDefaultLayout?`/home/user`:`/`),r=new Map([[`HOME`,this.useDefaultLayout?`/home/user`:`/`],[`PATH`,`/usr/bin:/bin`],[`IFS`,`
909
- `],[`OSTYPE`,`linux-gnu`],[`MACHTYPE`,`x86_64-pc-linux-gnu`],[`HOSTTYPE`,`x86_64`],[`HOSTNAME`,`localhost`],[`PWD`,n],[`OLDPWD`,n],[`OPTIND`,`1`],...Object.entries(e.env??{})]);if(this.limits=wb({...e.executionLimits,...e.maxCallDepth!==void 0&&{maxCallDepth:e.maxCallDepth},...e.maxCommandCount!==void 0&&{maxCommandCount:e.maxCommandCount},...e.maxLoopIterations!==void 0&&{maxLoopIterations:e.maxLoopIterations}}),e.fetch?this.secureFetch=e.fetch:e.network&&(this.secureFetch=Qb(e.network)),this.sleepFn=e.sleep,this.traceFn=e.trace,this.logger=e.logger,this.defenseInDepthConfig=e.defenseInDepth??!0,this.coverageWriter=e.coverage,this.state={env:r,cwd:n,previousDir:`/home/user`,functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:``,startTime:Date.now(),lastBackgroundPid:0,virtualPid:e.processInfo?.pid??1,virtualPpid:e.processInfo?.ppid??0,virtualUid:e.processInfo?.uid??1e3,virtualGid:e.processInfo?.gid??1e3,bashPid:e.processInfo?.pid??1,nextVirtualPid:(e.processInfo?.pid??1)+1,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1,posix:!1,allexport:!1,noclobber:!1,noglob:!1,noexec:!1,vi:!1,emacs:!1},shoptOptions:{extglob:!1,dotglob:!1,nullglob:!1,failglob:!1,globstar:!1,globskipdots:!0,nocaseglob:!1,nocasematch:!1,expand_aliases:!1,lastpipe:!1,xpg_echo:!1},inCondition:!1,loopDepth:0,exportedVars:new Set([`HOME`,`PATH`,`PWD`,`OLDPWD`,...Object.keys(e.env||{})]),readonlyVars:new Set([`SHELLOPTS`,`BASHOPTS`]),hashTable:new Map},this.state.env.set(`SHELLOPTS`,ng(this.state.options)),this.state.env.set(`BASHOPTS`,ag(this.state.shoptOptions)),$h(t,this.useDefaultLayout,{pid:this.state.virtualPid,ppid:this.state.virtualPpid,uid:this.state.virtualUid,gid:this.state.virtualGid}),n!==`/`&&t instanceof Jh)try{t.mkdirSync(n,{recursive:!0})}catch{}for(let t of Bh(e.commands))this.registerCommand(t);if(e.fetch||e.network)for(let e of Vh())this.registerCommand(e);if(e.python)for(let e of Hh())this.registerCommand(e);if(e.javascript){for(let e of Uh())this.registerCommand(e);let t=typeof e.javascript==`object`?e.javascript:Object.create(null);t.bootstrap&&(this.jsBootstrapCode=t.bootstrap)}if(e.customCommands)for(let t of e.customCommands)Wh(t)?this.registerCommand(Gh(t)):this.registerCommand({...t,trusted:t.trusted??!0})}registerCommand(e){this.commands.set(e.name,e);let t=this.fs;if(typeof t.writeFileSync==`function`){let n=`#!/bin/bash
908
+ ${e.terminator}`}function jx(e){return`(${Cx(e.body)})${Sx(e.redirections)}`}function Mx(e){return`{ ${Cx(e.body)}; }${Sx(e.redirections)}`}function Nx(e){return`((${$(e.expression.expression)}))${Sx(e.redirections)}`}function Px(e){return`[[ ${Ix(e.expression)} ]]${Sx(e.redirections)}`}function Fx(e){let t=ox(e.body);return`${e.name}() ${t}${Sx(e.redirections)}`}function $(e){switch(e.type){case`ArithNumber`:return String(e.value);case`ArithVariable`:return e.hasDollarPrefix?`$${e.name}`:e.name;case`ArithSpecialVar`:return`$${e.name}`;case`ArithBinary`:return`${$(e.left)} ${e.operator} ${$(e.right)}`;case`ArithUnary`:return e.prefix?`${e.operator}${$(e.operand)}`:`${$(e.operand)}${e.operator}`;case`ArithTernary`:return`${$(e.condition)} ? ${$(e.consequent)} : ${$(e.alternate)}`;case`ArithAssignment`:return`${e.subscript?`${e.variable}[${$(e.subscript)}]`:e.stringKey===void 0?e.variable:`${e.variable}[${e.stringKey}]`} ${e.operator} ${$(e.value)}`;case`ArithDynamicAssignment`:return`${e.subscript?`${$(e.target)}[${$(e.subscript)}]`:$(e.target)} ${e.operator} ${$(e.value)}`;case`ArithDynamicElement`:return`${$(e.nameExpr)}[${$(e.subscript)}]`;case`ArithGroup`:return`(${$(e.expression)})`;case`ArithNested`:return`$((${$(e.expression)}))`;case`ArithCommandSubst`:return`$(${e.command})`;case`ArithBracedExpansion`:return`\${${e.content}}`;case`ArithArrayElement`:return e.stringKey===void 0?e.index?`${e.array}[${$(e.index)}]`:e.array:`${e.array}[${e.stringKey}]`;case`ArithDynamicBase`:return`\${${e.baseExpr}}#${e.value}`;case`ArithDynamicNumber`:return`\${${e.prefix}}${e.suffix}`;case`ArithConcat`:return e.parts.map($).join(``);case`ArithDoubleSubscript`:return`${e.array}[${$(e.index)}]`;case`ArithNumberSubscript`:return`${e.number}[${e.errorToken}]`;case`ArithSyntaxError`:return e.errorToken;case`ArithSingleQuote`:return`'${e.content}'`;default:throw Error(`Unsupported arithmetic expression type: ${e.type}`)}}function Ix(e){switch(e.type){case`CondBinary`:return`${lx(e.left)} ${e.operator} ${lx(e.right)}`;case`CondUnary`:return`${e.operator} ${lx(e.operand)}`;case`CondNot`:return`! ${Ix(e.operand)}`;case`CondAnd`:return`${Ix(e.left)} && ${Ix(e.right)}`;case`CondOr`:return`${Ix(e.left)} || ${Ix(e.right)}`;case`CondGroup`:return`( ${Ix(e.expression)} )`;case`CondWord`:return lx(e.word);default:throw Error(`Unsupported conditional expression type: ${e.type}`)}}var Lx=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;jsBootstrapCode;transformPlugins=[];state;constructor(e={}){let t=e.fs??new Yh(e.files);this.fs=t,this.useDefaultLayout=!e.cwd&&!e.files;let n=e.cwd||(this.useDefaultLayout?`/home/user`:`/`),r=new Map([[`HOME`,this.useDefaultLayout?`/home/user`:`/`],[`PATH`,`/usr/bin:/bin`],[`IFS`,`
909
+ `],[`OSTYPE`,`linux-gnu`],[`MACHTYPE`,`x86_64-pc-linux-gnu`],[`HOSTTYPE`,`x86_64`],[`HOSTNAME`,`localhost`],[`PWD`,n],[`OLDPWD`,n],[`OPTIND`,`1`],...Object.entries(e.env??{})]);if(this.limits=Tb({...e.executionLimits,...e.maxCallDepth!==void 0&&{maxCallDepth:e.maxCallDepth},...e.maxCommandCount!==void 0&&{maxCommandCount:e.maxCommandCount},...e.maxLoopIterations!==void 0&&{maxLoopIterations:e.maxLoopIterations}}),e.fetch?this.secureFetch=e.fetch:e.network&&(this.secureFetch=$b(e.network)),this.sleepFn=e.sleep,this.traceFn=e.trace,this.logger=e.logger,this.defenseInDepthConfig=e.defenseInDepth??!0,this.coverageWriter=e.coverage,this.state={env:r,cwd:n,previousDir:`/home/user`,functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:``,startTime:Date.now(),lastBackgroundPid:0,virtualPid:e.processInfo?.pid??1,virtualPpid:e.processInfo?.ppid??0,virtualUid:e.processInfo?.uid??1e3,virtualGid:e.processInfo?.gid??1e3,bashPid:e.processInfo?.pid??1,nextVirtualPid:(e.processInfo?.pid??1)+1,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1,posix:!1,allexport:!1,noclobber:!1,noglob:!1,noexec:!1,vi:!1,emacs:!1},shoptOptions:{extglob:!1,dotglob:!1,nullglob:!1,failglob:!1,globstar:!1,globskipdots:!0,nocaseglob:!1,nocasematch:!1,expand_aliases:!1,lastpipe:!1,xpg_echo:!1},inCondition:!1,loopDepth:0,exportedVars:new Set([`HOME`,`PATH`,`PWD`,`OLDPWD`,...Object.keys(e.env||{})]),readonlyVars:new Set([`SHELLOPTS`,`BASHOPTS`]),hashTable:new Map},this.state.env.set(`SHELLOPTS`,rg(this.state.options)),this.state.env.set(`BASHOPTS`,og(this.state.shoptOptions)),eg(t,this.useDefaultLayout,{pid:this.state.virtualPid,ppid:this.state.virtualPpid,uid:this.state.virtualUid,gid:this.state.virtualGid}),n!==`/`&&t instanceof Yh)try{t.mkdirSync(n,{recursive:!0})}catch{}for(let t of Vh(e.commands))this.registerCommand(t);if(e.fetch||e.network)for(let e of Hh())this.registerCommand(e);if(e.python)for(let e of Uh())this.registerCommand(e);if(e.javascript){for(let e of Wh())this.registerCommand(e);let t=typeof e.javascript==`object`?e.javascript:Object.create(null);t.bootstrap&&(this.jsBootstrapCode=t.bootstrap)}if(e.customCommands)for(let t of e.customCommands)Gh(t)?this.registerCommand(Kh(t)):this.registerCommand({...t,trusted:t.trusted??!0})}registerCommand(e){this.commands.set(e.name,e);let t=this.fs;if(typeof t.writeFileSync==`function`){let n=`#!/bin/bash
910
910
  # Built-in command: ${e.name}
911
- `;try{t.writeFileSync(`/bin/${e.name}`,n)}catch{}try{t.writeFileSync(`/usr/bin/${e.name}`,n)}catch{}}}logResult(e){return this.logger&&(e.stdout&&this.logger.debug(`stdout`,{output:e.stdout}),e.stderr&&this.logger.info(`stderr`,{output:e.stderr}),this.logger.info(`exit`,{exitCode:e.exitCode})),e.stdout=zx(e.stdout),e.stderr=zx(e.stderr),e}async exec(e,t){if(this.state.callDepth===0&&(this.state.commandCount=0),this.state.commandCount++,this.state.commandCount>this.limits.maxCommandCount)return{stdout:``,stderr:`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option.
912
- `,exitCode:1,env:xn(this.state.env,t?.env)};if(!e.trim())return{stdout:``,stderr:``,exitCode:0,env:xn(this.state.env,t?.env)};this.logger?.info(`exec`,{command:e});let n=t?.cwd??this.state.cwd,r,i=n;if(t?.cwd)if(t.env&&`PWD`in t.env)r=t.env.PWD;else if(t?.env&&!(`PWD`in t.env))try{r=await this.fs.realpath(n),i=r}catch{r=n}else r=n;let a=t?.replaceEnv?new Map:new Map(this.state.env);if(t?.env)for(let[e,n]of Object.entries(t.env))a.set(e,n);r!==void 0&&a.set(`PWD`,r);let o={...this.state,env:a,cwd:i,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:t?.stdin,signal:t?.signal,extraArgs:t?.args},s=e;t?.rawScript||(s=Lx(e));let c=this.defenseInDepthConfig?vn.getInstance(this.defenseInDepthConfig):null,l=c?.activate();try{let e=async()=>{let e=Dt(s,{maxHeredocSize:this.limits.maxHeredocSize}),t;if(this.transformPlugins.length>0){let n=Object.create(null);for(let t of this.transformPlugins){let r=t.transform({ast:e,metadata:n});e=r.ast,r.metadata&&(n=Cn(n,r.metadata))}t=n}let n=await new Sb({fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,requireDefenseContext:c?.isEnabled()===!0,jsBootstrapCode:this.jsBootstrapCode},o).executeScript(e);return t&&(n.metadata=t),this.logResult(n)};return l?await l.run(e):await e()}catch(e){if(e instanceof ut||e instanceof lt)return this.logResult({stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,env:xn(this.state.env,t?.env)});if(e instanceof it)return this.logResult({stdout:e.stdout,stderr:e.stderr,exitCode:1,env:xn(this.state.env,t?.env)});if(e instanceof mt)return this.logResult({stdout:e.stdout,stderr:e.stderr,exitCode:124,env:xn(this.state.env,t?.env)});if(e instanceof ot)return this.logResult({stdout:e.stdout,stderr:En(e.stderr),exitCode:ot.EXIT_CODE,env:xn(this.state.env,t?.env)});if(e instanceof _n)return this.logResult({stdout:``,stderr:`bash: security violation: ${En(e.message)}
911
+ `;try{t.writeFileSync(`/bin/${e.name}`,n)}catch{}try{t.writeFileSync(`/usr/bin/${e.name}`,n)}catch{}}}logResult(e){return this.logger&&(e.stdout&&this.logger.debug(`stdout`,{output:e.stdout}),e.stderr&&this.logger.info(`stderr`,{output:e.stderr}),this.logger.info(`exit`,{exitCode:e.exitCode})),e.stdout=Bx(e.stdout),e.stderr=Bx(e.stderr),e}async exec(e,t){if(this.state.callDepth===0&&(this.state.commandCount=0),this.state.commandCount++,this.state.commandCount>this.limits.maxCommandCount)return{stdout:``,stderr:`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option.
912
+ `,exitCode:1,env:xn(this.state.env,t?.env)};if(!e.trim())return{stdout:``,stderr:``,exitCode:0,env:xn(this.state.env,t?.env)};this.logger?.info(`exec`,{command:e});let n=t?.cwd??this.state.cwd,r,i=n;if(t?.cwd)if(t.env&&`PWD`in t.env)r=t.env.PWD;else if(t?.env&&!(`PWD`in t.env))try{r=await this.fs.realpath(n),i=r}catch{r=n}else r=n;let a=t?.replaceEnv?new Map:new Map(this.state.env);if(t?.env)for(let[e,n]of Object.entries(t.env))a.set(e,n);r!==void 0&&a.set(`PWD`,r);let o={...this.state,env:a,cwd:i,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:t?.stdin,signal:t?.signal,extraArgs:t?.args},s=e;t?.rawScript||(s=Rx(e));let c=this.defenseInDepthConfig?vn.getInstance(this.defenseInDepthConfig):null,l=c?.activate();try{let e=async()=>{let e=Dt(s,{maxHeredocSize:this.limits.maxHeredocSize}),t;if(this.transformPlugins.length>0){let n=Object.create(null);for(let t of this.transformPlugins){let r=t.transform({ast:e,metadata:n});e=r.ast,r.metadata&&(n=Cn(n,r.metadata))}t=n}let n=await new Cb({fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,requireDefenseContext:c?.isEnabled()===!0,jsBootstrapCode:this.jsBootstrapCode},o).executeScript(e);return t&&(n.metadata=t),this.logResult(n)};return l?await l.run(e):await e()}catch(e){if(e instanceof ut||e instanceof lt)return this.logResult({stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,env:xn(this.state.env,t?.env)});if(e instanceof it)return this.logResult({stdout:e.stdout,stderr:e.stderr,exitCode:1,env:xn(this.state.env,t?.env)});if(e instanceof mt)return this.logResult({stdout:e.stdout,stderr:e.stderr,exitCode:124,env:xn(this.state.env,t?.env)});if(e instanceof ot)return this.logResult({stdout:e.stdout,stderr:En(e.stderr),exitCode:ot.EXIT_CODE,env:xn(this.state.env,t?.env)});if(e instanceof _n)return this.logResult({stdout:``,stderr:`bash: security violation: ${En(e.message)}
913
913
  `,exitCode:1,env:xn(this.state.env,t?.env)});if(e.name===`ParseException`)return this.logResult({stdout:``,stderr:`bash: syntax error: ${En(e.message)}
914
914
  `,exitCode:2,env:xn(this.state.env,t?.env)});if(e instanceof xt)return this.logResult({stdout:``,stderr:`bash: ${En(e.message)}
915
915
  `,exitCode:2,env:xn(this.state.env,t?.env)});if(e instanceof RangeError)return this.logResult({stdout:``,stderr:`bash: ${En(e.message)}
916
- `,exitCode:1,env:xn(this.state.env,t?.env)});throw e}finally{l?.deactivate()}}async readFile(e){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,e))}async writeFile(e,t){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,e),t)}getCwd(){return this.state.cwd}getEnv(){return Sn(this.state.env)}registerTransformPlugin(e){this.transformPlugins.push(e)}transform(e){let t=Dt(Lx(e),{maxHeredocSize:this.limits.maxHeredocSize}),n=Object.create(null);for(let e of this.transformPlugins){let r=e.transform({ast:t,metadata:n});t=r.ast,r.metadata&&(n=Cn(n,r.metadata))}return{script:tx(t),ast:t,metadata:n}}};function Lx(e){let t=e.split(`
916
+ `,exitCode:1,env:xn(this.state.env,t?.env)});throw e}finally{l?.deactivate()}}async readFile(e){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,e))}async writeFile(e,t){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,e),t)}getCwd(){return this.state.cwd}getEnv(){return Sn(this.state.env)}registerTransformPlugin(e){this.transformPlugins.push(e)}transform(e){let t=Dt(Rx(e),{maxHeredocSize:this.limits.maxHeredocSize}),n=Object.create(null);for(let e of this.transformPlugins){let r=e.transform({ast:t,metadata:n});t=r.ast,r.metadata&&(n=Cn(n,r.metadata))}return{script:nx(t),ast:t,metadata:n}}};function Rx(e){let t=e.split(`
917
917
  `),n=[],r=[];for(let e=0;e<t.length;e++){let i=t[e];if(r.length>0){let e=r[r.length-1];if((e.stripTabs?i.replace(/^\t+/,``):i)===e.delimiter){n.push(i.trimStart()),r.pop();continue}n.push(i);continue}let a=i.trimStart();n.push(a);for(let e of a.matchAll(/<<(-?)\s*(['"]?)([\w-]+)\2/g)){let t=e[1]===`-`,n=e[3];r.push({delimiter:n,stripTabs:t})}}return n.join(`
918
- `)}var Rx=new TextDecoder(`utf-8`,{fatal:!0});function zx(e){if(!e)return e;let t=!1;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>255)return e;r>127&&(t=!0)}if(!t)return e;let n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);try{return Rx.decode(n)}catch{return e}}var Bx=[`EACCES`,`escaping sandbox`,`EFBIG`],Vx=class{root;canonicalRoot;maxFileReadSize;allowSymlinks;constructor(e){this.root=Mn.resolve(e.root),this.maxFileReadSize=e.maxFileReadSize??10485760,this.allowSymlinks=e.allowSymlinks??!1,dn(this.root,`ReadWriteFs`),this.canonicalRoot=A.realpathSync(this.root)}resolveAndValidate(e,t){let n=this.allowSymlinks?ln(e,this.canonicalRoot):un(e,this.root,this.canonicalRoot);if(n===null)throw Error(`EACCES: permission denied, '${t}' resolves outside sandbox`);return n}validateParent(e,t){let n=Mn.dirname(e),r=this.resolveAndValidate(n,t);return Mn.join(r,Mn.basename(e))}toRealPath(e){let t=on(e),n=Mn.join(this.root,t);return Mn.resolve(n)}async readFile(e,t){return hn(await this.readFileBuffer(e),pn(t))}async readFileBuffer(e){k(e,`open`);let t=this.toRealPath(e),n=this.resolveAndValidate(t,e);try{let t=this.allowSymlinks?A.constants.O_RDONLY:A.constants.O_RDONLY|A.constants.O_NOFOLLOW,r=await A.promises.open(n,t);try{if(this.maxFileReadSize>0){let t=await r.stat();if(t.size>this.maxFileReadSize)throw Error(`EFBIG: file too large, read '${e}' (${t.size} bytes, max ${this.maxFileReadSize})`)}let t=await r.readFile();return new Uint8Array(t)}finally{await r.close()}}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, open '${e}'`);if(n.code===`EISDIR`)throw Error(`EISDIR: illegal operation on a directory, read '${e}'`);if(n.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`open`)}}async writeFile(e,t,n){k(e,`write`);let r=this.toRealPath(e),i=this.resolveAndValidate(r,e),a=mn(t,pn(n)),o=Mn.dirname(i);try{await A.promises.mkdir(o,{recursive:!0}),i=this.resolveAndValidate(r,e);let t=this.allowSymlinks?0:A.constants.O_NOFOLLOW,n=A.constants.O_WRONLY|A.constants.O_CREAT|A.constants.O_TRUNC|t,s=await A.promises.open(i,n,438);try{await s.writeFile(a)}finally{await s.close()}}catch(t){if(t.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`write`)}}async appendFile(e,t,n){k(e,`append`);let r=this.toRealPath(e),i=this.resolveAndValidate(r,e),a=mn(t,pn(n)),o=Mn.dirname(i);try{await A.promises.mkdir(o,{recursive:!0}),i=this.resolveAndValidate(r,e);let t=this.allowSymlinks?0:A.constants.O_NOFOLLOW,n=A.constants.O_WRONLY|A.constants.O_CREAT|A.constants.O_APPEND|t,s=await A.promises.open(i,n,438);try{await s.writeFile(a)}finally{await s.close()}}catch(t){if(t.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`append`)}}async exists(e){if(e.includes(`\0`))return!1;let t=this.toRealPath(e);try{let n=this.resolveAndValidate(t,e);return await A.promises.access(n),!0}catch{return!1}}async stat(e){k(e,`stat`);let t=this.toRealPath(e),n=this.resolveAndValidate(t,e);try{let t=await A.promises.lstat(n);if(!this.allowSymlinks&&t.isSymbolicLink())throw Error(`EACCES: permission denied, '${e}' is a symlink`);return{isFile:t.isFile(),isDirectory:t.isDirectory(),isSymbolicLink:t.isSymbolicLink(),mode:t.mode,size:t.size,mtime:t.mtime}}catch(t){if(t.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, stat '${e}'`);this.sanitizeError(t,e,`stat`)}}async lstat(e){k(e,`lstat`);let t=this.toRealPath(e),n=this.validateParent(t,e);try{let e=await A.promises.lstat(n);return{isFile:e.isFile(),isDirectory:e.isDirectory(),isSymbolicLink:e.isSymbolicLink(),mode:e.mode,size:e.size,mtime:e.mtime}}catch(t){if(t.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, lstat '${e}'`);this.sanitizeError(t,e,`lstat`)}}async mkdir(e,t){k(e,`mkdir`);let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{await A.promises.mkdir(r,{recursive:t?.recursive})}catch(t){let n=t;if(n.code===`EEXIST`)throw Error(`EEXIST: file already exists, mkdir '${e}'`);if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.sanitizeError(t,e,`mkdir`)}}async readdir(e){return(await this.readdirWithFileTypes(e)).map(e=>e.name)}async readdirWithFileTypes(e){k(e,`scandir`);let t=this.toRealPath(e),n=this.resolveAndValidate(t,e);try{if(!this.allowSymlinks&&(await A.promises.lstat(n)).isSymbolicLink())throw Error(`EACCES: permission denied, '${e}' is a symlink`);return(await A.promises.readdir(n,{withFileTypes:!0})).map(e=>({name:e.name,isFile:e.isFile(),isDirectory:e.isDirectory(),isSymbolicLink:e.isSymbolicLink()})).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);if(n.code===`ENOTDIR`)throw Error(`ENOTDIR: not a directory, scandir '${e}'`);this.sanitizeError(t,e,`scandir`)}}async rm(e,t){k(e,`rm`);let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{await A.promises.rm(r,{recursive:t?.recursive??!1,force:t?.force??!1})}catch(n){let r=n;if(r.code===`ENOENT`&&!t?.force)throw Error(`ENOENT: no such file or directory, rm '${e}'`);if(r.code===`ENOTEMPTY`)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);this.sanitizeError(n,e,`rm`)}}async cp(e,t,n){k(e,`cp`),k(t,`cp`);let r=this.toRealPath(e),i=this.toRealPath(t),a=this.resolveAndValidate(r,e),o=this.resolveAndValidate(i,t);try{await A.promises.cp(a,o,{recursive:n?.recursive??!1,filter:async e=>{try{if(A.lstatSync(e).isSymbolicLink()){let t=await A.promises.realpath(e).catch(()=>null);return t===null?!1:nn(t,this.canonicalRoot)}return!0}catch(e){return e.code===`ENOENT`}}})}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(n.code===`EISDIR`)throw Error(`EISDIR: is a directory, cp '${e}'`);this.sanitizeError(t,e,`cp`)}}async mv(e,t){k(e,`mv`),k(t,`mv`);let n=this.toRealPath(e),r=this.toRealPath(t),i=this.validateParent(n,e),a=this.validateParent(r,t);try{if((await A.promises.lstat(i)).isSymbolicLink()){let n=await A.promises.readlink(i),r=Mn.resolve(Mn.dirname(a),n);if(!nn(await A.promises.realpath(r).catch(()=>r),this.canonicalRoot))throw Error(`EACCES: permission denied, mv '${e}' -> '${t}' would create symlink escaping sandbox`)}}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mv '${e}'`);if(n.message?.includes(`EACCES`)||n.message?.includes(`escaping sandbox`))throw t}let o=Mn.dirname(a);try{await A.promises.mkdir(o,{recursive:!0})}catch(e){this.sanitizeError(e,t,`mv`)}try{await A.promises.rename(i,a)}catch(n){let r=n;if(r.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mv '${e}'`);if(r.code===`EXDEV`){await this.cp(e,t,{recursive:!0}),await this.rm(e,{recursive:!0});return}this.sanitizeError(n,e,`mv`)}try{if(A.lstatSync(a).isDirectory()&&this.findEscapingSymlinks(a).length>0)throw await A.promises.rename(a,i),Error(`EACCES: permission denied, mv '${e}' -> '${t}' would create symlinks escaping sandbox`)}catch(e){if(e.message?.includes(`EACCES`)||e.message?.includes(`escaping sandbox`))throw e}}resolvePath(e,t){return an(e,t)}getAllPaths(){let e=[];return this.scanDir(`/`,e),e}sanitizeError(e,t,n){cn(e,t,n,Bx)}findEscapingSymlinks(e){let t=[];try{let n=A.readdirSync(e);for(let r of n){let n=Mn.join(e,r);try{let r=A.lstatSync(n);if(r.isSymbolicLink()){let r=A.readlinkSync(n),i=Mn.resolve(e,r),a;try{a=A.realpathSync(i)}catch{a=i}nn(a,this.canonicalRoot)||t.push(n)}else r.isDirectory()&&t.push(...this.findEscapingSymlinks(n))}catch{}}}catch{}return t}scanDir(e,t){let n=this.toRealPath(e),r;try{r=this.resolveAndValidate(n,e)}catch{return}try{let n=A.readdirSync(r);for(let i of n){let n=e===`/`?`/${i}`:`${e}/${i}`;t.push(n);let a=Mn.join(r,i);A.lstatSync(a).isDirectory()&&this.scanDir(n,t)}}catch{}}async chmod(e,t){k(e,`chmod`);let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{let e=this.allowSymlinks?A.constants.O_RDONLY:A.constants.O_RDONLY|A.constants.O_NOFOLLOW,n=await A.promises.open(r,e);try{await n.chmod(t)}finally{await n.close()}}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);if(n.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`chmod`)}}async symlink(e,t){if(!this.allowSymlinks)throw Error(`EPERM: operation not permitted, symlink '${t}'`);k(t,`symlink`);let n=this.toRealPath(t),r=this.validateParent(n,t),i=on(t),a=on(Mn.dirname(i)),o=e.startsWith(`/`)?on(e):on(a===`/`?`/${e}`:`${a}/${e}`),s=Mn.join(this.canonicalRoot,o),c=Mn.dirname(r),l=e.startsWith(`/`)?s:Mn.relative(c,s)||`.`;try{await A.promises.symlink(l,r)}catch(e){if(e.code===`EEXIST`)throw Error(`EEXIST: file already exists, symlink '${t}'`);this.sanitizeError(e,t,`symlink`)}}async link(e,t){k(e,`link`),k(t,`link`);let n=this.toRealPath(e),r=this.toRealPath(t),i=this.resolveAndValidate(n,e),a=this.resolveAndValidate(r,t);try{await A.promises.link(i,a)}catch(n){let r=n;if(r.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(r.code===`EEXIST`)throw Error(`EEXIST: file already exists, link '${t}'`);if(r.code===`EPERM`)throw Error(`EPERM: operation not permitted, link '${e}'`);this.sanitizeError(n,e,`link`)}}async readlink(e){k(e,`readlink`);let t=this.toRealPath(e),n=this.validateParent(t,e);try{let t=await A.promises.readlink(n),r=on(e),i=Mn.dirname(r),a=Mn.isAbsolute(t)?t:Mn.resolve(Mn.dirname(n),t),o=await A.promises.realpath(a).catch(()=>a);if(nn(o,this.canonicalRoot)){let e=o.slice(this.canonicalRoot.length)||`/`;return i===`/`?e.startsWith(`/`)?e.slice(1)||`.`:e:Mn.relative(i,e)}return Mn.basename(t)}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, readlink '${e}'`);if(n.code===`EINVAL`)throw Error(`EINVAL: invalid argument, readlink '${e}'`);this.sanitizeError(t,e,`readlink`)}}async realpath(e){k(e,`realpath`);let t=this.toRealPath(e);try{this.resolveAndValidate(t,e)}catch{throw Error(`ENOENT: no such file or directory, realpath '${e}'`)}let n;try{n=await A.promises.realpath(t)}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, realpath '${e}'`);if(n.code===`ELOOP`)throw Error(`ELOOP: too many levels of symbolic links, realpath '${e}'`);this.sanitizeError(t,e,`realpath`)}if(nn(n,this.canonicalRoot))return n.slice(this.canonicalRoot.length)||`/`;throw Error(`ENOENT: no such file or directory, realpath '${e}'`)}async utimes(e,t,n){k(e,`utimes`);let r=this.toRealPath(e),i=this.resolveAndValidate(r,e);try{let e=this.allowSymlinks?A.constants.O_RDONLY:A.constants.O_RDONLY|A.constants.O_NOFOLLOW,r=await A.promises.open(i,e);try{await r.utimes(t,n)}finally{await r.close()}}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);if(n.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`utimes`)}}};function Hx(e){return e===``?`''`:/^[\w.\-/]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}const Ux=16*1024*1024;var Wx=class extends Error{limitBytes;actualBytes;partial;constructor(e,t,n){super(`Output exceeded ${e} byte buffer (got ${t}); narrow the command`),this.name=`StdoutOverflowError`,this.limitBytes=e,this.actualBytes=t,this.partial=n}};function Gx(e){if(!In(e))throw Error(`createBashInstance: cwd must be absolute (got: ${e})`);return new Ix({cwd:`/`,fs:new Vx({root:zn(e),allowSymlinks:!1})})}async function Kx(e,t){let n=await e.exec(t);if(n.stdout.length>Ux)throw new Wx(Ux,n.stdout.length,{stdout:n.stdout.slice(0,Ux),stderr:n.stderr,exitCode:n.exitCode});return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}}function qx(e){return e.startsWith(`**/`)?e.slice(3):e}async function Jx(e,t,n={}){let r=Gx(t),i=[`-rn`,`-F`];(n.caseInsensitive??!0)&&i.push(`-i`);for(let e of n.include??[])i.push(`--include=${Hx(qx(e))}`);for(let e of n.exclude??[])i.push(`--exclude=${Hx(qx(e))}`),i.push(`--exclude-dir=${Hx(qx(e))}`);let a=n.paths?.length?n.paths.map(Hx):[`.`],o=`grep ${i.join(` `)} ${Hx(e)} ${a.join(` `)}`,s;try{s=await Kx(r,o)}catch(e){if(e instanceof Wx)s=e.partial;else throw e}if(s.exitCode===1&&!s.stdout)return[];if(s.exitCode!==0&&s.exitCode!==1&&!s.stdout)throw Error(`grep exited ${s.exitCode}: ${s.stderr}`);let c=[],l=n.maxResults??1/0;for(let e of s.stdout.split(`
919
- `)){if(!e)continue;if(c.length>=l)break;let t=e.indexOf(`:`);if(t===-1)continue;let n=e.indexOf(`:`,t+1);if(n===-1)continue;let r=e.slice(0,t),i=e.slice(t+1,n),a=e.slice(n+1),o=Number.parseInt(i,10);Number.isFinite(o)&&c.push({path:r,line:o,text:a})}return c}const Yx=new Set([`.git`,i,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]);async function Xx(e){let t=zn(e),n=new Map,r=0,i=!1;async function a(e){if(i)return;let o;try{o=await ur(e,{withFileTypes:!0})}catch{return}for(let s of o){if(i)return;if(s.isDirectory()&&Yx.has(s.name))continue;let o=zn(e,s.name);if(s.isDirectory()){await a(o);continue}if(s.isFile()){if(r>=1e3){i=!0;return}try{let e=await dr(o);n.set(Rn(t,o),e.mtimeMs),r++}catch{}}}}return await a(t),{snapshot:n,truncated:i}}function Zx(e,t){let n=[];for(let[r,i]of t){let t=e.get(r);(t===void 0||t!==i)&&n.push(r)}for(let[r]of e)t.has(r)||n.push(r);return{changed:n}}var Qx=n(((e,t)=>{t.exports=function(e){return e.map(function(e){return e===``?`''`:e&&typeof e==`object`?e.op.replace(/(.)/g,`\\$1`):/["\s\\]/.test(e)&&!/'/.test(e)?`'`+e.replace(/(['])/g,`\\$1`)+`'`:/["'\s]/.test(e)?`"`+e.replace(/(["\\$`!])/g,`\\$1`)+`"`:String(e).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,`$1\\$2`)}).join(` `)}})),$x=n(((e,t)=>{for(var n=`(?:`+[`\\|\\|`,`\\&\\&`,`;;`,`\\|\\&`,`\\<\\(`,`\\<\\<\\<`,`>>`,`>\\&`,`<\\&`,`[&;()|<>]`].join(`|`)+`)`,r=RegExp(`^`+n+`$`),i=`|&;()<> \\t`,a=`"((\\\\"|[^"])*?)"`,o=`'((\\\\'|[^'])*?)'`,s=/^#$/,c=`'`,l=`"`,u=`$`,d=``,f=4294967296,p=0;p<4;p++)d+=(f*Math.random()).toString(16);var m=RegExp(`^`+d);function h(e,t){for(var n=t.lastIndex,r=[],i;i=t.exec(e);)r.push(i),t.lastIndex===i.index&&(t.lastIndex+=1);return t.lastIndex=n,r}function g(e,t,n){var r=typeof e==`function`?e(n):e[n];return r===void 0&&n!=``?r=``:r===void 0&&(r=`$`),typeof r==`object`?t+d+JSON.stringify(r)+d:t+r}function _(e,t,d){d||={};var f=d.escape||`\\`,p=`(\\`+f+`['"`+i+`]|[^\\s'"`+i+`])+`,m=h(e,new RegExp([`(`+n+`)`,`(`+p+`|`+a+`|`+o+`)+`].join(`|`),`g`));if(m.length===0)return[];t||={};var _=!1;return m.map(function(n){var i=n[0];if(!i||_)return;if(r.test(i))return{op:i};var a=!1,o=!1,d=``,p=!1,m;function h(){m+=1;var e,n,r=i.charAt(m);if(r===`{`){if(m+=1,i.charAt(m)===`}`)throw Error(`Bad substitution: `+i.slice(m-2,m+1));if(e=i.indexOf(`}`,m),e<0)throw Error(`Bad substitution: `+i.slice(m));n=i.slice(m,e),m=e}else if(/[*@#?$!_-]/.test(r))n=r,m+=1;else{var a=i.slice(m);e=a.match(/[^\w\d_]/),e?(n=a.slice(0,e.index),m+=e.index-1):(n=a,m=i.length)}return g(t,``,n)}for(m=0;m<i.length;m++){var v=i.charAt(m);if(p||=!a&&(v===`*`||v===`?`),o)d+=v,o=!1;else if(a)v===a?a=!1:a==c?d+=v:v===f?(m+=1,v=i.charAt(m),v===l||v===f||v===u?d+=v:d+=f+v):v===u?d+=h():d+=v;else if(v===l||v===c)a=v;else if(r.test(v))return{op:i};else if(s.test(v)){_=!0;var y={comment:e.slice(n.index+m+1)};return d.length?[d,y]:[y]}else v===f?o=!0:v===u?d+=h():d+=v}return p?{op:`glob`,pattern:d}:d}).reduce(function(e,t){return t===void 0?e:e.concat(t)},[])}t.exports=function(e,t,n){var r=_(e,t,n);return typeof t==`function`?r.reduce(function(e,t){if(typeof t==`object`)return e.concat(t);var n=t.split(RegExp(`(`+d+`.*?`+d+`)`,`g`));return n.length===1?e.concat(n[0]):e.concat(n.filter(Boolean).map(function(e){return m.test(e)?JSON.parse(e.split(d)[1]):e}))},[]):r}})),eS=t(n((e=>{e.quote=Qx(),e.parse=$x()}))(),1);const tS=[`node_modules`,`.git`,`dist`,`build`,`.next`,`.turbo`,`.nuxt`,`coverage`,`.cache`,`.parcel-cache`,`.vercel`,i,`.claude`];function nS(e){return e===`--recursive`||e===`--dereference-recursive`?!0:e.startsWith(`--`)||!e.startsWith(`-`)?!1:/[rR]/.test(e.slice(1))}const rS=[{command:`grep`,applies:e=>e.slice(1).some(nS),hasUserExcludes:e=>e.some(e=>e===`--exclude-dir`||e.startsWith(`--exclude-dir=`)),buildExcludeArgs:e=>e.map(e=>`--exclude-dir=${e}`),insertionIndex:()=>1},{command:`find`,applies:()=>!0,hasUserExcludes:e=>e.slice(1).some(e=>e===`-not`||e===`!`||e===`-prune`),buildExcludeArgs:e=>{let t=[];for(let n of e)t.push(`-not`,`-path`,`*/${n}/*`);return t},insertionIndex:e=>{for(let t=1;t<e.length;t++)if(e[t].startsWith(`-`))return t;return e.length}}];function iS(e){return e.map(e=>{let t=rS.find(t=>t.command===e.command);if(!t||!t.applies(e.args)||t.hasUserExcludes(e.args))return e;let n=t.buildExcludeArgs(tS),r=t.insertionIndex(e.args);return{command:e.command,args:[...e.args.slice(0,r),...n,...e.args.slice(r)]}})}function aS(e){return e.map(e=>e.args.map(Hx).join(` `)).join(` | `)}const oS=new Set([`cat`,`ls`,`grep`,`find`,`head`,`tail`,`wc`,`sort`,`uniq`,`cut`]),sS=new Set([`>`,`>>`,`<`,`>&`,`<&`,`|&`]),cS=new Set([`&`,`;`,`;;`,`&&`,`||`,`(`,`)`,`<(`,`>(`,`<<`,`<<-`]),lS=new Set([`-o`,`--output-file`,`--output`]),uS=[`-o=`,`--output-file=`,`--output=`],dS=new Set([`-exec`,`-execdir`,`-delete`,`-fprint`,`-fprintf`,`-fprint0`,`-ok`,`-okdir`]),fS=/[`]|\$\(|\$\{|\$'/;function pS(e){return typeof e==`object`&&!!e&&`op`in e}function mS(e){let t=typeof e.op==`string`?e.op:`(unknown)`;return sS.has(t)?{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use write_document or edit_document.`}:cS.has(t)?{category:`shell_construct_blocked`,message:`Shell construct '${t}' is not supported. Only pipes (|) are allowed between allowlisted stages.`}:{category:`shell_construct_blocked`,message:`Operator '${t}' is not supported.`}}function hS(e){let t=[];for(let n of e){if(typeof n==`string`){if(fS.test(n))return{error:{category:`shell_construct_blocked`,message:`Argument '${n}' contains a shell-injection pattern (backtick, $(), or \${}); not supported.`}};t.push(n);continue}if(!pS(n))return{error:{category:`shell_construct_blocked`,message:`Unrecognized token shape.`}};if(n.op===`glob`&&typeof n.pattern==`string`){t.push(n.pattern);continue}return typeof n.comment==`string`?{error:{category:`shell_construct_blocked`,message:`Comments are not allowed in exec commands.`}}:{error:mS(n)}}return{args:t}}function gS(e){if(!oS.has(e.command))return{category:`unknown_command`,message:`Command '${e.command}' is not in the allowlist. For pattern matching try 'grep'; for file listing try 'ls' or 'find'. Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut.`};for(let t of e.args.slice(1)){if(lS.has(t)||uS.some(e=>t.startsWith(e)))return{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use write_document or edit_document.`};if(e.command===`find`&&dS.has(t))return{category:`write_blocked`,message:`find flag '${t}' is blocked (executes commands or deletes files). Use exec for read-only discovery; chain with another allowlisted tool via '|' if you need to transform output.`}}return null}function _S(e){let t=e.trim();if(!t)return{error:{category:`unknown_command`,message:`Empty command.`}};let n;try{n=eS.parse(t)}catch{return{error:{category:`shell_construct_blocked`,message:`Failed to parse command — likely malformed quoting or an unsupported construct.`}}}let r=[],i=[];for(let e of n){if(pS(e)&&e.op===`|`){r.push(i),i=[];continue}i.push(e)}r.push(i);let a=[];for(let e of r){let t=hS(e);if(`error`in t)return t;if(t.args.length===0)return{error:{category:`shell_construct_blocked`,message:`Empty pipeline stage (trailing pipe or leading pipe).`}};let n={command:t.args[0],args:t.args},r=gS(n);if(r)return{error:r};a.push(n)}return{stages:a}}const vS=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function yS(e,t){let n=e.match(vS);if(!n)return null;try{let e=(0,_r.parse)(n[1]);if(He(e)){if(t){let n=t.safeParse(e);return n.success?n.data:null}return e}}catch{}return null}var bS=t(Fe(),1);const xS=new WeakMap;function SS(e){let t=xS.get(e);if(t)return t;let n=e.map(e=>(0,bS.default)(e.match,{dot:!0}));return xS.set(e,n),n}function CS(e,t){if(e.length===0)return{};let n=SS(e),r={},i=[],a=!1;for(let o=0;o<e.length;o++){if(!n[o](t))continue;a=!0;let s=e[o].frontmatter;if(s.title!==void 0&&(r.title=s.title),s.description!==void 0&&(r.description=s.description),s.tags!==void 0)for(let e of s.tags)i.includes(e)||i.push(e)}return a?(i.length>0&&(r.tags=i),r):{}}function wS(e){try{return Jn(zn(e,`.git`)).isDirectory()}catch{return!1}}function TS(e){return De({baseDir:zn(e),timeout:{block:5e3}})}async function ES(e,t,n=5){if(!wS(e))return{commits:[],source:`git-absent`};let r=TS(e),i=``;try{i=await r.raw(`log`,`-${Math.max(1,n)}`,`--format=%H|%aI|%an|%s`,`--follow`,`--`,t)}catch{return{commits:[],source:`git`}}let a=[];for(let e of i.split(`
920
- `)){if(!e)continue;let t=e.indexOf(`|`);if(t<0)continue;let n=e.indexOf(`|`,t+1);if(n<0)continue;let r=e.indexOf(`|`,n+1);r<0||a.push({hash:e.slice(0,t),date:e.slice(t+1,n),authorName:e.slice(n+1,r),subject:e.slice(r+1)})}return{commits:a,source:`git`}}const DS=5e3;async function OS(e){try{let t=(await De({baseDir:e,timeout:{block:DS}}).revparse([`--abbrev-ref`,`HEAD`])).trim();return t&&t!==`HEAD`?t:null}catch{return null}}function kS(e,t){return De({baseDir:t,timeout:{block:DS}}).env({GIT_DIR:e,GIT_WORK_TREE:t})}function AS(e,t){let n=Pe(t);return e.startsWith(n)?e.slice(n.length):e}async function jS(e,t,n,r,i){let a=``;try{a=await e.raw(`log`,t,`-${Math.max(1,i*2)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,`--`,n)}catch{return[]}let o=AS(t,r),s=Ne(o),c=[];for(let e of a.split(``)){let t=e.trimStart();if(!t)continue;let[n=``,i=``,a=``,l=``,u=``]=t.split(`\0`),d=n.trim();d.length===40&&c.push({hash:d,date:i,writerName:a,message:l,contributors:Ie(u),writerId:o,isAgent:s.isAgent,writerClassification:s.classification,branch:r})}return c}async function MS(e,t,n=5){let r=Le(e);if(!r)return{commits:[],source:`shadow-repo-absent`};let i=await OS(e);if(!i)return{commits:[],source:`shadow-repo`};let a=kS(r,zn(e)),o=``;try{o=await a.raw(`for-each-ref`,Pe(i),`--format=%(refname)`)}catch{return{commits:[],source:`shadow-repo`}}let s=o.split(`
921
- `).map(e=>e.trim()).filter(Boolean);return s.length===0?{commits:[],source:`shadow-repo`}:{commits:(await Promise.all(s.map(e=>jS(a,e,t,i,n)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,n),source:`shadow-repo`}}const NS=1e3,PS=new Set([`.git`,i,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),FS=/\.(md|mdx)$/i,IS=x({title:D().optional(),description:D().optional(),tags:T(D()).default([])});function LS(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}async function RS(e){try{let t=yS(await lr(e,`utf-8`),IS);return t?{title:t.title,description:t.description,tags:t.tags??[]}:{tags:[]}}catch{return null}}async function zS(e,t){if(!e)return null;let n=await ah(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.backlinks??n.results??n.links;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e,n=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;n&&i.push({source:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}async function BS(e,t){if(!e||t.length===0)return null;let n=[...new Set(t)],r=[];for(let e=0;e<n.length;e+=100)r.push(n.slice(e,e+100));let i=await Promise.all(r.map(async t=>{let n=await ah(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return n.ok?n.counts??{}:null})),a=new Map,o=!1;for(let e of i)if(e){o=!0;for(let[t,n]of Object.entries(e))typeof n==`number`&&Number.isFinite(n)&&a.set(t,n)}return o?a:null}async function VS(e,t){if(!e)return null;let n=await ah(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.forwardLinks??n.links??n.results;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){i.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let n=typeof t.docName==`string`?t.docName:void 0;n&&i.push({kind:`doc`,docName:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}function HS(e,t,n){let r=t??[],i=r.length===0?{}:CS(r,n),a=e?.title??i.title,o=e?.description??i.description,s=e?.tags??[],c=i.tags??[],l;if(c.length===0)l=s;else{let e=new Set;l=[];for(let t of c)e.has(t)||(e.add(t),l.push(t));for(let t of s)e.has(t)||(e.add(t),l.push(t))}return{title:a,description:o,tags:l}}async function US(e,t,n={}){let r=e.replace(/^\.\//,``).replace(/^\/+/,``),i=zn(t.projectDir,r),a=t.historyDepth??5,o=n.includeRichFields===!0,s=RS(i);if(!o){let e=HS(await s,t.folderRules,r);return{path:r,title:e.title,description:e.description,tags:e.tags,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null}}let[c,l,u,d,f]=await Promise.all([s,zS(t.serverUrl,LS(r)).catch(()=>null),VS(t.serverUrl,LS(r)).catch(()=>null),MS(t.projectDir,r,a).catch(()=>({commits:[],source:`shadow-repo`})),ES(t.projectDir,r,a).catch(()=>({commits:[],source:`git`}))]),p=HS(c,t.folderRules,r);return{path:r,title:p.title,description:p.description,tags:p.tags,backlinkCount:l?.length??null,backlinks:l,forwardLinkCount:u?.length??null,forwardLinks:u,history:d.commits,historySource:d.source,projectHistory:f.commits,projectHistorySource:f.source}}async function WS(e,t){let n={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},r=0,i=[{path:e,depth:0}];for(;i.length>0;){let e=i.shift();if(!e)break;if(r>=NS){n.truncated=!0;break}let a;try{a=await ur(e.path,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=NS){n.truncated=!0;break}r++;let a=o.name;if(o.isDirectory()){if(PS.has(a)||a.startsWith(`.`))continue;e.depth===0&&n.childDirCount++,i.push({path:`${e.path}/${a}`,depth:e.depth+1})}else if(o.isFile()&&FS.test(a)){n.recursiveMdCount++,e.depth===0&&n.directMdCount++;let r=`${e.path}/${a}`;try{let e=await dr(r);(!n.mostRecent||e.mtimeMs>n.mostRecent.mtimeMs)&&(n.mostRecent={absPath:r,relPath:Rn(t,r).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return n}async function GS(e,t){let n=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``),r=await WS(zn(t.projectDir,n),t.projectDir),i;if(r.mostRecent){let e=await RS(r.mostRecent.absPath);i={path:r.mostRecent.relPath,title:e?.title??Pn(r.mostRecent.relPath),updatedAt:new Date(r.mostRecent.mtimeMs).toISOString()}}let a={path:n,type:`directory`,directMdCount:r.directMdCount,recursiveMdCount:r.recursiveMdCount,childDirCount:r.childDirCount,mostRecentMd:i,truncated:r.truncated},o=t.folderRules??[];if(o.length>0){let e=CS(o,n);e.title!==void 0&&(a.title=e.title),e.description!==void 0&&(a.description=e.description),e.tags!==void 0&&e.tags.length>0&&(a.tags=e.tags)}return a}const KS=50*1024,qS=/\.(png|jpe?g|gif|webp|svg|pdf|zip|tar|gz|tgz|mp4|mov|mp3|wav|ico|bmp)$/i,JS=["**STOP — native tools on in-scope markdown (when project has `.open-knowledge/`).** When the active project contains `.open-knowledge/`, do NOT use your host's native `Read`, `Grep`, or `Glob` on `.md` / `.mdx` paths inside OK's content directory — use `exec` (this tool) instead. Native file tools skip frontmatter, backlinks, shadow-repo activity, and project git history that `exec` returns for every matched wiki file. Reserve native `Read`/`Grep`/`Glob` for source code, non-markdown paths, and projects without `.open-knowledge/`.",``,`Run a read-only bash-like command against the project content directory. Returns raw stdout plus enriched metadata for every wiki file referenced (frontmatter, backlink/forward-link counts, shadow-repo activity with agent/human attribution).`,``,`Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. Pipes (|) work between stages. Redirections, subshells, and writes are rejected.`,``,"cwd: the command runs in the explicit absolute `cwd` you pass, or in the MCP client's only advertised root when there is exactly one. If the client has zero or multiple roots, pass `cwd` explicitly. Paths inside the command resolve relative to that cwd; traversal above it is rejected.",``,"Stdout provenance headers (GNU-style): `ls <dir>/` prepends `<dir>/:`, single-file `cat`/`head`/`tail` prepends `==> <path> <==`, so the subject of the command is visible in raw output. Multi-file `cat a b` emits no header — the `enrichedPaths` array still lists every file. `head`/`tail` used as pipe trimmers (no file arg) defer to the upstream producer.",``,`Examples:`,'- `exec({ command: "cat articles/auth.md" })` — file contents + full enrichment','- `exec({ command: "ls articles/" })` — listing + per-file enrichment (slim)','- `exec({ command: "grep -rn oauth articles/ | head -5" })` — pipe with enrichment on matched files','- `exec({ command: "ls", cwd: "/abs/path/to/other-repo" })` — run in a different project'].join(`
922
- `);function YS(e){let t=e.split(`
923
- `),n=t[t.length-1]===``?t.length-1:t.length;if(n<=500&&e.length<=KS)return{text:e,truncated:!1,omittedLines:0};let r=Math.min(n,500),i=0,a=0;for(let e=0;e<r;e++){let n=t[e];if(i+=n.length+1,i>KS)break;a++}let o=t.slice(0,a).join(`
924
- `),s=n-a;return{text:`${o}\n<truncated: ${s} more lines — re-run with a more-specific query>`,truncated:!0,omittedLines:s}}function XS(e){let t=[];for(let n of e)if(n.command===`cat`)for(let e of n.args.slice(1))e.startsWith(`-`)||qS.test(e)&&t.push(e);return t}function ZS(e){for(let t=1;t<e.length;t++){let n=e[t],r=n.match(/^--lines=(\d+)$/);if(r)return Number(r[1]);if(n===`--lines`&&t+1<e.length){let n=Number(e[t+1]);if(Number.isFinite(n))return n}if(n===`-n`&&t+1<e.length){let n=Number(e[t+1]);if(Number.isFinite(n))return n}let i=n.match(/^-n(\d+)$/);if(i)return Number(i[1]);let a=n.match(/^-(\d+)$/);if(a)return Number(a[1])}return 10}function QS(e,t){if(e.length<2)return null;let n=e[e.length-1];if(n.command!==`head`&&n.command!==`tail`)return null;let r=ZS(n.args),i=t.split(`
925
- `),a=i[i.length-1]===``?i.length-1:i.length;if(a<r)return null;let o=i.slice(0,a),s=new Set(o.map(e=>{let t=e.indexOf(`:`);return t>0?e.slice(0,t):e})).size,c=e.slice(0,-1).map(e=>e.command).join(` | `);return{banner:`Output hit \`${n.command} -${r}\` cap (${a} lines, ${s} unique file${s===1?``:`s`}). The \`${c}\` stage may have had more matches that never reached stdout. For existence checks across many files, prefer \`grep -rl PATTERN <dir>\` (list files only, no head). For enumeration, drop the \`| ${n.command}\` or widen the cap.`}}function $S(e){return e.type===`directory`}function eC(e){let t=[e.title?`**${e.title}** (${e.path}/)`:`**${e.path}/** (directory)`];e.description&&t.push(e.description),e.tags&&e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`);let n=[];return n.push(`${e.recursiveMdCount} md file${e.recursiveMdCount===1?``:`s`}`),e.childDirCount>0&&n.push(`${e.childDirCount} subdir${e.childDirCount===1?``:`s`}`),t.push(n.join(`, `)),e.mostRecentMd&&t.push(`most recent: ${e.mostRecentMd.title??e.mostRecentMd.path} (${e.mostRecentMd.path})`),e.truncated&&t.push(`scan truncated`),`- ${t.join(` — `)}`}function tC(e){let t=[`**${e.title??e.path}** (${e.path})`];if(e.description&&t.push(e.description),e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`),e.backlinkCount!==null&&t.push(`backlinks: ${e.backlinkCount}`),e.forwardLinkCount!==null&&t.push(`forward links: ${e.forwardLinkCount}`),e.history&&e.history.length>0){let n=e.history.map(e=>{let t=e.writerClassification===`agent`?`agent: ${e.writerName}`:e.writerClassification===`principal`?`human: ${e.writerName}`:`${e.writerClassification}: ${e.writerName}`;return`${e.hash.slice(0,7)} [${t}] ${e.message}`});t.push(`OK edits: ${n.join(` · `)}`)}if(e.projectHistory&&e.projectHistory.length>0){let n=e.projectHistory.map(e=>`${e.hash.slice(0,7)} ${e.authorName}: ${e.subject}`);t.push(`commits: ${n.join(` · `)}`)}return`- ${t.join(` — `)}`}function nC(e,t,n){let r=null;for(let t=e.length-1;t>=0;t--){let n=e[t],i=n.command;if(i===`ls`||i===`cat`){r=n;break}if((i===`head`||i===`tail`)&&Th(wh(n)).length>0){r=n;break}}if(!r)return``;let i=Th(wh(r));if(r.command===`ls`){let e=i[i.length-1];if(!e||e===`.`)return``;let n=e.replace(/\/+/g,`/`);return n.startsWith(`./`)&&(n=n.slice(2)),n.endsWith(`/`)&&(n=n.slice(0,-1)),!n||!t.has(n)?``:`${n}/:\n`}let a=i.filter(e=>/\.(md|mdx)$/.test(e)&&n.has(e));return a.length===1?`==> ${a[0]} <==\n`:``}function rC(e){if(e.length===0)return``;let t=[``,`### Referenced files`,``];for(let n of e)t.push($S(n)?eC(n):tC(n));return t.join(`
926
- `)}async function iC(e,t){let n=[],r=[];return await Promise.all(t.map(async t=>{try{let i=await dr(zn(e,t));i.isDirectory()?r.push(t):i.isFile()&&n.push(t)}catch{/\.(md|mdx)$/i.test(t)&&n.push(t)}})),{files:n,dirs:r}}function aC(e,t){return q(t,{enrichedPaths:[],error:{category:e,message:t}},!0)}function oC(e,t){return e.map(e=>{let n=t(gh(e.path));return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}})}async function sC(e,t){let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return aC(`shell_construct_blocked`,`exec failed: ${n.error}`);let{cwd:r,config:i,url:a}=n,o=_S(e.command);if(`error`in o)return aC(o.error.category,o.error.message);let s=iS(o.stages),c=aS(s),l=await Xx(r),u=Gx(r),d=``,f=``;try{let e=await Kx(u,c);d=e.stdout,f=e.stderr}catch(e){return e instanceof Wx?aC(`output_overflow`,`Output exceeded 16 MB buffer. Narrow the command (e.g., add a more specific grep pattern, use head, restrict the path).`):aC(`shell_construct_blocked`,`exec failed: ${e instanceof Error?e.message:String(e)}`)}let p=await Xx(r),m=Zx(l.snapshot,p.snapshot);if(m.changed.length>0)return aC(`security_invariant_violation`,`Security invariant violated: file(s) in the content directory were modified during a read-only exec call: ${m.changed.join(`, `)}. This indicates a parser bug; the command has been logged.`);let h=YS(d),g=Nh(d,s),{files:_,dirs:v}=await iC(r,g),y=s.length===1&&s[0].command===`cat`&&_.length===1,b=i.folders,x=await Promise.all(_.map(e=>US(e,{projectDir:r,serverUrl:a,folderRules:b},{includeRichFields:y}).catch(()=>({path:e,tags:[],backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null})))),S=await Promise.all(v.map(e=>GS(e,{projectDir:r,folderRules:b}).catch(()=>({path:e,type:`directory`,directMdCount:0,recursiveMdCount:0,childDirCount:0,truncated:!1}))));if(!y&&a&&x.length>0){let e=await BS(a,x.map(e=>LS(e.path))).catch(()=>null);if(e)for(let t of x){let n=e.get(LS(t.path));typeof n==`number`&&(t.backlinkCount=n)}}let ee=new Map(x.map(e=>[e.path,e])),te=new Map(S.map(e=>[e.path,e])),ne=[];for(let e of g){let t=ee.get(e);if(t){ne.push(t);continue}let n=te.get(e);n&&ne.push(n)}let re=XS(s),C=[];re.length>0&&C.push(`File${re.length>1?`s`:``} ${re.join(`, `)} appear${re.length===1?`s`:``} to be binary (image/PDF/etc.) — exec returns text only (NG8). For binary retrieval, use native Read.`);let w=QS(s,d);w&&C.push(w.banner),f&&C.push(`stderr: ${f.trim()}`);let ie=C.length>0?`${C.join(`
927
- `)}\n\n`:``,ae=nC(s,te,ee)+h.text,T=`${ie}${ae}${rC(ne)}`,{resolve:E,ui:oe}=await hh({config:i,resolveCwd:async()=>r}),se=oC(ne,E),ce=oe;return q(T,{enrichedPaths:se,stdout:ae,stdoutTruncated:h.truncated,cwd:r,...ce?{ui:ce}:{},...C.length>0?{warnings:C}:{}})}function cC(e,t){e.tool(`exec`,JS,{command:D().describe(`Read-only bash command (allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut; pipes OK)`),cwd:D().optional().describe("Absolute host path to run the command from. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.")},async e=>{try{return await sC(e,t)}catch(e){return aC(`shell_construct_blocked`,`exec handler error: ${e instanceof Error?e.message:String(e)}`)}})}const lC=[`[Requires: Hocuspocus server] Find all pages that link to a given page.`,`Returns source page names, resolved titles, and context snippets as JSON.`,``,`**Parameters:**`,'- `docName` — Target page docName, typically without extension (for example, "articles/project-alpha"). A trailing `.md` or `.mdx` is stripped automatically.'].join(`
928
- `);function uC(e,t){e.tool(`get_backlinks`,lC,{docName:D().describe(`Target page docName`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=ih(e.docName);if(!a.ok)return K(a.error,!0);let o=await ah(i,`/api/backlinks?docName=${encodeURIComponent(a.docName)}`);if(!o.ok)return K(`Error: ${o.error}`,!0);let{ok:s,...c}=o,l=c,{resolve:u,ui:d}=await hh(t,r),f=(l.backlinks??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,n=t?u(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),p={...l,backlinks:f,ui:d,cwd:r};return q(JSON.stringify(p,null,2),p)})}const dC=[`[Operates on disk; no running OK server required] Read the effective merged Open Knowledge config (defaults → user → project).`,``,"Use this when you need to inspect the config mid-session — e.g., after a write that may have changed disk state, or to re-confirm the value of a field before composing a `set_config` patch.",``,"Read returns the FULL merged config or a sub-tree when `path` is provided. There is no allowlist on reads — every field is readable.",``,`**Parameters:**`,'- `path` (optional) — Dotted-segments array. `["folders"]` returns the folders array; `["mcp", "tools"]` returns the mcp.tools sub-tree. Omit for full config.',"- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
929
- `),fC={path:T(D()).optional().describe(`Dotted path as array of segments (e.g. ["mcp","tools","search"]). Omit to return the full merged config.`),cwd:D().optional().describe(qm)},pC={value:s().describe(`Resolved config value at the requested path (or full config).`),exists:ue().optional().describe('Whether the requested path resolved to a value. `false` distinguishes "path absent" from "path explicitly set to null"; absent on full-config reads.'),path:T(D()).optional().describe(`Echo of the requested dotted path (empty when reading the full config).`)};function mC(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=n[e]}return n}function hC(e,t){e.registerTool(`get_config`,{description:dC,inputSchema:fC,outputSchema:pC,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let n=await nh(t.resolveCwd,t.config,e.cwd);if(!n.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${n.error}`}]};let r=e.path??[],i=r.length>0?mC(n.config,r):n.config;return r.length>0&&i===void 0?q(`(no value at ${r.join(`.`)})`,{value:null,exists:!1,path:r}):q(JSON.stringify(i,null,2),{value:i,exists:!0,path:r})})}const gC=[`[Requires: Hocuspocus server] Find missing internal page targets across the corpus.`,`Returns grouped dead links keyed by missing target with source-doc rows as JSON.`,``,`**Parameters:**`,"- `sourceDocNames` (optional) — Referring source docs to narrow the audit with OR semantics"].join(`
930
- `);function _C(e,t){e.tool(`get_dead_links`,gC,{sourceDocNames:T(D()).optional().describe(`Referring source docs to narrow the audit with OR semantics`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=new URLSearchParams;for(let t of e.sourceDocNames??[]){let e=ih(t);if(!e.ok)return K(e.error,!0);a.append(`sourceDocName`,e.docName)}let o=a.toString(),s=await ah(i,`/api/dead-links${o?`?${o}`:``}`);if(!s.ok)return K(`Error: ${s.error}`,!0);let{ok:c,...l}=s,u=l,{resolve:d,ui:f}=await hh(t,r),p=(u.deadLinks??[]).map(e=>{let t=typeof e.target==`string`?e.target:null,n=t?d(t):null,r=(e.sources??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,n=t?d(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}});return{...e,sources:r,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),m={...u,deadLinks:p,ui:f,cwd:r};return q(JSON.stringify(m,null,2),m)})}const vC=[`[Requires: Hocuspocus server] Find all pages that a given page links to.`,`Returns forward links as JSON.`,``,`**Parameters:**`,"- `docName` — Source page docName, typically without extension. A trailing `.md` or `.mdx` is stripped automatically."].join(`
931
- `);function yC(e,t){e.tool(`get_forward_links`,vC,{docName:D().describe(`Source page docName`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=ih(e.docName);if(!a.ok)return K(a.error,!0);let o=await ah(i,`/api/forward-links?docName=${encodeURIComponent(a.docName)}`);if(!o.ok)return K(`Error: ${o.error}`,!0);let{ok:s,...c}=o,l=c,{resolve:u,ui:d}=await hh(t,r),f=(l.forwardLinks??[]).map(e=>{let t=e.kind===`doc`&&typeof e.docName==`string`?e.docName:null,n=t?u(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),p={...l,forwardLinks:f,ui:d,cwd:r};return q(JSON.stringify(p,null,2),p)})}const bC=[`[Requires: Hocuspocus server] List version history for a document.`,`Returns timeline entries from the shadow repo, sorted by timestamp descending.`,"Each entry includes a commit SHA that can be passed to `rollback_to_version`.",``,`**Parameters:**`,"- `docName` — Document name to query history for, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `branch` (optional) — Branch name (default: current branch)","- `limit` (optional) — Maximum entries to return (default 50, max 200)","- `offset` (optional) — Number of entries to skip for pagination (default 0)",'- `type` (optional) — Filter by entry type: "checkpoint", "upstream", or "wip"',"- `author` (optional) — Filter to entries by this author name or email","- `excludeAuthor` (optional) — Exclude entries by this author name or email"].join(`
932
- `);function xC(e,t){e.tool(`get_history`,bC,{docName:D().describe(`Document name to query history for`),branch:D().optional().describe(`Branch name (default: current branch)`),limit:C().int().min(1).max(200).optional().describe(`Maximum entries to return (default 50, max 200)`),offset:C().int().min(0).optional().describe(`Number of entries to skip for pagination (default 0)`),type:le([`checkpoint`,`upstream`,`wip`]).optional().describe(`Filter by entry type`),author:D().optional().describe(`Filter to entries by this author name or email`),excludeAuthor:D().optional().describe(`Exclude entries by this author name or email`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=ih(e.docName);if(!a.ok)return K(a.error,!0);let o=new URLSearchParams;o.set(`docName`,a.docName),e.branch&&o.set(`branch`,e.branch),e.limit!=null&&o.set(`limit`,String(e.limit)),e.offset!=null&&o.set(`offset`,String(e.offset)),e.type&&o.set(`type`,e.type),e.author&&o.set(`author`,e.author),e.excludeAuthor&&o.set(`excludeAuthor`,e.excludeAuthor);let s=await ah(i,`/api/history?${o.toString()}`);if(!s.ok)return K(`Error: ${s.error}`,!0);let{ok:c,...l}=s,u=await ph(a.docName,{config:t.config,resolveCwd:t.resolveCwd},r);return q(JSON.stringify(l,null,2),{...l,previewUrl:u?.url??null,...u?{previewUrlSource:u.source}:{}})})}const SC=[`[Requires: Hocuspocus server] Find the most-linked pages in the knowledge graph.`,`Returns hub pages ordered by inbound link count as JSON.`,``,`**Parameters:**`,"- `limit` (optional) — Maximum number of hubs to return (default 20)"].join(`
933
- `);function CC(e,t){e.tool(`get_hubs`,SC,{limit:C().int().positive().optional().describe(`Maximum number of hubs to return`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=await ah(i,`/api/hubs${e.limit?`?limit=${encodeURIComponent(String(e.limit))}`:``}`);if(!a.ok)return K(`Error: ${a.error}`,!0);let{ok:o,...s}=a,c=s,{resolve:l,ui:u}=await hh(t,r),d=(c.hubs??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,n=t?l(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),f={...c,hubs:d,ui:u,cwd:r};return q(JSON.stringify(f,null,2),f)})}const wC=[`[Requires: Hocuspocus server] Find disconnected pages in the knowledge graph.`,`Returns orphaned pages as JSON.`,``,`**Parameters:**`,"- `mode` (optional) — Orphan lens: `incoming`, `outgoing`, or `both` (default `both`)"].join(`
934
- `);function TC(e,t){e.tool(`get_orphans`,wC,{mode:le(me).optional().describe(`Filter which type of graph disconnection to surface`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=await ah(i,`/api/orphans${e.mode?`?mode=${encodeURIComponent(e.mode)}`:``}`);if(!a.ok)return K(`Error: ${a.error}`,!0);let{ok:o,...s}=a,c=s,{resolve:l,ui:u}=await hh(t,r),d=(c.orphans??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,n=t?l(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),f={...c,orphans:d,ui:u,cwd:r};return q(JSON.stringify(f,null,2),f)})}function EC(e,t){return`${$m(`ingest`)}Capture this external source into the project knowledge base as raw reference material. The KB is **closed-loop**: external sources are pulled INTO the knowledge base here so downstream docs cite local paths, never bare web URLs. This applies whether a user shared the source OR you fetched it yourself to ground a knowledge-base claim — agent-initiated fetches are not exempt. **Raw preservation only** — no summary, no analysis, no interpretation. Summarizing is the job of the \`research\` tool later.
918
+ `)}var zx=new TextDecoder(`utf-8`,{fatal:!0});function Bx(e){if(!e)return e;let t=!1;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>255)return e;r>127&&(t=!0)}if(!t)return e;let n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);try{return zx.decode(n)}catch{return e}}var Vx=[`EACCES`,`escaping sandbox`,`EFBIG`],Hx=class{root;canonicalRoot;maxFileReadSize;allowSymlinks;constructor(e){this.root=Mn.resolve(e.root),this.maxFileReadSize=e.maxFileReadSize??10485760,this.allowSymlinks=e.allowSymlinks??!1,dn(this.root,`ReadWriteFs`),this.canonicalRoot=A.realpathSync(this.root)}resolveAndValidate(e,t){let n=this.allowSymlinks?ln(e,this.canonicalRoot):un(e,this.root,this.canonicalRoot);if(n===null)throw Error(`EACCES: permission denied, '${t}' resolves outside sandbox`);return n}validateParent(e,t){let n=Mn.dirname(e),r=this.resolveAndValidate(n,t);return Mn.join(r,Mn.basename(e))}toRealPath(e){let t=on(e),n=Mn.join(this.root,t);return Mn.resolve(n)}async readFile(e,t){return hn(await this.readFileBuffer(e),pn(t))}async readFileBuffer(e){k(e,`open`);let t=this.toRealPath(e),n=this.resolveAndValidate(t,e);try{let t=this.allowSymlinks?A.constants.O_RDONLY:A.constants.O_RDONLY|A.constants.O_NOFOLLOW,r=await A.promises.open(n,t);try{if(this.maxFileReadSize>0){let t=await r.stat();if(t.size>this.maxFileReadSize)throw Error(`EFBIG: file too large, read '${e}' (${t.size} bytes, max ${this.maxFileReadSize})`)}let t=await r.readFile();return new Uint8Array(t)}finally{await r.close()}}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, open '${e}'`);if(n.code===`EISDIR`)throw Error(`EISDIR: illegal operation on a directory, read '${e}'`);if(n.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`open`)}}async writeFile(e,t,n){k(e,`write`);let r=this.toRealPath(e),i=this.resolveAndValidate(r,e),a=mn(t,pn(n)),o=Mn.dirname(i);try{await A.promises.mkdir(o,{recursive:!0}),i=this.resolveAndValidate(r,e);let t=this.allowSymlinks?0:A.constants.O_NOFOLLOW,n=A.constants.O_WRONLY|A.constants.O_CREAT|A.constants.O_TRUNC|t,s=await A.promises.open(i,n,438);try{await s.writeFile(a)}finally{await s.close()}}catch(t){if(t.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`write`)}}async appendFile(e,t,n){k(e,`append`);let r=this.toRealPath(e),i=this.resolveAndValidate(r,e),a=mn(t,pn(n)),o=Mn.dirname(i);try{await A.promises.mkdir(o,{recursive:!0}),i=this.resolveAndValidate(r,e);let t=this.allowSymlinks?0:A.constants.O_NOFOLLOW,n=A.constants.O_WRONLY|A.constants.O_CREAT|A.constants.O_APPEND|t,s=await A.promises.open(i,n,438);try{await s.writeFile(a)}finally{await s.close()}}catch(t){if(t.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`append`)}}async exists(e){if(e.includes(`\0`))return!1;let t=this.toRealPath(e);try{let n=this.resolveAndValidate(t,e);return await A.promises.access(n),!0}catch{return!1}}async stat(e){k(e,`stat`);let t=this.toRealPath(e),n=this.resolveAndValidate(t,e);try{let t=await A.promises.lstat(n);if(!this.allowSymlinks&&t.isSymbolicLink())throw Error(`EACCES: permission denied, '${e}' is a symlink`);return{isFile:t.isFile(),isDirectory:t.isDirectory(),isSymbolicLink:t.isSymbolicLink(),mode:t.mode,size:t.size,mtime:t.mtime}}catch(t){if(t.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, stat '${e}'`);this.sanitizeError(t,e,`stat`)}}async lstat(e){k(e,`lstat`);let t=this.toRealPath(e),n=this.validateParent(t,e);try{let e=await A.promises.lstat(n);return{isFile:e.isFile(),isDirectory:e.isDirectory(),isSymbolicLink:e.isSymbolicLink(),mode:e.mode,size:e.size,mtime:e.mtime}}catch(t){if(t.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, lstat '${e}'`);this.sanitizeError(t,e,`lstat`)}}async mkdir(e,t){k(e,`mkdir`);let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{await A.promises.mkdir(r,{recursive:t?.recursive})}catch(t){let n=t;if(n.code===`EEXIST`)throw Error(`EEXIST: file already exists, mkdir '${e}'`);if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.sanitizeError(t,e,`mkdir`)}}async readdir(e){return(await this.readdirWithFileTypes(e)).map(e=>e.name)}async readdirWithFileTypes(e){k(e,`scandir`);let t=this.toRealPath(e),n=this.resolveAndValidate(t,e);try{if(!this.allowSymlinks&&(await A.promises.lstat(n)).isSymbolicLink())throw Error(`EACCES: permission denied, '${e}' is a symlink`);return(await A.promises.readdir(n,{withFileTypes:!0})).map(e=>({name:e.name,isFile:e.isFile(),isDirectory:e.isDirectory(),isSymbolicLink:e.isSymbolicLink()})).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);if(n.code===`ENOTDIR`)throw Error(`ENOTDIR: not a directory, scandir '${e}'`);this.sanitizeError(t,e,`scandir`)}}async rm(e,t){k(e,`rm`);let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{await A.promises.rm(r,{recursive:t?.recursive??!1,force:t?.force??!1})}catch(n){let r=n;if(r.code===`ENOENT`&&!t?.force)throw Error(`ENOENT: no such file or directory, rm '${e}'`);if(r.code===`ENOTEMPTY`)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);this.sanitizeError(n,e,`rm`)}}async cp(e,t,n){k(e,`cp`),k(t,`cp`);let r=this.toRealPath(e),i=this.toRealPath(t),a=this.resolveAndValidate(r,e),o=this.resolveAndValidate(i,t);try{await A.promises.cp(a,o,{recursive:n?.recursive??!1,filter:async e=>{try{if(A.lstatSync(e).isSymbolicLink()){let t=await A.promises.realpath(e).catch(()=>null);return t===null?!1:nn(t,this.canonicalRoot)}return!0}catch(e){return e.code===`ENOENT`}}})}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(n.code===`EISDIR`)throw Error(`EISDIR: is a directory, cp '${e}'`);this.sanitizeError(t,e,`cp`)}}async mv(e,t){k(e,`mv`),k(t,`mv`);let n=this.toRealPath(e),r=this.toRealPath(t),i=this.validateParent(n,e),a=this.validateParent(r,t);try{if((await A.promises.lstat(i)).isSymbolicLink()){let n=await A.promises.readlink(i),r=Mn.resolve(Mn.dirname(a),n);if(!nn(await A.promises.realpath(r).catch(()=>r),this.canonicalRoot))throw Error(`EACCES: permission denied, mv '${e}' -> '${t}' would create symlink escaping sandbox`)}}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mv '${e}'`);if(n.message?.includes(`EACCES`)||n.message?.includes(`escaping sandbox`))throw t}let o=Mn.dirname(a);try{await A.promises.mkdir(o,{recursive:!0})}catch(e){this.sanitizeError(e,t,`mv`)}try{await A.promises.rename(i,a)}catch(n){let r=n;if(r.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mv '${e}'`);if(r.code===`EXDEV`){await this.cp(e,t,{recursive:!0}),await this.rm(e,{recursive:!0});return}this.sanitizeError(n,e,`mv`)}try{if(A.lstatSync(a).isDirectory()&&this.findEscapingSymlinks(a).length>0)throw await A.promises.rename(a,i),Error(`EACCES: permission denied, mv '${e}' -> '${t}' would create symlinks escaping sandbox`)}catch(e){if(e.message?.includes(`EACCES`)||e.message?.includes(`escaping sandbox`))throw e}}resolvePath(e,t){return an(e,t)}getAllPaths(){let e=[];return this.scanDir(`/`,e),e}sanitizeError(e,t,n){cn(e,t,n,Vx)}findEscapingSymlinks(e){let t=[];try{let n=A.readdirSync(e);for(let r of n){let n=Mn.join(e,r);try{let r=A.lstatSync(n);if(r.isSymbolicLink()){let r=A.readlinkSync(n),i=Mn.resolve(e,r),a;try{a=A.realpathSync(i)}catch{a=i}nn(a,this.canonicalRoot)||t.push(n)}else r.isDirectory()&&t.push(...this.findEscapingSymlinks(n))}catch{}}}catch{}return t}scanDir(e,t){let n=this.toRealPath(e),r;try{r=this.resolveAndValidate(n,e)}catch{return}try{let n=A.readdirSync(r);for(let i of n){let n=e===`/`?`/${i}`:`${e}/${i}`;t.push(n);let a=Mn.join(r,i);A.lstatSync(a).isDirectory()&&this.scanDir(n,t)}}catch{}}async chmod(e,t){k(e,`chmod`);let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{let e=this.allowSymlinks?A.constants.O_RDONLY:A.constants.O_RDONLY|A.constants.O_NOFOLLOW,n=await A.promises.open(r,e);try{await n.chmod(t)}finally{await n.close()}}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);if(n.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`chmod`)}}async symlink(e,t){if(!this.allowSymlinks)throw Error(`EPERM: operation not permitted, symlink '${t}'`);k(t,`symlink`);let n=this.toRealPath(t),r=this.validateParent(n,t),i=on(t),a=on(Mn.dirname(i)),o=e.startsWith(`/`)?on(e):on(a===`/`?`/${e}`:`${a}/${e}`),s=Mn.join(this.canonicalRoot,o),c=Mn.dirname(r),l=e.startsWith(`/`)?s:Mn.relative(c,s)||`.`;try{await A.promises.symlink(l,r)}catch(e){if(e.code===`EEXIST`)throw Error(`EEXIST: file already exists, symlink '${t}'`);this.sanitizeError(e,t,`symlink`)}}async link(e,t){k(e,`link`),k(t,`link`);let n=this.toRealPath(e),r=this.toRealPath(t),i=this.resolveAndValidate(n,e),a=this.resolveAndValidate(r,t);try{await A.promises.link(i,a)}catch(n){let r=n;if(r.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(r.code===`EEXIST`)throw Error(`EEXIST: file already exists, link '${t}'`);if(r.code===`EPERM`)throw Error(`EPERM: operation not permitted, link '${e}'`);this.sanitizeError(n,e,`link`)}}async readlink(e){k(e,`readlink`);let t=this.toRealPath(e),n=this.validateParent(t,e);try{let t=await A.promises.readlink(n),r=on(e),i=Mn.dirname(r),a=Mn.isAbsolute(t)?t:Mn.resolve(Mn.dirname(n),t),o=await A.promises.realpath(a).catch(()=>a);if(nn(o,this.canonicalRoot)){let e=o.slice(this.canonicalRoot.length)||`/`;return i===`/`?e.startsWith(`/`)?e.slice(1)||`.`:e:Mn.relative(i,e)}return Mn.basename(t)}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, readlink '${e}'`);if(n.code===`EINVAL`)throw Error(`EINVAL: invalid argument, readlink '${e}'`);this.sanitizeError(t,e,`readlink`)}}async realpath(e){k(e,`realpath`);let t=this.toRealPath(e);try{this.resolveAndValidate(t,e)}catch{throw Error(`ENOENT: no such file or directory, realpath '${e}'`)}let n;try{n=await A.promises.realpath(t)}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, realpath '${e}'`);if(n.code===`ELOOP`)throw Error(`ELOOP: too many levels of symbolic links, realpath '${e}'`);this.sanitizeError(t,e,`realpath`)}if(nn(n,this.canonicalRoot))return n.slice(this.canonicalRoot.length)||`/`;throw Error(`ENOENT: no such file or directory, realpath '${e}'`)}async utimes(e,t,n){k(e,`utimes`);let r=this.toRealPath(e),i=this.resolveAndValidate(r,e);try{let e=this.allowSymlinks?A.constants.O_RDONLY:A.constants.O_RDONLY|A.constants.O_NOFOLLOW,r=await A.promises.open(i,e);try{await r.utimes(t,n)}finally{await r.close()}}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);if(n.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`utimes`)}}};function Ux(e){return e===``?`''`:/^[\w.\-/]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}const Wx=16*1024*1024;var Gx=class extends Error{limitBytes;actualBytes;partial;constructor(e,t,n){super(`Output exceeded ${e} byte buffer (got ${t}); narrow the command`),this.name=`StdoutOverflowError`,this.limitBytes=e,this.actualBytes=t,this.partial=n}};function Kx(e){if(!In(e))throw Error(`createBashInstance: cwd must be absolute (got: ${e})`);return new Lx({cwd:`/`,fs:new Hx({root:zn(e),allowSymlinks:!1})})}async function qx(e,t){let n=await e.exec(t);if(n.stdout.length>Wx)throw new Gx(Wx,n.stdout.length,{stdout:n.stdout.slice(0,Wx),stderr:n.stderr,exitCode:n.exitCode});return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}}function Jx(e){return e.startsWith(`**/`)?e.slice(3):e}async function Yx(e,t,n={}){let r=Kx(t),i=[`-rn`,`-F`];(n.caseInsensitive??!0)&&i.push(`-i`);for(let e of n.include??[])i.push(`--include=${Ux(Jx(e))}`);for(let e of n.exclude??[])i.push(`--exclude=${Ux(Jx(e))}`),i.push(`--exclude-dir=${Ux(Jx(e))}`);let a=n.paths?.length?n.paths.map(Ux):[`.`],o=`grep ${i.join(` `)} ${Ux(e)} ${a.join(` `)}`,s;try{s=await qx(r,o)}catch(e){if(e instanceof Gx)s=e.partial;else throw e}if(s.exitCode===1&&!s.stdout)return[];if(s.exitCode!==0&&s.exitCode!==1&&!s.stdout)throw Error(`grep exited ${s.exitCode}: ${s.stderr}`);let c=[],l=n.maxResults??1/0;for(let e of s.stdout.split(`
919
+ `)){if(!e)continue;if(c.length>=l)break;let t=e.indexOf(`:`);if(t===-1)continue;let n=e.indexOf(`:`,t+1);if(n===-1)continue;let r=e.slice(0,t),i=e.slice(t+1,n),a=e.slice(n+1),o=Number.parseInt(i,10);Number.isFinite(o)&&c.push({path:r,line:o,text:a})}return c}const Xx=new Set([`.git`,i,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]);async function Zx(e){let t=zn(e),n=new Map,r=0,i=!1;async function a(e){if(i)return;let o;try{o=await ur(e,{withFileTypes:!0})}catch{return}for(let s of o){if(i)return;if(s.isDirectory()&&Xx.has(s.name))continue;let o=zn(e,s.name);if(s.isDirectory()){await a(o);continue}if(s.isFile()){if(r>=1e3){i=!0;return}try{let e=await dr(o);n.set(Rn(t,o),e.mtimeMs),r++}catch{}}}}return await a(t),{snapshot:n,truncated:i}}function Qx(e,t){let n=[];for(let[r,i]of t){let t=e.get(r);(t===void 0||t!==i)&&n.push(r)}for(let[r]of e)t.has(r)||n.push(r);return{changed:n}}var $x=n(((e,t)=>{t.exports=function(e){return e.map(function(e){return e===``?`''`:e&&typeof e==`object`?e.op.replace(/(.)/g,`\\$1`):/["\s\\]/.test(e)&&!/'/.test(e)?`'`+e.replace(/(['])/g,`\\$1`)+`'`:/["'\s]/.test(e)?`"`+e.replace(/(["\\$`!])/g,`\\$1`)+`"`:String(e).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,`$1\\$2`)}).join(` `)}})),eS=n(((e,t)=>{for(var n=`(?:`+[`\\|\\|`,`\\&\\&`,`;;`,`\\|\\&`,`\\<\\(`,`\\<\\<\\<`,`>>`,`>\\&`,`<\\&`,`[&;()|<>]`].join(`|`)+`)`,r=RegExp(`^`+n+`$`),i=`|&;()<> \\t`,a=`"((\\\\"|[^"])*?)"`,o=`'((\\\\'|[^'])*?)'`,s=/^#$/,c=`'`,l=`"`,u=`$`,d=``,f=4294967296,p=0;p<4;p++)d+=(f*Math.random()).toString(16);var m=RegExp(`^`+d);function h(e,t){for(var n=t.lastIndex,r=[],i;i=t.exec(e);)r.push(i),t.lastIndex===i.index&&(t.lastIndex+=1);return t.lastIndex=n,r}function g(e,t,n){var r=typeof e==`function`?e(n):e[n];return r===void 0&&n!=``?r=``:r===void 0&&(r=`$`),typeof r==`object`?t+d+JSON.stringify(r)+d:t+r}function _(e,t,d){d||={};var f=d.escape||`\\`,p=`(\\`+f+`['"`+i+`]|[^\\s'"`+i+`])+`,m=h(e,new RegExp([`(`+n+`)`,`(`+p+`|`+a+`|`+o+`)+`].join(`|`),`g`));if(m.length===0)return[];t||={};var _=!1;return m.map(function(n){var i=n[0];if(!i||_)return;if(r.test(i))return{op:i};var a=!1,o=!1,d=``,p=!1,m;function h(){m+=1;var e,n,r=i.charAt(m);if(r===`{`){if(m+=1,i.charAt(m)===`}`)throw Error(`Bad substitution: `+i.slice(m-2,m+1));if(e=i.indexOf(`}`,m),e<0)throw Error(`Bad substitution: `+i.slice(m));n=i.slice(m,e),m=e}else if(/[*@#?$!_-]/.test(r))n=r,m+=1;else{var a=i.slice(m);e=a.match(/[^\w\d_]/),e?(n=a.slice(0,e.index),m+=e.index-1):(n=a,m=i.length)}return g(t,``,n)}for(m=0;m<i.length;m++){var v=i.charAt(m);if(p||=!a&&(v===`*`||v===`?`),o)d+=v,o=!1;else if(a)v===a?a=!1:a==c?d+=v:v===f?(m+=1,v=i.charAt(m),v===l||v===f||v===u?d+=v:d+=f+v):v===u?d+=h():d+=v;else if(v===l||v===c)a=v;else if(r.test(v))return{op:i};else if(s.test(v)){_=!0;var y={comment:e.slice(n.index+m+1)};return d.length?[d,y]:[y]}else v===f?o=!0:v===u?d+=h():d+=v}return p?{op:`glob`,pattern:d}:d}).reduce(function(e,t){return t===void 0?e:e.concat(t)},[])}t.exports=function(e,t,n){var r=_(e,t,n);return typeof t==`function`?r.reduce(function(e,t){if(typeof t==`object`)return e.concat(t);var n=t.split(RegExp(`(`+d+`.*?`+d+`)`,`g`));return n.length===1?e.concat(n[0]):e.concat(n.filter(Boolean).map(function(e){return m.test(e)?JSON.parse(e.split(d)[1]):e}))},[]):r}})),tS=t(n((e=>{e.quote=$x(),e.parse=eS()}))(),1);const nS=[`node_modules`,`.git`,`dist`,`build`,`.next`,`.turbo`,`.nuxt`,`coverage`,`.cache`,`.parcel-cache`,`.vercel`,i,`.claude`];function rS(e){return e===`--recursive`||e===`--dereference-recursive`?!0:e.startsWith(`--`)||!e.startsWith(`-`)?!1:/[rR]/.test(e.slice(1))}const iS=[{command:`grep`,applies:e=>e.slice(1).some(rS),hasUserExcludes:e=>e.some(e=>e===`--exclude-dir`||e.startsWith(`--exclude-dir=`)),buildExcludeArgs:e=>e.map(e=>`--exclude-dir=${e}`),insertionIndex:()=>1},{command:`find`,applies:()=>!0,hasUserExcludes:e=>e.slice(1).some(e=>e===`-not`||e===`!`||e===`-prune`),buildExcludeArgs:e=>{let t=[];for(let n of e)t.push(`-not`,`-path`,`*/${n}/*`);return t},insertionIndex:e=>{for(let t=1;t<e.length;t++)if(e[t].startsWith(`-`))return t;return e.length}}];function aS(e){return e.map(e=>{let t=iS.find(t=>t.command===e.command);if(!t||!t.applies(e.args)||t.hasUserExcludes(e.args))return e;let n=t.buildExcludeArgs(nS),r=t.insertionIndex(e.args);return{command:e.command,args:[...e.args.slice(0,r),...n,...e.args.slice(r)]}})}function oS(e){return e.map(e=>e.args.map(Ux).join(` `)).join(` | `)}const sS=new Set([`cat`,`ls`,`grep`,`find`,`head`,`tail`,`wc`,`sort`,`uniq`,`cut`]),cS=new Set([`>`,`>>`,`<`,`>&`,`<&`,`|&`]),lS=new Set([`&`,`;`,`;;`,`&&`,`||`,`(`,`)`,`<(`,`>(`,`<<`,`<<-`]),uS=new Set([`-o`,`--output-file`,`--output`]),dS=[`-o=`,`--output-file=`,`--output=`],fS=new Set([`-exec`,`-execdir`,`-delete`,`-fprint`,`-fprintf`,`-fprint0`,`-ok`,`-okdir`]),pS=/[`]|\$\(|\$\{|\$'/;function mS(e){return typeof e==`object`&&!!e&&`op`in e}function hS(e){let t=typeof e.op==`string`?e.op:`(unknown)`;return cS.has(t)?{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use write_document or edit_document.`}:lS.has(t)?{category:`shell_construct_blocked`,message:`Shell construct '${t}' is not supported. Only pipes (|) are allowed between allowlisted stages.`}:{category:`shell_construct_blocked`,message:`Operator '${t}' is not supported.`}}function gS(e){let t=[];for(let n of e){if(typeof n==`string`){if(pS.test(n))return{error:{category:`shell_construct_blocked`,message:`Argument '${n}' contains a shell-injection pattern (backtick, $(), or \${}); not supported.`}};t.push(n);continue}if(!mS(n))return{error:{category:`shell_construct_blocked`,message:`Unrecognized token shape.`}};if(n.op===`glob`&&typeof n.pattern==`string`){t.push(n.pattern);continue}return typeof n.comment==`string`?{error:{category:`shell_construct_blocked`,message:`Comments are not allowed in exec commands.`}}:{error:hS(n)}}return{args:t}}function _S(e){if(!sS.has(e.command))return{category:`unknown_command`,message:`Command '${e.command}' is not in the allowlist. For pattern matching try 'grep'; for file listing try 'ls' or 'find'. Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut.`};for(let t of e.args.slice(1)){if(uS.has(t)||dS.some(e=>t.startsWith(e)))return{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use write_document or edit_document.`};if(e.command===`find`&&fS.has(t))return{category:`write_blocked`,message:`find flag '${t}' is blocked (executes commands or deletes files). Use exec for read-only discovery; chain with another allowlisted tool via '|' if you need to transform output.`}}return null}function vS(e){let t=e.trim();if(!t)return{error:{category:`unknown_command`,message:`Empty command.`}};let n;try{n=tS.parse(t)}catch{return{error:{category:`shell_construct_blocked`,message:`Failed to parse command — likely malformed quoting or an unsupported construct.`}}}let r=[],i=[];for(let e of n){if(mS(e)&&e.op===`|`){r.push(i),i=[];continue}i.push(e)}r.push(i);let a=[];for(let e of r){let t=gS(e);if(`error`in t)return t;if(t.args.length===0)return{error:{category:`shell_construct_blocked`,message:`Empty pipeline stage (trailing pipe or leading pipe).`}};let n={command:t.args[0],args:t.args},r=_S(n);if(r)return{error:r};a.push(n)}return{stages:a}}const yS=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function bS(e,t){let n=e.match(yS);if(!n)return null;try{let e=(0,_r.parse)(n[1]);if(He(e)){if(t){let n=t.safeParse(e);return n.success?n.data:null}return e}}catch{}return null}var xS=t(Fe(),1);const SS=new WeakMap;function CS(e){let t=SS.get(e);if(t)return t;let n=e.map(e=>(0,xS.default)(e.match,{dot:!0}));return SS.set(e,n),n}function wS(e,t){if(e.length===0)return{};let n=CS(e),r={},i=[],a=!1;for(let o=0;o<e.length;o++){if(!n[o](t))continue;a=!0;let s=e[o].frontmatter;if(s.title!==void 0&&(r.title=s.title),s.description!==void 0&&(r.description=s.description),s.tags!==void 0)for(let e of s.tags)i.includes(e)||i.push(e)}return a?(i.length>0&&(r.tags=i),r):{}}function TS(e){try{return Jn(zn(e,`.git`)).isDirectory()}catch{return!1}}function ES(e){return De({baseDir:zn(e),timeout:{block:5e3}})}async function DS(e,t,n=5){if(!TS(e))return{commits:[],source:`git-absent`};let r=ES(e),i=``;try{i=await r.raw(`log`,`-${Math.max(1,n)}`,`--format=%H|%aI|%an|%s`,`--follow`,`--`,t)}catch{return{commits:[],source:`git`}}let a=[];for(let e of i.split(`
920
+ `)){if(!e)continue;let t=e.indexOf(`|`);if(t<0)continue;let n=e.indexOf(`|`,t+1);if(n<0)continue;let r=e.indexOf(`|`,n+1);r<0||a.push({hash:e.slice(0,t),date:e.slice(t+1,n),authorName:e.slice(n+1,r),subject:e.slice(r+1)})}return{commits:a,source:`git`}}const OS=5e3;async function kS(e){try{let t=(await De({baseDir:e,timeout:{block:OS}}).revparse([`--abbrev-ref`,`HEAD`])).trim();return t&&t!==`HEAD`?t:null}catch{return null}}function AS(e,t){return De({baseDir:t,timeout:{block:OS}}).env({GIT_DIR:e,GIT_WORK_TREE:t})}function jS(e,t){let n=Pe(t);return e.startsWith(n)?e.slice(n.length):e}async function MS(e,t,n,r,i){let a=``;try{a=await e.raw(`log`,t,`-${Math.max(1,i*2)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,`--`,n)}catch{return[]}let o=jS(t,r),s=Ne(o),c=[];for(let e of a.split(``)){let t=e.trimStart();if(!t)continue;let[n=``,i=``,a=``,l=``,u=``]=t.split(`\0`),d=n.trim();d.length===40&&c.push({hash:d,date:i,writerName:a,message:l,contributors:Ie(u),writerId:o,isAgent:s.isAgent,writerClassification:s.classification,branch:r})}return c}async function NS(e,t,n=5){let r=Le(e);if(!r)return{commits:[],source:`shadow-repo-absent`};let i=await kS(e);if(!i)return{commits:[],source:`shadow-repo`};let a=AS(r,zn(e)),o=``;try{o=await a.raw(`for-each-ref`,Pe(i),`--format=%(refname)`)}catch{return{commits:[],source:`shadow-repo`}}let s=o.split(`
921
+ `).map(e=>e.trim()).filter(Boolean);return s.length===0?{commits:[],source:`shadow-repo`}:{commits:(await Promise.all(s.map(e=>MS(a,e,t,i,n)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,n),source:`shadow-repo`}}const PS=1e3,FS=new Set([`.git`,i,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),IS=/\.(md|mdx)$/i,LS=x({title:D().optional(),description:D().optional(),tags:T(D()).default([])});function RS(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}async function zS(e){try{let t=bS(await lr(e,`utf-8`),LS);return t?{title:t.title,description:t.description,tags:t.tags??[]}:{tags:[]}}catch{return null}}async function BS(e,t){if(!e)return null;let n=await ah(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.backlinks??n.results??n.links;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e,n=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;n&&i.push({source:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}async function VS(e,t){if(!e||t.length===0)return null;let n=[...new Set(t)],r=[];for(let e=0;e<n.length;e+=100)r.push(n.slice(e,e+100));let i=await Promise.all(r.map(async t=>{let n=await ah(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return n.ok?n.counts??{}:null})),a=new Map,o=!1;for(let e of i)if(e){o=!0;for(let[t,n]of Object.entries(e))typeof n==`number`&&Number.isFinite(n)&&a.set(t,n)}return o?a:null}async function HS(e,t){if(!e)return null;let n=await ah(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.forwardLinks??n.links??n.results;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){i.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let n=typeof t.docName==`string`?t.docName:void 0;n&&i.push({kind:`doc`,docName:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}function US(e,t,n){let r=t??[],i=r.length===0?{}:wS(r,n),a=e?.title??i.title,o=e?.description??i.description,s=e?.tags??[],c=i.tags??[],l;if(c.length===0)l=s;else{let e=new Set;l=[];for(let t of c)e.has(t)||(e.add(t),l.push(t));for(let t of s)e.has(t)||(e.add(t),l.push(t))}return{title:a,description:o,tags:l}}async function WS(e,t,n={}){let r=e.replace(/^\.\//,``).replace(/^\/+/,``),i=zn(t.projectDir,r),a=t.historyDepth??5,o=n.includeRichFields===!0,s=zS(i);if(!o){let e=US(await s,t.folderRules,r);return{path:r,title:e.title,description:e.description,tags:e.tags,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null}}let[c,l,u,d,f]=await Promise.all([s,BS(t.serverUrl,RS(r)).catch(()=>null),HS(t.serverUrl,RS(r)).catch(()=>null),NS(t.projectDir,r,a).catch(()=>({commits:[],source:`shadow-repo`})),DS(t.projectDir,r,a).catch(()=>({commits:[],source:`git`}))]),p=US(c,t.folderRules,r);return{path:r,title:p.title,description:p.description,tags:p.tags,backlinkCount:l?.length??null,backlinks:l,forwardLinkCount:u?.length??null,forwardLinks:u,history:d.commits,historySource:d.source,projectHistory:f.commits,projectHistorySource:f.source}}async function GS(e,t){let n={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},r=0,i=[{path:e,depth:0}];for(;i.length>0;){let e=i.shift();if(!e)break;if(r>=PS){n.truncated=!0;break}let a;try{a=await ur(e.path,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=PS){n.truncated=!0;break}r++;let a=o.name;if(o.isDirectory()){if(FS.has(a)||a.startsWith(`.`))continue;e.depth===0&&n.childDirCount++,i.push({path:`${e.path}/${a}`,depth:e.depth+1})}else if(o.isFile()&&IS.test(a)){n.recursiveMdCount++,e.depth===0&&n.directMdCount++;let r=`${e.path}/${a}`;try{let e=await dr(r);(!n.mostRecent||e.mtimeMs>n.mostRecent.mtimeMs)&&(n.mostRecent={absPath:r,relPath:Rn(t,r).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return n}async function KS(e,t){let n=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``),r=await GS(zn(t.projectDir,n),t.projectDir),i;if(r.mostRecent){let e=await zS(r.mostRecent.absPath);i={path:r.mostRecent.relPath,title:e?.title??Pn(r.mostRecent.relPath),updatedAt:new Date(r.mostRecent.mtimeMs).toISOString()}}let a={path:n,type:`directory`,directMdCount:r.directMdCount,recursiveMdCount:r.recursiveMdCount,childDirCount:r.childDirCount,mostRecentMd:i,truncated:r.truncated},o=t.folderRules??[];if(o.length>0){let e=wS(o,n);e.title!==void 0&&(a.title=e.title),e.description!==void 0&&(a.description=e.description),e.tags!==void 0&&e.tags.length>0&&(a.tags=e.tags)}return a}const qS=50*1024,JS=/\.(png|jpe?g|gif|webp|svg|pdf|zip|tar|gz|tgz|mp4|mov|mp3|wav|ico|bmp)$/i,YS=["**STOP — native tools on in-scope markdown (when project has `.open-knowledge/`).** When the active project contains `.open-knowledge/`, do NOT use your host's native `Read`, `Grep`, or `Glob` on `.md` / `.mdx` paths inside OK's content directory — use `exec` (this tool) instead. Native file tools skip frontmatter, backlinks, shadow-repo activity, and project git history that `exec` returns for every matched wiki file. Reserve native `Read`/`Grep`/`Glob` for source code, non-markdown paths, and projects without `.open-knowledge/`.",``,`Run a read-only bash-like command against the project content directory. Returns raw stdout plus enriched metadata for every wiki file referenced (frontmatter, backlink/forward-link counts, shadow-repo activity with agent/human attribution).`,``,`Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. Pipes (|) work between stages. Redirections, subshells, and writes are rejected.`,``,"cwd: the command runs in the explicit absolute `cwd` you pass, or in the MCP client's only advertised root when there is exactly one. If the client has zero or multiple roots, pass `cwd` explicitly. Paths inside the command resolve relative to that cwd; traversal above it is rejected.",``,"Stdout provenance headers (GNU-style): `ls <dir>/` prepends `<dir>/:`, single-file `cat`/`head`/`tail` prepends `==> <path> <==`, so the subject of the command is visible in raw output. Multi-file `cat a b` emits no header — the `enrichedPaths` array still lists every file. `head`/`tail` used as pipe trimmers (no file arg) defer to the upstream producer.",``,`Examples:`,'- `exec({ command: "cat articles/auth.md" })` — file contents + full enrichment','- `exec({ command: "ls articles/" })` — listing + per-file enrichment (slim)','- `exec({ command: "grep -rn oauth articles/ | head -5" })` — pipe with enrichment on matched files','- `exec({ command: "ls", cwd: "/abs/path/to/other-repo" })` — run in a different project'].join(`
922
+ `);function XS(e){let t=e.split(`
923
+ `),n=t[t.length-1]===``?t.length-1:t.length;if(n<=500&&e.length<=qS)return{text:e,truncated:!1,omittedLines:0};let r=Math.min(n,500),i=0,a=0;for(let e=0;e<r;e++){let n=t[e];if(i+=n.length+1,i>qS)break;a++}let o=t.slice(0,a).join(`
924
+ `),s=n-a;return{text:`${o}\n<truncated: ${s} more lines — re-run with a more-specific query>`,truncated:!0,omittedLines:s}}function ZS(e){let t=[];for(let n of e)if(n.command===`cat`)for(let e of n.args.slice(1))e.startsWith(`-`)||JS.test(e)&&t.push(e);return t}function QS(e){for(let t=1;t<e.length;t++){let n=e[t],r=n.match(/^--lines=(\d+)$/);if(r)return Number(r[1]);if(n===`--lines`&&t+1<e.length){let n=Number(e[t+1]);if(Number.isFinite(n))return n}if(n===`-n`&&t+1<e.length){let n=Number(e[t+1]);if(Number.isFinite(n))return n}let i=n.match(/^-n(\d+)$/);if(i)return Number(i[1]);let a=n.match(/^-(\d+)$/);if(a)return Number(a[1])}return 10}function $S(e,t){if(e.length<2)return null;let n=e[e.length-1];if(n.command!==`head`&&n.command!==`tail`)return null;let r=QS(n.args),i=t.split(`
925
+ `),a=i[i.length-1]===``?i.length-1:i.length;if(a<r)return null;let o=i.slice(0,a),s=new Set(o.map(e=>{let t=e.indexOf(`:`);return t>0?e.slice(0,t):e})).size,c=e.slice(0,-1).map(e=>e.command).join(` | `);return{banner:`Output hit \`${n.command} -${r}\` cap (${a} lines, ${s} unique file${s===1?``:`s`}). The \`${c}\` stage may have had more matches that never reached stdout. For existence checks across many files, prefer \`grep -rl PATTERN <dir>\` (list files only, no head). For enumeration, drop the \`| ${n.command}\` or widen the cap.`}}function eC(e){return e.type===`directory`}function tC(e){let t=[e.title?`**${e.title}** (${e.path}/)`:`**${e.path}/** (directory)`];e.description&&t.push(e.description),e.tags&&e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`);let n=[];return n.push(`${e.recursiveMdCount} md file${e.recursiveMdCount===1?``:`s`}`),e.childDirCount>0&&n.push(`${e.childDirCount} subdir${e.childDirCount===1?``:`s`}`),t.push(n.join(`, `)),e.mostRecentMd&&t.push(`most recent: ${e.mostRecentMd.title??e.mostRecentMd.path} (${e.mostRecentMd.path})`),e.truncated&&t.push(`scan truncated`),`- ${t.join(` — `)}`}function nC(e){let t=[`**${e.title??e.path}** (${e.path})`];if(e.description&&t.push(e.description),e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`),e.backlinkCount!==null&&t.push(`backlinks: ${e.backlinkCount}`),e.forwardLinkCount!==null&&t.push(`forward links: ${e.forwardLinkCount}`),e.history&&e.history.length>0){let n=e.history.map(e=>{let t=e.writerClassification===`agent`?`agent: ${e.writerName}`:e.writerClassification===`principal`?`human: ${e.writerName}`:`${e.writerClassification}: ${e.writerName}`;return`${e.hash.slice(0,7)} [${t}] ${e.message}`});t.push(`OK edits: ${n.join(` · `)}`)}if(e.projectHistory&&e.projectHistory.length>0){let n=e.projectHistory.map(e=>`${e.hash.slice(0,7)} ${e.authorName}: ${e.subject}`);t.push(`commits: ${n.join(` · `)}`)}return`- ${t.join(` — `)}`}function rC(e,t,n){let r=null;for(let t=e.length-1;t>=0;t--){let n=e[t],i=n.command;if(i===`ls`||i===`cat`){r=n;break}if((i===`head`||i===`tail`)&&Eh(Th(n)).length>0){r=n;break}}if(!r)return``;let i=Eh(Th(r));if(r.command===`ls`){let e=i[i.length-1];if(!e||e===`.`)return``;let n=e.replace(/\/+/g,`/`);return n.startsWith(`./`)&&(n=n.slice(2)),n.endsWith(`/`)&&(n=n.slice(0,-1)),!n||!t.has(n)?``:`${n}/:\n`}let a=i.filter(e=>/\.(md|mdx)$/.test(e)&&n.has(e));return a.length===1?`==> ${a[0]} <==\n`:``}function iC(e){if(e.length===0)return``;let t=[``,`### Referenced files`,``];for(let n of e)t.push(eC(n)?tC(n):nC(n));return t.join(`
926
+ `)}async function aC(e,t){let n=[],r=[];return await Promise.all(t.map(async t=>{try{let i=await dr(zn(e,t));i.isDirectory()?r.push(t):i.isFile()&&n.push(t)}catch{/\.(md|mdx)$/i.test(t)&&n.push(t)}})),{files:n,dirs:r}}function oC(e,t){return q(t,{enrichedPaths:[],error:{category:e,message:t}},!0)}function sC(e,t){return e.map(e=>{let n=t(_h(e.path));return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}})}async function cC(e,t){let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return oC(`shell_construct_blocked`,`exec failed: ${n.error}`);let{cwd:r,config:i,url:a}=n,o=vS(e.command);if(`error`in o)return oC(o.error.category,o.error.message);let s=aS(o.stages),c=oS(s),l=await Zx(r),u=Kx(r),d=``,f=``;try{let e=await qx(u,c);d=e.stdout,f=e.stderr}catch(e){return e instanceof Gx?oC(`output_overflow`,`Output exceeded 16 MB buffer. Narrow the command (e.g., add a more specific grep pattern, use head, restrict the path).`):oC(`shell_construct_blocked`,`exec failed: ${e instanceof Error?e.message:String(e)}`)}let p=await Zx(r),m=Qx(l.snapshot,p.snapshot);if(m.changed.length>0)return oC(`security_invariant_violation`,`Security invariant violated: file(s) in the content directory were modified during a read-only exec call: ${m.changed.join(`, `)}. This indicates a parser bug; the command has been logged.`);let h=XS(d),g=Ph(d,s),{files:_,dirs:v}=await aC(r,g),y=s.length===1&&s[0].command===`cat`&&_.length===1,b=i.folders,x=await Promise.all(_.map(e=>WS(e,{projectDir:r,serverUrl:a,folderRules:b},{includeRichFields:y}).catch(()=>({path:e,tags:[],backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null})))),S=await Promise.all(v.map(e=>KS(e,{projectDir:r,folderRules:b}).catch(()=>({path:e,type:`directory`,directMdCount:0,recursiveMdCount:0,childDirCount:0,truncated:!1}))));if(!y&&a&&x.length>0){let e=await VS(a,x.map(e=>RS(e.path))).catch(()=>null);if(e)for(let t of x){let n=e.get(RS(t.path));typeof n==`number`&&(t.backlinkCount=n)}}let ee=new Map(x.map(e=>[e.path,e])),te=new Map(S.map(e=>[e.path,e])),ne=[];for(let e of g){let t=ee.get(e);if(t){ne.push(t);continue}let n=te.get(e);n&&ne.push(n)}let re=ZS(s),C=[];re.length>0&&C.push(`File${re.length>1?`s`:``} ${re.join(`, `)} appear${re.length===1?`s`:``} to be binary (image/PDF/etc.) — exec returns text only (NG8). For binary retrieval, use native Read.`);let w=$S(s,d);w&&C.push(w.banner),f&&C.push(`stderr: ${f.trim()}`);let ie=C.length>0?`${C.join(`
927
+ `)}\n\n`:``,ae=rC(s,te,ee)+h.text,T=`${ie}${ae}${iC(ne)}`,{resolve:E,ui:oe}=await gh({config:i,resolveCwd:async()=>r}),se=sC(ne,E),ce=oe;return q(T,{enrichedPaths:se,stdout:ae,stdoutTruncated:h.truncated,cwd:r,...ce?{ui:ce}:{},...C.length>0?{warnings:C}:{}})}function lC(e,t){e.tool(`exec`,YS,{command:D().describe(`Read-only bash command (allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut; pipes OK)`),cwd:D().optional().describe("Absolute host path to run the command from. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.")},async e=>{try{return await cC(e,t)}catch(e){return oC(`shell_construct_blocked`,`exec handler error: ${e instanceof Error?e.message:String(e)}`)}})}const uC=[`[Requires: Hocuspocus server] Find all pages that link to a given page.`,`Returns source page names, resolved titles, and context snippets as JSON.`,``,`**Parameters:**`,'- `docName` — Target page docName, typically without extension (for example, "articles/project-alpha"). A trailing `.md` or `.mdx` is stripped automatically.'].join(`
928
+ `);function dC(e,t){e.tool(`get_backlinks`,uC,{docName:D().describe(`Target page docName`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=ih(e.docName);if(!a.ok)return K(a.error,!0);let o=await ah(i,`/api/backlinks?docName=${encodeURIComponent(a.docName)}`);if(!o.ok)return K(`Error: ${o.error}`,!0);let{ok:s,...c}=o,l=c,{resolve:u,ui:d}=await gh(t,r),f=(l.backlinks??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,n=t?u(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),p={...l,backlinks:f,ui:d,cwd:r};return q(JSON.stringify(p,null,2),p)})}const fC=[`[Operates on disk; no running OK server required] Read the effective merged Open Knowledge config (defaults → user → project).`,``,"Use this when you need to inspect the config mid-session — e.g., after a write that may have changed disk state, or to re-confirm the value of a field before composing a `set_config` patch.",``,"Read returns the FULL merged config or a sub-tree when `path` is provided. There is no allowlist on reads — every field is readable.",``,`**Parameters:**`,'- `path` (optional) — Dotted-segments array. `["folders"]` returns the folders array; `["mcp", "tools"]` returns the mcp.tools sub-tree. Omit for full config.',"- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
929
+ `),pC={path:T(D()).optional().describe(`Dotted path as array of segments (e.g. ["mcp","tools","search"]). Omit to return the full merged config.`),cwd:D().optional().describe(qm)},mC={value:s().describe(`Resolved config value at the requested path (or full config).`),exists:ue().optional().describe('Whether the requested path resolved to a value. `false` distinguishes "path absent" from "path explicitly set to null"; absent on full-config reads.'),path:T(D()).optional().describe(`Echo of the requested dotted path (empty when reading the full config).`)};function hC(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=n[e]}return n}function gC(e,t){e.registerTool(`get_config`,{description:fC,inputSchema:pC,outputSchema:mC,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let n=await nh(t.resolveCwd,t.config,e.cwd);if(!n.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${n.error}`}]};let r=e.path??[],i=r.length>0?hC(n.config,r):n.config;return r.length>0&&i===void 0?q(`(no value at ${r.join(`.`)})`,{value:null,exists:!1,path:r}):q(JSON.stringify(i,null,2),{value:i,exists:!0,path:r})})}const _C=[`[Requires: Hocuspocus server] Find missing internal page targets across the corpus.`,`Returns grouped dead links keyed by missing target with source-doc rows as JSON.`,``,`**Parameters:**`,"- `sourceDocNames` (optional) — Referring source docs to narrow the audit with OR semantics"].join(`
930
+ `);function vC(e,t){e.tool(`get_dead_links`,_C,{sourceDocNames:T(D()).optional().describe(`Referring source docs to narrow the audit with OR semantics`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=new URLSearchParams;for(let t of e.sourceDocNames??[]){let e=ih(t);if(!e.ok)return K(e.error,!0);a.append(`sourceDocName`,e.docName)}let o=a.toString(),s=await ah(i,`/api/dead-links${o?`?${o}`:``}`);if(!s.ok)return K(`Error: ${s.error}`,!0);let{ok:c,...l}=s,u=l,{resolve:d,ui:f}=await gh(t,r),p=(u.deadLinks??[]).map(e=>{let t=typeof e.target==`string`?e.target:null,n=t?d(t):null,r=(e.sources??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,n=t?d(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}});return{...e,sources:r,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),m={...u,deadLinks:p,ui:f,cwd:r};return q(JSON.stringify(m,null,2),m)})}const yC=[`[Requires: Hocuspocus server] Find all pages that a given page links to.`,`Returns forward links as JSON.`,``,`**Parameters:**`,"- `docName` — Source page docName, typically without extension. A trailing `.md` or `.mdx` is stripped automatically."].join(`
931
+ `);function bC(e,t){e.tool(`get_forward_links`,yC,{docName:D().describe(`Source page docName`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=ih(e.docName);if(!a.ok)return K(a.error,!0);let o=await ah(i,`/api/forward-links?docName=${encodeURIComponent(a.docName)}`);if(!o.ok)return K(`Error: ${o.error}`,!0);let{ok:s,...c}=o,l=c,{resolve:u,ui:d}=await gh(t,r),f=(l.forwardLinks??[]).map(e=>{let t=e.kind===`doc`&&typeof e.docName==`string`?e.docName:null,n=t?u(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),p={...l,forwardLinks:f,ui:d,cwd:r};return q(JSON.stringify(p,null,2),p)})}const xC=[`[Requires: Hocuspocus server] List version history for a document.`,`Returns timeline entries from the shadow repo, sorted by timestamp descending.`,"Each entry includes a commit SHA that can be passed to `rollback_to_version`.",``,`**Parameters:**`,"- `docName` — Document name to query history for, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `branch` (optional) — Branch name (default: current branch)","- `limit` (optional) — Maximum entries to return (default 50, max 200)","- `offset` (optional) — Number of entries to skip for pagination (default 0)",'- `type` (optional) — Filter by entry type: "checkpoint", "upstream", or "wip"',"- `author` (optional) — Filter to entries by this author name or email","- `excludeAuthor` (optional) — Exclude entries by this author name or email"].join(`
932
+ `);function SC(e,t){e.tool(`get_history`,xC,{docName:D().describe(`Document name to query history for`),branch:D().optional().describe(`Branch name (default: current branch)`),limit:C().int().min(1).max(200).optional().describe(`Maximum entries to return (default 50, max 200)`),offset:C().int().min(0).optional().describe(`Number of entries to skip for pagination (default 0)`),type:le([`checkpoint`,`upstream`,`wip`]).optional().describe(`Filter by entry type`),author:D().optional().describe(`Filter to entries by this author name or email`),excludeAuthor:D().optional().describe(`Exclude entries by this author name or email`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=ih(e.docName);if(!a.ok)return K(a.error,!0);let o=new URLSearchParams;o.set(`docName`,a.docName),e.branch&&o.set(`branch`,e.branch),e.limit!=null&&o.set(`limit`,String(e.limit)),e.offset!=null&&o.set(`offset`,String(e.offset)),e.type&&o.set(`type`,e.type),e.author&&o.set(`author`,e.author),e.excludeAuthor&&o.set(`excludeAuthor`,e.excludeAuthor);let s=await ah(i,`/api/history?${o.toString()}`);if(!s.ok)return K(`Error: ${s.error}`,!0);let{ok:c,...l}=s,u=await mh(a.docName,{config:t.config,resolveCwd:t.resolveCwd},r);return q(JSON.stringify(l,null,2),{...l,previewUrl:u?.url??null,...u?{previewUrlSource:u.source}:{}})})}const CC=[`[Requires: Hocuspocus server] Find the most-linked pages in the knowledge graph.`,`Returns hub pages ordered by inbound link count as JSON.`,``,`**Parameters:**`,"- `limit` (optional) — Maximum number of hubs to return (default 20)"].join(`
933
+ `);function wC(e,t){e.tool(`get_hubs`,CC,{limit:C().int().positive().optional().describe(`Maximum number of hubs to return`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=await ah(i,`/api/hubs${e.limit?`?limit=${encodeURIComponent(String(e.limit))}`:``}`);if(!a.ok)return K(`Error: ${a.error}`,!0);let{ok:o,...s}=a,c=s,{resolve:l,ui:u}=await gh(t,r),d=(c.hubs??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,n=t?l(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),f={...c,hubs:d,ui:u,cwd:r};return q(JSON.stringify(f,null,2),f)})}const TC=[`[Requires: Hocuspocus server] Find disconnected pages in the knowledge graph.`,`Returns orphaned pages as JSON.`,``,`**Parameters:**`,"- `mode` (optional) — Orphan lens: `incoming`, `outgoing`, or `both` (default `both`)"].join(`
934
+ `);function EC(e,t){e.tool(`get_orphans`,TC,{mode:le(me).optional().describe(`Filter which type of graph disconnection to surface`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=await ah(i,`/api/orphans${e.mode?`?mode=${encodeURIComponent(e.mode)}`:``}`);if(!a.ok)return K(`Error: ${a.error}`,!0);let{ok:o,...s}=a,c=s,{resolve:l,ui:u}=await gh(t,r),d=(c.orphans??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,n=t?l(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),f={...c,orphans:d,ui:u,cwd:r};return q(JSON.stringify(f,null,2),f)})}function DC(e,t){return`${$m(`ingest`)}Capture this external source into the project knowledge base as raw reference material. The KB is **closed-loop**: external sources are pulled INTO the knowledge base here so downstream docs cite local paths, never bare web URLs. This applies whether a user shared the source OR you fetched it yourself to ground a knowledge-base claim — agent-initiated fetches are not exempt. **Raw preservation only** — no summary, no analysis, no interpretation. Summarizing is the job of the \`research\` tool later.
935
935
 
936
936
  Source: ${e}
937
937
 
@@ -1012,17 +1012,19 @@ If the source is directly relevant to an existing article or research doc, updat
1012
1012
  - **No promotion to a canonical article** — that's the \`consolidate\` tool's job, later
1013
1013
  - **No silent chaining into research** — ingest completes on its own; the user explicitly opts into \`research\`
1014
1014
  - **No synthesis inside the raw file** — the takeaways live in chat or a separate summary doc, never mixed into the preserved source
1015
- `}const DC=[`Fetch an external source (URL or local file) and save raw content as reference material in the project content directory.`,`Raw preservation only — no analysis or interpretation.`,`The knowledge base is closed-loop: web sources cited by KB docs MUST resolve to a local doc captured here, not bare URLs.`,``,`**Use when:**`,`- Capturing reference material for the project knowledge base`,`- Saving a URL or document for later research`,`- Archiving an external source alongside the codebase`,`- The user shares a URL or document they want preserved`,"- **You yourself fetched a URL (`WebFetch` / `WebSearch` / equivalent) to ground a claim that is about to land in a knowledge-base doc** — agent-initiated fetches are not exempt from the closed-loop rule",``,`**Triggers on:**`,`- "ingest", "save this source", "capture this URL", "add to external sources"`,`- User shares a URL, article, or document to preserve in the knowledge base`,`- Agent fetches a URL via WebFetch/WebSearch to support a knowledge-base claim — preserve the source before citing it`,`- Research workflow needs raw sources before analysis`].join(`
1016
- `);function OC(e,t){e.tool(`ingest`,DC,{source:D().describe(`URL, file path, or identifier of the source to ingest`),cwd:D().optional().describe(qm)},async e=>{let n=await nh(t.resolveCwd,t.config,e.cwd);return n.ok?q(EC(e.source,n.config.content.dir),{previewUrl:null}):K(`Error: ${n.error}`,!0)})}const kC=[`[Requires: Hocuspocus server] List available documents from the Hocuspocus server.`,`Returns document names, optionally filtered by directory.`,``,`**Parameters:**`,"- `dir` (optional) — Filter to documents in this directory"].join(`
1017
- `);function AC(e,t){e.tool(`list_documents`,kC,{dir:D().optional().describe(`Optional directory to filter documents`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=await ah(i,`/api/documents${e.dir?`?dir=${encodeURIComponent(e.dir)}`:``}`);if(!a.ok)return K(`Error: ${a.error}`,!0);let{ok:o,...s}=a,c=s,{resolve:l,ui:u}=await hh(t,r),d=(c.documents??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,n=t?l(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),f={...c,documents:d,ui:u,cwd:r};return q(JSON.stringify(f,null,2),f)})}const jC=[`Read a wiki file with enriched context: contents + frontmatter metadata + recent shadow-repo activity (agent vs human attribution) + backlink/forward-link context.`,``,`**Use when:**`,`- Loading an article for context`,`- Understanding who changed a file recently and whether it was an agent or human`,`- Seeing how this page links out and what links back to it`,``,"**When the project has `.open-knowledge/`**, strongly prefer this over your native `Read` for wiki files — one call returns what otherwise takes 3-4. In projects without `.open-knowledge/`, use native `Read` as usual.",``,`**Parameters:**`,"- `path` — Project-root-relative path to the file, including extension (e.g. `articles/auth/sso.md`). To pass this document to `edit_document` / `write_document` / `get_backlinks`, strip the extension (they take extension-less `docName`).","- `since` (reserved) — Reserved for shadow-log since-filter; currently unused."].join(`
1018
- `);function MC(e){if(!e||e.length===0)return``;let t=[``,`### Recent activity (OK edits)`,``];for(let n of e){let e=n.writerClassification===`agent`?`agent: ${n.writerName}`:n.writerClassification===`principal`?`human: ${n.writerName}`:`${n.writerClassification}: ${n.writerName}`,r=n.hash.slice(0,7);t.push(`- ${r} ${n.date} [${e}] ${n.message}`)}return t.join(`
1019
- `)}function NC(e){if(!e||e.length===0)return``;let t=[``,`### Commit history (project git)`,``];for(let n of e){let e=n.hash.slice(0,7);t.push(`- ${e} ${n.date} ${n.authorName} — ${n.subject}`)}return t.join(`
1020
- `)}function PC(e){if(!e||e.length===0)return``;let t=[``,`### Backlinks (${e.length})`,``];for(let n of e){let e=n.title?` — "${n.title}"`:``,r=n.snippet?` — "${n.snippet}"`:``;t.push(`- ${n.source}${e}${r}`)}return t.join(`
1021
- `)}function FC(e){if(!e||e.length===0)return``;let t=[``,`### Forward links (${e.length})`,``];for(let n of e){if(n.kind===`external`){let e=n.title?` — "${n.title}"`:``,r=n.snippet?` — "${n.snippet}"`:``;t.push(`- ${n.url}${e}${r}`);continue}let e=n.title?` — "${n.title}"`:``,r=n.snippet?` — "${n.snippet}"`:``;t.push(`- ${n.docName}${e}${r}`)}return t.join(`
1022
- `)}function IC(e){return e.replace(/^\.\//,``).replace(/^\/+/,``)}function LC(e){return e.replace(/\.(md|mdx)$/i,``)}async function RC(e,t){let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)throw Error(n.error);let{cwd:r,config:i,url:a}=n,o=IC(e.path),s=zn(r,o),c=i.mcp.tools.read_document.historyDepth,[l,u]=await Promise.all([lr(s,`utf-8`),US(o,{projectDir:r,serverUrl:a,historyDepth:c,folderRules:i.folders},{includeRichFields:!0})]),d=o.split(`/`).pop()?.replace(/\.md$/,``).replace(/\.mdx$/,``)??o,f=u.title??d,p=u.description??``,m=u.tags,h=[];h.push(`## ${f}`),p&&h.push(`**Description:** ${p}`),m.length>0&&h.push(`**Tags:** ${m.join(`, `)}`),h.push(`**Path:** ${o}`);let g=MC(u.history);g&&h.push(g);let _=NC(u.projectHistory);_&&h.push(_);let v=PC(u.backlinks);v&&h.push(v);let y=FC(u.forwardLinks);return y&&h.push(y),h.push(``,`### Content`,``,l),h.join(`
1023
- `)}function zC(e,t){e.tool(`read_document`,jC,{path:D().describe(`Project-root-relative path to the file`),since:D().optional().describe(`Reserved; currently unused (§15 Future Work)`),cwd:D().optional().describe("Absolute host path to resolve `path` against. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.")},async e=>{try{let n=await RC(e,t),r=await ph(LC(IC(e.path)),{config:t.config,resolveCwd:t.resolveCwd},await t.resolveCwd(e.cwd));return r?q(n,{previewUrl:r.url,previewUrlSource:r.source}):q(n,{previewUrl:null})}catch(e){return K(`Error: ${e instanceof Error?e.message:String(e)}`,!0)}})}const BC=["[Requires: Hocuspocus server] Rename a document through the managed rename flow at `POST /api/rename`.",`Renames the target document and rewrites inbound wiki-links plus supported internal inline Markdown links in affected docs.`,``,`**Parameters:**`,"- `docName` — Current document name, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `newDocName` — New document name, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.",'- `summary` — Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline. If omitted, a default like "Renamed X → Y" is generated. Provide your own summary to explain the why. Avoid including secrets or PII — summaries are persisted to git history.'].join(`
1024
- `);function VC(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{fromDocName:t,toDocName:n}=e;return typeof t==`string`&&typeof n==`string`?[{fromDocName:t,toDocName:n}]:[]}):[]}function HC(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{docName:t,rewrites:n}=e;return typeof t==`string`&&typeof n==`number`?[{docName:t,rewrites:n}]:[]}):[]}function UC(e,t,n=`${t}s`){return e===1?t:n}function WC(e,t){e.tool(`rename_document`,BC,{docName:D().describe(`Current document name`),newDocName:D().describe(`New document name`),summary:Jm.describe(`Optional one-line user-outcome description (≤80 chars). Defaults to "Renamed X → Y" when omitted. Appears as a bullet in the timeline.`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=ih(e.docName);if(!a.ok)return K(a.error,!0);let o=ih(e.newDocName);if(!o.ok)return K(o.error,!0);let s=t.identityRef?.current,c=await oh(i,`/api/rename`,{docName:a.docName,newDocName:o.docName,...e.summary===void 0?{}:{summary:e.summary},...s?{agentId:s.connectionId,agentName:s.displayName,clientName:s.clientInfo?.name,colorSeed:s.colorSeed}:{}});if(!c.ok){let e=typeof c.error==`string`?c.error:`Rename failed`,t={ok:!1,error:e};return q(`Error: ${e}`,t,!0)}let l=VC(c.renamed),u=HC(c.rewrittenDocs),d=l.map(({fromDocName:e,toDocName:t})=>`${e} -> ${t}`).join(`, `)||`${a.docName} -> ${o.docName}`,f=u.length===0?`No inbound links required updates.`:`Rewrote ${u.length} ${UC(u.length,`document`)}.`,p={config:t.config,resolveCwd:t.resolveCwd},m=await ph(o.docName,p,r),h=await ph(a.docName,p,r),g=c.summary&&typeof c.summary==`object`?c.summary:void 0,_=typeof g?.hint==`string`?g.hint:void 0,v={ok:!0,renamed:l,rewrittenDocs:u,previewUrl:m?.url??null,...m?{previewUrlSource:m.source}:{},...h?{previousPreviewUrl:h.url}:{},...g?{summary:g}:{}},y=[`Renamed ${d}. ${f}`];return _&&y.push(_),q(y.join(`
1025
- `),v)})}function GC(e,t){return`${$m(`research`)}Conduct **evidence-driven research** on this topic and produce a provisional research article in the Open Knowledge content directory. This workflow mirrors the discipline of the \`eng:research\` skill, scoped to Open Knowledge's wiki-provisional layer.
1015
+ `}const OC=[`Fetch an external source (URL or local file) and save raw content as reference material in the project content directory.`,`Raw preservation only — no analysis or interpretation.`,`The knowledge base is closed-loop: web sources cited by KB docs MUST resolve to a local doc captured here, not bare URLs.`,``,`**Use when:**`,`- Capturing reference material for the project knowledge base`,`- Saving a URL or document for later research`,`- Archiving an external source alongside the codebase`,`- The user shares a URL or document they want preserved`,"- **You yourself fetched a URL (`WebFetch` / `WebSearch` / equivalent) to ground a claim that is about to land in a knowledge-base doc** — agent-initiated fetches are not exempt from the closed-loop rule",``,`**Triggers on:**`,`- "ingest", "save this source", "capture this URL", "add to external sources"`,`- User shares a URL, article, or document to preserve in the knowledge base`,`- Agent fetches a URL via WebFetch/WebSearch to support a knowledge-base claim — preserve the source before citing it`,`- Research workflow needs raw sources before analysis`].join(`
1016
+ `);function kC(e,t){e.tool(`ingest`,OC,{source:D().describe(`URL, file path, or identifier of the source to ingest`),cwd:D().optional().describe(qm)},async e=>{let n=await nh(t.resolveCwd,t.config,e.cwd);return n.ok?q(DC(e.source,n.config.content.dir),{previewUrl:null}):K(`Error: ${n.error}`,!0)})}const AC=[`[Requires: Hocuspocus server] List available documents from the Hocuspocus server.`,`Returns document names, optionally filtered by directory.`,``,`**Parameters:**`,"- `dir` (optional) — Filter to documents in this directory"].join(`
1017
+ `);function jC(e,t){e.tool(`list_documents`,AC,{dir:D().optional().describe(`Optional directory to filter documents`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=await ah(i,`/api/documents${e.dir?`?dir=${encodeURIComponent(e.dir)}`:``}`);if(!a.ok)return K(`Error: ${a.error}`,!0);let{ok:o,...s}=a,c=s,{resolve:l,ui:u}=await gh(t,r),d=(c.documents??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,n=t?l(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),f={...c,documents:d,ui:u,cwd:r};return q(JSON.stringify(f,null,2),f)})}const MC=[`Read a wiki file with enriched context: contents + frontmatter metadata + recent shadow-repo activity (agent vs human attribution) + backlink/forward-link context.`,``,`**Use when:**`,`- Loading an article for context`,`- Understanding who changed a file recently and whether it was an agent or human`,`- Seeing how this page links out and what links back to it`,``,"**When the project has `.open-knowledge/`**, strongly prefer this over your native `Read` for wiki files — one call returns what otherwise takes 3-4. In projects without `.open-knowledge/`, use native `Read` as usual.",``,`**Parameters:**`,"- `path` — Project-root-relative path to the file, including extension (e.g. `articles/auth/sso.md`). To pass this document to `edit_document` / `write_document` / `get_backlinks`, strip the extension (they take extension-less `docName`).","- `since` (reserved) — Reserved for shadow-log since-filter; currently unused."].join(`
1018
+ `);function NC(e){if(!e||e.length===0)return``;let t=[``,`### Recent activity (OK edits)`,``];for(let n of e){let e=n.writerClassification===`agent`?`agent: ${n.writerName}`:n.writerClassification===`principal`?`human: ${n.writerName}`:`${n.writerClassification}: ${n.writerName}`,r=n.hash.slice(0,7);t.push(`- ${r} ${n.date} [${e}] ${n.message}`)}return t.join(`
1019
+ `)}function PC(e){if(!e||e.length===0)return``;let t=[``,`### Commit history (project git)`,``];for(let n of e){let e=n.hash.slice(0,7);t.push(`- ${e} ${n.date} ${n.authorName} — ${n.subject}`)}return t.join(`
1020
+ `)}function FC(e){if(!e||e.length===0)return``;let t=[``,`### Backlinks (${e.length})`,``];for(let n of e){let e=n.title?` — "${n.title}"`:``,r=n.snippet?` — "${n.snippet}"`:``;t.push(`- ${n.source}${e}${r}`)}return t.join(`
1021
+ `)}function IC(e){if(!e||e.length===0)return``;let t=[``,`### Forward links (${e.length})`,``];for(let n of e){if(n.kind===`external`){let e=n.title?` — "${n.title}"`:``,r=n.snippet?` — "${n.snippet}"`:``;t.push(`- ${n.url}${e}${r}`);continue}let e=n.title?` — "${n.title}"`:``,r=n.snippet?` — "${n.snippet}"`:``;t.push(`- ${n.docName}${e}${r}`)}return t.join(`
1022
+ `)}function LC(e){return e.replace(/^\.\//,``).replace(/^\/+/,``)}function RC(e){return e.replace(/\.(md|mdx)$/i,``)}async function zC(e,t){let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)throw Error(n.error);let{cwd:r,config:i,url:a}=n,o=LC(e.path),s=zn(r,o),c=i.mcp.tools.read_document.historyDepth,[l,u]=await Promise.all([lr(s,`utf-8`),WS(o,{projectDir:r,serverUrl:a,historyDepth:c,folderRules:i.folders},{includeRichFields:!0})]),d=o.split(`/`).pop()?.replace(/\.md$/,``).replace(/\.mdx$/,``)??o,f=u.title??d,p=u.description??``,m=u.tags,h=[];h.push(`## ${f}`),p&&h.push(`**Description:** ${p}`),m.length>0&&h.push(`**Tags:** ${m.join(`, `)}`),h.push(`**Path:** ${o}`);let g=NC(u.history);g&&h.push(g);let _=PC(u.projectHistory);_&&h.push(_);let v=FC(u.backlinks);v&&h.push(v);let y=IC(u.forwardLinks);return y&&h.push(y),h.push(``,`### Content`,``,l),h.join(`
1023
+ `)}function BC(e,t){e.tool(`read_document`,MC,{path:D().describe(`Project-root-relative path to the file`),since:D().optional().describe(`Reserved; currently unused (§15 Future Work)`),cwd:D().optional().describe("Absolute host path to resolve `path` against. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.")},async e=>{try{let n=await zC(e,t),r=await mh(RC(LC(e.path)),{config:t.config,resolveCwd:t.resolveCwd},await t.resolveCwd(e.cwd));return r?q(n,{previewUrl:r.url,previewUrlSource:r.source}):q(n,{previewUrl:null})}catch(e){return K(`Error: ${e instanceof Error?e.message:String(e)}`,!0)}})}const VC=["[Requires: Hocuspocus server] Rename a document through the managed rename flow at `POST /api/rename-path` (kind: file).",`Renames the target document and rewrites inbound wiki-links plus supported internal inline Markdown links in affected docs.`,``,`**Parameters:**`,"- `docName` — Current document name, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `newDocName` — New document name, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.",'- `summary` — Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline. If omitted, a default like "Renamed X → Y" is generated. Provide your own summary to explain the why. Avoid including secrets or PII — summaries are persisted to git history.',``,`**Errors:**`,"- 400 — case-only renames (e.g. `Auth` → `auth`) are not supported.","- 400 — destination document is excluded by the workspace `content.include` / `content.exclude` config.",`- 404 — source document does not exist.`,`- 409 — destination document already exists.`].join(`
1024
+ `);function HC(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{fromDocName:t,toDocName:n}=e;return typeof t==`string`&&typeof n==`string`?[{fromDocName:t,toDocName:n}]:[]}):[]}function UC(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{docName:t,rewrites:n}=e;return typeof t==`string`&&typeof n==`number`?[{docName:t,rewrites:n}]:[]}):[]}function WC(e,t,n=`${t}s`){return e===1?t:n}function GC(e,t){e.tool(`rename_document`,VC,{docName:D().describe(`Current document name`),newDocName:D().describe(`New document name`),summary:Jm.describe(`Optional one-line user-outcome description (≤80 chars). Defaults to "Renamed X → Y" when omitted. Appears as a bullet in the timeline.`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=ih(e.docName);if(!a.ok)return K(a.error,!0);let o=ih(e.newDocName);if(!o.ok)return K(o.error,!0);let s=t.identityRef?.current,c=await oh(i,`/api/rename-path`,{kind:`file`,fromPath:a.docName,toPath:o.docName,...e.summary===void 0?{}:{summary:e.summary},...s?{agentId:s.connectionId,agentName:s.displayName,clientName:s.clientInfo?.name,colorSeed:s.colorSeed}:{}});if(!c.ok){let e=typeof c.error==`string`?c.error:`Rename failed`,t=sh(c.colliding),n={ok:!1,error:e,...t.length>0?{colliding:t}:{}};return q(`Error: ${e}`,n,!0)}let l=HC(c.renamed),u=UC(c.rewrittenDocs),d=l.map(({fromDocName:e,toDocName:t})=>`${e} -> ${t}`).join(`, `)||`${a.docName} -> ${o.docName}`,f=u.length===0?`No inbound links required updates.`:`Rewrote ${u.length} ${WC(u.length,`document`)}.`,p={config:t.config,resolveCwd:t.resolveCwd},m=await mh(o.docName,p,r),h=await mh(a.docName,p,r),g=c.summary&&typeof c.summary==`object`?c.summary:void 0,_=typeof g?.hint==`string`?g.hint:void 0,v={ok:!0,renamed:l,rewrittenDocs:u,previewUrl:m?.url??null,...m?{previewUrlSource:m.source}:{},...h?{previousPreviewUrl:h.url}:{},...g?{summary:g}:{}},y=[`Renamed ${d}. ${f}`];return _&&y.push(_),q(y.join(`
1025
+ `),v)})}const KC=["[Requires: Hocuspocus server] Rename a folder through the managed rename flow at `POST /api/rename-path` (kind: folder).",`Atomically moves the folder and rewrites inbound wiki-links + supported internal inline Markdown links across every affected doc. One call replaces N rename_document calls.`,``,`**Parameters:**`,"- `fromFolder` — Current folder path relative to the content directory (no leading or trailing slash). Example: `articles` or `notes/drafts`.","- `toFolder` New folder path relative to the content directory. Example: `essays` or `notes/published`. Parent directories are auto-created.",'- `summary` — Optional one-line user-outcome description (≤80 chars). Applied to every affected-doc contributor entry. If omitted, a default like "Renamed X → Y" is generated. Provide your own summary to explain the why. Avoid including secrets or PII — summaries are persisted to git history.',``,`**Errors:**`,"- 400 — case-only renames (e.g. `Articles` → `articles`) are not supported.","- 400 — destination folder is excluded by the workspace `content.include` / `content.exclude` config.",`- 404 — source folder does not exist.`,`- 409 — destination folder already exists or rename would collide.`].join(`
1026
+ `);function qC(e){return!(typeof e!=`string`||e.length===0||e.startsWith(`/`)||e.endsWith(`/`)||e.includes(`..`))}function JC(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{fromDocName:t,toDocName:n}=e;return typeof t==`string`&&typeof n==`string`?[{fromDocName:t,toDocName:n}]:[]}):[]}function YC(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{docName:t,rewrites:n}=e;return typeof t==`string`&&typeof n==`number`?[{docName:t,rewrites:n}]:[]}):[]}function XC(e,t){e.tool(`rename_folder`,KC,{fromFolder:D().describe(`Current folder path (relative, no trailing slash)`),toFolder:D().describe(`New folder path (relative, no trailing slash)`),summary:Jm.describe(`Optional one-line user-outcome description (≤80 chars). Applied to every affected-doc contributor entry.`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);if(!qC(e.fromFolder))return K(`fromFolder must be a relative path with no leading/trailing slash`,!0);if(!qC(e.toFolder))return K(`toFolder must be a relative path with no leading/trailing slash`,!0);let a=t.identityRef?.current,o=await oh(i,`/api/rename-path`,{kind:`folder`,fromPath:e.fromFolder,toPath:e.toFolder,...e.summary===void 0?{}:{summary:e.summary},...a?{agentId:a.connectionId,agentName:a.displayName,clientName:a.clientInfo?.name,colorSeed:a.colorSeed}:{}});if(!o.ok){let e=typeof o.error==`string`?o.error:`Folder rename failed`,t=sh(o.colliding),n={ok:!1,error:e,...t.length>0?{colliding:t}:{}};return q(`Error: ${e}`,n,!0)}let s=JC(o.renamed),c=YC(o.rewrittenDocs),l={config:t.config,resolveCwd:t.resolveCwd},u={},d;for(let{toDocName:e}of s){let t=await mh(e,l,r);t&&(u[e]=t.url,d??=t.source)}let f=o.summary&&typeof o.summary==`object`?o.summary:void 0,p=typeof f?.hint==`string`?f.hint:void 0,m={ok:!0,renamed:s,rewrittenDocs:c,previewUrls:u,...d?{previewUrlSource:d}:{},...f?{summary:f}:{}},h=[];return s.length===0?h.push(`No managed docs under ${e.fromFolder}/ — nothing to rename. Empty folders are not tracked; create a doc inside the folder first.`):h.push(`Renamed folder ${e.fromFolder}/ → ${e.toFolder}/ (${s.length} doc${s.length===1?``:`s`}, ${c.length} rewrite${c.length===1?``:`s`}).`),p&&h.push(p),q(h.join(`
1027
+ `),m)})}function ZC(e,t){return`${$m(`research`)}Conduct **evidence-driven research** on this topic and produce a provisional research article in the Open Knowledge content directory. This workflow mirrors the discipline of the \`eng:research\` skill, scoped to Open Knowledge's wiki-provisional layer.
1026
1028
 
1027
1029
  Topic: ${e}
1028
1030
  Content directory: \`${t}\` (from \`${i}/config.yml\`)
@@ -1372,18 +1374,18 @@ In headless mode, write the recap into the research article's "Further reading"
1372
1374
  - **Don't skip the scoping gate in Supervised mode.** The user's rubric shapes everything downstream; you cannot recover a wrong-scope article cheaply.
1373
1375
  - **Don't mix 1P codebase analysis into the article unless asked.** Findings drift from factual synthesis to opinion when you do.
1374
1376
  - **Don't overwrite existing research silently.** If the topic was researched before, either iterate (Path C) or create a clearly-named successor (\`crdt-alternatives-2.md\`) and mark the old one as superseded.
1375
- `}const KC=[`Analyze a topic by gathering sources via ingest and writing provisional findings into the project content directory.`,`Provisional, not canonical — findings live here until decisions solidify.`,``,`**Use when:**`,`- Researching a topic before committing to an approach`,`- Exploring a decision space or comparing alternatives`,`- Synthesizing multiple sources into structured analysis`,`- Spec conversations and exploratory work that is not yet canonical`,``,`**Triggers on:**`,`- "research", "investigate", "compare options for", "analyze alternatives"`,`- User asks to explore trade-offs, gather evidence, or evaluate approaches`,`- A decision needs structured analysis grounded in external sources`].join(`
1376
- `);function qC(e,t){e.tool(`research`,KC,{topic:D().describe(`The topic, question, or anchor URL to research`),cwd:D().optional().describe(qm)},async e=>{let n=await nh(t.resolveCwd,t.config,e.cwd);return n.ok?q(GC(e.topic,n.config.content.dir),{previewUrl:null}):K(`Error: ${n.error}`,!0)})}const JC=[`[Requires: Hocuspocus server] Restore a document to a historical version via the CRDT layer.`,`The restore is append-only — it creates a new version with the old content,`,`preserving all history. All connected editors see the change in real-time.`,``,`**Parameters:**`,"- `docName` — Document name to restore, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `commitSha` — The 40-character SHA of the shadow repo commit to restore to."," Use `get_history` to find available versions.",'- `summary` — Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline. If omitted, a default like "Restored to <sha-short>" is generated. Provide your own summary to explain the why. Avoid including secrets or PII — summaries are persisted to git history.'].join(`
1377
- `);function YC(e,t){e.tool(`rollback_to_version`,JC,{docName:D().describe(`Document name to restore`),commitSha:D().length(40).regex(/^[0-9a-f]+$/i).describe(`40-character commit SHA from the shadow repo timeline`),summary:Jm.describe(`Optional one-line user-outcome description (≤80 chars). Defaults to "Restored to <sha-short>" when omitted. Appears as a bullet in the timeline.`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=ih(e.docName);if(!a.ok)return K(a.error,!0);let o=a.docName,s=await ah(i,`/api/history/${e.commitSha}?docName=${encodeURIComponent(o)}`);if(!s.ok)return K(`Error: ${s.error??`Version not found`}`,!0);let c=t.identityRef?.current,l=await oh(i,`/api/rollback`,{docName:o,commitSha:e.commitSha,...e.summary===void 0?{}:{summary:e.summary},...c?{agentId:c.connectionId,agentName:c.displayName,clientName:c.clientInfo?.name,colorSeed:c.colorSeed}:{}});if(!l.ok)return K(`Error: ${l.error}`,!0);let u=l.summary&&typeof l.summary==`object`?l.summary:void 0,d=typeof u?.hint==`string`?u.hint:void 0,f=[`Restored "${o}" to version ${e.commitSha.slice(0,8)} (${s.author}, ${s.timestamp}). The change has been applied to all connected editors.`];d&&f.push(d);let p=await ph(o,{config:t.config,resolveCwd:t.resolveCwd},r);return q(f.join(`
1378
- `),{previewUrl:p?.url??null,...p?{previewUrlSource:p.source}:{},...u?{summary:u}:{}})})}const XC=[`[Requires: Hocuspocus server] Save a version checkpoint of all documents.`,`Creates a checkpoint commit in the shadow repo and project repo,`,`preserving the current state of all documents. The checkpoint can later`,"be found via `get_history` and restored via `rollback_to_version`."].join(`
1379
- `);function ZC(e,t,n,r,i){e.tool(`save_version`,XC,{cwd:D().optional().describe(qm)},async(e={})=>{let a=await rh(r,t,n,e.cwd);if(!a.ok)return K(`Error: ${a.error}`,!0);if(!a.url)return K(Ym,!0);let{url:o}=a,s=i?.current,c=await oh(o,`/api/save-version`,{...s?{writers:[{id:`agent-${s.connectionId}`,name:s.displayName,email:`agent-${s.connectionId}@openknowledge.local`}]}:{}});return c.ok?q(`Checkpoint saved. Checkpoint ref: ${c.checkpointRef}`,{checkpointRef:c.checkpointRef,previewUrl:null}):K(`Error: ${c.error}`,!0)})}const QC=[`Search wiki content with metadata-enriched results. Matches are grouped by file; each file is annotated with its title, description, and tags so you can judge relevance without opening it first.`,``,`**Use when:**`,`- Finding all articles mentioning a topic`,`- Locating a specific term across the wiki before deciding which file to read`,``,"**When the project has `.open-knowledge/`**, strongly prefer this over your native `Grep` for wiki search — results include article metadata so you can skip irrelevant matches without extra reads. In projects without `.open-knowledge/`, use native `Grep` as usual.",``,`**Parameters:**`,"- `query` — Literal text to search for (fixed-string match, no regex)","- `case_sensitive` (optional, default false) — case-sensitive match"].join(`
1380
- `);function $C(e){let t=new Map;for(let n of e){let e=t.get(n.path);e?e.push(n):t.set(n.path,[n])}return[...t.entries()].map(([e,t])=>({path:e,matches:t}))}async function ew(e,t){let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)throw Error(n.error);let{cwd:r,config:a,url:o}=n,s=a.mcp.tools.search.maxResults,c=a.content.include,l=a.content.exclude,u=await Jx(e.query,r,{caseInsensitive:!(e.case_sensitive??!1),include:c,exclude:[...l,`node_modules`,`.git`,`.claude`,`.changeset`,i],maxResults:s+1}),d=u.length>s,f=d?u.slice(0,s):u,{resolve:p,ui:m}=await hh({config:a,resolveCwd:async()=>r},r);if(f.length===0)return{text:`No matches for "${e.query}".`,structured:{query:e.query,matchCount:0,fileCount:0,truncated:!1,results:[],ui:m,cwd:r}};let h=$C(f),g=new Map,_=a.folders;await Promise.all(h.map(async e=>{try{let t=await US(e.path,{projectDir:r,serverUrl:o,folderRules:_});g.set(e.path,t)}catch{}}));let v=[];v.push(`## Search results for "${e.query}" (${f.length} match${f.length===1?``:`es`} in ${h.length} file${h.length===1?``:`s`})`,``);let y=[];for(let e of h){let t=g.get(e.path),n=t?.title??e.path;v.push(`### ${n} (${e.path})`),t?.tags?.length&&v.push(`Tags: ${t.tags.join(`, `)}`),t?.description&&v.push(`${t.description}`);for(let t of e.matches)v.push(`- Line ${t.line}: ${t.text}`);v.push(``);let r=gh(e.path),i=p(r);y.push({path:e.path,docName:r,title:t?.title??null,description:t?.description??null,tags:t?.tags??[],matches:e.matches.map(e=>({line:e.line,text:e.text})),previewUrl:i?.url??null,...i?{previewUrlSource:i.source}:{}})}return d&&v.push(`_${f.length} of ${u.length}+ matches shown. Raise \`mcp.tools.search.maxResults\` in config.yml to see more._`),{text:v.join(`
1381
- `),structured:{query:e.query,matchCount:f.length,fileCount:h.length,truncated:d,results:y,ui:m,cwd:r}}}function tw(e,t){e.tool(`search`,QC,{query:D().describe(`Literal text to search for`),case_sensitive:ue().optional().describe(`Case-sensitive search (default false)`),cwd:D().optional().describe("Absolute host path to search in. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.")},async e=>{try{let{text:n,structured:r}=await ew(e,t);return r?q(n,r):K(n)}catch(e){return K(`Error: ${e instanceof Error?e.message:String(e)}`,!0)}})}const nw=[`[Operates on disk; no running OK server required] Set fields in the Open Knowledge config (project + user-global YAML).`,``,`Pass a deep-partial patch over the agent-settable allowlist. The server picks the write target (project vs user) automatically based on where the path is already set + per-field default scope.`,``,`**Allowlist** (only these paths are agent-settable):`,"- `content.include` — globs of files to include in the wiki","- `content.exclude` — globs to exclude","- `folders[]` — folder-rule defaults (whole-array replace; for per-rule upsert use `set_folder_rule`)","- `mcp.tools.search.maxResults` — search result cap","- `mcp.tools.read_document.historyDepth` — number of history entries returned",``,"Other paths are rejected with `NOT_AGENT_SETTABLE`. To inspect what is currently set, call `get_config`.",``,"**Patch semantics:** RFC 7396 spirit (TypeScript-only — no wire format). Top-level keys present are written; absent keys are unchanged; `null` clears a field; nested objects merge recursively; arrays replace wholesale.",``,"**Mixed scope:** if leaves in a single patch resolve to different scopes (e.g., one project-only field + one user-only field), the call fails with `MIXED_SCOPE` — retry per-scope.",``,`**Parameters:**`,"- `patch` — Deep-partial config patch over the allowlist (see above).","- `cwd` (optional) — Project root."].join(`
1382
- `),rw={patch:w({}).describe(`Deep-partial config patch over the agent-settable allowlist. See description for the 5 allowed paths. Null at any path clears the field; arrays replace wholesale.`),cwd:D().optional().describe(qm)},iw={result:y([x({ok:E(!0),applied:T(D()),scope:le([`user`,`project`]),path:D(),current:S(D(),s())}),x({ok:E(!1),error:re})])};function aw(e){let t=[];function n(e,r){if(e!==void 0){if(e===null||Array.isArray(e)||typeof e!=`object`){t.push(r);return}for(let[t,i]of Object.entries(e))n(i,[...r,t])}}for(let[t,r]of Object.entries(e))n(r,[t]);return t}function ow(e){return e.map(e=>({path:[...e],meta:p(Ge,e)}))}function sw(e,t,n){return t?.project?`project`:t?.user?`user`:n??`user`}function cw(e,t,n){let r=Be(e.map(e=>e.path),{cwd:t,...n===void 0?{}:{homedirOverride:n}}),i=e.map(e=>{let t=r.get(e.path.join(`.`));return{path:e.path,scope:sw(e.path,t,e.meta?.defaultScope)}}),a=new Set(i.map(e=>e.scope));if(a.size>1)return{mixed:{code:`MIXED_SCOPE`,paths:i.map(({path:e,scope:t})=>({path:e.map(String),scope:t}))}};let[o]=a;return{scope:o??`user`,perLeaf:i}}function lw(e){return{isError:!0,structuredContent:{result:{ok:!1,error:e}},content:[{type:`text`,text:`${l(e)}\n\nPlease fix and try again.`}]}}function uw(e,t){e.registerTool(`set_config`,{description:nw,inputSchema:rw,outputSchema:iw,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!1}},async e=>{let n=await nh(t.resolveCwd,t.config,e.cwd);if(!n.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${n.error}`}]};let{cwd:r}=n,i=e.patch,a=aw(i);if(a.length===0)return lw({code:`SCHEMA_INVALID`,issues:[{path:[],message:`Patch is empty — pass at least one leaf value.`,issueCode:`empty_patch`}]});let o=ow(a),s=o.find(e=>e.meta?.agentSettable!==!0);if(s)return lw({code:`NOT_AGENT_SETTABLE`,path:s.path.map(String)});let c=cw(o,r,t.homedirOverride);if(`mixed`in c)return lw(c.mixed);let l=await Re({cwd:r,scope:c.scope,patch:i,...t.homedirOverride===void 0?{}:{homedirOverride:t.homedirOverride}});if(!l.ok)return lw(l.error);let u={result:{ok:!0,applied:l.appliedPaths,scope:c.scope,path:l.path,current:l.effective}};return q(JSON.stringify(u.result,null,2),u)})}const dw=["[Operates on disk; no running OK server required] Upsert one or more folder rules in the project `folders[]` array.",``,"Folder rules apply default frontmatter (title / description / tags) to every doc whose path matches `match` (a glob like `specs/**` or `reports/*/**`). Use this tool to add a new rule, replace an existing one keyed by `match`, or rename via `new_match`.",``,`Always pass an array — even for a single rule. The tool runs all rules transactionally: if any rule produces an invalid merged config, NO rules are applied to disk.`,``,'**To remove a rule**, use `set_config({patch: {folders: [<filtered-array>]}})` — read folders via `get_config({path: ["folders"]})`, drop the entry, then write back.',``,`**Parameters:**`,"- `rules` — Array of `{match, frontmatter, new_match?}`.",' - `match` — Glob pattern that identifies the rule (e.g. `"specs/**"`). Required.',' - `frontmatter` — `{title?, description?, tags?: string[]}` to apply. Required (use `{}` for "match the rule but apply no frontmatter").'," - `new_match` — If set, rename the rule keyed by `match` to this glob. If both already exist, the rename target is overwritten.","- `cwd` (optional) — Project root."].join(`
1383
- `),fw={rules:T(x({match:D().min(1).describe(`Glob pattern (e.g. "specs/**", "reports/*/**") that identifies the rule.`),frontmatter:_.describe("Default frontmatter to apply to matched docs: `{title?, description?, tags?: string[]}`."),new_match:D().min(1).optional().describe("If set, rename the existing rule keyed by `match` to this new glob.")})).min(1).describe("One or more folder rules to upsert. Always an array — pass `[{...}]` for a single rule."),cwd:D().optional().describe(qm)},pw={result:y([x({ok:E(!0),applied:T(D()),scope:E(`project`),path:D(),current:S(D(),s())}),x({ok:E(!1),error:re})])};function mw(e,t){e.registerTool(`set_folder_rule`,{description:dw,inputSchema:fw,outputSchema:pw,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!1}},async e=>{let n=await nh(t.resolveCwd,t.config,e.cwd);if(!n.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${n.error}`}]};let{cwd:r}=n,i=await Ve({cwd:r,rules:e.rules.map(e=>({match:e.match,frontmatter:e.frontmatter,...e.new_match===void 0?{}:{new_match:e.new_match}})),scope:`project`,...t.homedirOverride===void 0?{}:{homedirOverride:t.homedirOverride}});if(!i.ok)return{isError:!0,structuredContent:{result:{ok:!1,error:i.error}},content:[{type:`text`,text:`${l(i.error)}\n\nPlease fix and try again.`}]};let a={result:{ok:!0,applied:i.appliedPaths,scope:`project`,path:i.path,current:i.effective}};return q(JSON.stringify(a.result,null,2),a)})}const hw=[`[Requires: Hocuspocus server] Find missing link candidates for a target page.`,"Returns JSON with structure: `{ target: { docName, title, aliases }, mentions: [{ source, excerpt, offset }], truncated }`.","Each mention includes an `offset` you can pass to `edit_document` for precision patching.","When `truncated` is true, the scan hit its time budget before reading every admitted document.",``,`**Parameters:**`,'- `docName` — Target page docName, typically without extension (for example, "articles/project-alpha"). A trailing `.md` or `.mdx` is stripped automatically.'].join(`
1384
- `);function gw(e,t){e.tool(`suggest_links`,hw,{docName:D().describe(`Target page docName`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=ih(e.docName);if(!a.ok)return K(a.error,!0);let o=await ah(i,`/api/suggest-links?docName=${encodeURIComponent(a.docName)}`);if(!o.ok)return K(`Error: ${o.error}`,!0);let{ok:s,...c}=o,l=await ph(a.docName,{config:t.config,resolveCwd:t.resolveCwd},r);return q(JSON.stringify(c,null,2),{...c,previewUrl:l?.url??null,...l?{previewUrlSource:l.source}:{}})})}const _w=[`[Requires: Hocuspocus server] Write markdown content to a document via the CRDT layer.`,`Content is applied through Hocuspocus and propagated to all connected editors in real-time.`,``,'**Link liberally.** Every noun-phrase that names another document in this knowledge base should be a `[[wiki-link]]`, not plain prose. Backlinks are the primary navigation surface — underlinked documents become islands. Redlinks (links to pages that don\'t exist yet) are fine; they signal "this should exist." Prefer `[[Page Name]]` over Markdown `[text](./page.md)` — only wiki-links participate in the backlinks index.',``,`**Parameters:**`,'- `docName` — Document name, typically without extension (e.g., "my-doc" or "notes/meeting"). A trailing `.md` or `.mdx` is stripped automatically. New documents are created as `.md` by default; to create a `.mdx` file, first place it on disk, then use this tool for edits.',"- `markdown` — Markdown content to write",'- `position` — Where to insert: "append", "prepend", or "replace"','- `summary` — Optional one-line user-outcome description of this edit (≤80 chars). Appears as a bullet in the document timeline so readers can scan intent without opening every diff. Prefer outcome phrasing ("Fixed token-refresh race") over structural ("Added 3 lines"). Avoid including secrets or PII — summaries are persisted to git history.'].join(`
1385
- `);function vw(e,t){e.tool(`write_document`,_w,{docName:D().describe(`Document name to write to`),markdown:D().describe(`Markdown content to write`),position:le([`append`,`prepend`,`replace`]).describe(`Where to insert the content`),summary:Jm,cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:a}=n;if(!a)return K(Ym,!0);let o=ih(e.docName);if(!o.ok)return K(o.error,!0);let s=t.identityRef?.current,c=await oh(a,`/api/agent-write-md`,{docName:o.docName,markdown:e.markdown,position:e.position,...e.summary===void 0?{}:{summary:e.summary},...s?{agentId:s.connectionId,agentName:s.displayName,clientName:s.clientInfo?.name,colorSeed:s.colorSeed}:{}});if(!c.ok)return K(`Error: ${c.error}`,!0);let l=Se(Ce(i,r)),u=_h(o.docName,{config:i,lockDir:l}),d=typeof c.subscriberCount==`number`?c.subscriberCount:void 0,f=(typeof c.systemSubscriberCount==`number`?c.systemSubscriberCount:void 0)===0,p=d===0,m=Array.isArray(c.hints)?c.hints:void 0,h=c.summary&&typeof c.summary==`object`?c.summary:void 0,g=typeof h?.hint==`string`?h.hint:void 0,_=[`Written successfully (${e.position}).`];if(u&&_.push(`Preview: ${u.url}`),f&&_.push(u?`Open ${u.url} in your preview browser.`:`No preview attached. Start the UI.`),g&&_.push(g),m)for(let e of m)e.message&&_.push(e.message);let v=_.join(`
1386
- `);if(!u&&!f&&!p&&!m&&!h)return K(v);let y={};return u&&(y.previewUrl=u.url,y.previewUrlSource=u.source),f&&(y.warning={message:`Open the previewUrl in your preview browser.`,action:`attach-preview-once`,previewUrl:u?.url??null}),m&&(y.hints=m),h&&(y.summary=h),q(v,y)})}function yw(e,t){let n=t.logger,r=Km(e,{logger:t.logger,identityRef:t.identityRef}),i=e=>async r=>{try{let i=await t.resolveCwd(r);return(Mm()??n)?.debug(`tool cwd resolved`,{tool:e,cwd:i,...r?{explicit:r}:{}}),i}catch(t){throw(Mm()??n)?.warn(`tool call failed`,{tool:e,error:t instanceof Error?t.message:String(t),...r?{explicit:r}:{}}),t}};cC(r,{resolveCwd:i(`exec`),serverUrl:t.serverUrl,config:t.config}),OC(r,{config:t.config,resolveCwd:i(`ingest`)}),qC(r,{config:t.config,resolveCwd:i(`research`)}),lh(r,{config:t.config,resolveCwd:i(`consolidate`)}),zC(r,{resolveCwd:i(`read_document`),config:t.config,serverUrl:t.serverUrl}),tw(r,{resolveCwd:i(`search`),config:t.config,serverUrl:t.serverUrl}),gw(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`suggest_links`)}),vw(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`write_document`),identityRef:t.identityRef}),yh(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`edit_document`),identityRef:t.identityRef}),WC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`rename_document`),identityRef:t.identityRef}),xC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_history`)}),ZC(r,t.config,t.serverUrl,i(`save_version`),t.identityRef),YC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`rollback_to_version`),identityRef:t.identityRef}),AC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`list_documents`)}),uC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_backlinks`)}),yC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_forward_links`)}),TC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_orphans`)}),CC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_hubs`)}),_C(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_dead_links`)}),hC(r,{config:t.config,resolveCwd:i(`get_config`)}),uw(r,{config:t.config,resolveCwd:i(`set_config`)}),mw(r,{config:t.config,resolveCwd:i(`set_folder_rule`)})}function bw(e){return e&&typeof e==`object`&&`code`in e&&typeof e.code==`string`?e.code:e instanceof Error&&e.name?e.name:typeof e}var xw=class extends Error{};function Sw(e){let t=Ue(e.startupCwd),n=null,r=null,i=async()=>n===null?(r||=(async()=>{let t=await e.listRoots(),r=await Promise.all(t.roots.map(async e=>e.uri.startsWith(`file://`)?await Ue(or(e.uri)):null)),i=[...new Set(r.filter(e=>e!==null))];return n=i,e.logger?.info(`roots resolved`,{roots:i,count:i.length}),i})().finally(()=>{r=null}),await r):n;return{async resolveCwd(n){if(n){let t=await Ue(n);return e.logger?.debug(`cwd resolved`,{cwd:t,routing:`explicit`}),t}if(e.bypassProjectSelection){let n=await t;return e.logger?.debug(`cwd resolved`,{cwd:n,routing:`bypass`}),n}let r;try{r=await i()}catch(t){throw e.logger?.warn(`roots/list unavailable`,{error:t instanceof Error?t.message:String(t),errorType:bw(t)}),new xw(`Client roots unavailable; pass cwd explicitly.`)}if(r.length===0)throw new xw(`No client roots available; pass cwd explicitly.`);if(r.length>1)throw new xw(`Multiple roots available; pass cwd explicitly.`);return e.logger?.debug(`cwd resolved`,{cwd:r[0],routing:`single-root`}),r[0]},invalidateRoots(){n=null,r=null,e.logger?.info(`roots cache invalidated`)}}}function Cw(e){let t=Ue(e.startupCwd),n;return{async resolveCwdForTools(t){let r=await e.resolveCwd(t);return n=r,r},async getKeepaliveCwd(){return e.bypassProjectSelection?await t:n}}}let ww;function Tw(e,t){let{dir:n,include:r,exclude:i}=e.content,a=i.length>0?i.map(e=>`\`${e}\``).join(`, `):`(none)`;return`# Open Knowledge (OK) — collaborative markdown via MCP
1377
+ `}const QC=[`Analyze a topic by gathering sources via ingest and writing provisional findings into the project content directory.`,`Provisional, not canonical — findings live here until decisions solidify.`,``,`**Use when:**`,`- Researching a topic before committing to an approach`,`- Exploring a decision space or comparing alternatives`,`- Synthesizing multiple sources into structured analysis`,`- Spec conversations and exploratory work that is not yet canonical`,``,`**Triggers on:**`,`- "research", "investigate", "compare options for", "analyze alternatives"`,`- User asks to explore trade-offs, gather evidence, or evaluate approaches`,`- A decision needs structured analysis grounded in external sources`].join(`
1378
+ `);function $C(e,t){e.tool(`research`,QC,{topic:D().describe(`The topic, question, or anchor URL to research`),cwd:D().optional().describe(qm)},async e=>{let n=await nh(t.resolveCwd,t.config,e.cwd);return n.ok?q(ZC(e.topic,n.config.content.dir),{previewUrl:null}):K(`Error: ${n.error}`,!0)})}const ew=[`[Requires: Hocuspocus server] Restore a document to a historical version via the CRDT layer.`,`The restore is append-only — it creates a new version with the old content,`,`preserving all history. All connected editors see the change in real-time.`,``,`**Parameters:**`,"- `docName` — Document name to restore, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `commitSha` — The 40-character SHA of the shadow repo commit to restore to."," Use `get_history` to find available versions.",'- `summary` — Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline. If omitted, a default like "Restored to <sha-short>" is generated. Provide your own summary to explain the why. Avoid including secrets or PII — summaries are persisted to git history.'].join(`
1379
+ `);function tw(e,t){e.tool(`rollback_to_version`,ew,{docName:D().describe(`Document name to restore`),commitSha:D().length(40).regex(/^[0-9a-f]+$/i).describe(`40-character commit SHA from the shadow repo timeline`),summary:Jm.describe(`Optional one-line user-outcome description (≤80 chars). Defaults to "Restored to <sha-short>" when omitted. Appears as a bullet in the timeline.`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=ih(e.docName);if(!a.ok)return K(a.error,!0);let o=a.docName,s=await ah(i,`/api/history/${e.commitSha}?docName=${encodeURIComponent(o)}`);if(!s.ok)return K(`Error: ${s.error??`Version not found`}`,!0);let c=t.identityRef?.current,l=await oh(i,`/api/rollback`,{docName:o,commitSha:e.commitSha,...e.summary===void 0?{}:{summary:e.summary},...c?{agentId:c.connectionId,agentName:c.displayName,clientName:c.clientInfo?.name,colorSeed:c.colorSeed}:{}});if(!l.ok)return K(`Error: ${l.error}`,!0);let u=l.summary&&typeof l.summary==`object`?l.summary:void 0,d=typeof u?.hint==`string`?u.hint:void 0,f=[`Restored "${o}" to version ${e.commitSha.slice(0,8)} (${s.author}, ${s.timestamp}). The change has been applied to all connected editors.`];d&&f.push(d);let p=await mh(o,{config:t.config,resolveCwd:t.resolveCwd},r);return q(f.join(`
1380
+ `),{previewUrl:p?.url??null,...p?{previewUrlSource:p.source}:{},...u?{summary:u}:{}})})}const nw=[`[Requires: Hocuspocus server] Save a version checkpoint of all documents.`,`Creates a checkpoint commit in the shadow repo and project repo,`,`preserving the current state of all documents. The checkpoint can later`,"be found via `get_history` and restored via `rollback_to_version`."].join(`
1381
+ `);function rw(e,t,n,r,i){e.tool(`save_version`,nw,{cwd:D().optional().describe(qm)},async(e={})=>{let a=await rh(r,t,n,e.cwd);if(!a.ok)return K(`Error: ${a.error}`,!0);if(!a.url)return K(Ym,!0);let{url:o}=a,s=i?.current,c=await oh(o,`/api/save-version`,{...s?{writers:[{id:`agent-${s.connectionId}`,name:s.displayName,email:`agent-${s.connectionId}@openknowledge.local`}]}:{}});return c.ok?q(`Checkpoint saved. Checkpoint ref: ${c.checkpointRef}`,{checkpointRef:c.checkpointRef,previewUrl:null}):K(`Error: ${c.error}`,!0)})}const iw=[`Search wiki content with metadata-enriched results. Matches are grouped by file; each file is annotated with its title, description, and tags so you can judge relevance without opening it first.`,``,`**Use when:**`,`- Finding all articles mentioning a topic`,`- Locating a specific term across the wiki before deciding which file to read`,``,"**When the project has `.open-knowledge/`**, strongly prefer this over your native `Grep` for wiki search — results include article metadata so you can skip irrelevant matches without extra reads. In projects without `.open-knowledge/`, use native `Grep` as usual.",``,`**Parameters:**`,"- `query` — Literal text to search for (fixed-string match, no regex)","- `case_sensitive` (optional, default false) — case-sensitive match"].join(`
1382
+ `);function aw(e){let t=new Map;for(let n of e){let e=t.get(n.path);e?e.push(n):t.set(n.path,[n])}return[...t.entries()].map(([e,t])=>({path:e,matches:t}))}async function ow(e,t){let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)throw Error(n.error);let{cwd:r,config:a,url:o}=n,s=a.mcp.tools.search.maxResults,c=a.content.include,l=a.content.exclude,u=await Yx(e.query,r,{caseInsensitive:!(e.case_sensitive??!1),include:c,exclude:[...l,`node_modules`,`.git`,`.claude`,`.changeset`,i],maxResults:s+1}),d=u.length>s,f=d?u.slice(0,s):u,{resolve:p,ui:m}=await gh({config:a,resolveCwd:async()=>r},r);if(f.length===0)return{text:`No matches for "${e.query}".`,structured:{query:e.query,matchCount:0,fileCount:0,truncated:!1,results:[],ui:m,cwd:r}};let h=aw(f),g=new Map,_=a.folders;await Promise.all(h.map(async e=>{try{let t=await WS(e.path,{projectDir:r,serverUrl:o,folderRules:_});g.set(e.path,t)}catch{}}));let v=[];v.push(`## Search results for "${e.query}" (${f.length} match${f.length===1?``:`es`} in ${h.length} file${h.length===1?``:`s`})`,``);let y=[];for(let e of h){let t=g.get(e.path),n=t?.title??e.path;v.push(`### ${n} (${e.path})`),t?.tags?.length&&v.push(`Tags: ${t.tags.join(`, `)}`),t?.description&&v.push(`${t.description}`);for(let t of e.matches)v.push(`- Line ${t.line}: ${t.text}`);v.push(``);let r=_h(e.path),i=p(r);y.push({path:e.path,docName:r,title:t?.title??null,description:t?.description??null,tags:t?.tags??[],matches:e.matches.map(e=>({line:e.line,text:e.text})),previewUrl:i?.url??null,...i?{previewUrlSource:i.source}:{}})}return d&&v.push(`_${f.length} of ${u.length}+ matches shown. Raise \`mcp.tools.search.maxResults\` in config.yml to see more._`),{text:v.join(`
1383
+ `),structured:{query:e.query,matchCount:f.length,fileCount:h.length,truncated:d,results:y,ui:m,cwd:r}}}function sw(e,t){e.tool(`search`,iw,{query:D().describe(`Literal text to search for`),case_sensitive:ue().optional().describe(`Case-sensitive search (default false)`),cwd:D().optional().describe("Absolute host path to search in. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.")},async e=>{try{let{text:n,structured:r}=await ow(e,t);return r?q(n,r):K(n)}catch(e){return K(`Error: ${e instanceof Error?e.message:String(e)}`,!0)}})}const cw=[`[Operates on disk; no running OK server required] Set fields in the Open Knowledge config (project + user-global YAML).`,``,`Pass a deep-partial patch over the agent-settable allowlist. The server picks the write target (project vs user) automatically based on where the path is already set + per-field default scope.`,``,`**Allowlist** (only these paths are agent-settable):`,"- `content.include` — globs of files to include in the wiki","- `content.exclude` — globs to exclude","- `folders[]` — folder-rule defaults (whole-array replace; for per-rule upsert use `set_folder_rule`)","- `mcp.tools.search.maxResults` — search result cap","- `mcp.tools.read_document.historyDepth` — number of history entries returned",``,"Other paths are rejected with `NOT_AGENT_SETTABLE`. To inspect what is currently set, call `get_config`.",``,"**Patch semantics:** RFC 7396 spirit (TypeScript-only — no wire format). Top-level keys present are written; absent keys are unchanged; `null` clears a field; nested objects merge recursively; arrays replace wholesale.",``,"**Mixed scope:** if leaves in a single patch resolve to different scopes (e.g., one project-only field + one user-only field), the call fails with `MIXED_SCOPE` — retry per-scope.",``,`**Parameters:**`,"- `patch` — Deep-partial config patch over the allowlist (see above).","- `cwd` (optional) — Project root."].join(`
1384
+ `),lw={patch:w({}).describe(`Deep-partial config patch over the agent-settable allowlist. See description for the 5 allowed paths. Null at any path clears the field; arrays replace wholesale.`),cwd:D().optional().describe(qm)},uw={result:y([x({ok:E(!0),applied:T(D()),scope:le([`user`,`project`]),path:D(),current:S(D(),s())}),x({ok:E(!1),error:re})])};function dw(e){let t=[];function n(e,r){if(e!==void 0){if(e===null||Array.isArray(e)||typeof e!=`object`){t.push(r);return}for(let[t,i]of Object.entries(e))n(i,[...r,t])}}for(let[t,r]of Object.entries(e))n(r,[t]);return t}function fw(e){return e.map(e=>({path:[...e],meta:p(Ge,e)}))}function pw(e,t,n){return t?.project?`project`:t?.user?`user`:n??`user`}function mw(e,t,n){let r=Be(e.map(e=>e.path),{cwd:t,...n===void 0?{}:{homedirOverride:n}}),i=e.map(e=>{let t=r.get(e.path.join(`.`));return{path:e.path,scope:pw(e.path,t,e.meta?.defaultScope)}}),a=new Set(i.map(e=>e.scope));if(a.size>1)return{mixed:{code:`MIXED_SCOPE`,paths:i.map(({path:e,scope:t})=>({path:e.map(String),scope:t}))}};let[o]=a;return{scope:o??`user`,perLeaf:i}}function hw(e){return{isError:!0,structuredContent:{result:{ok:!1,error:e}},content:[{type:`text`,text:`${l(e)}\n\nPlease fix and try again.`}]}}function gw(e,t){e.registerTool(`set_config`,{description:cw,inputSchema:lw,outputSchema:uw,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!1}},async e=>{let n=await nh(t.resolveCwd,t.config,e.cwd);if(!n.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${n.error}`}]};let{cwd:r}=n,i=e.patch,a=dw(i);if(a.length===0)return hw({code:`SCHEMA_INVALID`,issues:[{path:[],message:`Patch is empty — pass at least one leaf value.`,issueCode:`empty_patch`}]});let o=fw(a),s=o.find(e=>e.meta?.agentSettable!==!0);if(s)return hw({code:`NOT_AGENT_SETTABLE`,path:s.path.map(String)});let c=mw(o,r,t.homedirOverride);if(`mixed`in c)return hw(c.mixed);let l=await Re({cwd:r,scope:c.scope,patch:i,...t.homedirOverride===void 0?{}:{homedirOverride:t.homedirOverride}});if(!l.ok)return hw(l.error);let u={result:{ok:!0,applied:l.appliedPaths,scope:c.scope,path:l.path,current:l.effective}};return q(JSON.stringify(u.result,null,2),u)})}const _w=["[Operates on disk; no running OK server required] Upsert one or more folder rules in the project `folders[]` array.",``,"Folder rules apply default frontmatter (title / description / tags) to every doc whose path matches `match` (a glob like `specs/**` or `reports/*/**`). Use this tool to add a new rule, replace an existing one keyed by `match`, or rename via `new_match`.",``,`Always pass an array — even for a single rule. The tool runs all rules transactionally: if any rule produces an invalid merged config, NO rules are applied to disk.`,``,'**To remove a rule**, use `set_config({patch: {folders: [<filtered-array>]}})` — read folders via `get_config({path: ["folders"]})`, drop the entry, then write back.',``,`**Parameters:**`,"- `rules` — Array of `{match, frontmatter, new_match?}`.",' - `match` — Glob pattern that identifies the rule (e.g. `"specs/**"`). Required.',' - `frontmatter` — `{title?, description?, tags?: string[]}` to apply. Required (use `{}` for "match the rule but apply no frontmatter").'," - `new_match` — If set, rename the rule keyed by `match` to this glob. If both already exist, the rename target is overwritten.","- `cwd` (optional) — Project root."].join(`
1385
+ `),vw={rules:T(x({match:D().min(1).describe(`Glob pattern (e.g. "specs/**", "reports/*/**") that identifies the rule.`),frontmatter:_.describe("Default frontmatter to apply to matched docs: `{title?, description?, tags?: string[]}`."),new_match:D().min(1).optional().describe("If set, rename the existing rule keyed by `match` to this new glob.")})).min(1).describe("One or more folder rules to upsert. Always an array — pass `[{...}]` for a single rule."),cwd:D().optional().describe(qm)},yw={result:y([x({ok:E(!0),applied:T(D()),scope:E(`project`),path:D(),current:S(D(),s())}),x({ok:E(!1),error:re})])};function bw(e,t){e.registerTool(`set_folder_rule`,{description:_w,inputSchema:vw,outputSchema:yw,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!1}},async e=>{let n=await nh(t.resolveCwd,t.config,e.cwd);if(!n.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${n.error}`}]};let{cwd:r}=n,i=await Ve({cwd:r,rules:e.rules.map(e=>({match:e.match,frontmatter:e.frontmatter,...e.new_match===void 0?{}:{new_match:e.new_match}})),scope:`project`,...t.homedirOverride===void 0?{}:{homedirOverride:t.homedirOverride}});if(!i.ok)return{isError:!0,structuredContent:{result:{ok:!1,error:i.error}},content:[{type:`text`,text:`${l(i.error)}\n\nPlease fix and try again.`}]};let a={result:{ok:!0,applied:i.appliedPaths,scope:`project`,path:i.path,current:i.effective}};return q(JSON.stringify(a.result,null,2),a)})}const xw=[`[Requires: Hocuspocus server] Find missing link candidates for a target page.`,"Returns JSON with structure: `{ target: { docName, title, aliases }, mentions: [{ source, excerpt, offset }], truncated }`.","Each mention includes an `offset` you can pass to `edit_document` for precision patching.","When `truncated` is true, the scan hit its time budget before reading every admitted document.",``,`**Parameters:**`,'- `docName` — Target page docName, typically without extension (for example, "articles/project-alpha"). A trailing `.md` or `.mdx` is stripped automatically.'].join(`
1386
+ `);function Sw(e,t){e.tool(`suggest_links`,xw,{docName:D().describe(`Target page docName`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=ih(e.docName);if(!a.ok)return K(a.error,!0);let o=await ah(i,`/api/suggest-links?docName=${encodeURIComponent(a.docName)}`);if(!o.ok)return K(`Error: ${o.error}`,!0);let{ok:s,...c}=o,l=await mh(a.docName,{config:t.config,resolveCwd:t.resolveCwd},r);return q(JSON.stringify(c,null,2),{...c,previewUrl:l?.url??null,...l?{previewUrlSource:l.source}:{}})})}const Cw=[`[Requires: Hocuspocus server] Write markdown content to a document via the CRDT layer.`,`Content is applied through Hocuspocus and propagated to all connected editors in real-time.`,``,'**Link liberally.** Every noun-phrase that names another document in this knowledge base should be a `[[wiki-link]]`, not plain prose. Backlinks are the primary navigation surface — underlinked documents become islands. Redlinks (links to pages that don\'t exist yet) are fine; they signal "this should exist." Prefer `[[Page Name]]` over Markdown `[text](./page.md)` — only wiki-links participate in the backlinks index.',``,`**Parameters:**`,'- `docName` — Document name, typically without extension (e.g., "my-doc" or "notes/meeting"). A trailing `.md` or `.mdx` is stripped automatically. New documents are created as `.md` by default; to create a `.mdx` file, first place it on disk, then use this tool for edits.',"- `markdown` — Markdown content to write",'- `position` — Where to insert: "append", "prepend", or "replace"','- `summary` — Optional one-line user-outcome description of this edit (≤80 chars). Appears as a bullet in the document timeline so readers can scan intent without opening every diff. Prefer outcome phrasing ("Fixed token-refresh race") over structural ("Added 3 lines"). Avoid including secrets or PII — summaries are persisted to git history.'].join(`
1387
+ `);function ww(e,t){e.tool(`write_document`,Cw,{docName:D().describe(`Document name to write to`),markdown:D().describe(`Markdown content to write`),position:le([`append`,`prepend`,`replace`]).describe(`Where to insert the content`),summary:Jm,cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:a}=n;if(!a)return K(Ym,!0);let o=ih(e.docName);if(!o.ok)return K(o.error,!0);let s=t.identityRef?.current,c=await oh(a,`/api/agent-write-md`,{docName:o.docName,markdown:e.markdown,position:e.position,...e.summary===void 0?{}:{summary:e.summary},...s?{agentId:s.connectionId,agentName:s.displayName,clientName:s.clientInfo?.name,colorSeed:s.colorSeed}:{}});if(!c.ok)return K(`Error: ${c.error}`,!0);let l=Se(Ce(i,r)),u=vh(o.docName,{config:i,lockDir:l}),d=typeof c.subscriberCount==`number`?c.subscriberCount:void 0,f=(typeof c.systemSubscriberCount==`number`?c.systemSubscriberCount:void 0)===0,p=d===0,m=Array.isArray(c.hints)?c.hints:void 0,h=c.summary&&typeof c.summary==`object`?c.summary:void 0,g=typeof h?.hint==`string`?h.hint:void 0,_=[`Written successfully (${e.position}).`];if(u&&_.push(`Preview: ${u.url}`),f&&_.push(u?`Open ${u.url} in your preview browser.`:`No preview attached. Start the UI.`),g&&_.push(g),m)for(let e of m)e.message&&_.push(e.message);let v=_.join(`
1388
+ `);if(!u&&!f&&!p&&!m&&!h)return K(v);let y={};return u&&(y.previewUrl=u.url,y.previewUrlSource=u.source),f&&(y.warning={message:`Open the previewUrl in your preview browser.`,action:`attach-preview-once`,previewUrl:u?.url??null}),m&&(y.hints=m),h&&(y.summary=h),q(v,y)})}function Tw(e,t){let n=t.logger,r=Km(e,{logger:t.logger,identityRef:t.identityRef}),i=e=>async r=>{try{let i=await t.resolveCwd(r);return(Mm()??n)?.debug(`tool cwd resolved`,{tool:e,cwd:i,...r?{explicit:r}:{}}),i}catch(t){throw(Mm()??n)?.warn(`tool call failed`,{tool:e,error:t instanceof Error?t.message:String(t),...r?{explicit:r}:{}}),t}};lC(r,{resolveCwd:i(`exec`),serverUrl:t.serverUrl,config:t.config}),kC(r,{config:t.config,resolveCwd:i(`ingest`)}),$C(r,{config:t.config,resolveCwd:i(`research`)}),uh(r,{config:t.config,resolveCwd:i(`consolidate`)}),BC(r,{resolveCwd:i(`read_document`),config:t.config,serverUrl:t.serverUrl}),sw(r,{resolveCwd:i(`search`),config:t.config,serverUrl:t.serverUrl}),Sw(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`suggest_links`)}),ww(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`write_document`),identityRef:t.identityRef}),bh(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`edit_document`),identityRef:t.identityRef}),GC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`rename_document`),identityRef:t.identityRef}),XC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`rename_folder`),identityRef:t.identityRef}),SC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_history`)}),rw(r,t.config,t.serverUrl,i(`save_version`),t.identityRef),tw(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`rollback_to_version`),identityRef:t.identityRef}),jC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`list_documents`)}),dC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_backlinks`)}),bC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_forward_links`)}),EC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_orphans`)}),wC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_hubs`)}),vC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_dead_links`)}),gC(r,{config:t.config,resolveCwd:i(`get_config`)}),gw(r,{config:t.config,resolveCwd:i(`set_config`)}),bw(r,{config:t.config,resolveCwd:i(`set_folder_rule`)})}function Ew(e){return e&&typeof e==`object`&&`code`in e&&typeof e.code==`string`?e.code:e instanceof Error&&e.name?e.name:typeof e}var Dw=class extends Error{};function Ow(e){let t=Ue(e.startupCwd),n=null,r=null,i=async()=>n===null?(r||=(async()=>{let t=await e.listRoots(),r=await Promise.all(t.roots.map(async e=>e.uri.startsWith(`file://`)?await Ue(or(e.uri)):null)),i=[...new Set(r.filter(e=>e!==null))];return n=i,e.logger?.info(`roots resolved`,{roots:i,count:i.length}),i})().finally(()=>{r=null}),await r):n;return{async resolveCwd(n){if(n){let t=await Ue(n);return e.logger?.debug(`cwd resolved`,{cwd:t,routing:`explicit`}),t}if(e.bypassProjectSelection){let n=await t;return e.logger?.debug(`cwd resolved`,{cwd:n,routing:`bypass`}),n}let r;try{r=await i()}catch(t){throw e.logger?.warn(`roots/list unavailable`,{error:t instanceof Error?t.message:String(t),errorType:Ew(t)}),new Dw(`Client roots unavailable; pass cwd explicitly.`)}if(r.length===0)throw new Dw(`No client roots available; pass cwd explicitly.`);if(r.length>1)throw new Dw(`Multiple roots available; pass cwd explicitly.`);return e.logger?.debug(`cwd resolved`,{cwd:r[0],routing:`single-root`}),r[0]},invalidateRoots(){n=null,r=null,e.logger?.info(`roots cache invalidated`)}}}function kw(e){let t=Ue(e.startupCwd),n;return{async resolveCwdForTools(t){let r=await e.resolveCwd(t);return n=r,r},async getKeepaliveCwd(){return e.bypassProjectSelection?await t:n}}}let Aw;function jw(e,t){let{dir:n,include:r,exclude:i}=e.content,a=i.length>0?i.map(e=>`\`${e}\``).join(`, `):`(none)`;return`# Open Knowledge (OK) — collaborative markdown via MCP
1387
1389
 
1388
1390
  **STOP** *(when \`.open-knowledge/\` exists)* — do NOT use native \`Read\`, \`Grep\`, \`Glob\`, \`Edit\`, \`Write\` on in-scope \`.md\` / \`.mdx\`. Reads: \`exec\` / \`read_document\` / \`search\`. Writes: \`write_document\` / \`edit_document\` ONLY.
1389
1391
 
@@ -1404,8 +1406,8 @@ Claude Code Desktop: \`preview_start("open-knowledge-ui")\`. Other hosts: open-U
1404
1406
  Detailed conventions (wiki-link authoring, frontmatter, anti-patterns) live in the installed \`open-knowledge\` Agent Skill. If missing, run \`npx @inkeep/open-knowledge init\`.
1405
1407
 
1406
1408
  **Escape hatch.** Native \`Read\`/\`Grep\`/\`Glob\` on \`.md\` is allowed when the project has no \`.open-knowledge/\`, when no OK MCP is registered, or right after a failed OK MCP call (then prefix with \`Open Knowledge MCP unavailable:\`). Non-markdown: native tools always.
1407
- `}async function Ew(e,t){try{let t=e.replace(`ws://`,`http://`).replace(`wss://`,`https://`);return(await fetch(`${t}/api/document`,{signal:AbortSignal.timeout(2e3)})).ok}catch(n){return t.warn(`Hocuspocus probe failed`,{serverUrl:e,error:n instanceof Error?n.message:String(n)}),!1}}async function Dw(e){let{projectDir:t,serverUrl:n,config:r,startupConfig:i,bypassProjectSelection:a=!1}=e;if(ww=Am(),ww.info(`MCP server starting`,{startupCwd:t,bypassProjectSelection:a,serverUrlType:typeof n==`string`?`explicit`:`lazy`}),typeof n==`string`){let e=await Ew(n,ww);ww.info(`Hocuspocus detection complete`,{serverUrl:n,available:e})}else ww.info(`server discovery is lazy per effective cwd`);let o=new mm({name:xe,version:be},{instructions:Tw(i,{dynamicConfig:typeof r==`function`&&!a})}),s=Sw({startupCwd:t,bypassProjectSelection:a,listRoots:()=>o.server.listRoots(),logger:ww}),c=Cw({startupCwd:t,resolveCwd:s.resolveCwd,bypassProjectSelection:a}),l=c.resolveCwdForTools;o.server.setNotificationHandler(Td,async()=>{s.invalidateRoots()});let u=async e=>{if(typeof n==`string`)return n.replace(`ws://`,`http://`).replace(`wss://`,`https://`);let t=e??await l();return(typeof n==`function`?await n(t):n)?.replace(`ws://`,`http://`).replace(`wss://`,`https://`)},d=sr(),f=process.env.AGENT_LABEL||void 0,p={current:{connectionId:d,label:f,displayName:f??`Agent`,colorSeed:f??d}};o.server.oninitialized=()=>{let e=o.server.getClientVersion();p.current={connectionId:d,clientInfo:e?{name:e.name,version:e.version}:void 0,label:f,displayName:f??e?.name??`Agent`,colorSeed:f??e?.name??d},ww?.info(`agent identity established`,{displayName:p.current.displayName,connectionId:d.slice(0,8),clientName:e?.name})},yw(o,{serverUrl:u,resolveCwd:l,config:r,identityRef:p,logger:ww});let m=new Dm;await o.connect(m),ww.info(`MCP server running on stdio`);let{startKeepalive:h}=await import(`./keepalive-BIRIvYdO.mjs`),g=h({resolveWsUrl:async()=>{let e=await c.getKeepaliveCwd();if(!e)return;let t=await u(e);if(t)return t.replace(/^http:/,`ws:`).replace(/^https:/,`wss:`)},connectionId:`agent-${d}`,logger:ww.child(`keepalive`)}),_=e=>{ww?.info(`MCP server shutting down`,{signal:e});try{g.close()}catch{}process.exit(0)};process.on(`SIGINT`,()=>_(`SIGINT`)),process.on(`SIGTERM`,()=>_(`SIGTERM`))}const Ow=[`/_npx/`,`/.npm/_npx/`,`/_bunx/`,`/.bun/install/cache/`,`/pnpm/dlx/`],kw=new Set([`/usr/local/bin/ok`,`/usr/local/bin/open-knowledge`,`/opt/homebrew/bin/ok`,`/opt/homebrew/bin/open-knowledge`]);function Aw(e){if(!e||e.length===0)return`unknown`;for(let t of Ow)if(e.includes(t))return`npx-cache`;return kw.has(e)||e.startsWith(`/Applications/`)||e.includes(`.app/Contents/`)?`stable-shim`:e.startsWith(`/`)?`absolute-pin`:`unknown`}function jw(e,t){switch(e){case`npx-cache`:return"This MCP was launched via a package-manager cache (npx / bunx / pnpm dlx) and just resolved a different package version than the running server. Stop `ok start` so the next launch matches, or run `ok init --pin` for a stable launch path.";case`stable-shim`:return"The CLI shim was likely upgraded while a project server is still running (a desktop auto-update or `npm i -g` / `brew upgrade` will do this). Close and reopen the project window, or stop `ok start`, so the next launch matches.";case`absolute-pin`:return`This MCP is launched from a pinned path${t?` (${t})`:``} that no longer matches the running server. Re-run \`ok init --pin\` from your current install to refresh, or stop \`ok start\` so the next launch matches.`;default:return"Stop `ok start` and retry, or align CLI versions across your installs."}}function Mw(e){return e?/\bENOENT\b/i.test(e):!1}function Nw(e){switch(Aw(e)){case`absolute-pin`:return"This failure usually means the CLI entry script no longer exists at the pinned path (common after changing how you installed Open Knowledge or removing an old global package). Re-run `ok init --pin` from your current install and update your editor MCP config, or use an unpinned launcher such as `npx @inkeep/open-knowledge mcp`.";case`stable-shim`:return"The expected `ok` shim is missing on disk. Reinstall or repair your Open Knowledge CLI. If you switched install sources, run `ok init --pin` again so your editor matches the binary you have.";case`npx-cache`:return"The package-manager cache copy used for this launch may have been removed. Retry once, or run `ok init --pin` so your editor uses a durable absolute path.";default:return"Often means the configured launcher path does not exist (stale pin, moved install, or missing runtime). Re-run `ok init --pin` from your current install or fix the MCP command in your editor settings."}}function Pw(e,t,n){let r=`spawn failed: ${e}${t?` stderr:\n${t}`:``}`;return Mw(e)&&(r+=`\n\n${Nw(n)}`),r}function Fw(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function Iw(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t))return{action:`disk-only`,message:`invalid --port value '${e.portOverride}' — disk-only mode`};if(t>0){let n=`ws://${e.host}:${t}`;return{action:`connect`,url:n,message:`using --port override, connecting to ${n}`}}return{action:`disk-only`,message:`--port=0 — disk-only mode`}}let t=e.readLock();if(t&&t.port>0&&e.isAlive(t.pid)){let n=e.expectedProtocolVersion??1,r=t.protocolVersion;if(r===n){let e=`ws://localhost:${t.port}`;return{action:`connect`,url:e,message:`connected to running instance at ${e} (pid ${t.pid})`}}let i=r===void 0?`unknown (pre-version-field lock)`:`v${r}`,a=t.runtimeVersion?` runtime ${t.runtimeVersion}`:``,o=e.launchPath??process.argv[1],s=Aw(o),c=jw(s,o);return{action:`incompatible`,message:`Open Knowledge server at port ${t.port} (pid ${t.pid}${a}) speaks protocol ${i}; this MCP needs protocol v${n}.\n`+c,expectedProtocolVersion:n,actualProtocolVersion:r,lock:t,launchShape:s,launchPath:o}}return e.envAutoStart===`0`?{action:`disk-only`,message:`auto-spawn disabled via OK_MCP_AUTOSTART=0 — disk-only mode`}:e.configAutoStart?t?{action:`spawn`,message:`existing lock is not usable (port=${t.port}, pid=${t.pid}) — spawning ok start`}:{action:`spawn`,message:`no running instance — spawning ok start`}:{action:`disk-only`,message:`auto-spawn disabled via config.mcp.autoStart=false — disk-only mode`}}async function Lw(e){let t=e.readLock??(()=>we(e.lockDir)),n=e.isAlive??Te,r=e.sleep??(e=>fr(e)),i=e.spawn??jn,a=e.readErrorLog??(e=>Hn(e)?Gn(e,`utf-8`).trim():``),o=e.openErrorLog??(e=>Wn(e,`w`)),s=e.closeFd??Vn,c=e.timeoutMs??5e3,l=e.pollIntervalMs??100,u=e.launchPath??process.argv[1],d=Iw({host:e.host,portOverride:e.portOverride,envAutoStart:e.envAutoStart,configAutoStart:e.configAutoStart,readLock:t,isAlive:n,launchPath:e.launchPath});if(e.logger?.info(`auto-start decision`,{action:d.action,message:d.message,contentDir:e.contentDir}),d.action===`connect`)return{serverUrl:d.url,message:d.message};if(d.action===`disk-only`)return{serverUrl:void 0,message:d.message};if(d.action===`incompatible`)throw e.logger?.error(`protocol mismatch — refusing to connect`,void 0,{expectedProtocolVersion:d.expectedProtocolVersion,actualProtocolVersion:d.actualProtocolVersion,lockPid:d.lock.pid,lockPort:d.lock.port,lockRuntimeVersion:d.lock.runtimeVersion,launchShape:d.launchShape,launchPath:d.launchPath}),Error(d.message);Hn(e.lockDir)||Un(e.lockDir,{recursive:!0});let f=Ln(e.lockDir,`last-spawn-error.log`),p=o(f),m,h,g=kn();e.logger?.info(`spawning server`,{command:g.command,cwd:e.contentDir,timeoutMs:c});try{try{m=i(g.command,[...g.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,p],cwd:e.contentDir,env:{...process.env,OK_LOCK_KIND:`mcp-spawned`,OK_PARENT_PID:String(process.pid)}}),m.on(`error`,e=>{h=e instanceof Error?e.message:String(e)}),m.unref()}catch(e){h=e instanceof Error?e.message:String(e)}}finally{try{s(p)}catch{}}let _=Date.now()+c;for(;Date.now()<_;){if(h){let t=a(f);throw e.logger?.error(`spawn failed`,void 0,{error:h,stderr:t,launchPath:u,stalePinHint:Mw(h)}),Error(Pw(h,t,u))}await r(l);let i=t();if(i&&i.port>0&&n(i.pid)){let t=`ws://localhost:${i.port}`;return e.logger?.info(`server ready after spawn`,{url:t,pid:i.pid}),{serverUrl:t,message:`spawned ok start; connected at ${t} (pid ${i.pid})`}}}if(h){let t=a(f);throw e.logger?.error(`spawn failed (post-deadline)`,void 0,{error:h,stderr:t,launchPath:u,stalePinHint:Mw(h)}),Error(Pw(h,t,u))}let v=a(f),y=(c/1e3).toFixed(c%1e3==0?0:2),b=m?.pid,x=``;throw typeof b==`number`&&(x=n(b)?` child pid=${b} is still running — raise OK_MCP_SPAWN_TIMEOUT_MS if this is a slow boot.`:` child pid=${b} exited — check last-spawn-error.log.`),e.logger?.error(`spawn poll timeout`,void 0,{timeoutMs:c,childPid:b,childAlive:typeof b==`number`?n(b):void 0,stderr:v||void 0}),Error(`server did not start within ${y}s.${x}${v?` stderr:\n${v}`:``}`)}function Rw(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)return async()=>void 0;let n=`ws://${e.host}:${t}`;return async()=>n}let t=e.ensureServerRunningFn??Lw,n=e.cacheMs??1e3,r=new Map,i=new Map;return async a=>{let o=await Ue(a??e.startupCwd),s=Date.now(),c=r.get(o);if(c&&c.expiresAt>s)return e.logger?.debug(`server url cache hit`,{cwd:o,url:c.url}),c.url;let l=i.get(o);if(l)return e.logger?.debug(`server url resolution pending`,{cwd:o}),await l;e.logger?.debug(`server url cache miss`,{cwd:o});let u=(async()=>{let i=await e.resolveConfig(o),a=Ce(i,o),s=Se(a),c=e.readLock,l=c?()=>c(s):void 0,u=await t({lockDir:s,contentDir:a,host:i.server.host,portOverride:void 0,envAutoStart:e.envAutoStart,configAutoStart:i.mcp.autoStart,logger:e.logger,timeoutMs:e.timeoutMs,pollIntervalMs:e.pollIntervalMs,spawn:e.spawn,readLock:l,isAlive:e.isAlive,sleep:e.sleep,readErrorLog:e.readErrorLog,openErrorLog:e.openErrorLog,closeFd:e.closeFd,launchPath:e.launchPath});return r.set(o,{url:u.serverUrl,expiresAt:Date.now()+n}),u.serverUrl})();i.set(o,u);try{return await u}finally{i.delete(o)}}}function zw(e){return new r(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override port discovery and connect to this port (0 = disk-only)`,void 0).action(async t=>{try{let n=e(),r=process.cwd(),i=Ke({startupCwd:r,startupConfig:n}),a=Fw(process.env.OK_MCP_SPAWN_TIMEOUT_MS),o,s;if(t.port!==void 0){let e=Number.parseInt(t.port,10);Number.isNaN(e)?(o=void 0,s=`invalid --port value '${t.port}' — disk-only mode`):e>0?(o=`ws://${n.server.host}:${e}`,s=`using --port override, connecting to ${o}`):(o=void 0,s=`--port=0 — disk-only mode`)}else o=Rw({startupCwd:r,resolveConfig:i,host:n.server.host,portOverride:void 0,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:a}),s=`project server discovery/autostart is lazy per effective cwd`;process.stderr.write(`[mcp] ${s}\n`),await Dw({projectDir:r,serverUrl:o,config:i,startupConfig:n,bypassProjectSelection:t.port!==void 0})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function Bw(e){return new r(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-D3e-de44.mjs`),r=e(),i=process.cwd(),a=Ce(r,i),o;try{o=t({projectDir:i,contentDir:a,include:r.content.include,exclude:r.content.exclude})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function Vw(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Hw(e,t,n=process.cwd()){let r=e.op??`sync`,i=we(Se(Ce(t,n)));if(i&&i.port>0){let t=`http://127.0.0.1:${i.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${i.port})…\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({op:r})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??`Server responded with ${n.status}`)}Vw(e.json,{type:`triggered`,op:r,port:i.port}),e.json||process.stderr.write(`✓ ${r} triggered\n`);return}catch(t){let n=t instanceof Error?t.message:String(t);e.json||process.stderr.write(`Server trigger failed (${n}), running directly…\n`)}}e.json||process.stderr.write(`Running ${r} directly (no live server)…\n`);let a=De({baseDir:n});if(r===`sync`||r===`pull`){Vw(e.json,{type:`step`,step:`pull`});let t=await a.pull();Vw(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(Vw(e.json,{type:`step`,step:`push`}),await a.push(),Vw(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
1408
- `)),Vw(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function Uw(e){return new r(`sync`).description(`Commit, pull, and push to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Hw({json:t.json,op:`sync`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ sync failed: ${n}\n`),process.exit(1)}})}function Ww(e){return new r(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Hw({json:t.json,op:`pull`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ pull failed: ${n}\n`),process.exit(1)}})}function Gw(e){return new r(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Hw({json:t.json,op:`push`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ push failed: ${n}\n`),process.exit(1)}})}async function Kw(e={}){let t=zn(e.cwd??process.cwd()),n;try{n=await Ae({projectDir:t,rootDir:e.root})}catch(e){return e instanceof ke?{status:`prerequisite-missing`,message:`${Ze(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${Ze(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(n.created.length===0&&n.configEdits.length===0)return{status:`no-op`,message:`${Xe(`Your knowledge base is already seeded.`)}\n${Ye(`Nothing to do.`)}`,plan:n,exitCode:0};if(e.dryRun)return{status:`dry-run`,message:`${$e(`Plan (dry-run — no changes made):`)}\n\n${qw(n,t)}`,plan:n,exitCode:0};if(!e.yes&&!await Jw(`${$e(`Plan:`)}\n\n${qw(n,t)}\n\n${$e(`Apply?`)} ${Ye(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:Ye(`Cancelled.`),plan:n,exitCode:0};let r=await Oe(n,{projectDir:t});if(r.errors.length>0){let e=r.errors.map(e=>` ${Ze(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${Qe(`Applied`)} ${r.applied} entries, ${Qe(String(r.errors.length))} error(s):`,...e].join(`
1409
- `),plan:n,exitCode:1}}return{status:`applied`,message:`${Xe(`✓ Seeded knowledge base`)} ${Ye(`(${r.applied} entries, ${r.durationMs}ms)`)}`,plan:n,exitCode:0}}function qw(e,t){let n=[],r=e.created.filter(e=>e.kind===`folder`),i=e.created.filter(e=>e.kind===`file`);if(r.length>0){n.push($e(`Folders to create:`));for(let e of r)n.push(` ${Xe(`+`)} ${Je(Rn(t,zn(t,e.path))||e.path)}${Ye(`/`)}`)}if(i.length>0){n.length>0&&n.push(``),n.push($e(`Files to create:`));for(let e of i)n.push(` ${Xe(`+`)} ${Je(Rn(t,zn(t,e.path))||e.path)}`)}if(e.configEdits.length>0){n.length>0&&n.push(``),n.push($e(`config.yml folders: entries to add:`));for(let t of e.configEdits)n.push(` ${Xe(`+`)} ${Je(t.folderMatch)} ${Ye(`—`)} ${t.entry.frontmatter.title??``}`)}if(e.skipped.length>0){n.length>0&&n.push(``),n.push(Ye(`Already present (skipped):`));for(let t of e.skipped)n.push(` ${Ye(`· ${t.path} (${t.reason})`)}`)}if(e.warnings.length>0){n.length>0&&n.push(``),n.push(Qe(`Warnings:`));for(let t of e.warnings)n.push(` ${Qe(`!`)} ${t}`)}return n.join(`
1410
- `)}async function Jw(e,t){let n=gr({input:t??process.stdin,output:process.stdout});try{let t=(await n.question(e)).trim().toLowerCase();return t===``||t===`y`||t===`yes`}finally{n.close()}}function Yw(){return new r(`seed`).description(`Scaffold the Karpathy three-layer knowledge-base structure (external-sources/, research/, articles/) + log.md + config.yml folders: entries. Use --root to place them inside a subfolder instead of the project root.`).argument(`[path]`,`Project directory (defaults to cwd)`).option(`-r, --root <path>`,`Subfolder (relative to the project dir) to scaffold into — created if missing. Defaults to the project root when omitted in non-interactive runs; prompts on a TTY.`).option(`-y, --yes`,`Skip confirmation prompt`).option(`--dry-run`,`Print the plan and exit without writing`).action(async(e,t)=>{let n=await Kw({cwd:e??process.cwd(),root:t.root,yes:t.yes,dryRun:t.dryRun});process.stdout.write(`${n.message}\n`),n.exitCode!==0&&(process.exitCode=n.exitCode)})}function Xw(e,t){return{server:Zw(`server`,e),ui:Zw(`ui`,t)}}function Zw(e,t){switch(t.status){case`missing`:return{name:e,state:`missing`,alive:!1};case`corrupt`:return{name:e,state:`corrupt`,alive:!1};case`foreign-host`:return{name:e,state:`foreign-host`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:`unknown`};case`dead-pid`:return{name:e,state:`dead-pid`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!1};case`alive`:return{name:e,state:`alive`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!0}}}function Qw(e){return`${$w(e.server)}\n${$w(e.ui)}`}function $w(e){let t=e.name===`server`?`server`:`ui `;return e.state===`missing`?`${t} not running`:e.state===`corrupt`?`${t} lock file corrupt — run \`ok clean\``:e.state===`foreign-host`?`${t} foreign host (${e.host}) pid=${e.pid} port=${e.port}`:e.state===`dead-pid`?`${t} stale (dead pid=${e.pid}) — run \`ok clean\``:`${t} alive pid=${e.pid} port=${e.port} started=${e.startedAt}`}function eT(e){let t=e.inspect??(t=>No(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=Xw(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(Qw(r)),r}function tT(e){return new r(`status`).description(`Show live state of the server + ui lockfiles for this project`).option(`--json`,`Emit structured JSON instead of formatted text`).action(t=>{eT({lockDir:Se(Ce(e(),process.cwd())),json:t.json===!0})})}function nT(e,t){let n=[];return e.status===`alive`&&n.push({name:`server`,pid:e.lock.pid,port:e.lock.port}),t.status===`alive`&&n.push({name:`ui`,pid:t.lock.pid,port:t.lock.port}),{targets:n}}function rT(e){let t=e.inspect??(t=>No(e.lockDir,t)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=nT(t(`server`),t(`ui`));if(a.targets.length===0)return r(`No running open-knowledge processes.`),{stopped:[],failed:[],hadTargets:!1};let o=[],s=[];for(let e of a.targets)try{n(e.pid,`SIGTERM`),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}return o.length>0&&r(`Stopped: ${o.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),s.length>0&&i(`Failed to stop: ${s.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:o,failed:s,hadTargets:!0}}function iT(e){return new r(`stop`).description(`Stop the running open-knowledge server and UI (live only)`).action(()=>{rT({lockDir:Se(Ce(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}const aT=1e4,oT=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function sT(e){let t=e.upstreamTimeoutMs??aT,n=pr((n,r)=>{lT(n,r,e.upstreamHost,e.upstreamPort,t)});await new Promise((t,r)=>{let i=e=>r(e);n.once(`error`,i),n.listen(e.listenPort,e.host,()=>{n.off(`error`,i),t()})});let r=n.address();return{httpServer:n,port:typeof r==`object`&&r?r.port:e.listenPort,close:()=>new Promise(e=>{n.close(()=>e())})}}function cT(e,t,n){lT(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??aT)}function lT(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of oT)delete a[e];e.setTimeout(3e4,()=>{if(t.headersSent)try{t.end()}catch{}else try{t.writeHead(408,{"Content-Type":`text/plain`}),t.end(`Request Timeout`)}catch{}try{e.socket?.destroy()}catch{}});let o=mr({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of oT)delete n[e];t.writeHead(e.statusCode??502,n),e.pipe(t),e.once(`error`,()=>{try{t.end()}catch{}})});i>0&&o.setTimeout(i,()=>{if(!t.headersSent)t.writeHead(504,{"Content-Type":`text/plain`}),t.end(`Gateway Timeout`);else try{t.end()}catch{}o.destroy()}),o.on(`error`,()=>{if(!t.headersSent)t.writeHead(502,{"Content-Type":`text/plain`}),t.end(`Bad Gateway`);else try{t.end()}catch{}}),e.on(`error`,()=>{o.destroy()}),e.pipe(o)}async function uT(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function dT(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:r}=await import(`node:path`),{acquireUiLock:i,createAssetServeMiddleware:o,createContentFilter:s,readServerLock:c,releaseUiLock:l,updateUiLockPort:u}=await import(`./dist-U4KUxqv5.mjs`),{default:d}=await import(`./build-DPvitIN3.mjs`),{resolveContentDir:f,resolveLockDir:p}=await import(`./paths-rUSBGS5c.mjs`),m=f(e.config,e.cwd),h=p(m);i(h,{port:0,worktreeRoot:e.cwd});let g=import.meta.dirname??new URL(`.`,import.meta.url).pathname,_=[r(g,`public`),r(g,`../../app/dist`),r(g,`../../../app/dist`)].find(e=>t(e)),v=_?d(_,{single:!0,gzip:!0,immutable:!0,extensions:[]}):null,y=t(m)?o({contentFilter:s({projectDir:e.cwd,contentDir:m,includePatterns:e.config.content.include,excludePatterns:e.config.content.exclude}),contentSirv:d(m,{dotfiles:!1,dev:!0,extensions:[]}),inlineExtensions:he,assetExtensions:oe,blocklistExtensions:de}):null,b=e.port,x=null,S=(e,t)=>{let n=e.url?.split(`?`)[0];if((n===`/`||n===``)&&(e.url=`/index.html`),n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){x?.();let n=c(h),r=n&&n.port>0?`ws://localhost:${n.port}/collab`:null,i=JSON.stringify({collabUrl:r,previewUrl:null,port:b});t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,e.method===`HEAD`?t.end():t.end(i);return}if(n?.startsWith(`/api/`)){x?.();let r=c(h);if(!r||r.port<=0){t.writeHead(503,{"Content-Type":`application/json`,"Cache-Control":`no-store`}),t.end(JSON.stringify({error:"Collab server not running. Start `ok start` or run `ok status`.",path:n}));return}cT(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(y){y(e,t,()=>{v?v(e,t):fT(t)});return}if(v){v(e,t);return}fT(t)},ee=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],te=[],ne=e.port;try{for(let e of ee){let t=n(S);te.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(ne,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(ne=e.port),n()})})}}catch(e){await Promise.all(te.map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})));try{l(h)}catch{}throw e}let re=ne;b=re,u(h,re);let C=e.scheduler??a,w=e.safetyNetMs??432e5,ie=null,ae=!1,T=!1,E=()=>{ae||(ae=!0,ie!==null&&(C.clearTimeout(ie),ie=null))},se=()=>{if(E(),!T){T=!0;try{l(h)}catch{}}},ce=()=>{ae||w<=0||(ie!==null&&(C.clearTimeout(ie),ie=null),ie=C.setTimeout(()=>{ie=null,console.warn(`[ui] safety-net (${w}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of te)try{e.close()}catch{}se()},w))},le=()=>{ae||w<=0||ce()};return x=le,ce(),{httpServers:te,port:re,release:se,detachSafetyNet:E,nudgeSafetyNet:le}}function fT(e){e.writeHead(404),e.end(`Not found`)}function pT(e,t){if(e!==void 0){let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<0||t>65535)throw Error(`Invalid --port value '${e}'`);return t}if(t!==void 0&&t!==``){let e=Number.parseInt(t,10);if(Number.isNaN(e)||e<0||e>65535)throw Error(`Invalid PORT env value '${t}'`);return e}return 0}async function mT(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-U4KUxqv5.mjs`);return t(e.lockDir)}),n=await t();if(!n)throw Error(`UI lock collision reported but the lock disappeared before handling — retry acquiring.`);if(n.port===e.requestedPort&&n.port>0)return{mode:`already-running`,port:n.port};let r=n.port;if(r===0){let n=Date.now()+(e.pollDeadlineMs??2e3),i=e.pollIntervalMs??100;for(;Date.now()<n;){await new Promise(e=>{setTimeout(e,i)});let e=await t();if(e&&e.port>0){r=e.port;break}}if(r===0)throw Error("UI did not bind within 2s; run `ok clean`");if(r===e.requestedPort)return{mode:`already-running`,port:r}}return{mode:`proxy`,handle:await sT({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function hT(e){return new r(`ui`).description(`Serve the Open Knowledge React editor UI`).option(`-p, --port <port>`,`UI port (default: $PORT env or 0 / kernel-allocated)`).option(`-H, --host <host>`,"UI host. Default: two-socket loopback bind (`[::1]` + `127.0.0.1`) so cross-family collisions fail loud (D-033). Pass an explicit host (e.g. `127.0.0.1`, `0.0.0.0`) to bind a single socket on that host.").action(async t=>{let{dim:n}=await import(`./colors-CswooXAS.mjs`),{UiLockCollisionError:r}=await import(`./dist-U4KUxqv5.mjs`),{resolveContentDir:i,resolveLockDir:a}=await import(`./paths-rUSBGS5c.mjs`),o=e(),s=t.host,c;try{c=pT(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}try{let e=await dT({config:o,cwd:process.cwd(),port:c,host:s}),t=s===void 0||s===`::`||s===`0.0.0.0`?`localhost`:s;console.log(`${n(`[ui]`)} listening on http://${t}:${e.port}`);let r=!1,i=t=>{if(r)return;r=!0,console.log(n(`\n[ui] Shutting down (${t})...`)),e.detachSafetyNet();let i=()=>{try{e.release()}finally{process.exit(process.exitCode??0)}};uT(e.httpServers).then(i,i),setTimeout(i,2e3).unref()};process.once(`SIGINT`,()=>i(`SIGINT`)),process.once(`SIGTERM`,()=>i(`SIGTERM`));return}catch(e){if(!(e instanceof r))throw e;let t=a(i(o,process.cwd())),l=s??`localhost`,u;try{u=await mT({requestedPort:c,host:l,lockDir:t})}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}u.mode===`already-running`&&(console.log(`UI already running at http://${l}:${u.port}`),process.exit(0)),console.log(`UI running at http://${l}:${u.upstreamPort}; acting as HTTP proxy on port ${u.handle.port}`);let d=!1,f=e=>{d||(d=!0,console.log(n(`\n[ui-proxy] Shutting down (${e})...`)),u.handle.close().finally(()=>process.exit(process.exitCode??0)),setTimeout(()=>process.exit(process.exitCode??0),2e3).unref())};process.once(`SIGINT`,()=>f(`SIGINT`)),process.once(`SIGTERM`,()=>f(`SIGTERM`))}})}process.argv.includes(`--no-color`)?(process.env.NO_COLOR=`1`,delete process.env.FORCE_COLOR):process.argv.includes(`--color`)&&(process.env.FORCE_COLOR=`1`,delete process.env.NO_COLOR);const gT=new r;let _T;gT.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).version(be).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts(),n=t.cwd;n!==void 0&&process.chdir(n);let{config:r}=We(n),i=e.args.length===0?t:e.commands[0]?.opts()??{};i.host!==void 0&&(r.server.host=i.host),process.env.HOST&&(r.server.host=process.env.HOST),_T=r});const vT=On(()=>_T);gT.addCommand(vT,{isDefault:!0});const yT=zw(()=>_T);gT.addCommand(yT),gT.addCommand(qe()),gT.addCommand(Yw()),gT.addCommand(rs());const bT=Bw(()=>_T);gT.addCommand(bT);const xT=hT(()=>_T);gT.addCommand(xT),gT.addCommand(iT(()=>_T)),gT.addCommand(Io(()=>_T)),gT.addCommand(tT(()=>_T)),gT.addCommand($o()),gT.addCommand(Mo(()=>_T)),gT.addCommand(Ko(()=>_T)),gT.addCommand(Uw(()=>_T)),gT.addCommand(Gw(()=>_T)),gT.addCommand(Ww(()=>_T)),await gT.parseAsync();export{};
1409
+ `}async function Mw(e,t){try{let t=e.replace(`ws://`,`http://`).replace(`wss://`,`https://`);return(await fetch(`${t}/api/document`,{signal:AbortSignal.timeout(2e3)})).ok}catch(n){return t.warn(`Hocuspocus probe failed`,{serverUrl:e,error:n instanceof Error?n.message:String(n)}),!1}}async function Nw(e){let{projectDir:t,serverUrl:n,config:r,startupConfig:i,bypassProjectSelection:a=!1}=e;if(Aw=Am(),Aw.info(`MCP server starting`,{startupCwd:t,bypassProjectSelection:a,serverUrlType:typeof n==`string`?`explicit`:`lazy`}),typeof n==`string`){let e=await Mw(n,Aw);Aw.info(`Hocuspocus detection complete`,{serverUrl:n,available:e})}else Aw.info(`server discovery is lazy per effective cwd`);let o=new mm({name:xe,version:be},{instructions:jw(i,{dynamicConfig:typeof r==`function`&&!a})}),s=Ow({startupCwd:t,bypassProjectSelection:a,listRoots:()=>o.server.listRoots(),logger:Aw}),c=kw({startupCwd:t,resolveCwd:s.resolveCwd,bypassProjectSelection:a}),l=c.resolveCwdForTools;o.server.setNotificationHandler(Td,async()=>{s.invalidateRoots()});let u=async e=>{if(typeof n==`string`)return n.replace(`ws://`,`http://`).replace(`wss://`,`https://`);let t=e??await l();return(typeof n==`function`?await n(t):n)?.replace(`ws://`,`http://`).replace(`wss://`,`https://`)},d=sr(),f=process.env.AGENT_LABEL||void 0,p={current:{connectionId:d,label:f,displayName:f??`Agent`,colorSeed:f??d}};o.server.oninitialized=()=>{let e=o.server.getClientVersion();p.current={connectionId:d,clientInfo:e?{name:e.name,version:e.version}:void 0,label:f,displayName:f??e?.name??`Agent`,colorSeed:f??e?.name??d},Aw?.info(`agent identity established`,{displayName:p.current.displayName,connectionId:d.slice(0,8),clientName:e?.name})},Tw(o,{serverUrl:u,resolveCwd:l,config:r,identityRef:p,logger:Aw});let m=new Dm;await o.connect(m),Aw.info(`MCP server running on stdio`);let{startKeepalive:h}=await import(`./keepalive-BIRIvYdO.mjs`),g=h({resolveWsUrl:async()=>{let e=await c.getKeepaliveCwd();if(!e)return;let t=await u(e);if(t)return t.replace(/^http:/,`ws:`).replace(/^https:/,`wss:`)},connectionId:`agent-${d}`,logger:Aw.child(`keepalive`)}),_=e=>{Aw?.info(`MCP server shutting down`,{signal:e});try{g.close()}catch{}process.exit(0)};process.on(`SIGINT`,()=>_(`SIGINT`)),process.on(`SIGTERM`,()=>_(`SIGTERM`))}const Pw=[`/_npx/`,`/.npm/_npx/`,`/_bunx/`,`/.bun/install/cache/`,`/pnpm/dlx/`],Fw=new Set([`/usr/local/bin/ok`,`/usr/local/bin/open-knowledge`,`/opt/homebrew/bin/ok`,`/opt/homebrew/bin/open-knowledge`]);function Iw(e){if(!e||e.length===0)return`unknown`;for(let t of Pw)if(e.includes(t))return`npx-cache`;return Fw.has(e)||e.startsWith(`/Applications/`)||e.includes(`.app/Contents/`)?`stable-shim`:e.startsWith(`/`)?`absolute-pin`:`unknown`}function Lw(e,t){switch(e){case`npx-cache`:return"This MCP was launched via a package-manager cache (npx / bunx / pnpm dlx) and just resolved a different package version than the running server. Stop `ok start` so the next launch matches, or run `ok init --pin` for a stable launch path.";case`stable-shim`:return"The CLI shim was likely upgraded while a project server is still running (a desktop auto-update or `npm i -g` / `brew upgrade` will do this). Close and reopen the project window, or stop `ok start`, so the next launch matches.";case`absolute-pin`:return`This MCP is launched from a pinned path${t?` (${t})`:``} that no longer matches the running server. Re-run \`ok init --pin\` from your current install to refresh, or stop \`ok start\` so the next launch matches.`;default:return"Stop `ok start` and retry, or align CLI versions across your installs."}}function Rw(e){return e?/\bENOENT\b/i.test(e):!1}function zw(e){switch(Iw(e)){case`absolute-pin`:return"This failure usually means the CLI entry script no longer exists at the pinned path (common after changing how you installed Open Knowledge or removing an old global package). Re-run `ok init --pin` from your current install and update your editor MCP config, or use an unpinned launcher such as `npx @inkeep/open-knowledge mcp`.";case`stable-shim`:return"The expected `ok` shim is missing on disk. Reinstall or repair your Open Knowledge CLI. If you switched install sources, run `ok init --pin` again so your editor matches the binary you have.";case`npx-cache`:return"The package-manager cache copy used for this launch may have been removed. Retry once, or run `ok init --pin` so your editor uses a durable absolute path.";default:return"Often means the configured launcher path does not exist (stale pin, moved install, or missing runtime). Re-run `ok init --pin` from your current install or fix the MCP command in your editor settings."}}function Bw(e,t,n){let r=`spawn failed: ${e}${t?` stderr:\n${t}`:``}`;return Rw(e)&&(r+=`\n\n${zw(n)}`),r}function Vw(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function Hw(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t))return{action:`disk-only`,message:`invalid --port value '${e.portOverride}' — disk-only mode`};if(t>0){let n=`ws://${e.host}:${t}`;return{action:`connect`,url:n,message:`using --port override, connecting to ${n}`}}return{action:`disk-only`,message:`--port=0 — disk-only mode`}}let t=e.readLock();if(t&&t.port>0&&e.isAlive(t.pid)){let n=e.expectedProtocolVersion??1,r=t.protocolVersion;if(r===n){let e=`ws://localhost:${t.port}`;return{action:`connect`,url:e,message:`connected to running instance at ${e} (pid ${t.pid})`}}let i=r===void 0?`unknown (pre-version-field lock)`:`v${r}`,a=t.runtimeVersion?` runtime ${t.runtimeVersion}`:``,o=e.launchPath??process.argv[1],s=Iw(o),c=Lw(s,o);return{action:`incompatible`,message:`Open Knowledge server at port ${t.port} (pid ${t.pid}${a}) speaks protocol ${i}; this MCP needs protocol v${n}.\n`+c,expectedProtocolVersion:n,actualProtocolVersion:r,lock:t,launchShape:s,launchPath:o}}return e.envAutoStart===`0`?{action:`disk-only`,message:`auto-spawn disabled via OK_MCP_AUTOSTART=0 — disk-only mode`}:e.configAutoStart?t?{action:`spawn`,message:`existing lock is not usable (port=${t.port}, pid=${t.pid}) — spawning ok start`}:{action:`spawn`,message:`no running instance — spawning ok start`}:{action:`disk-only`,message:`auto-spawn disabled via config.mcp.autoStart=false — disk-only mode`}}async function Uw(e){let t=e.readLock??(()=>we(e.lockDir)),n=e.isAlive??Te,r=e.sleep??(e=>fr(e)),i=e.spawn??jn,a=e.readErrorLog??(e=>Hn(e)?Gn(e,`utf-8`).trim():``),o=e.openErrorLog??(e=>Wn(e,`w`)),s=e.closeFd??Vn,c=e.timeoutMs??5e3,l=e.pollIntervalMs??100,u=e.launchPath??process.argv[1],d=Hw({host:e.host,portOverride:e.portOverride,envAutoStart:e.envAutoStart,configAutoStart:e.configAutoStart,readLock:t,isAlive:n,launchPath:e.launchPath});if(e.logger?.info(`auto-start decision`,{action:d.action,message:d.message,contentDir:e.contentDir}),d.action===`connect`)return{serverUrl:d.url,message:d.message};if(d.action===`disk-only`)return{serverUrl:void 0,message:d.message};if(d.action===`incompatible`)throw e.logger?.error(`protocol mismatch — refusing to connect`,void 0,{expectedProtocolVersion:d.expectedProtocolVersion,actualProtocolVersion:d.actualProtocolVersion,lockPid:d.lock.pid,lockPort:d.lock.port,lockRuntimeVersion:d.lock.runtimeVersion,launchShape:d.launchShape,launchPath:d.launchPath}),Error(d.message);Hn(e.lockDir)||Un(e.lockDir,{recursive:!0});let f=Ln(e.lockDir,`last-spawn-error.log`),p=o(f),m,h,g=kn();e.logger?.info(`spawning server`,{command:g.command,cwd:e.contentDir,timeoutMs:c});try{try{m=i(g.command,[...g.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,p],cwd:e.contentDir,env:{...process.env,OK_LOCK_KIND:`mcp-spawned`,OK_PARENT_PID:String(process.pid)}}),m.on(`error`,e=>{h=e instanceof Error?e.message:String(e)}),m.unref()}catch(e){h=e instanceof Error?e.message:String(e)}}finally{try{s(p)}catch{}}let _=Date.now()+c;for(;Date.now()<_;){if(h){let t=a(f);throw e.logger?.error(`spawn failed`,void 0,{error:h,stderr:t,launchPath:u,stalePinHint:Rw(h)}),Error(Bw(h,t,u))}await r(l);let i=t();if(i&&i.port>0&&n(i.pid)){let t=`ws://localhost:${i.port}`;return e.logger?.info(`server ready after spawn`,{url:t,pid:i.pid}),{serverUrl:t,message:`spawned ok start; connected at ${t} (pid ${i.pid})`}}}if(h){let t=a(f);throw e.logger?.error(`spawn failed (post-deadline)`,void 0,{error:h,stderr:t,launchPath:u,stalePinHint:Rw(h)}),Error(Bw(h,t,u))}let v=a(f),y=(c/1e3).toFixed(c%1e3==0?0:2),b=m?.pid,x=``;throw typeof b==`number`&&(x=n(b)?` child pid=${b} is still running — raise OK_MCP_SPAWN_TIMEOUT_MS if this is a slow boot.`:` child pid=${b} exited — check last-spawn-error.log.`),e.logger?.error(`spawn poll timeout`,void 0,{timeoutMs:c,childPid:b,childAlive:typeof b==`number`?n(b):void 0,stderr:v||void 0}),Error(`server did not start within ${y}s.${x}${v?` stderr:\n${v}`:``}`)}function Ww(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)return async()=>void 0;let n=`ws://${e.host}:${t}`;return async()=>n}let t=e.ensureServerRunningFn??Uw,n=e.cacheMs??1e3,r=new Map,i=new Map;return async a=>{let o=await Ue(a??e.startupCwd),s=Date.now(),c=r.get(o);if(c&&c.expiresAt>s)return e.logger?.debug(`server url cache hit`,{cwd:o,url:c.url}),c.url;let l=i.get(o);if(l)return e.logger?.debug(`server url resolution pending`,{cwd:o}),await l;e.logger?.debug(`server url cache miss`,{cwd:o});let u=(async()=>{let i=await e.resolveConfig(o),a=Ce(i,o),s=Se(a),c=e.readLock,l=c?()=>c(s):void 0,u=await t({lockDir:s,contentDir:a,host:i.server.host,portOverride:void 0,envAutoStart:e.envAutoStart,configAutoStart:i.mcp.autoStart,logger:e.logger,timeoutMs:e.timeoutMs,pollIntervalMs:e.pollIntervalMs,spawn:e.spawn,readLock:l,isAlive:e.isAlive,sleep:e.sleep,readErrorLog:e.readErrorLog,openErrorLog:e.openErrorLog,closeFd:e.closeFd,launchPath:e.launchPath});return r.set(o,{url:u.serverUrl,expiresAt:Date.now()+n}),u.serverUrl})();i.set(o,u);try{return await u}finally{i.delete(o)}}}function Gw(e){return new r(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override port discovery and connect to this port (0 = disk-only)`,void 0).action(async t=>{try{let n=e(),r=process.cwd(),i=Ke({startupCwd:r,startupConfig:n}),a=Vw(process.env.OK_MCP_SPAWN_TIMEOUT_MS),o,s;if(t.port!==void 0){let e=Number.parseInt(t.port,10);Number.isNaN(e)?(o=void 0,s=`invalid --port value '${t.port}' — disk-only mode`):e>0?(o=`ws://${n.server.host}:${e}`,s=`using --port override, connecting to ${o}`):(o=void 0,s=`--port=0 — disk-only mode`)}else o=Ww({startupCwd:r,resolveConfig:i,host:n.server.host,portOverride:void 0,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:a}),s=`project server discovery/autostart is lazy per effective cwd`;process.stderr.write(`[mcp] ${s}\n`),await Nw({projectDir:r,serverUrl:o,config:i,startupConfig:n,bypassProjectSelection:t.port!==void 0})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function Kw(e){return new r(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-CfADaMr4.mjs`),r=e(),i=process.cwd(),a=Ce(r,i),o;try{o=t({projectDir:i,contentDir:a,include:r.content.include,exclude:r.content.exclude})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function qw(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Jw(e,t,n=process.cwd()){let r=e.op??`sync`,i=we(Se(Ce(t,n)));if(i&&i.port>0){let t=`http://127.0.0.1:${i.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${i.port})…\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({op:r})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??`Server responded with ${n.status}`)}qw(e.json,{type:`triggered`,op:r,port:i.port}),e.json||process.stderr.write(`✓ ${r} triggered\n`);return}catch(t){let n=t instanceof Error?t.message:String(t);e.json||process.stderr.write(`Server trigger failed (${n}), running directly…\n`)}}e.json||process.stderr.write(`Running ${r} directly (no live server)…\n`);let a=De({baseDir:n});if(r===`sync`||r===`pull`){qw(e.json,{type:`step`,step:`pull`});let t=await a.pull();qw(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(qw(e.json,{type:`step`,step:`push`}),await a.push(),qw(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
1410
+ `)),qw(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function Yw(e){return new r(`sync`).description(`Commit, pull, and push to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Jw({json:t.json,op:`sync`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ sync failed: ${n}\n`),process.exit(1)}})}function Xw(e){return new r(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Jw({json:t.json,op:`pull`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ pull failed: ${n}\n`),process.exit(1)}})}function Zw(e){return new r(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Jw({json:t.json,op:`push`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ push failed: ${n}\n`),process.exit(1)}})}async function Qw(e={}){let t=zn(e.cwd??process.cwd()),n;try{n=await Ae({projectDir:t,rootDir:e.root})}catch(e){return e instanceof ke?{status:`prerequisite-missing`,message:`${Ze(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${Ze(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(n.created.length===0&&n.configEdits.length===0)return{status:`no-op`,message:`${Xe(`Your knowledge base is already seeded.`)}\n${Ye(`Nothing to do.`)}`,plan:n,exitCode:0};if(e.dryRun)return{status:`dry-run`,message:`${$e(`Plan (dry-run — no changes made):`)}\n\n${$w(n,t)}`,plan:n,exitCode:0};if(!e.yes&&!await eT(`${$e(`Plan:`)}\n\n${$w(n,t)}\n\n${$e(`Apply?`)} ${Ye(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:Ye(`Cancelled.`),plan:n,exitCode:0};let r=await Oe(n,{projectDir:t});if(r.errors.length>0){let e=r.errors.map(e=>` ${Ze(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${Qe(`Applied`)} ${r.applied} entries, ${Qe(String(r.errors.length))} error(s):`,...e].join(`
1411
+ `),plan:n,exitCode:1}}return{status:`applied`,message:`${Xe(`✓ Seeded knowledge base`)} ${Ye(`(${r.applied} entries, ${r.durationMs}ms)`)}`,plan:n,exitCode:0}}function $w(e,t){let n=[],r=e.created.filter(e=>e.kind===`folder`),i=e.created.filter(e=>e.kind===`file`);if(r.length>0){n.push($e(`Folders to create:`));for(let e of r)n.push(` ${Xe(`+`)} ${Je(Rn(t,zn(t,e.path))||e.path)}${Ye(`/`)}`)}if(i.length>0){n.length>0&&n.push(``),n.push($e(`Files to create:`));for(let e of i)n.push(` ${Xe(`+`)} ${Je(Rn(t,zn(t,e.path))||e.path)}`)}if(e.configEdits.length>0){n.length>0&&n.push(``),n.push($e(`config.yml folders: entries to add:`));for(let t of e.configEdits)n.push(` ${Xe(`+`)} ${Je(t.folderMatch)} ${Ye(`—`)} ${t.entry.frontmatter.title??``}`)}if(e.skipped.length>0){n.length>0&&n.push(``),n.push(Ye(`Already present (skipped):`));for(let t of e.skipped)n.push(` ${Ye(`· ${t.path} (${t.reason})`)}`)}if(e.warnings.length>0){n.length>0&&n.push(``),n.push(Qe(`Warnings:`));for(let t of e.warnings)n.push(` ${Qe(`!`)} ${t}`)}return n.join(`
1412
+ `)}async function eT(e,t){let n=gr({input:t??process.stdin,output:process.stdout});try{let t=(await n.question(e)).trim().toLowerCase();return t===``||t===`y`||t===`yes`}finally{n.close()}}function tT(){return new r(`seed`).description(`Scaffold the Karpathy three-layer knowledge-base structure (external-sources/, research/, articles/) + log.md + config.yml folders: entries. Use --root to place them inside a subfolder instead of the project root.`).argument(`[path]`,`Project directory (defaults to cwd)`).option(`-r, --root <path>`,`Subfolder (relative to the project dir) to scaffold into — created if missing. Defaults to the project root when omitted in non-interactive runs; prompts on a TTY.`).option(`-y, --yes`,`Skip confirmation prompt`).option(`--dry-run`,`Print the plan and exit without writing`).action(async(e,t)=>{let n=await Qw({cwd:e??process.cwd(),root:t.root,yes:t.yes,dryRun:t.dryRun});process.stdout.write(`${n.message}\n`),n.exitCode!==0&&(process.exitCode=n.exitCode)})}function nT(e,t){return{server:rT(`server`,e),ui:rT(`ui`,t)}}function rT(e,t){switch(t.status){case`missing`:return{name:e,state:`missing`,alive:!1};case`corrupt`:return{name:e,state:`corrupt`,alive:!1};case`foreign-host`:return{name:e,state:`foreign-host`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:`unknown`};case`dead-pid`:return{name:e,state:`dead-pid`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!1};case`alive`:return{name:e,state:`alive`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!0}}}function iT(e){return`${aT(e.server)}\n${aT(e.ui)}`}function aT(e){let t=e.name===`server`?`server`:`ui `;return e.state===`missing`?`${t} not running`:e.state===`corrupt`?`${t} lock file corrupt — run \`ok clean\``:e.state===`foreign-host`?`${t} foreign host (${e.host}) pid=${e.pid} port=${e.port}`:e.state===`dead-pid`?`${t} stale (dead pid=${e.pid}) — run \`ok clean\``:`${t} alive pid=${e.pid} port=${e.port} started=${e.startedAt}`}function oT(e){let t=e.inspect??(t=>No(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=nT(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(iT(r)),r}function sT(e){return new r(`status`).description(`Show live state of the server + ui lockfiles for this project`).option(`--json`,`Emit structured JSON instead of formatted text`).action(t=>{oT({lockDir:Se(Ce(e(),process.cwd())),json:t.json===!0})})}function cT(e,t){let n=[];return e.status===`alive`&&n.push({name:`server`,pid:e.lock.pid,port:e.lock.port}),t.status===`alive`&&n.push({name:`ui`,pid:t.lock.pid,port:t.lock.port}),{targets:n}}function lT(e){let t=e.inspect??(t=>No(e.lockDir,t)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=cT(t(`server`),t(`ui`));if(a.targets.length===0)return r(`No running open-knowledge processes.`),{stopped:[],failed:[],hadTargets:!1};let o=[],s=[];for(let e of a.targets)try{n(e.pid,`SIGTERM`),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}return o.length>0&&r(`Stopped: ${o.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),s.length>0&&i(`Failed to stop: ${s.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:o,failed:s,hadTargets:!0}}function uT(e){return new r(`stop`).description(`Stop the running open-knowledge server and UI (live only)`).action(()=>{lT({lockDir:Se(Ce(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}const dT=1e4,fT=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function pT(e){let t=e.upstreamTimeoutMs??dT,n=pr((n,r)=>{hT(n,r,e.upstreamHost,e.upstreamPort,t)});await new Promise((t,r)=>{let i=e=>r(e);n.once(`error`,i),n.listen(e.listenPort,e.host,()=>{n.off(`error`,i),t()})});let r=n.address();return{httpServer:n,port:typeof r==`object`&&r?r.port:e.listenPort,close:()=>new Promise(e=>{n.close(()=>e())})}}function mT(e,t,n){hT(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??dT)}function hT(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of fT)delete a[e];e.setTimeout(3e4,()=>{if(t.headersSent)try{t.end()}catch{}else try{t.writeHead(408,{"Content-Type":`text/plain`}),t.end(`Request Timeout`)}catch{}try{e.socket?.destroy()}catch{}});let o=mr({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of fT)delete n[e];t.writeHead(e.statusCode??502,n),e.pipe(t),e.once(`error`,()=>{try{t.end()}catch{}})});i>0&&o.setTimeout(i,()=>{if(!t.headersSent)t.writeHead(504,{"Content-Type":`text/plain`}),t.end(`Gateway Timeout`);else try{t.end()}catch{}o.destroy()}),o.on(`error`,()=>{if(!t.headersSent)t.writeHead(502,{"Content-Type":`text/plain`}),t.end(`Bad Gateway`);else try{t.end()}catch{}}),e.on(`error`,()=>{o.destroy()}),e.pipe(o)}async function gT(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function _T(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:r}=await import(`node:path`),{acquireUiLock:i,createAssetServeMiddleware:o,createContentFilter:s,readServerLock:c,releaseUiLock:l,updateUiLockPort:u}=await import(`./dist-BnZHVzE4.mjs`),{default:d}=await import(`./build-DPvitIN3.mjs`),{resolveContentDir:f,resolveLockDir:p}=await import(`./paths-EnLHpVly.mjs`),m=f(e.config,e.cwd),h=p(m);i(h,{port:0,worktreeRoot:e.cwd});let g=import.meta.dirname??new URL(`.`,import.meta.url).pathname,_=[r(g,`public`),r(g,`../../app/dist`),r(g,`../../../app/dist`)].find(e=>t(e)),v=_?d(_,{single:!0,gzip:!0,immutable:!0,extensions:[]}):null,y=t(m)?o({contentFilter:s({projectDir:e.cwd,contentDir:m,includePatterns:e.config.content.include,excludePatterns:e.config.content.exclude}),contentSirv:d(m,{dotfiles:!1,dev:!0,extensions:[]}),inlineExtensions:he,assetExtensions:oe,blocklistExtensions:de}):null,b=e.port,x=null,S=(e,t)=>{let n=e.url?.split(`?`)[0];if((n===`/`||n===``)&&(e.url=`/index.html`),n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){x?.();let n=c(h),r=n&&n.port>0?`ws://localhost:${n.port}/collab`:null,i=JSON.stringify({collabUrl:r,previewUrl:null,port:b});t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,e.method===`HEAD`?t.end():t.end(i);return}if(n?.startsWith(`/api/`)){x?.();let r=c(h);if(!r||r.port<=0){t.writeHead(503,{"Content-Type":`application/json`,"Cache-Control":`no-store`}),t.end(JSON.stringify({error:"Collab server not running. Start `ok start` or run `ok status`.",path:n}));return}mT(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(y){y(e,t,()=>{v?v(e,t):vT(t)});return}if(v){v(e,t);return}vT(t)},ee=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],te=[],ne=e.port;try{for(let e of ee){let t=n(S);te.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(ne,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(ne=e.port),n()})})}}catch(e){await Promise.all(te.map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})));try{l(h)}catch{}throw e}let re=ne;b=re,u(h,re);let C=e.scheduler??a,w=e.safetyNetMs??432e5,ie=null,ae=!1,T=!1,E=()=>{ae||(ae=!0,ie!==null&&(C.clearTimeout(ie),ie=null))},se=()=>{if(E(),!T){T=!0;try{l(h)}catch{}}},ce=()=>{ae||w<=0||(ie!==null&&(C.clearTimeout(ie),ie=null),ie=C.setTimeout(()=>{ie=null,console.warn(`[ui] safety-net (${w}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of te)try{e.close()}catch{}se()},w))},le=()=>{ae||w<=0||ce()};return x=le,ce(),{httpServers:te,port:re,release:se,detachSafetyNet:E,nudgeSafetyNet:le}}function vT(e){e.writeHead(404),e.end(`Not found`)}function yT(e,t){if(e!==void 0){let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<0||t>65535)throw Error(`Invalid --port value '${e}'`);return t}if(t!==void 0&&t!==``){let e=Number.parseInt(t,10);if(Number.isNaN(e)||e<0||e>65535)throw Error(`Invalid PORT env value '${t}'`);return e}return 0}async function bT(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-BnZHVzE4.mjs`);return t(e.lockDir)}),n=await t();if(!n)throw Error(`UI lock collision reported but the lock disappeared before handling — retry acquiring.`);if(n.port===e.requestedPort&&n.port>0)return{mode:`already-running`,port:n.port};let r=n.port;if(r===0){let n=Date.now()+(e.pollDeadlineMs??2e3),i=e.pollIntervalMs??100;for(;Date.now()<n;){await new Promise(e=>{setTimeout(e,i)});let e=await t();if(e&&e.port>0){r=e.port;break}}if(r===0)throw Error("UI did not bind within 2s; run `ok clean`");if(r===e.requestedPort)return{mode:`already-running`,port:r}}return{mode:`proxy`,handle:await pT({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function xT(e){return new r(`ui`).description(`Serve the Open Knowledge React editor UI`).option(`-p, --port <port>`,`UI port (default: $PORT env or 0 / kernel-allocated)`).option(`-H, --host <host>`,"UI host. Default: two-socket loopback bind (`[::1]` + `127.0.0.1`) so cross-family collisions fail loud (D-033). Pass an explicit host (e.g. `127.0.0.1`, `0.0.0.0`) to bind a single socket on that host.").action(async t=>{let{dim:n}=await import(`./colors-CswooXAS.mjs`),{UiLockCollisionError:r}=await import(`./dist-BnZHVzE4.mjs`),{resolveContentDir:i,resolveLockDir:a}=await import(`./paths-EnLHpVly.mjs`),o=e(),s=t.host,c;try{c=yT(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}try{let e=await _T({config:o,cwd:process.cwd(),port:c,host:s}),t=s===void 0||s===`::`||s===`0.0.0.0`?`localhost`:s;console.log(`${n(`[ui]`)} listening on http://${t}:${e.port}`);let r=!1,i=t=>{if(r)return;r=!0,console.log(n(`\n[ui] Shutting down (${t})...`)),e.detachSafetyNet();let i=()=>{try{e.release()}finally{process.exit(process.exitCode??0)}};gT(e.httpServers).then(i,i),setTimeout(i,2e3).unref()};process.once(`SIGINT`,()=>i(`SIGINT`)),process.once(`SIGTERM`,()=>i(`SIGTERM`));return}catch(e){if(!(e instanceof r))throw e;let t=a(i(o,process.cwd())),l=s??`localhost`,u;try{u=await bT({requestedPort:c,host:l,lockDir:t})}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}u.mode===`already-running`&&(console.log(`UI already running at http://${l}:${u.port}`),process.exit(0)),console.log(`UI running at http://${l}:${u.upstreamPort}; acting as HTTP proxy on port ${u.handle.port}`);let d=!1,f=e=>{d||(d=!0,console.log(n(`\n[ui-proxy] Shutting down (${e})...`)),u.handle.close().finally(()=>process.exit(process.exitCode??0)),setTimeout(()=>process.exit(process.exitCode??0),2e3).unref())};process.once(`SIGINT`,()=>f(`SIGINT`)),process.once(`SIGTERM`,()=>f(`SIGTERM`))}})}process.argv.includes(`--no-color`)?(process.env.NO_COLOR=`1`,delete process.env.FORCE_COLOR):process.argv.includes(`--color`)&&(process.env.FORCE_COLOR=`1`,delete process.env.NO_COLOR);const ST=new r;let CT;ST.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).version(be).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts(),n=t.cwd;n!==void 0&&process.chdir(n);let{config:r}=We(n),i=e.args.length===0?t:e.commands[0]?.opts()??{};i.host!==void 0&&(r.server.host=i.host),process.env.HOST&&(r.server.host=process.env.HOST),CT=r});const wT=On(()=>CT);ST.addCommand(wT,{isDefault:!0});const TT=Gw(()=>CT);ST.addCommand(TT),ST.addCommand(qe()),ST.addCommand(tT()),ST.addCommand(rs());const ET=Kw(()=>CT);ST.addCommand(ET);const DT=xT(()=>CT);ST.addCommand(DT),ST.addCommand(uT(()=>CT)),ST.addCommand(Io(()=>CT)),ST.addCommand(sT(()=>CT)),ST.addCommand($o()),ST.addCommand(Mo(()=>CT)),ST.addCommand(Ko(()=>CT)),ST.addCommand(Yw(()=>CT)),ST.addCommand(Zw(()=>CT)),ST.addCommand(Xw(()=>CT)),await ST.parseAsync();export{};
1411
1413
  //# sourceMappingURL=cli.mjs.map