alchemylab-opencode 1.0.26 → 2.0.1

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 (123) hide show
  1. package/NODE_COMPAT.md +23 -174
  2. package/dist/20260127222353_familiar_lady_ursula-KV747FJX.js +14 -0
  3. package/dist/{chunk-LTCXIXYM.js → 20260211171708_add_project_commands-GDOHPDPF.js} +3 -1
  4. package/dist/20260213144116_wakeful_the_professor-ZVDD54AK.js +14 -0
  5. package/dist/20260225215848_workspace-ZMSOZSPA.js +14 -0
  6. package/dist/20260227213759_add_session_workspace_id-ROENWPKA.js +14 -0
  7. package/dist/20260228203230_blue_harpoon-IW3Z4TQZ.js +14 -0
  8. package/dist/20260303231226_add_workspace_fields-OUVZMNAG.js +14 -0
  9. package/dist/20260309230000_move_org_to_state-NOXAPU5V.js +14 -0
  10. package/dist/20260312043431_session_message_cursor-DJ4T3T4R.js +14 -0
  11. package/dist/20260323234822_events-72GIKJ2A.js +14 -0
  12. package/dist/20260410174513_workspace-name-JXSWFBJN.js +14 -0
  13. package/dist/20260413175956_chief_energizer-4HEWZ6U3.js +14 -0
  14. package/dist/20260423070820_add_icon_url_override-X5SHFGTI.js +14 -0
  15. package/dist/20260427172553_slow_nightmare-PS5T2AH2.js +14 -0
  16. package/dist/{chunk-PWFRMDDF.js → 20260428004200_add_session_path-LGW75WYA.js} +3 -0
  17. package/dist/{valibot--1zFm7rT-FSYJNYJ6.js → 20260501142318_next_venus-J3TLVXZ6.js} +3 -1
  18. package/dist/20260504145000_add_sync_owner-3R52GB4C.js +14 -0
  19. package/dist/20260507164347_add_workspace_time-JHDRCZAR.js +14 -0
  20. package/dist/20260510033149_session_usage-UGBVOXZB.js +53 -0
  21. package/dist/20260511000411_data_migration_state-FB4LBFSE.js +14 -0
  22. package/dist/20260511173437_session-metadata-T2XHGWHS.js +14 -0
  23. package/dist/20260601010001_normalize_storage_paths-5MAY5GT3.js +14 -0
  24. package/dist/{chunk-YRY5Y3QL.js → 20260601202201_amazing_prowler-PET224YG.js} +3 -1
  25. package/dist/20260602002951_lowly_union_jack-PG6XDMGL.js +14 -0
  26. package/dist/20260602182828_add_project_directories-ZCH2ACGG.js +14 -0
  27. package/dist/20260603001617_session_message_projection_indexes-XVLJTUF2.js +14 -0
  28. package/dist/20260603040000_session_message_projection_order-XG6RACZQ.js +14 -0
  29. package/dist/20260603141458_session_input_inbox-K2VQ7V6E.js +14 -0
  30. package/dist/20260603160727_jittery_ezekiel_stane-WKJLRDO7.js +14 -0
  31. package/dist/20260604172448_event_sourced_session_input-NTXOECR7.js +14 -0
  32. package/dist/20260605003541_add_session_context_snapshot-DXMQEXMT.js +14 -0
  33. package/dist/{zod-Bwrt9trS-HVDOFWRP.js → 20260605042240_add_context_epoch_agent-W6IQYZXE.js} +3 -1
  34. package/dist/20260611035744_credential-XTMSYTJD.js +14 -0
  35. package/dist/20260611192811_lush_chimera-XPLIQMJD.js +14 -0
  36. package/dist/20260612174303_project_dir_strategy-FR2NGQKK.js +14 -0
  37. package/dist/20260622142730_simplify_session_context_epoch-NTQZR3RE.js +14 -0
  38. package/dist/20260622170816_reset_v2_session_state-5JPHJTZG.js +14 -0
  39. package/dist/20260622202450_simplify_session_input-2EXF2HMV.js +14 -0
  40. package/dist/app-runtime-HQBOCDV5.js +14 -0
  41. package/dist/chunk-4FEBIOI5.js +865 -0
  42. package/dist/chunk-4K2RXRZL.js +14 -0
  43. package/dist/chunk-4RFMKEKM.js +1455 -0
  44. package/dist/chunk-BM2C7NHL.js +41 -0
  45. package/dist/chunk-MKEMZFJI.js +393 -0
  46. package/dist/chunk-OMDJ6ZZ2.js +684 -0
  47. package/dist/chunk-OWMG4NNF.js +186 -0
  48. package/dist/chunk-QRABYJKL.js +14 -0
  49. package/dist/chunk-RHIWAYN5.js +14 -0
  50. package/dist/{arktype-aI7TBD0R-TFNARRIP.js → chunk-VURLSDCB.js} +3 -1
  51. package/dist/chunk-Z5TLIUAI.js +28 -0
  52. package/dist/code-mode-7BQJUARW.js +40 -0
  53. package/dist/copilot-provider-TX4YFKJZ.js +14 -0
  54. package/dist/photon-VQS5F5BI.js +14 -0
  55. package/dist/pty.node-Y3N2XKYG.js +14 -0
  56. package/dist/run.js +3 -1
  57. package/dist/serve.js +3 -1
  58. package/dist/server-BFUQR7MX.js +17 -0
  59. package/dist/session-6RNXZNG6.js +14 -0
  60. package/dist/{chunk-2ANK3QEN.js → worktree-QHQHX3SG.js} +3 -1
  61. package/package.json +83 -50
  62. package/patches/@ai-sdk%2Famazon-bedrock@4.0.166.patch +164 -0
  63. package/patches/@ai-sdk%2Fanthropic@3.0.111.patch +528 -0
  64. package/patches/@ai-sdk%2Fgoogle@3.0.73.patch +69 -0
  65. package/patches/@ai-sdk%2Fgroq@3.0.31.patch +79 -0
  66. package/patches/@ai-sdk%2Fmistral@3.0.51.patch +714 -0
  67. package/patches/@ai-sdk%2Fopenai-compatible@2.0.41.patch +39 -0
  68. package/patches/@ai-sdk%2Fopenai@3.0.88.patch +280 -0
  69. package/patches/@ai-sdk%2Fxai@3.0.139.patch +296 -0
  70. package/patches/@modelcontextprotocol%2Fsdk@1.29.0.patch +647 -0
  71. package/patches/@npmcli%2Fagent@4.0.2.patch +13 -0
  72. package/patches/@silvia-odwyer%2Fphoton-node@0.3.4.patch +285 -0
  73. package/patches/effect@4.0.0-beta.83.patch +57 -0
  74. package/patches/gcp-metadata@8.1.2.patch +14 -0
  75. package/patches/pacote@21.5.0.patch +18 -0
  76. package/postinstall.cjs +146 -0
  77. package/dist/chunk-5P5WLADX.js +0 -18
  78. package/dist/chunk-7KKA6WBY.js +0 -12
  79. package/dist/chunk-A7EXZZPC.js +0 -12
  80. package/dist/chunk-CZVKIDQZ.js +0 -12
  81. package/dist/chunk-FXLFZ5DL.js +0 -12
  82. package/dist/chunk-G752V4OP.js +0 -2187
  83. package/dist/chunk-GBXMNWYD.js +0 -18
  84. package/dist/chunk-IR6PDN4W.js +0 -13
  85. package/dist/chunk-M4CB72HE.js +0 -13
  86. package/dist/chunk-MBZTOEAD.js +0 -12
  87. package/dist/default-u_dwuiYb-652AQZKX.js +0 -12
  88. package/dist/effect-QlVUlMFu-JVYEXAZL.js +0 -12
  89. package/dist/log-MVJ7H4K5.js +0 -12
  90. package/dist/pty.node-X2EITEZ4.js +0 -12
  91. package/dist/registry-ISXIFNPG.js +0 -12
  92. package/dist/run-AUCA7EKA.js +0 -20
  93. package/dist/run-service-MT3LOWLS.js +0 -12
  94. package/dist/schema-YWIVP7UR.js +0 -12
  95. package/dist/server-PIYRZLBG.js +0 -12
  96. package/dist/session-ACBIJ2VE.js +0 -12
  97. package/dist/share-next-MPGA7EO4.js +0 -12
  98. package/dist/sury-CWZTCd75-3YHH6KVI.js +0 -12
  99. package/dist/typebox-Dei93FPO-GLI7OCTY.js +0 -12
  100. package/dist/valibot-D_HTw1Gn-E5NKVIOV.js +0 -12
  101. package/dist/worktree-E4DGSBLJ.js +0 -12
  102. package/dist/zod-DSgpEGAE-DSH6V7MG.js +0 -12
  103. package/packages/opencode/migration/20260127222353_familiar_lady_ursula/migration.sql +0 -90
  104. package/packages/opencode/migration/20260127222353_familiar_lady_ursula/snapshot.json +0 -796
  105. package/packages/opencode/migration/20260211171708_add_project_commands/migration.sql +0 -1
  106. package/packages/opencode/migration/20260211171708_add_project_commands/snapshot.json +0 -806
  107. package/packages/opencode/migration/20260213144116_wakeful_the_professor/migration.sql +0 -11
  108. package/packages/opencode/migration/20260213144116_wakeful_the_professor/snapshot.json +0 -897
  109. package/packages/opencode/migration/20260225215848_workspace/migration.sql +0 -7
  110. package/packages/opencode/migration/20260225215848_workspace/snapshot.json +0 -959
  111. package/packages/opencode/migration/20260227213759_add_session_workspace_id/migration.sql +0 -2
  112. package/packages/opencode/migration/20260227213759_add_session_workspace_id/snapshot.json +0 -983
  113. package/packages/opencode/migration/20260228203230_blue_harpoon/migration.sql +0 -17
  114. package/packages/opencode/migration/20260228203230_blue_harpoon/snapshot.json +0 -1102
  115. package/packages/opencode/migration/20260303231226_add_workspace_fields/migration.sql +0 -5
  116. package/packages/opencode/migration/20260303231226_add_workspace_fields/snapshot.json +0 -1013
  117. package/packages/opencode/migration/20260309230000_move_org_to_state/migration.sql +0 -3
  118. package/packages/opencode/migration/20260309230000_move_org_to_state/snapshot.json +0 -1156
  119. package/packages/opencode/migration/20260312043431_session_message_cursor/migration.sql +0 -4
  120. package/packages/opencode/migration/20260312043431_session_message_cursor/snapshot.json +0 -1168
  121. package/packages/opencode/migration/20260323234822_events/migration.sql +0 -13
  122. package/packages/opencode/migration/20260323234822_events/snapshot.json +0 -1271
  123. package/packages/opencode/migration/20260409000000_add_session_metadata/migration.sql +0 -1
@@ -0,0 +1,684 @@
1
+ // Built by esbuild from opencode-server source
2
+ if (typeof globalThis.Bun === 'undefined') {
3
+ globalThis.Bun = {
4
+ version: '0.0.0-node-compat',
5
+ stdin: { async text() { const chunks = []; for await (const c of process.stdin) chunks.push(c); return Buffer.concat(chunks).toString(); } },
6
+ which(cmd) { try { return require('child_process').execFileSync('which', [cmd], { encoding: 'utf8' }).trim(); } catch { return null; } },
7
+ };
8
+ }
9
+ if (typeof globalThis.__name === 'undefined') { globalThis.__name = (t, n) => { Object.defineProperty(t, 'name', { value: n, configurable: true }); return t; }; }
10
+ if (typeof globalThis.__export === 'undefined') { globalThis.__export = (t, a) => { for (const k in a) Object.defineProperty(t, k, { get: a[k], enumerable: true }); }; }
11
+ import { createRequire as __alchemyCreateRequire } from 'node:module';
12
+ const require = __alchemyCreateRequire(import.meta.url);
13
+
14
+ import{$a as km,$b as Jl,Aa as xs,Ab as V,Ac as xd,Ba as vs,C as xl,Ca as _l,Cc as Fe,D as vl,Da as Bt,Db as ta,E as co,Ea as gr,Eb as jm,F as Dt,Fb as $m,Ga as Ft,Gb as Um,Gc as Is,H as hs,Ha as Al,Hb as Bm,Hc as na,Ib as Fm,Ja as ws,Jb as qm,K as le,Kb as Vm,Kc as ks,L as he,Lb as Wm,Lc as vd,M as lo,Ma as de,Mb as Gm,Mc as wd,N as wl,Nb as Hm,Nc as oa,O as El,P as Qe,Pb as Ll,Pc as bs,Qa as Zi,Qb as Nl,Ra as Qi,Rb as jl,S as Ut,Sa as ea,Sb as $l,Sc as yr,T as pr,Ta as Qt,Tb as Ul,U as Yt,Ua as hm,Ub as Bl,Va as Sm,Vb as Fl,Wa as xm,Wb as ql,X as Hi,Xa as vm,Xb as Vl,Y as Il,Ya as wm,Yb as Wl,Za as Em,Zb as Gl,_ as Re,_a as Im,_b as Hl,a as xe,aa as kl,ab as bm,ac as Kl,b as kt,ba as bl,bb as Dm,bc as Xl,c as io,ca as Dl,cb as Tm,cc as zl,d as us,da as Ji,db as _m,dc as Yl,e as $t,ea as ur,eb as Am,ec as Zl,f as it,fb as Om,fc as Ql,g as zt,gb as Rm,gc as ed,h as bt,ha as Ki,hb as Cm,hc as td,i as Te,ia as po,ib as Pm,ic as nd,j as fs,ja as Xi,jb as Mm,jc as od,k as ao,ka as Ss,kb as Lm,kc as rd,la as zi,lb as Nm,lc as sd,ma as fr,mb as Ol,mc as id,na as uo,nb as Es,nc as ad,oa as wn,oc as cd,p as ms,pa as z,pb as en,pc as ld,q as hl,qa as Ve,qb as Rl,qc as dd,ra as fo,rb as Cl,rc as pd,sa as ht,sb as Pl,sc as ud,t as dr,ta as se,tb as qt,tc as fd,ua as Yi,ub as mo,uc as md,va as Tl,vc as gd,w as Sl,wa as M,wc as yd,x as gs,xa as Zt,xb as tn,xc as hd,y as ys,ya as mr,yb as En,yc as Sd,zb as Ml}from"./chunk-BM2C7NHL.js";import{a as r,b as ke,c as ft,d as R,e as yl}from"./chunk-RHIWAYN5.js";var Sa=ft((h_,Zd)=>{var Yd=r(e=>{if(typeof e=="string"){if(/^0o?[0-7]+$/.test(e))return parseInt(e.replace(/^0o?/,""),8);if(/^[1-9][0-9]*$/.test(e))return parseInt(e,10);throw new Error(`invalid umask value: ${e}`)}else{if(typeof e!="number")throw new Error(`invalid umask value: ${e}`);if(e=Math.floor(e),e<0||e>511)throw new Error(`invalid umask value: ${e}`);return e}},"parse"),cy=r((e,t,n)=>{try{return e[t]=Yd(n),!0}catch{return!1}},"validate");Zd.exports={parse:Yd,validate:cy}});var bo=ft((x_,wa)=>{var sn=ke("nopt"),{validate:ly}=Sa(),xa=class{static{r(this,"Umask")}},va=class{static{r(this,"Semver")}},dy=ke("semver/functions/valid"),py=r((e,t,n)=>{let o=dy(n);if(!o)return!1;e[t]=o},"validateSemver"),uy=sn.typeDefs.path.validate,fy=r((e,t,n)=>typeof n!="string"?!1:uy(e,t,n),"validatePath");wa.exports={...sn.typeDefs,semver:{type:va,validate:py,description:"full valid SemVer string"},Umask:{type:xa,validate:ly,description:"octal number in range 0o000..0o777 (0..511)"},url:{...sn.typeDefs.url,description:'full url with "http://"'},path:{...sn.typeDefs.path,validate:fy,description:"valid filesystem path"},Number:{...sn.typeDefs.Number,description:"numeric value"},Boolean:{...sn.typeDefs.Boolean,description:"boolean value (true or false)"},Date:{...sn.typeDefs.Date,description:"valid Date string"}};sn.typeDefs=wa.exports});var tp=ft((w_,ep)=>{var{URL:Qd}=ke("node:url");ep.exports=e=>{let t=new Qd(e),n=`${t.protocol}//${t.host}${t.pathname}`,o=new Qd(".",n);return`//${o.host}${o.pathname}`}});var Ea=ft((E_,np)=>{var my=/(?<!\\)(\\*)\$\{([^${}?]+)(\?)?\}/g;np.exports=(e,t)=>e.replace(my,(n,o,s,i)=>{let a=i==="?"?"":`\${${s}}`,c=t[s]!==void 0?t[s]:a;return o.length%2?n.slice((o.length+1)/2):o.slice(o.length/2)+c})});var sp=ft((I_,rp)=>{var Do=bo(),gy=Ea(),{resolve:op}=ke("node:path"),{parse:yy}=Sa(),Ia=r((e,t,n,o=!1)=>{if(typeof e!="string"&&!Array.isArray(e))return e;let{platform:s,types:i,home:a,env:c}=n,l=new Set([].concat(i[t])),f=l.has(Do.path.type),g=l.has(Do.Boolean.type),d=f||l.has(Do.String.type),h=l.has(Do.Umask.type),b=l.has(Do.Number.type),_=!o&&l.has(Array),P=l.has(Do.Date.type);if(Array.isArray(e))return _?e.map(C=>Ia(C,t,n,!0)):e;if(e=e.trim(),_)return Ia(e.split(`
15
+
16
+ `),t,n);if(g&&!d&&e==="")return!0;if(!d&&!f&&!b)switch(e){case"true":return!0;case"false":return!1;case"null":return null;case"undefined":return}if(e=gy(e,c),P)return new Date(e);if(f&&((s==="win32"?/^~(\/|\\)/:/^~\//).test(e)&&a?e=op(a,e.slice(2)):e=op(e)),h)try{return yy(e)}catch{return e}return b&&!isNaN(e)&&(e=+e),e},"parseField");rp.exports=Ia});var lp=ft((b_,cp)=>{var hy=r((e,t)=>!/^[/@_]/.test(e)&&typeof ka(t)=="string"&&`npm_config_${e.replace(/-/g,"_").toLowerCase()}`,"envKey"),ka=r(e=>Array.isArray(e)?e.map(t=>ka(t)).join(`
17
+
18
+ `):e==null||e===!1?"":typeof e=="object"?null:String(e),"envVal"),ip=r((e,t)=>!Array.isArray(t)||!Array.isArray(e)?e===t:Sy(e,t),"sameConfigValue"),Sy=r((e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},"sameArrayValue"),ap=r((e,t,n)=>{let o=ka(n),s=hy(t,o);s&&o!==null&&(e[s]=o)},"setEnv"),xy=r(e=>{let{env:t,defaults:n,definitions:o,list:[s,i]}=e;t.INIT_CWD=process.cwd();let a=new Set(Object.keys(s)),c=new Set(Object.keys(i));for(let l in s){let{deprecated:f,envExport:g=!0}=o[l]||{};f||g===!1||(ip(n[l],s[l])?ip(i[l],s[l])||ap(t,l,s[l]):c.has(l)&&!a.has(l)||ap(t,l,s[l]))}t.HOME=e.home,t.npm_config_global_prefix=e.globalPrefix,t.npm_config_local_prefix=e.localPrefix,s.editor&&(t.EDITOR=s.editor),s["node-options"]&&(t.NODE_OPTIONS=s["node-options"]),t.npm_config_node_gyp=s["node-gyp"],t.npm_config_npm_version=s["npm-version"]||"unknown",t.npm_execpath=e.npmBin,t.NODE=t.npm_node_execpath=e.execPath},"setEnvs");cp.exports=xy});var pp=ft((T_,dp)=>{"use strict";var ba=class extends Error{static{r(this,"ErrInvalidAuth")}constructor(t){let n="Invalid auth configuration found: ";n+=t.map(o=>{if(o.action==="delete")return`\`${o.key}\` is not allowed in ${o.where} config`;if(o.action==="rename")return`\`${o.from}\` must be renamed to \`${o.to}\` in ${o.where} config`}).join(", "),n+="\nPlease run `npm config fix` to repair your configuration.`",super(n),this.code="ERR_INVALID_AUTH",this.problems=t}};dp.exports={ErrInvalidAuth:ba}});var mp=ft((A_,fp)=>{var vy=bo(),up=r(e=>{if(!e||typeof e!="function"&&typeof e!="object")return e;if(Array.isArray(e))return e.map(t=>up(t));for(let{type:t,description:n}of Object.values(vy))if(t===e)return n||t;return e},"typeDescription");fp.exports=e=>[].concat(up(e)).filter(t=>t!==void 0)});var xp=ft((R_,Oa)=>{var{walkUp:wy}=ke("walk-up-path"),gp=ke("ini"),Wt=ke("nopt"),{log:mt,time:Ey}=ke("proc-log"),{resolve:Tr,dirname:qs,join:Da}=ke("node:path"),{homedir:Iy}=ke("node:os"),{readFile:ky,writeFile:by,chmod:Dy,unlink:Ty,stat:yp,mkdir:_y}=ke("node:fs/promises"),Ay=["npm-version","global-prefix","local-prefix"],Ta=r((...e)=>yp(Tr(...e)).then(t=>t.isFile()).catch(()=>!1),"fileExists"),Oy=r((...e)=>yp(Tr(...e)).then(t=>t.isDirectory()).catch(()=>!1),"dirExists"),Vs=r((e,t)=>Object.prototype.hasOwnProperty.call(e,t),"hasOwnProperty"),To=bo(),An=tp(),Ry=Ea(),Cy=sp(),Py=lp(),hp=new Set(["global","user","project"]),br=new Set(["default","builtin",...hp,"env","cli"]),_a=class{static{r(this,"Config")}#n=!1;#o;#e=null;#r=[];static get typeDefs(){return To}constructor({definitions:t,shorthands:n,flatten:o,nerfDarts:s=[],npmPath:i,env:a=process.env,argv:c=process.argv,platform:l=process.platform,execPath:f=process.execPath,cwd:g=process.cwd(),excludeNpmCwd:d=!1,warn:h=!0}){this.nerfDarts=s,this.definitions=t;let{types:b,defaults:_,deprecated:P}=Sp(t);this.deprecated=P,this.#o=o,this.types=b,this.shorthands=n,this.defaults=_,this.npmPath=i,this.npmBin=Da(this.npmPath,"bin/npm-cli.js"),this.argv=c,this.env=a,this.execPath=f,this.platform=l,this.cwd=g,this.excludeNpmCwd=d,this.globalPrefix=null,this.localPrefix=null,this.localPackage=null,this.home=null;let C=[...br];this.data=new Map;let J=null;for(let te of C)this.data.set(te,J=new Aa(J));this.data.set=()=>{throw new Error("cannot change internal config data structure")},this.data.delete=()=>{throw new Error("cannot change internal config data structure")},this.sources=new Map([]);for(let{data:te}of this.data.values())this.list.unshift(te);this.#n=!1,this.warn=h}get list(){let t=[];for(let{data:n}of this.data.values())t.unshift(n);return t}get loaded(){return this.#n}get prefix(){return this.#t("global")?this.globalPrefix:this.localPrefix}find(t){if(!this.loaded)throw new Error("call config.load() before reading values");let n=[...this.data.entries()];for(let o=n.length-1;o>-1;o--){let[s,{data:i}]=n[o];if(Vs(i,t))return s}return null}get(t,n){if(!this.loaded)throw new Error("call config.load() before reading values");return this.#t(t,n)}#t(t,n=null){if(n!==null&&!br.has(n))throw new Error("invalid config location param: "+n);let{data:o}=this.data.get(n||"cli");return n===null||Vs(o,t)?o[t]:void 0}set(t,n,o="cli"){if(!this.loaded)throw new Error("call config.load() before setting values");if(!br.has(o))throw new Error("invalid config location param: "+o);this.#a(t);let{data:s,raw:i}=this.data.get(o);s[t]=n,["global","user","project"].includes(o)&&(i[t]=n),this.data.get(o)[_o]=null,this.#e=null}get flat(){if(this.#e)return this.#e;let t=Ey.start("config:load:flatten");this.#e={};for(let{data:n}of this.data.values())this.#o(n,this.#e);return this.#e.nodeBin=this.execPath,this.#e.npmBin=this.npmBin,t(),this.#e}delete(t,n="cli"){if(!this.loaded)throw new Error("call config.load() before deleting values");if(!br.has(n))throw new Error("invalid config location param: "+n);let{data:o,raw:s}=this.data.get(n);delete o[t],["global","user","project"].includes(n)&&delete s[t]}async load(){if(this.loaded)throw new Error("attempting to load npm config multiple times");this.loadDefaults(),await this.loadBuiltinConfig(),this.loadCLI(),this.loadEnv(),await this.loadProjectConfig(),await this.loadUserConfig(),await this.loadGlobalConfig(),this.#n=!0,this.globalPrefix=this.get("prefix"),this.setEnvs()}loadDefaults(){this.loadGlobalPrefix(),this.loadHome();let t={...this.defaults,prefix:this.globalPrefix};try{t["npm-version"]=ke(Da(this.npmPath,"package.json")).version}catch{}this.#s(t,"default","default values");let{data:n}=this.data.get("default");Object.defineProperty(n,"globalconfig",{get:r(()=>Tr(this.#t("prefix"),"etc/npmrc"),"get"),set(o){Object.defineProperty(n,"globalconfig",{value:o,configurable:!0,writable:!0,enumerable:!0})},configurable:!0,enumerable:!0})}loadHome(){this.home=this.env.HOME||Iy()}loadGlobalPrefix(){if(this.globalPrefix)throw new Error("cannot load default global prefix more than once");this.env.PREFIX?this.globalPrefix=this.env.PREFIX:this.platform==="win32"?this.globalPrefix=qs(this.execPath):(this.globalPrefix=qs(qs(this.execPath)),this.env.DESTDIR&&(this.globalPrefix=Da(this.env.DESTDIR,this.globalPrefix)))}loadEnv(){let t=Object.create(null);for(let[n,o]of Object.entries(this.env)){if(!/^npm_config_/i.test(n)||o==="")continue;let s=n.slice(11);s.startsWith("//")||(s=s.replace(/(?!^)_/g,"-").toLowerCase()),t[s]=o}this.#s(t,"env","environment")}loadCLI(){for(let n of Object.keys(this.shorthands))n.length>1&&this.argv.includes(`-${n}`)&&mt.warn(`-${n} is not a valid single-hyphen cli flag and will be removed in the future`);Wt.invalidHandler=(n,o,s)=>this.invalidHandler(n,o,s,"command line options","cli"),Wt.unknownHandler=(n,o)=>this.unknownHandler(n,o),Wt.abbrevHandler=this.abbrevHandler;let t=Wt(this.types,this.shorthands,this.argv);Wt.invalidHandler=null,Wt.unknownHandler=null,this.parsedArgv=t.argv,delete t.argv,this.#s(t,"cli","command line options")}get valid(){for(let[t,{valid:n}]of this.data.entries())if(n===!1||n===null&&!this.validate(t))return!1;return!0}validate(t){if(t){let n=this.data.get(t);return n[_o]=!0,Wt.invalidHandler=(o,s,i)=>this.invalidHandler(o,s,i,n.source,t),Wt.clean(n.data,this.types,To),Wt.invalidHandler=null,n[_o]}else{let n=!0,o=[];for(let s of this.data.keys()){if(s==="default"||s==="builtin"||s==="cli")continue;let i=this.validate(s);if(n=n&&i,["global","user","project"].includes(s)){for(let c of["_authtoken","-authtoken"])this.get(c,s)&&o.push({action:"delete",key:c,where:s});let a=An(this.get("registry"));for(let c of["_auth","_authToken","username","_password"])this.get(c,s)&&(c==="username"&&!this.get("_password",s)?o.push({action:"delete",key:c,where:s}):c==="_password"&&!this.get("username",s)?o.push({action:"delete",key:c,where:s}):o.push({action:"rename",from:c,to:`${a}:${c}`,where:s}))}}if(o.length){let{ErrInvalidAuth:s}=pp();throw new s(o)}return n}}repair(t){if(!t)try{this.validate()}catch(n){if(n.code!=="ERR_INVALID_AUTH")throw n;t=n.problems}finally{t||(t=[])}for(let n of t)if(n.action==="delete")this.delete(n.key,n.where);else if(n.action==="rename"){let o=this.data.get(n.where).raw?.[n.from],s=this.get(n.from,n.where);this.set(n.to,o||s,n.where),this.delete(n.from,n.where)}}isDefault(t){let[n,...o]=[...br],s=this.data.get(n).data;return Vs(s,t)&&o.every(i=>{let a=this.data.get(i).data;return!Vs(a,t)})}invalidHandler(t,n,o,s,i){let a=mp();mt.warn("invalid config",t+"="+JSON.stringify(n),`set in ${s}`),this.data.get(i)[_o]=!1,Array.isArray(o)&&(o.includes(To.url.type)?o=To.url.type:o.includes(To.path.type)&&(o=To.path.type));let c=a(o),l=c.filter(d=>d!==void 0&&d!==Array),f="Must be"+this.#c(l,c),g=l.length===1?l[0]:[...new Set(l.map(d=>typeof d=="string"?d:JSON.stringify(d)))].join(", ");mt.warn("invalid config",f,g)}abbrevHandler(t,n){mt.warn(`Expanding --${t} to --${n}. This will stop working in the next major version of npm.`)}unknownHandler(t,n){n&&this.queueWarning(`unknown:${n}`,`"${n}" is being parsed as a normal command line argument.`)}#c(t,n){let o;return t.length===1&&n.includes(Array)?o=" one or more":t.length>1&&n.includes(Array)?o=" one or more of:":t.length>1?o=" one of:":o="",o}#s(t,n,o,s=null){let i=this.data.get(n);if(i.source){let a=`double-loading "${n}" configs from ${o}, previously loaded from ${i.source}`;throw new Error(a)}if(this.sources.has(o)){let a=`double-loading config "${o}" as "${n}", previously loaded as "${this.sources.get(o)}"`;throw new Error(a)}if(i.source=o,this.sources.set(o,n),s)i.loadError=s,s.code!=="ENOENT"&&mt.verbose("config",`error loading ${n} config`,s);else{i.raw=t;e:for(let[a,c]of Object.entries(t)){let l=Ry(a,this.env),f=this.parseField(c,l);if(n!=="default"&&(this.#a(l),this.definitions[a]?.exclusive)){for(let g of this.definitions[a].exclusive)if(!this.isDefault(g)){if(n==="env"){let d=this.data.get("cli").data;if(Object.hasOwn(d,g))continue e}throw new TypeError(`--${a} cannot be provided when using --${g}`)}}(n!=="default"||a==="npm-version")&&this.checkUnknown(n,a),i.data[l]=f}}}checkUnknown(t,n){if(!this.definitions[n]){if(Ay.includes(n))return;let o=t!=="cli"?" See `npm help npmrc` for supported config options.":"";if(!n.includes(":")){this.queueWarning(n,`Unknown ${t} config "${t==="cli"?"--":""}${n}". This will stop working in the next major version of npm.${o}`);return}let s=n.split(":").pop();!this.definitions[s]&&!this.nerfDarts.includes(s)&&this.queueWarning(s,`Unknown ${t} config "${s}" (${n}). This will stop working in the next major version of npm.${o}`)}}#a(t){this.deprecated[t]&&mt.warn("config",t,this.deprecated[t])}parseField(t,n,o=!1){return Cy(t,n,this,o)}async#i(t,n){mt.silly("config",`load:file:${t}`),await ky(t,"utf8").then(o=>{let s=gp.parse(o);return n==="project"&&s.prefix&&mt.error("config",`prefix cannot be changed from project config: ${t}.`),this.#s(s,n,t)},o=>this.#s(null,n,t,o))}loadBuiltinConfig(){return this.#i(Tr(this.npmPath,"npmrc"),"builtin")}async loadProjectConfig(){if(await this.loadLocalPrefix(),this.localPackage==null&&(this.localPackage=await Ta(this.localPrefix,"package.json")),this.#t("global")===!0||this.#t("location")==="global"){this.data.get("project").source="(global mode enabled, ignored)",this.sources.set(this.data.get("project").source,"project");return}let t=Tr(this.localPrefix,".npmrc");if(t!==this.#t("userconfig"))return this.#i(t,"project");this.data.get("project").source='(same as "user" config, ignored)',this.sources.set(this.data.get("project").source,"project")}async loadLocalPrefix(){let t=this.#t("prefix","cli");if(t){this.localPrefix=t;return}let n=this.#t("workspaces","cli"),o=this.#t("global")||this.#t("location")==="global";for(let s of wy(this.cwd)){if(this.excludeNpmCwd&&s===this.npmPath)break;let i=await Ta(s,"package.json");if(!this.localPrefix&&(i||await Oy(s,"node_modules"))){if(this.localPrefix=s,this.localPackage=i,n===!1||o)return;continue}if(this.localPrefix&&i){let a=ke("@npmcli/package-json"),{content:c}=await a.normalize(s).catch(()=>({content:{}}));if(!c?.workspaces)continue;let f=await ke("@npmcli/map-workspaces")({cwd:s,pkg:c});for(let g of f.values())if(g===this.localPrefix){await Ta(this.localPrefix,".npmrc")&&mt.warn("config",`ignoring workspace config at ${this.localPrefix}/.npmrc`);let{data:d}=this.data.get("default");d.workspace=[this.localPrefix],this.localPrefix=s,this.localPackage=i,mt.info("config",`found workspace root at ${this.localPrefix}`);return}}}this.localPrefix||(this.localPrefix=this.cwd)}loadUserConfig(){return this.#i(this.#t("userconfig"),"user")}loadGlobalConfig(){return this.#i(this.#t("globalconfig"),"global")}async save(t){if(!this.loaded)throw new Error("call config.load() before saving");if(!hp.has(t))throw new Error("invalid config location param: "+t);let n=this.data.get(t);if(n[Dr]=null,t==="user"){let a=An(this.get("registry")),c=this.get(`${a}:email`,"user");c&&(this.delete(`${a}:email`,"user"),this.set("email",c,"user"))}let o=gp.stringify(n.raw).trim()+`
19
+ `;if(!o.trim()){await Ty(n.source).catch(()=>{});return}let s=qs(n.source);await _y(s,{recursive:!0}),await by(n.source,o,"utf8");let i=t==="user"?384:438;await Dy(n.source,i)}clearCredentialsByURI(t,n="user"){let o=An(t);if(An(this.get("registry"))===o){this.delete("-authtoken",n),this.delete("_authToken",n),this.delete("_authtoken",n),this.delete("_auth",n),this.delete("_password",n),this.delete("username",n);let i=this.get(`${o}:email`,n);i&&this.set("email",i,n)}this.delete(`${o}:_authToken`,n),this.delete(`${o}:_auth`,n),this.delete(`${o}:_password`,n),this.delete(`${o}:username`,n),this.delete(`${o}:email`,n),this.delete(`${o}:certfile`,n),this.delete(`${o}:keyfile`,n)}setCredentialsByURI(t,{token:n,username:o,password:s,certfile:i,keyfile:a}){let c=An(t);if(this.delete(`${c}:always-auth`,"user"),this.delete(`${c}:email`,"user"),i&&a&&(this.set(`${c}:certfile`,i,"user"),this.set(`${c}:keyfile`,a,"user")),n)this.set(`${c}:_authToken`,n,"user"),this.delete(`${c}:_password`,"user"),this.delete(`${c}:username`,"user");else if(o||s){if(!o)throw new Error("must include username");if(!s)throw new Error("must include password");this.delete(`${c}:_authToken`,"user"),this.set(`${c}:username`,o,"user");let l=Buffer.from(s,"utf8").toString("base64");this.set(`${c}:_password`,l,"user")}else if(!i||!a)throw new Error("No credentials to set.")}getCredentialsByURI(t){let n=An(t),o=An(this.get("registry")),s={},i=this.get(`${n}:email`)||this.get("email");i&&(n===o&&this.set("email",i,"user"),s.email=i);let a=this.get(`${n}:certfile`),c=this.get(`${n}:keyfile`);a&&c&&(s.certfile=a,s.keyfile=c);let l=this.get(`${n}:_authToken`);if(l)return s.token=l,s;let f=this.get(`${n}:username`),g=this.get(`${n}:_password`);if(f&&g){s.username=f,s.password=Buffer.from(g,"base64").toString("utf8");let h=`${s.username}:${s.password}`;return s.auth=Buffer.from(h,"utf8").toString("base64"),s}let d=this.get(`${n}:_auth`);if(d){let b=Buffer.from(d,"base64").toString("utf8").split(":");return s.username=b.shift(),s.password=b.join(":"),s.auth=d,s}return s}setEnvs(){Py(this)}removeWarning(t){this.#r=this.#r.filter(n=>n.type!==t)}getUnknownPositionals(){return this.#r.filter(t=>t.type.startsWith("unknown:")).map(t=>t.type.slice(8))}removeUnknownPositional(t){this.removeWarning(`unknown:${t}`)}queueWarning(t,...n){this.warn?mt.warn(...n):this.#r.push({type:t,args:n})}logWarnings(){for(let t of this.#r)mt.warn(...t.args);this.#r=[]}},Dr=Symbol("loadError"),_o=Symbol("valid"),Aa=class{static{r(this,"ConfigData")}#n;#o=null;#e=null;constructor(t){this.#n=Object.create(t&&t.data),this.#e={},this[_o]=!0}get data(){return this.#n}get valid(){return this[_o]}set source(t){if(this.#o)throw new Error("cannot set ConfigData source more than once");this.#o=t}get source(){return this.#o}set loadError(t){if(this[Dr]||Object.keys(this.#e).length)throw new Error("cannot set ConfigData loadError after load");this[Dr]=t}get loadError(){return this[Dr]}set raw(t){if(Object.keys(this.#e).length||this[Dr])throw new Error("cannot set ConfigData raw after load");this.#e=t}get raw(){return this.#e}},Sp=r(e=>{let t={},n={},o={};for(let[s,i]of Object.entries(e))n[s]=i.default,t[s]=i.type,i.deprecated&&(o[s]=i.deprecated.trim().replace(/\n +/,`
20
+ `));return{types:t,defaults:n,deprecated:o}},"getTypesFromDefinitions");Oa.exports=_a;Oa.exports.getTypesFromDefinitions=Sp});var kp=ft((P_,Ip)=>{var My=["type","description","default","key"],Ly=["default","defaultDescription","deprecated","description","exclusive","flatten","hint","key","short","type","typeDescription","usage","envExport","alias","required"],{semver:{type:Ny},Umask:{type:jy},url:{type:$y},path:{type:Uy}}=bo(),Ra=class{static{r(this,"Definition")}constructor(t,n){this.key=t,this.envExport=!0,Object.assign(this,n),this.validate(),this.defaultDescription||(this.defaultDescription=Ep(this.default)),this.typeDescription||(this.typeDescription=wp(this.type)),this.hint||(this.type===Number?this.hint="<number>":this.hint=`<${this.key}>`),this.usage||(this.usage=By(this))}validate(){for(let t of My)if(!Object.prototype.hasOwnProperty.call(this,t))throw new Error(`config lacks ${t}: ${this.key}`);if(!this.key)throw new Error(`config lacks key: ${this.key}`);for(let t of Object.keys(this))if(!Ly.includes(t))throw new Error(`config defines unknown field ${t}: ${this.key}`)}describe(){let t=_r(this.description),n=this.envExport?"":`
21
+ This value is not exported to the environment for child processes.
22
+ `,o=this.deprecated?`* DEPRECATED: ${_r(this.deprecated)}
23
+ `:"",s=this.exclusive?`
24
+ This config cannot be used with: \`${this.exclusive.join("`, `")}\``:"";return Fy(`#### \`${this.key}\`
25
+
26
+ * Default: ${_r(this.defaultDescription)}
27
+ * Type: ${_r(this.typeDescription)}
28
+ ${o}
29
+ ${t}
30
+ ${s}
31
+ ${n}`)}},By=r(e=>{let t="";if(!Array.isArray(e.type))return e.short&&(t=`-${e.short}|`),e.type===Boolean&&e.default!==!1?t=`${t}--no-${e.key}`:t=`${t}--${e.key}`,e.type!==Boolean&&(t=`${t} ${e.hint}`),t;t=`--${e.key}`,e.short&&(t=`-${e.short}|--${e.key}`);let n=e.type,o=n.includes(Array),s=n.includes(Boolean);if(n=n.filter(c=>c!==null&&c!==Array&&c!==Boolean),!n.length)return t;let i;n.some(c=>typeof c!="string")?i=e.hint:i=`<${n.filter(c=>c).join("|")}>`,s&&(t=`--no-${e.key}|${t}`);let a=`${t} ${i}`;return o?`${a} [${a} ...]`:a},"describeUsage"),wp=r(e=>{if(Array.isArray(e)){let t=e.filter(a=>a!==Array).map(a=>wp(a)),n=t.length>1?[t.pop()]:[],o=t.length>1?", or ":" or ",s=[t.join(", ")].concat(n).join(o),i=e.includes(Array)?" (can be set multiple times)":"";return`${s}${i}`}switch(e){case String:return"String";case Number:return"Number";case jy:return"Octal numeric string in range 0000..0777 (0..511)";case Boolean:return"Boolean";case Date:return"Date";case Uy:return"Path";case Ny:return"SemVer string";case $y:return"URL";default:return Ep(e)}},"describeType"),Ep=r(e=>typeof e=="string"?JSON.stringify(e):String(e),"describeValue"),_r=r(e=>{let t=e.match(/\n +/);return t?e.split(t[0]).join(`
32
+ `).trim():e.trim()},"unindent"),vp=r(e=>{let t=Math.min(Math.max(20,process.stdout.columns)||80,80)-5;return _r(e).split(/[ \n]+/).reduce((n,o)=>{let s=n.split(`
33
+ `).pop(),i=s.length&&s.length+o.length>t?`
34
+ `:" ";return n+i+o})},"wrap"),Fy=r(e=>{let t=!1;return e.split(`
35
+
36
+ `).map(n=>t||n.startsWith("```")?(t=!n.endsWith("```"),n):n.charAt(0)==="*"?"* "+n.slice(1).trim().split(`
37
+ * `).map(o=>vp(o).replace(/\n/g,`
38
+ `)).join(`
39
+ * `):vp(n)).join(`
40
+
41
+ `)},"wrapAll");Ip.exports=Ra});var _p=ft((L_,Tp)=>{var p=kp(),bp=ke("ci-info"),qy=ke("node:querystring"),{join:Ca}=ke("node:path"),Or=process.platform==="win32",{readFileSync:Vy}=ke("node:fs"),Wy=r(e=>{try{return Vy(e,"utf8")}catch(t){if(t.code!=="ENOENT")throw t;return null}},"maybeReadFile"),Gy=r(e=>{let t=e.include||[],n=e.omit||[],o=e.only;return/^prod(uction)?$/.test(o)||e.production?n.push("dev"):e.production===!1&&t.push("dev"),/^dev/.test(e.also)&&t.push("dev"),e.dev&&t.push("dev"),e.optional===!1?n.push("optional"):e.optional===!0&&t.push("optional"),e.omit=[...new Set(n)].filter(s=>!t.includes(s)),e.include=[...new Set(t)],e.omit.includes("dev")&&(process.env.NODE_ENV="production"),e.omit},"buildOmitList"),Hy=process.env.EDITOR||process.env.VISUAL||(Or?`${process.env.SYSTEMROOT}\\notepad.exe`:"vi"),Jy=Or?process.env.ComSpec||"cmd":process.env.SHELL||"sh",{networkInterfaces:Ky}=ke("node:os"),Xy=r(()=>{try{return Object.values(Ky()).map(e=>e.map(({address:t})=>t)).reduce((e,t)=>e.concat(t),[null])}catch{return[null]}},"getLocalAddresses"),zy=/UTF-?8$/i.test(process.env.LC_ALL||process.env.LC_CTYPE||process.env.LANG),Yy=Or&&process.env.LOCALAPPDATA||"~",Zy=Or?"npm-cache":".npm",Qy=`${Yy}/${Zy}`,{semver:{type:Dp},Umask:{type:eh},url:{type:Ar},path:{type:Ot}}=bo(),I=r((e,t,n)=>{let o=e.replace(/-([a-z])/g,(s,i)=>i.toUpperCase());n[o]=t[e]},"flatten"),wt={_auth:new p("_auth",{default:null,type:[null,String],description:`
42
+ A basic-auth string to use when authenticating against the npm registry.
43
+ This will ONLY be used to authenticate against the npm registry. For other
44
+ registries you will need to scope it like "//other-registry.tld/:_auth"
45
+
46
+ Warning: This should generally not be set via a command-line option. It
47
+ is safer to use a registry-provided authentication bearer token stored in
48
+ the ~/.npmrc file by running \`npm login\`.
49
+ `,flatten:I}),access:new p("access",{default:null,defaultDescription:`
50
+ 'public' for new packages, existing packages it will not change the current level
51
+ `,type:[null,"restricted","public"],description:"\n If you do not want your scoped package to be publicly viewable (and\n installable) set `--access=restricted`.\n\n Unscoped packages cannot be set to `restricted`.\n\n Note: This defaults to not changing the current access level for existing\n packages. Specifying a value of `restricted` or `public` during\n publish will change the access for an existing package the same way that\n `npm access set status` would.\n ",flatten:I}),all:new p("all",{default:!1,type:Boolean,short:"a",description:"\n When running `npm outdated` and `npm ls`, setting `--all` will show\n all outdated or installed packages, rather than only those directly\n depended upon by the current project.\n ",flatten:I}),"allow-same-version":new p("allow-same-version",{default:!1,type:Boolean,description:`
52
+ Prevents throwing an error when \`npm version\` is used to set the new
53
+ version to the same value as the current version.
54
+ `,flatten:I}),"allow-git":new p("allow-git",{default:"all",type:["all","none","root"],description:"\n Limits the ability for npm to fetch dependencies from git references.\n That is, dependencies that point to a git repo instead of a version or semver range.\n Please note that this could leave your tree incomplete and some packages may not function as intended or designed.\n\n `all` allows any git dependencies to be fetched and installed.\n `none` prevents any git dependencies from being fetched and installed.\n `root` only allows git dependencies defined in your project's package.json to be fetched installed. Also allows git dependencies to be fetched for other commands like `npm view`\n ",flatten:I}),also:new p("also",{default:null,type:[null,"dev","development"],description:"\n When set to `dev` or `development`, this is an alias for\n `--include=dev`.\n ",deprecated:"Please use --include=dev instead.",flatten(e,t,n){wt.omit.flatten("omit",t,n)}}),audit:new p("audit",{default:!0,type:Boolean,description:`
55
+ When "true" submit audit reports alongside the current npm command to the
56
+ default registry and all registries configured for scopes. See the
57
+ documentation for [\`npm audit\`](/commands/npm-audit) for details on what
58
+ is submitted.
59
+ `,flatten:I}),"audit-level":new p("audit-level",{default:null,type:[null,"info","low","moderate","high","critical","none"],description:`
60
+ The minimum level of vulnerability for \`npm audit\` to exit with
61
+ a non-zero exit code.
62
+ `,flatten:I}),"auth-type":new p("auth-type",{default:"web",type:["legacy","web"],description:"\n What authentication strategy to use with `login`.\n Note that if an `otp` config is given, this value will always be set to `legacy`.\n ",flatten:I}),before:new p("before",{default:null,hint:"<date>",type:[null,Date],exclusive:["min-release-age"],description:"\n If passed to `npm install`, will rebuild the npm tree such that only\n versions that were available **on or before** the given date are\n installed. If there are no versions available for the current set of\n dependencies, the command will error.\n\n If the requested version is a `dist-tag` and the given tag does not\n pass the `--before` filter, the most recent version less than or equal\n to that tag will be used. For example, `foo@latest` might install\n `foo@1.2` even though `latest` is `2.0`.\n ",flatten:I}),"bin-links":new p("bin-links",{default:!0,type:Boolean,description:`
63
+ Tells npm to create symlinks (or \`.cmd\` shims on Windows) for package
64
+ executables.
65
+
66
+ Set to false to have it not do this. This can be used to work around the
67
+ fact that some file systems don't support symlinks, even on ostensibly
68
+ Unix systems.
69
+ `,flatten:I}),browser:new p("browser",{default:null,defaultDescription:'\n macOS: `"open"`, Windows: `"start"`, Others: `"xdg-open"`\n ',type:[null,Boolean,String],description:`
70
+ The browser that is called by npm commands to open websites.
71
+
72
+ Set to \`false\` to suppress browser behavior and instead print urls to
73
+ terminal.
74
+
75
+ Set to \`true\` to use default system URL opener.
76
+ `,flatten:I}),"bypass-2fa":new p("bypass-2fa",{default:!1,type:Boolean,description:`
77
+ When creating a Granular Access Token with \`npm token create\`,
78
+ setting this to true will allow the token to bypass two-factor
79
+ authentication. This is useful for automation and CI/CD workflows.
80
+ `,flatten:I}),ca:new p("ca",{default:null,type:[null,String,Array],description:`
81
+ The Certificate Authority signing certificate that is trusted for SSL
82
+ connections to the registry. Values should be in PEM format (Windows
83
+ calls it "Base-64 encoded X.509 (.CER)") with newlines replaced by the
84
+ string "\\n". For example:
85
+
86
+ \`\`\`ini
87
+ ca="-----BEGIN CERTIFICATE-----\\nXXXX\\nXXXX\\n-----END CERTIFICATE-----"
88
+ \`\`\`
89
+
90
+ Set to \`null\` to only allow "known" registrars, or to a specific CA
91
+ cert to trust only that specific signing authority.
92
+
93
+ Multiple CAs can be trusted by specifying an array of certificates:
94
+
95
+ \`\`\`ini
96
+ ca[]="..."
97
+ ca[]="..."
98
+ \`\`\`
99
+
100
+ See also the \`strict-ssl\` config.
101
+ `,flatten:I}),cache:new p("cache",{default:Qy,defaultDescription:"\n Windows: `%LocalAppData%\\npm-cache`, Posix: `~/.npm`\n ",type:Ot,description:`
102
+ The location of npm's cache directory.
103
+ `,flatten(e,t,n){n.cache=Ca(t.cache,"_cacache"),n.npxCache=Ca(t.cache,"_npx"),n.tufCache=Ca(t.cache,"_tuf")}}),"cache-max":new p("cache-max",{default:1/0,type:Number,description:"\n `--cache-max=0` is an alias for `--prefer-online`\n ",deprecated:"\n This option has been deprecated in favor of `--prefer-online`\n ",flatten(e,t,n){t[e]<=0&&(n.preferOnline=!0)}}),"cache-min":new p("cache-min",{default:0,type:Number,description:"\n `--cache-min=9999 (or bigger)` is an alias for `--prefer-offline`.\n ",deprecated:"\n This option has been deprecated in favor of `--prefer-offline`.\n ",flatten(e,t,n){t[e]>=9999&&(n.preferOffline=!0)}}),cafile:new p("cafile",{default:null,type:Ot,description:`
104
+ A path to a file containing one or multiple Certificate Authority signing
105
+ certificates. Similar to the \`ca\` setting, but allows for multiple
106
+ CA's, as well as for the CA information to be stored in a file on disk.
107
+ `,flatten(e,t,n){if(!t.cafile)return;let o=Wy(t.cafile);if(!o)return;let s="-----END CERTIFICATE-----";n.ca=o.replace(/\r\n/g,`
108
+ `).split(s).filter(i=>i.trim()).map(i=>i.trimLeft()+s)}}),call:new p("call",{default:"",type:String,short:"c",description:'\n Optional companion option for `npm exec`, `npx` that allows for\n specifying a custom command to be run along with the installed packages.\n\n ```bash\n npm exec --package yo --package generator-node --call "yo node"\n ```\n ',flatten:I}),cert:new p("cert",{default:null,type:[null,String],description:`
109
+ A client certificate to pass when accessing the registry. Values should
110
+ be in PEM format (Windows calls it "Base-64 encoded X.509 (.CER)") with
111
+ newlines replaced by the string "\\n". For example:
112
+
113
+ \`\`\`ini
114
+ cert="-----BEGIN CERTIFICATE-----\\nXXXX\\nXXXX\\n-----END CERTIFICATE-----"
115
+ \`\`\`
116
+
117
+ It is _not_ the path to a certificate file, though you can set a registry-scoped
118
+ "certfile" path like "//other-registry.tld/:certfile=/path/to/cert.pem".
119
+ `,deprecated:"\n `key` and `cert` are no longer used for most registry operations.\n Use registry scoped `keyfile` and `certfile` instead.\n Example:\n //other-registry.tld/:keyfile=/path/to/key.pem\n //other-registry.tld/:certfile=/path/to/cert.crt\n ",flatten:I}),cidr:new p("cidr",{default:null,type:[null,String,Array],description:`
120
+ This is a list of CIDR address to be used when configuring limited access
121
+ tokens with the \`npm token create\` command.
122
+ `,flatten:I}),color:new p("color",{default:!process.env.NO_COLOR||process.env.NO_COLOR==="0",usage:"--color|--no-color|--color always",defaultDescription:`
123
+ true unless the NO_COLOR environ is set to something other than '0'
124
+ `,type:["always",Boolean],description:`
125
+ If false, never shows colors. If \`"always"\` then always shows colors.
126
+ If true, then only prints color codes for tty file descriptors.
127
+ `,flatten(e,t,n){n.color=t.color?t.color==="always"?!0:!!process.stdout.isTTY:!1,n.logColor=t.color?t.color==="always"?!0:!!process.stderr.isTTY:!1}}),"commit-hooks":new p("commit-hooks",{default:!0,type:Boolean,description:"\n Run git commit hooks when using the `npm version` command.\n ",flatten:I}),cpu:new p("cpu",{default:null,type:[null,String],description:"\n Override CPU architecture of native modules to install.\n Acceptable values are same as `cpu` field of package.json,\n which comes from `process.arch`.\n ",flatten:I}),depth:new p("depth",{default:null,defaultDescription:"\n `Infinity` if `--all` is set; otherwise, `0`\n ",type:[null,Number],description:"\n The depth to go when recursing packages for `npm ls`.\n\n If not set, `npm ls` will show only the immediate dependencies of the\n root project. If `--all` is set, then npm will show all dependencies\n by default.\n ",flatten:I}),description:new p("description",{default:!0,type:Boolean,usage:"--no-description",description:"\n Show the description in `npm search`\n ",flatten(e,t,n){n.search=n.search||{limit:20},n.search[e]=t[e]}}),dev:new p("dev",{default:!1,type:Boolean,description:"\n Alias for `--include=dev`.\n ",deprecated:"Please use --include=dev instead.",flatten(e,t,n){wt.omit.flatten("omit",t,n)}}),diff:new p("diff",{default:[],hint:"<package-spec>",type:[String,Array],description:"\n Define arguments to compare in `npm diff`.\n ",flatten:I}),"diff-ignore-all-space":new p("diff-ignore-all-space",{default:!1,type:Boolean,description:"\n Ignore whitespace when comparing lines in `npm diff`.\n ",flatten:I}),"diff-name-only":new p("diff-name-only",{default:!1,type:Boolean,description:"\n Prints only filenames when using `npm diff`.\n ",flatten:I}),"diff-no-prefix":new p("diff-no-prefix",{default:!1,type:Boolean,description:"\n Do not show any source or destination prefix in `npm diff` output.\n\n Note: this causes `npm diff` to ignore the `--diff-src-prefix` and\n `--diff-dst-prefix` configs.\n ",flatten:I}),"diff-dst-prefix":new p("diff-dst-prefix",{default:"b/",hint:"<path>",type:String,description:"\n Destination prefix to be used in `npm diff` output.\n ",flatten:I}),"diff-src-prefix":new p("diff-src-prefix",{default:"a/",hint:"<path>",type:String,description:"\n Source prefix to be used in `npm diff` output.\n ",flatten:I}),"diff-text":new p("diff-text",{default:!1,type:Boolean,description:"\n Treat all files as text in `npm diff`.\n ",flatten:I}),"diff-unified":new p("diff-unified",{default:3,type:Number,description:"\n The number of lines of context to print in `npm diff`.\n ",flatten:I}),"dry-run":new p("dry-run",{default:!1,type:Boolean,description:"\n Indicates that you don't want npm to make any changes and that it should\n only report what it would have done. This can be passed into any of the\n commands that modify your local installation, eg, `install`,\n `update`, `dedupe`, `uninstall`, as well as `pack` and\n `publish`.\n\n Note: This is NOT honored by other network related commands, eg\n `dist-tags`, `owner`, etc.\n ",flatten:I}),editor:new p("editor",{default:Hy,defaultDescription:`
128
+ The EDITOR or VISUAL environment variables, or '%SYSTEMROOT%\\notepad.exe' on Windows,
129
+ or 'vi' on Unix systems
130
+ `,type:String,description:"\n The command to run for `npm edit` and `npm config edit`.\n ",flatten:I}),"engine-strict":new p("engine-strict",{default:!1,type:Boolean,description:`
131
+ If set to true, then npm will stubbornly refuse to install (or even
132
+ consider installing) any package that claims to not be compatible with
133
+ the current Node.js version.
134
+
135
+ This can be overridden by setting the \`--force\` flag.
136
+ `,flatten:I}),"expect-result-count":new p("expect-result-count",{default:null,type:[null,Number],hint:"<count>",exclusive:["expect-results"],description:`
137
+ Tells to expect a specific number of results from the command.
138
+ `}),"expect-results":new p("expect-results",{default:null,type:[null,Boolean],exclusive:["expect-result-count"],description:`
139
+ Tells npm whether or not to expect results from the command.
140
+ Can be either true (expect some results) or false (expect no results).
141
+ `}),expires:new p("expires",{default:null,type:[null,Number],description:`
142
+ When creating a Granular Access Token with \`npm token create\`,
143
+ this sets the expiration in days. If not specified, the server
144
+ will determine the default expiration.
145
+ `,flatten:I}),"fetch-retries":new p("fetch-retries",{default:2,type:Number,description:`
146
+ The "retries" config for the \`retry\` module to use when fetching
147
+ packages from the registry.
148
+
149
+ npm will retry idempotent read requests to the registry in the case
150
+ of network failures or 5xx HTTP errors.
151
+ `,flatten(e,t,n){n.retry=n.retry||{},n.retry.retries=t[e]}}),"fetch-retry-factor":new p("fetch-retry-factor",{default:10,type:Number,description:`
152
+ The "factor" config for the \`retry\` module to use when fetching
153
+ packages.
154
+ `,flatten(e,t,n){n.retry=n.retry||{},n.retry.factor=t[e]}}),"fetch-retry-maxtimeout":new p("fetch-retry-maxtimeout",{default:6e4,defaultDescription:"60000 (1 minute)",type:Number,description:`
155
+ The "maxTimeout" config for the \`retry\` module to use when fetching
156
+ packages.
157
+ `,flatten(e,t,n){n.retry=n.retry||{},n.retry.maxTimeout=t[e]}}),"fetch-retry-mintimeout":new p("fetch-retry-mintimeout",{default:1e4,defaultDescription:"10000 (10 seconds)",type:Number,description:`
158
+ The "minTimeout" config for the \`retry\` module to use when fetching
159
+ packages.
160
+ `,flatten(e,t,n){n.retry=n.retry||{},n.retry.minTimeout=t[e]}}),"fetch-timeout":new p("fetch-timeout",{default:300*1e3,defaultDescription:`${300*1e3} (5 minutes)`,type:Number,description:`
161
+ The maximum amount of time to wait for HTTP requests to complete.
162
+ `,flatten(e,t,n){n.timeout=t[e]}}),force:new p("force",{default:!1,type:Boolean,short:"f",description:`
163
+ Removes various protections against unfortunate side effects, common
164
+ mistakes, unnecessary performance degradation, and malicious input.
165
+
166
+ * Allow clobbering non-npm files in global installs.
167
+ * Allow the \`npm version\` command to work on an unclean git repository.
168
+ * Allow deleting the cache folder with \`npm cache clean\`.
169
+ * Allow installing packages that have an \`engines\` declaration
170
+ requiring a different version of npm.
171
+ * Allow installing packages that have an \`engines\` declaration
172
+ requiring a different version of \`node\`, even if \`--engine-strict\`
173
+ is enabled.
174
+ * Allow \`npm audit fix\` to install modules outside your stated
175
+ dependency range (including SemVer-major changes).
176
+ * Allow unpublishing all versions of a published package.
177
+ * Allow conflicting peerDependencies to be installed in the root project.
178
+ * Implicitly set \`--yes\` during \`npm init\`.
179
+ * Allow clobbering existing values in \`npm pkg\`
180
+ * Allow unpublishing of entire packages (not just a single version).
181
+
182
+ If you don't have a clear idea of what you want to do, it is strongly
183
+ recommended that you do not use this option!
184
+ `,flatten:I}),"foreground-scripts":new p("foreground-scripts",{default:!1,defaultDescription:"`false` unless when using `npm pack` or `npm publish` where it\n defaults to `true`",type:Boolean,description:`
185
+ Run all build scripts (ie, \`preinstall\`, \`install\`, and
186
+ \`postinstall\`) scripts for installed packages in the foreground
187
+ process, sharing standard input, output, and error with the main npm
188
+ process.
189
+
190
+ Note that this will generally make installs run slower, and be much
191
+ noisier, but can be useful for debugging.
192
+ `,flatten:I}),"format-package-lock":new p("format-package-lock",{default:!0,type:Boolean,description:"\n Format `package-lock.json` or `npm-shrinkwrap.json` as a human\n readable file.\n ",flatten:I}),fund:new p("fund",{default:!0,type:Boolean,description:'\n When "true" displays the message at the end of each `npm install`\n acknowledging the number of dependencies looking for funding.\n See [`npm fund`](/commands/npm-fund) for details.\n ',flatten:I}),git:new p("git",{default:"git",type:String,description:`
193
+ The command to use for git commands. If git is installed on the
194
+ computer, but is not in the \`PATH\`, then set this to the full path to
195
+ the git binary.
196
+ `,flatten:I}),"git-tag-version":new p("git-tag-version",{default:!0,type:Boolean,description:`
197
+ Tag the commit when using the \`npm version\` command. Setting this to
198
+ false results in no commit being made at all.
199
+ `,flatten:I}),global:new p("global",{default:!1,type:Boolean,short:"g",description:`
200
+ Operates in "global" mode, so that packages are installed into the
201
+ \`prefix\` folder instead of the current working directory. See
202
+ [folders](/configuring-npm/folders) for more on the differences in
203
+ behavior.
204
+
205
+ * packages are installed into the \`{prefix}/lib/node_modules\` folder,
206
+ instead of the current working directory.
207
+ * bin files are linked to \`{prefix}/bin\`
208
+ * man pages are linked to \`{prefix}/share/man\`
209
+ `,flatten:r((e,t,n)=>{I(e,t,n),n.global&&(n.location="global")},"flatten")}),globalconfig:new p("globalconfig",{type:Ot,default:"",defaultDescription:`
210
+ The global --prefix setting plus 'etc/npmrc'. For example,
211
+ '/usr/local/etc/npmrc'
212
+ `,description:`
213
+ The config file to read for global config options.
214
+ `,flatten:I}),"global-style":new p("global-style",{default:!1,type:Boolean,description:"\n Only install direct dependencies in the top level `node_modules`,\n but hoist on deeper dependencies.\n Sets `--install-strategy=shallow`.\n ",deprecated:"\n This option has been deprecated in favor of `--install-strategy=shallow`\n ",flatten(e,t,n){t[e]&&(t["install-strategy"]="shallow",n.installStrategy="shallow")}}),heading:new p("heading",{default:"npm",type:String,description:`
215
+ The string that starts all the debugging log output.
216
+ `,flatten:I}),"https-proxy":new p("https-proxy",{default:null,type:[null,Ar],description:"\n A proxy to use for outgoing https requests. If the `HTTPS_PROXY` or\n `https_proxy` or `HTTP_PROXY` or `http_proxy` environment variables\n are set, proxy settings will be honored by the underlying\n `make-fetch-happen` library.\n ",flatten:I}),"if-present":new p("if-present",{default:!1,type:Boolean,envExport:!1,description:`
217
+ If true, npm will not exit with an error code when \`run\` is
218
+ invoked for a script that isn't defined in the \`scripts\` section of
219
+ \`package.json\`. This option can be used when it's desirable to
220
+ optionally run a script when it's present and fail if the script fails.
221
+ This is useful, for example, when running scripts that may only apply for
222
+ some builds in an otherwise generic CI setup.
223
+ `,flatten:I}),"ignore-scripts":new p("ignore-scripts",{default:!1,type:Boolean,description:"\n If true, npm does not run scripts specified in package.json files.\n\n Note that commands explicitly intended to run a particular script, such\n as `npm start`, `npm stop`, `npm restart`, `npm test`, and `npm\n run` will still run their intended script if `ignore-scripts` is\n set, but they will *not* run any pre- or post-scripts.\n ",flatten:I}),include:new p("include",{default:[],type:[Array,"prod","dev","optional","peer"],description:`
224
+ Option that allows for defining which types of dependencies to install.
225
+
226
+ This is the inverse of \`--omit=<type>\`.
227
+
228
+ Dependency types specified in \`--include\` will not be omitted,
229
+ regardless of the order in which omit/include are specified on the
230
+ command-line.
231
+ `,flatten(e,t,n){wt.omit.flatten("omit",t,n)}}),"include-staged":new p("include-staged",{default:!1,type:Boolean,description:`
232
+ Allow installing "staged" published packages, as defined by [npm RFC PR
233
+ #92](https://github.com/npm/rfcs/pull/92).
234
+
235
+ This is experimental, and not implemented by the npm public registry.
236
+ `,flatten:I}),"include-workspace-root":new p("include-workspace-root",{default:!1,type:Boolean,envExport:!1,description:`
237
+ Include the workspace root when workspaces are enabled for a command.
238
+
239
+ When false, specifying individual workspaces via the \`workspace\` config,
240
+ or all workspaces via the \`workspaces\` flag, will cause npm to operate only
241
+ on the specified workspaces, and not on the root project.
242
+ `,flatten:I}),"include-attestations":new p("include-attestations",{default:!1,type:Boolean,description:`
243
+ When used with \`npm audit signatures --json\`, includes the full
244
+ sigstore attestation bundles in the JSON output for each verified
245
+ package. The bundles contain DSSE envelopes, verification material,
246
+ and transparency log entries.
247
+ `,flatten:I}),"init-author-email":new p("init-author-email",{default:"",hint:"<email>",type:String,description:`
248
+ The value \`npm init\` should use by default for the package author's
249
+ email.
250
+ `}),"init-author-name":new p("init-author-name",{default:"",hint:"<name>",type:String,description:"\n The value `npm init` should use by default for the package author's name.\n "}),"init-author-url":new p("init-author-url",{default:"",type:["",Ar],hint:"<url>",description:"\n The value `npm init` should use by default for the package author's homepage.\n "}),"init-license":new p("init-license",{default:"ISC",hint:"<license>",type:String,description:"\n The value `npm init` should use by default for the package license.\n "}),"init-module":new p("init-module",{default:"~/.npm-init.js",type:Ot,hint:"<module>",description:`
251
+ A module that will be loaded by the \`npm init\` command. See the
252
+ documentation for the
253
+ [init-package-json](https://github.com/npm/init-package-json) module for
254
+ more information, or [npm init](/commands/npm-init).
255
+ `}),"init-type":new p("init-type",{default:"commonjs",type:String,hint:"<type>",description:"\n The value that `npm init` should use by default for the package.json type field.\n "}),"init-version":new p("init-version",{default:"1.0.0",type:Dp,hint:"<version>",description:`
256
+ The value that \`npm init\` should use by default for the package
257
+ version number, if not already set in package.json.
258
+ `}),"init-private":new p("init-private",{default:!1,type:Boolean,description:"\n The value `npm init` should use by default for the package's private flag.\n ",flatten:I}),"init.author.email":new p("init.author.email",{default:"",type:String,deprecated:"\n Use `--init-author-email` instead.",description:"\n Alias for `--init-author-email`\n "}),"init.author.name":new p("init.author.name",{default:"",type:String,deprecated:"\n Use `--init-author-name` instead.\n ",description:"\n Alias for `--init-author-name`\n "}),"init.author.url":new p("init.author.url",{default:"",type:["",Ar],deprecated:"\n Use `--init-author-url` instead.\n ",description:"\n Alias for `--init-author-url`\n "}),"init.license":new p("init.license",{default:"ISC",type:String,deprecated:"\n Use `--init-license` instead.\n ",description:"\n Alias for `--init-license`\n "}),"init.module":new p("init.module",{default:"~/.npm-init.js",type:Ot,deprecated:"\n Use `--init-module` instead.\n ",description:"\n Alias for `--init-module`\n "}),"init.version":new p("init.version",{default:"1.0.0",type:Dp,deprecated:"\n Use `--init-version` instead.\n ",description:"\n Alias for `--init-version`\n "}),"install-links":new p("install-links",{default:!1,type:Boolean,description:`
259
+ When set file: protocol dependencies will be packed and installed as
260
+ regular dependencies instead of creating a symlink. This option has
261
+ no effect on workspaces.
262
+ `,flatten:I}),"install-strategy":new p("install-strategy",{default:"hoisted",type:["hoisted","nested","shallow","linked"],description:`
263
+ Sets the strategy for installing packages in node_modules.
264
+ hoisted (default): Install non-duplicated in top-level, and duplicated as
265
+ necessary within directory structure.
266
+ nested: (formerly --legacy-bundling) install in place, no hoisting.
267
+ shallow (formerly --global-style) only install direct deps at top-level.
268
+ linked: (experimental) install in node_modules/.store, link in place,
269
+ unhoisted.
270
+ `,flatten:I}),json:new p("json",{default:!1,type:Boolean,description:`
271
+ Whether or not to output JSON data, rather than the normal output.
272
+
273
+ * In \`npm pkg set\` it enables parsing set values with JSON.parse()
274
+ before saving them to your \`package.json\`.
275
+
276
+ Not supported by all npm commands.
277
+ `,flatten:I}),key:new p("key",{default:null,type:[null,String],description:`
278
+ A client key to pass when accessing the registry. Values should be in
279
+ PEM format with newlines replaced by the string "\\n". For example:
280
+
281
+ \`\`\`ini
282
+ key="-----BEGIN PRIVATE KEY-----\\nXXXX\\nXXXX\\n-----END PRIVATE KEY-----"
283
+ \`\`\`
284
+
285
+ It is _not_ the path to a key file, though you can set a registry-scoped
286
+ "keyfile" path like "//other-registry.tld/:keyfile=/path/to/key.pem".
287
+ `,deprecated:"\n `key` and `cert` are no longer used for most registry operations.\n Use registry scoped `keyfile` and `certfile` instead.\n Example:\n //other-registry.tld/:keyfile=/path/to/key.pem\n //other-registry.tld/:certfile=/path/to/cert.crt\n ",flatten:I}),"legacy-bundling":new p("legacy-bundling",{default:!1,type:Boolean,description:`
288
+ Instead of hoisting package installs in \`node_modules\`, install packages
289
+ in the same manner that they are depended on. This may cause very deep
290
+ directory structures and duplicate package installs as there is no
291
+ de-duplicating.
292
+ Sets \`--install-strategy=nested\`.
293
+ `,deprecated:"\n This option has been deprecated in favor of `--install-strategy=nested`\n ",flatten(e,t,n){t[e]&&(t["install-strategy"]="nested",n.installStrategy="nested")}}),"legacy-peer-deps":new p("legacy-peer-deps",{default:!1,type:Boolean,description:"\n Causes npm to completely ignore `peerDependencies` when building a\n package tree, as in npm versions 3 through 6.\n\n If a package cannot be installed because of overly strict\n `peerDependencies` that collide, it provides a way to move forward\n resolving the situation.\n\n This differs from `--omit=peer`, in that `--omit=peer` will avoid\n unpacking `peerDependencies` on disk, but will still design a tree such\n that `peerDependencies` _could_ be unpacked in a correct place.\n\n Use of `legacy-peer-deps` is not recommended, as it will not enforce\n the `peerDependencies` contract that meta-dependencies may rely on.\n ",flatten:I}),libc:new p("libc",{default:null,type:[null,String],description:`
294
+ Override libc of native modules to install.
295
+ Acceptable values are same as \`libc\` field of package.json
296
+ `,flatten:I}),link:new p("link",{default:!1,type:Boolean,description:`
297
+ Used with \`npm ls\`, limiting output to only those packages that are
298
+ linked.
299
+ `}),"local-address":new p("local-address",{default:null,type:Xy(),typeDescription:"IP Address",description:`
300
+ The IP address of the local interface to use when making connections to
301
+ the npm registry. Must be IPv4 in versions of Node prior to 0.12.
302
+ `,flatten:I}),location:new p("location",{default:"user",short:"L",type:["global","user","project"],defaultDescription:'\n "user" unless `--global` is passed, which will also set this value to "global"\n ',description:`
303
+ When passed to \`npm config\` this refers to which config file to use.
304
+
305
+ When set to "global" mode, packages are installed into the \`prefix\` folder
306
+ instead of the current working directory. See
307
+ [folders](/configuring-npm/folders) for more on the differences in behavior.
308
+
309
+ * packages are installed into the \`{prefix}/lib/node_modules\` folder,
310
+ instead of the current working directory.
311
+ * bin files are linked to \`{prefix}/bin\`
312
+ * man pages are linked to \`{prefix}/share/man\`
313
+ `,flatten:r((e,t,n)=>{I(e,t,n),n.global&&(n.location="global"),t.location==="global"&&(n.global=!0)},"flatten")}),"lockfile-version":new p("lockfile-version",{default:null,type:[null,1,2,3,"1","2","3"],defaultDescription:`
314
+ Version 3 if no lockfile, auto-converting v1 lockfiles to v3; otherwise,
315
+ maintain current lockfile version.`,description:`
316
+ Set the lockfile format version to be used in package-lock.json and
317
+ npm-shrinkwrap-json files. Possible options are:
318
+
319
+ 1: The lockfile version used by npm versions 5 and 6. Lacks some data that
320
+ is used during the install, resulting in slower and possibly less
321
+ deterministic installs. Prevents lockfile churn when interoperating with
322
+ older npm versions.
323
+
324
+ 2: The default lockfile version used by npm version 7 and 8. Includes both
325
+ the version 1 lockfile data and version 3 lockfile data, for maximum
326
+ determinism and interoperability, at the expense of more bytes on disk.
327
+
328
+ 3: Only the new lockfile information introduced in npm version 7. Smaller
329
+ on disk than lockfile version 2, but not interoperable with older npm
330
+ versions. Ideal if all users are on npm version 7 and higher.
331
+ `,flatten:r((e,t,n)=>{n.lockfileVersion=t[e]&&parseInt(t[e],10)},"flatten")}),loglevel:new p("loglevel",{default:"notice",type:["silent","error","warn","notice","http","info","verbose","silly"],description:`
332
+ What level of logs to report. All logs are written to a debug log,
333
+ with the path to that file printed if the execution of a command fails.
334
+
335
+ Any logs of a higher level than the setting are shown. The default is
336
+ "notice".
337
+
338
+ See also the \`foreground-scripts\` config.
339
+ `,flatten(e,t,n){n.silent=t[e]==="silent"}}),"logs-dir":new p("logs-dir",{default:null,type:[null,Ot],defaultDescription:"\n A directory named `_logs` inside the cache\n ",description:`
340
+ The location of npm's log directory. See [\`npm
341
+ logging\`](/using-npm/logging) for more information.
342
+ `}),"logs-max":new p("logs-max",{default:10,type:Number,description:`
343
+ The maximum number of log files to store.
344
+
345
+ If set to 0, no log files will be written for the current run.
346
+ `}),long:new p("long",{default:!1,type:Boolean,short:"l",description:"\n Show extended information in `ls`, `search`, and `help-search`.\n "}),name:new p("name",{default:null,type:[null,String],hint:"<name>",description:`
347
+ When creating a Granular Access Token with \`npm token create\`,
348
+ this sets the name/description for the token.
349
+ `,flatten:I}),maxsockets:new p("maxsockets",{default:15,type:Number,description:`
350
+ The maximum number of connections to use per origin (protocol/host/port
351
+ combination).
352
+ `,flatten(e,t,n){n.maxSockets=t[e]}}),message:new p("message",{default:"%s",type:String,short:"m",description:`
353
+ Commit message which is used by \`npm version\` when creating version commit.
354
+
355
+ Any "%s" in the message will be replaced with the version number.
356
+ `,flatten:I}),"min-release-age":new p("min-release-age",{default:null,hint:"<days>",type:[null,Number],exclusive:["before"],envExport:!1,description:`
357
+ If set, npm will build the npm tree such that only versions that were
358
+ available more than the given number of days ago will be installed. If
359
+ there are no versions available for the current set of dependencies, the
360
+ command will error.
361
+
362
+ This flag is a complement to \`before\`, which accepts an exact date
363
+ instead of a relative number of days.
364
+ `,flatten:r((e,t,n)=>{t["min-release-age"]!==null&&(n.before=new Date(Date.now()-864e5*t["min-release-age"]),t.before=n.before,delete t["min-release-age"])},"flatten")}),"node-gyp":new p("node-gyp",{default:(()=>{try{return ke.resolve("node-gyp/bin/node-gyp.js")}catch{return""}})(),defaultDescription:`
365
+ The path to the node-gyp bin that ships with npm
366
+ `,type:Ot,description:`
367
+ This is the location of the "node-gyp" bin. By default it uses one that ships with npm itself.
368
+
369
+ You can use this config to specify your own "node-gyp" to run when it is required to build a package.
370
+ `,flatten:I}),"node-options":new p("node-options",{default:null,type:[null,String],description:`
371
+ Options to pass through to Node.js via the \`NODE_OPTIONS\` environment
372
+ variable. This does not impact how npm itself is executed but it does
373
+ impact how lifecycle scripts are called.
374
+ `}),noproxy:new p("noproxy",{default:"",defaultDescription:`
375
+ The value of the NO_PROXY environment variable
376
+ `,type:[String,Array],description:`
377
+ Domain extensions that should bypass any proxies.
378
+
379
+ Also accepts a comma-delimited string.
380
+ `,flatten(e,t,n){Array.isArray(t[e])?n.noProxy=t[e].join(","):n.noProxy=t[e]}}),offline:new p("offline",{default:!1,type:Boolean,description:`
381
+ Force offline mode: no network requests will be done during install. To allow
382
+ the CLI to fill in missing cache data, see \`--prefer-offline\`.
383
+ `,flatten:I}),omit:new p("omit",{default:process.env.NODE_ENV==="production"?["dev"]:[],defaultDescription:`
384
+ 'dev' if the \`NODE_ENV\` environment variable is set to 'production';
385
+ otherwise, empty.
386
+ `,type:[Array,"dev","optional","peer"],description:"\n Dependency types to omit from the installation tree on disk.\n\n Note that these dependencies _are_ still resolved and added to the\n `package-lock.json` or `npm-shrinkwrap.json` file. They are just\n not physically installed on disk.\n\n If a package type appears in both the `--include` and `--omit`\n lists, then it will be included.\n\n If the resulting omit list includes `'dev'`, then the `NODE_ENV`\n environment variable will be set to `'production'` for all lifecycle\n scripts.\n ",flatten(e,t,n){n.omit=Gy(t)}}),"omit-lockfile-registry-resolved":new p("omit-lockfile-registry-resolved",{default:!1,type:Boolean,description:`
387
+ This option causes npm to create lock files without a \`resolved\` key for
388
+ registry dependencies. Subsequent installs will need to resolve tarball
389
+ endpoints with the configured registry, likely resulting in a longer install
390
+ time.
391
+ `,flatten:I}),only:new p("only",{default:null,type:[null,"prod","production"],deprecated:"\n Use `--omit=dev` to omit dev dependencies from the install.\n ",description:"\n When set to `prod` or `production`, this is an alias for\n `--omit=dev`.\n ",flatten(e,t,n){wt.omit.flatten("omit",t,n)}}),orgs:new p("orgs",{default:null,type:[null,String,Array],description:`
392
+ When creating a Granular Access Token with \`npm token create\`,
393
+ this limits the token access to specific organizations.
394
+ `,flatten:I}),optional:new p("optional",{default:null,type:[null,Boolean],deprecated:`
395
+ Use \`--omit=optional\` to exclude optional dependencies, or
396
+ \`--include=optional\` to include them.
397
+
398
+ Default value does install optional deps unless otherwise omitted.
399
+ `,description:`
400
+ Alias for --include=optional or --omit=optional
401
+ `,flatten(e,t,n){wt.omit.flatten("omit",t,n)}}),os:new p("os",{default:null,type:[null,String],description:"\n Override OS of native modules to install.\n Acceptable values are same as `os` field of package.json,\n which comes from `process.platform`.\n ",flatten:I}),otp:new p("otp",{default:null,type:[null,String],description:`
402
+ This is a one-time password from a two-factor authenticator. It's needed
403
+ when publishing or changing package permissions with \`npm access\`.
404
+
405
+ If not set, and a registry response fails with a challenge for a one-time
406
+ password, npm will prompt on the command line for one.
407
+ `,flatten(e,t,n){I(e,t,n),t.otp&&(t["auth-type"]="legacy",I("auth-type",t,n))}}),package:new p("package",{default:[],hint:"<package-spec>",type:[String,Array],description:"\n The package or packages to install for [`npm exec`](/commands/npm-exec)\n ",flatten:I}),"package-lock":new p("package-lock",{default:!0,type:Boolean,description:"\n If set to false, then ignore `package-lock.json` files when installing.\n This will also prevent _writing_ `package-lock.json` if `save` is\n true.\n ",flatten:r((e,t,n)=>{I(e,t,n),n.packageLockOnly&&(n.packageLock=!0)},"flatten")}),"package-lock-only":new p("package-lock-only",{default:!1,type:Boolean,description:"\n If set to true, the current operation will only use the `package-lock.json`,\n ignoring `node_modules`.\n\n For `update` this means only the `package-lock.json` will be updated,\n instead of checking `node_modules` and downloading dependencies.\n\n For `list` this means the output will be based on the tree described by the\n `package-lock.json`, rather than the contents of `node_modules`.\n ",flatten:r((e,t,n)=>{I(e,t,n),n.packageLockOnly&&(n.packageLock=!0)},"flatten")}),"pack-destination":new p("pack-destination",{default:".",type:String,description:"\n Directory in which `npm pack` will save tarballs.\n ",flatten:I}),packages:new p("packages",{default:[],type:[null,String,Array],description:`
408
+ When creating a Granular Access Token with \`npm token create\`,
409
+ this limits the token access to specific packages.
410
+ `,flatten:I}),parseable:new p("parseable",{default:!1,type:Boolean,short:"p",description:`
411
+ Output parseable results from commands that write to standard output. For
412
+ \`npm search\`, this will be tab-separated table format.
413
+ `,flatten:I}),"prefer-dedupe":new p("prefer-dedupe",{default:!1,type:Boolean,description:`
414
+ Prefer to deduplicate packages if possible, rather than
415
+ choosing a newer version of a dependency.
416
+ `,flatten:I}),"prefer-offline":new p("prefer-offline",{default:!1,type:Boolean,description:`
417
+ If true, staleness checks for cached data will be bypassed, but missing
418
+ data will be requested from the server. To force full offline mode, use
419
+ \`--offline\`.
420
+ `,flatten:I}),"prefer-online":new p("prefer-online",{default:!1,type:Boolean,description:`
421
+ If true, staleness checks for cached data will be forced, making the CLI
422
+ look for updates immediately even for fresh package data.
423
+ `,flatten:I}),prefix:new p("prefix",{type:Ot,short:"C",default:"",defaultDescription:`
424
+ In global mode, the folder where the node executable is installed.
425
+ Otherwise, the nearest parent folder containing either a package.json
426
+ file or a node_modules folder.
427
+ `,description:`
428
+ The location to install global items. If set on the command line, then
429
+ it forces non-global commands to run in the specified folder.
430
+ `}),preid:new p("preid",{default:"",hint:"prerelease-id",type:String,description:'\n The "prerelease identifier" to use as a prefix for the "prerelease" part\n of a semver. Like the `rc` in `1.2.0-rc.8`.\n ',flatten:I}),production:new p("production",{default:null,type:[null,Boolean],deprecated:"Use `--omit=dev` instead.",description:"Alias for `--omit=dev`",flatten(e,t,n){wt.omit.flatten("omit",t,n)}}),progress:new p("progress",{default:!(bp.isCI||!process.stderr.isTTY||!process.stdout.isTTY||process.env.TERM==="dumb"),defaultDescription:"\n `true` when not in CI and both stderr and stdout are TTYs and not in a dumb terminal\n ",type:Boolean,description:"\n When set to `true`, npm will display a progress bar during time\n intensive operations, if `process.stderr` and `process.stdout` are a TTY.\n\n Set to `false` to suppress the progress bar.\n ",flatten(e,t,n){n.progress=!!t.progress&&!!process.stderr.isTTY&&!!process.stdout.isTTY&&process.env.TERM!=="dumb"}}),provenance:new p("provenance",{default:!1,type:Boolean,exclusive:["provenance-file"],description:`
431
+ When publishing from a supported cloud CI/CD system, the package will be
432
+ publicly linked to where it was built and published from.
433
+ `,flatten:I}),"provenance-file":new p("provenance-file",{default:null,type:Ot,hint:"<file>",exclusive:["provenance"],description:`
434
+ When publishing, the provenance bundle at the given path will be used.
435
+ `,flatten:I}),proxy:new p("proxy",{default:null,type:[null,!1,Ar],description:"\n A proxy to use for outgoing http requests. If the `HTTP_PROXY` or\n `http_proxy` environment variables are set, proxy settings will be\n honored by the underlying `request` library.\n ",flatten:I}),"read-only":new p("read-only",{default:!1,type:Boolean,description:`
436
+ This is used to mark a token as unable to publish when configuring
437
+ limited access tokens with the \`npm token create\` command.
438
+ `,flatten:I}),"rebuild-bundle":new p("rebuild-bundle",{default:!0,type:Boolean,description:`
439
+ Rebuild bundled dependencies after installation.
440
+ `,flatten:I}),registry:new p("registry",{default:"https://registry.npmjs.org/",type:Ar,description:`
441
+ The base URL of the npm registry.
442
+ `,flatten:I}),"replace-registry-host":new p("replace-registry-host",{default:"npmjs",hint:"<npmjs|never|always> | hostname",type:["npmjs","never","always",String],description:`
443
+ Defines behavior for replacing the registry host in a lockfile with the
444
+ configured registry.
445
+
446
+ The default behavior is to replace package dist URLs from the default
447
+ registry (https://registry.npmjs.org) to the configured registry. If set to
448
+ "never", then use the registry value. If set to "always", then replace the
449
+ registry host with the configured host every time.
450
+
451
+ You may also specify a bare hostname (e.g., "registry.npmjs.org").
452
+ `,flatten:I}),save:new p("save",{default:!0,defaultDescription:"`true` unless when using `npm update` where it\n defaults to `false`",usage:"-S|--save|--no-save|--save-prod|--save-dev|--save-optional|--save-peer|--save-bundle",type:Boolean,short:"S",description:"\n Save installed packages to a `package.json` file as dependencies.\n\n When used with the `npm rm` command, removes the dependency from\n `package.json`.\n\n Will also prevent writing to `package-lock.json` if set to `false`.\n ",flatten:I}),"save-bundle":new p("save-bundle",{default:!1,type:Boolean,short:"B",description:"\n If a package would be saved at install time by the use of `--save`,\n `--save-dev`, or `--save-optional`, then also put it in the\n `bundleDependencies` list.\n\n Ignored if `--save-peer` is set, since peerDependencies cannot be bundled.\n ",flatten(e,t,n){n.saveBundle=t["save-bundle"]&&!t["save-peer"]}}),"save-dev":new p("save-dev",{default:!1,type:Boolean,short:"D",exclusive:["save-optional","save-peer","save-prod"],description:"\n Save installed packages to a package.json file as `devDependencies`.\n ",flatten(e,t,n){if(!t[e]){n.saveType==="dev"&&delete n.saveType;return}n.saveType="dev"}}),"save-exact":new p("save-exact",{default:!1,type:Boolean,short:"E",description:`
453
+ Dependencies saved to package.json will be configured with an exact
454
+ version rather than using npm's default semver range operator.
455
+ `,flatten(e,t,n){wt["save-prefix"].flatten("save-prefix",t,n)}}),"save-optional":new p("save-optional",{default:!1,type:Boolean,short:"O",exclusive:["save-dev","save-peer","save-prod"],description:`
456
+ Save installed packages to a package.json file as
457
+ \`optionalDependencies\`.
458
+ `,flatten(e,t,n){if(!t[e]){n.saveType==="optional"?delete n.saveType:n.saveType==="peerOptional"&&(n.saveType="peer");return}n.saveType!=="peerOptional"&&(n.saveType==="peer"?n.saveType="peerOptional":n.saveType="optional")}}),"save-peer":new p("save-peer",{default:!1,type:Boolean,exclusive:["save-dev","save-optional","save-prod"],description:"\n Save installed packages to a package.json file as `peerDependencies`\n ",flatten(e,t,n){if(!t[e]){n.saveType==="peer"?delete n.saveType:n.saveType==="peerOptional"&&(n.saveType="optional");return}n.saveType!=="peerOptional"&&(n.saveType==="optional"?n.saveType="peerOptional":n.saveType="peer")}}),"save-prefix":new p("save-prefix",{default:"^",type:String,description:"\n Configure how versions of packages installed to a package.json file via\n `--save` or `--save-dev` get prefixed.\n\n For example if a package has version `1.2.3`, by default its version is\n set to `^1.2.3` which allows minor upgrades for that package, but after\n `npm config set save-prefix='~'` it would be set to `~1.2.3` which\n only allows patch upgrades.\n ",flatten(e,t,n){n.savePrefix=t["save-exact"]?"":t["save-prefix"],t["save-prefix"]=n.savePrefix}}),"save-prod":new p("save-prod",{default:!1,type:Boolean,short:"P",exclusive:["save-dev","save-optional","save-peer"],description:"\n Save installed packages into `dependencies` specifically. This is\n useful if a package already exists in `devDependencies` or\n `optionalDependencies`, but you want to move it to be a non-optional\n production dependency.\n\n This is the default behavior if `--save` is true, and neither\n `--save-dev` or `--save-optional` are true.\n ",flatten(e,t,n){if(!t[e]){n.saveType==="prod"&&delete n.saveType;return}n.saveType="prod"}}),"sbom-format":new p("sbom-format",{default:null,type:["cyclonedx","spdx"],description:`
459
+ SBOM format to use when generating SBOMs.
460
+ `,flatten:I}),"sbom-type":new p("sbom-type",{default:"library",type:["library","application","framework"],description:"\n The type of package described by the generated SBOM. For SPDX, this is the\n value for the `primaryPackagePurpose` field. For CycloneDX, this is the\n value for the `type` field.\n ",flatten:I}),scope:new p("scope",{default:"",defaultDescription:`
461
+ the scope of the current project, if any, or ""
462
+ `,type:String,hint:"<@scope>",description:`
463
+ Associate an operation with a scope for a scoped registry.
464
+
465
+ Useful when logging in to or out of a private registry:
466
+
467
+ \`\`\`
468
+ # log in, linking the scope to the custom registry
469
+ npm login --scope=@mycorp --registry=https://registry.mycorp.com
470
+
471
+ # log out, removing the link and the auth token
472
+ npm logout --scope=@mycorp
473
+ \`\`\`
474
+
475
+ This will cause \`@mycorp\` to be mapped to the registry for future
476
+ installation of packages specified according to the pattern
477
+ \`@mycorp/package\`.
478
+
479
+ This will also cause \`npm init\` to create a scoped package.
480
+
481
+ \`\`\`
482
+ # accept all defaults, and create a package named "@foo/whatever",
483
+ # instead of just named "whatever"
484
+ npm init --scope=@foo --yes
485
+ \`\`\`
486
+ `,flatten(e,t,n){let o=t[e],s=o&&!/^@/.test(o)?`@${o}`:o;n.scope=s,n.projectScope=s}}),scopes:new p("scopes",{default:null,type:[null,String,Array],description:`
487
+ When creating a Granular Access Token with \`npm token create\`,
488
+ this limits the token access to specific scopes. Provide
489
+ a scope name (with or without @ prefix).
490
+ `,flatten:I}),"packages-all":new p("packages-all",{default:!1,type:Boolean,description:`
491
+ When creating a Granular Access Token with \`npm token create\`,
492
+ grants the token access to all packages instead of limiting to
493
+ specific packages.
494
+ `,flatten:I}),"packages-and-scopes-permission":new p("packages-and-scopes-permission",{default:null,type:[null,"read-only","read-write","no-access"],description:`
495
+ When creating a Granular Access Token with \`npm token create\`,
496
+ sets the permission level for packages and scopes. Options are
497
+ "read-only", "read-write", or "no-access".
498
+ `,flatten:I}),"orgs-permission":new p("orgs-permission",{default:null,type:[null,"read-only","read-write","no-access"],description:`
499
+ When creating a Granular Access Token with \`npm token create\`,
500
+ sets the permission level for organizations. Options are
501
+ "read-only", "read-write", or "no-access".
502
+ `,flatten:I}),password:new p("password",{default:null,type:[null,String],description:`
503
+ Password for authentication. Can be provided via command line when
504
+ creating tokens, though it's generally safer to be prompted for it.
505
+ `,flatten:I}),"token-description":new p("token-description",{default:null,type:[null,String],description:"\n Description text for the token when using `npm token create`.\n ",flatten:I}),"script-shell":new p("script-shell",{default:null,defaultDescription:`
506
+ '/bin/sh' on POSIX systems, 'cmd.exe' on Windows
507
+ `,type:[null,String],description:"\n The shell to use for scripts run with the `npm exec`,\n `npm run` and `npm init <package-spec>` commands.\n ",flatten(e,t,n){n.scriptShell=t[e]||void 0}}),searchexclude:new p("searchexclude",{default:"",type:String,description:`
508
+ Space-separated options that limit the results from search.
509
+ `,flatten(e,t,n){n.search=n.search||{limit:20},n.search.exclude=t[e].toLowerCase()}}),searchlimit:new p("searchlimit",{default:20,type:Number,description:`
510
+ Number of items to limit search results to. Will not apply at all to
511
+ legacy searches.
512
+ `,flatten(e,t,n){n.search=n.search||{},n.search.limit=t[e]}}),searchopts:new p("searchopts",{default:"",type:String,description:`
513
+ Space-separated options that are always passed to search.
514
+ `,flatten(e,t,n){n.search=n.search||{limit:20},n.search.opts=qy.parse(t[e])}}),searchstaleness:new p("searchstaleness",{default:900,type:Number,description:`
515
+ The age of the cache, in seconds, before another registry request is made
516
+ if using legacy search endpoint.
517
+ `,flatten(e,t,n){n.search=n.search||{limit:20},n.search.staleness=t[e]}}),shell:new p("shell",{default:Jy,defaultDescription:`
518
+ SHELL environment variable, or "bash" on Posix, or "cmd.exe" on Windows
519
+ `,type:String,description:"\n The shell to run for the `npm explore` command.\n ",flatten:I}),shrinkwrap:new p("shrinkwrap",{default:!0,type:Boolean,deprecated:`
520
+ Use the --package-lock setting instead.
521
+ `,description:`
522
+ Alias for --package-lock
523
+ `,flatten(e,t,n){t["package-lock"]=t.shrinkwrap,wt["package-lock"].flatten("package-lock",t,n)}}),"sign-git-commit":new p("sign-git-commit",{default:!1,type:Boolean,description:`
524
+ If set to true, then the \`npm version\` command will commit the new
525
+ package version using \`-S\` to add a signature.
526
+
527
+ Note that git requires you to have set up GPG keys in your git configs
528
+ for this to work properly.
529
+ `,flatten:I}),"sign-git-tag":new p("sign-git-tag",{default:!1,type:Boolean,description:`
530
+ If set to true, then the \`npm version\` command will tag the version
531
+ using \`-s\` to add a signature.
532
+
533
+ Note that git requires you to have set up GPG keys in your git configs
534
+ for this to work properly.
535
+ `,flatten:I}),"strict-peer-deps":new p("strict-peer-deps",{default:!1,type:Boolean,description:`
536
+ If set to \`true\`, and \`--legacy-peer-deps\` is not set, then _any_
537
+ conflicting \`peerDependencies\` will be treated as an install failure,
538
+ even if npm could reasonably guess the appropriate resolution based on
539
+ non-peer dependency relationships.
540
+
541
+ By default, conflicting \`peerDependencies\` deep in the dependency graph
542
+ will be resolved using the nearest non-peer dependency specification,
543
+ even if doing so will result in some packages receiving a peer dependency
544
+ outside the range set in their package's \`peerDependencies\` object.
545
+
546
+ When such an override is performed, a warning is printed, explaining the
547
+ conflict and the packages involved. If \`--strict-peer-deps\` is set,
548
+ then this warning is treated as a failure.
549
+ `,flatten:I}),"strict-ssl":new p("strict-ssl",{default:!0,type:Boolean,description:`
550
+ Whether or not to do SSL key validation when making requests to the
551
+ registry via https.
552
+
553
+ See also the \`ca\` config.
554
+ `,flatten(e,t,n){n.strictSSL=t[e]}}),tag:new p("tag",{default:"latest",type:String,description:`
555
+ If you ask npm to install a package and don't tell it a specific version,
556
+ then it will install the specified tag.
557
+
558
+ It is the tag added to the package@version specified in the
559
+ \`npm dist-tag add\` command, if no explicit tag is given.
560
+
561
+ When used by the \`npm diff\` command, this is the tag used to fetch the
562
+ tarball that will be compared with the local files by default.
563
+
564
+ If used in the \`npm publish\` command, this is the tag that will be
565
+ added to the package submitted to the registry.
566
+ `,flatten(e,t,n){n.defaultTag=t[e]}}),"tag-version-prefix":new p("tag-version-prefix",{default:"v",type:String,description:`
567
+ If set, alters the prefix used when tagging a new version when performing
568
+ a version increment using \`npm version\`. To remove the prefix
569
+ altogether, set it to the empty string: \`""\`.
570
+
571
+ Because other tools may rely on the convention that npm version tags look
572
+ like \`v1.0.0\`, _only use this property if it is absolutely necessary_.
573
+ In particular, use care when overriding this setting for public packages.
574
+ `,flatten:I}),timing:new p("timing",{default:!1,type:Boolean,description:`
575
+ If true, writes timing information to a process specific json file in
576
+ the cache or \`logs-dir\`. The file name ends with \`-timing.json\`.
577
+
578
+ You can quickly view it with this [json](https://npm.im/json) command
579
+ line: \`cat ~/.npm/_logs/*-timing.json | npm exec -- json -g\`.
580
+
581
+ Timing information will also be reported in the terminal. To suppress this
582
+ while still writing the timing file, use \`--silent\`.
583
+ `}),umask:new p("umask",{default:0,type:eh,description:`
584
+ The "umask" value to use when setting the file creation mode on files and
585
+ folders.
586
+
587
+ Folders and executables are given a mode which is \`0o777\` masked
588
+ against this value. Other files are given a mode which is \`0o666\`
589
+ masked against this value.
590
+
591
+ Note that the underlying system will _also_ apply its own umask value to
592
+ files and folders that are created, and npm does not circumvent this, but
593
+ rather adds the \`--umask\` config to it.
594
+
595
+ Thus, the effective default umask value on most POSIX systems is 0o22,
596
+ meaning that folders and executables are created with a mode of 0o755 and
597
+ other files are created with a mode of 0o644.
598
+ `,flatten:I}),unicode:new p("unicode",{default:zy,defaultDescription:"\n false on windows, true on mac/unix systems with a unicode locale, as\n defined by the `LC_ALL`, `LC_CTYPE`, or `LANG` environment variables.\n ",type:Boolean,description:`
599
+ When set to true, npm uses unicode characters in the tree output. When
600
+ false, it uses ascii characters instead of unicode glyphs.
601
+ `,flatten:I}),"update-notifier":new p("update-notifier",{default:!0,type:Boolean,description:`
602
+ Set to false to suppress the update notification when using an older
603
+ version of npm than the latest.
604
+ `}),usage:new p("usage",{default:!1,type:Boolean,short:["?","H","h"],description:`
605
+ Show short usage output about the command specified.
606
+ `}),"user-agent":new p("user-agent",{default:"npm/{npm-version} node/{node-version} {platform} {arch} workspaces/{workspaces} {ci}",type:String,description:"\n Sets the User-Agent request header. The following fields are replaced\n with their actual counterparts:\n\n * `{npm-version}` - The npm version in use\n * `{node-version}` - The Node.js version in use\n * `{platform}` - The value of `process.platform`\n * `{arch}` - The value of `process.arch`\n * `{workspaces}` - Set to `true` if the `workspaces` or `workspace`\n options are set.\n * `{ci}` - The value of the `ci-name` config, if set, prefixed with\n `ci/`, or an empty string if `ci-name` is empty.\n ",flatten(e,t,n){let o=t[e],s=bp.name?.toLowerCase().split(" ").join("-")||null,i=!1;(t.workspaces||t.workspace&&t.workspace.length)&&(i=!0),n.userAgent=o.replace(/\{node-version\}/gi,process.version).replace(/\{npm-version\}/gi,t["npm-version"]).replace(/\{platform\}/gi,process.platform).replace(/\{arch\}/gi,process.arch).replace(/\{workspaces\}/gi,i).replace(/\{ci\}/gi,s?`ci/${s}`:"").trim(),process.env.npm_config_user_agent=n.userAgent}}),userconfig:new p("userconfig",{default:"~/.npmrc",type:Ot,description:"\n The location of user-level configuration settings.\n\n This may be overridden by the `npm_config_userconfig` environment\n variable or the `--userconfig` command line option, but may _not_\n be overridden by settings in the `globalconfig` file.\n "}),version:new p("version",{default:!1,type:Boolean,short:"v",description:`
607
+ If true, output the npm version and exit successfully.
608
+
609
+ Only relevant when specified explicitly on the command line.
610
+ `}),versions:new p("versions",{default:!1,type:Boolean,description:`
611
+ If true, output the npm version as well as node's \`process.versions\`
612
+ map and the version in the current working directory's \`package.json\`
613
+ file if one exists, and exit successfully.
614
+
615
+ Only relevant when specified explicitly on the command line.
616
+ `}),viewer:new p("viewer",{default:Or?"browser":"man",defaultDescription:`
617
+ "man" on Posix, "browser" on Windows
618
+ `,type:String,description:`
619
+ The program to use to view help content.
620
+
621
+ Set to \`"browser"\` to view html help content in the default web browser.
622
+ `}),which:new p("which",{default:null,hint:"<fundingSourceNumber>",type:[null,Number],description:`
623
+ If there are multiple funding sources, which 1-indexed source URL to open.
624
+ `}),workspace:new p("workspace",{default:[],type:[String,Array],hint:"<workspace-name>",short:"w",envExport:!1,description:`
625
+ Enable running a command in the context of the configured workspaces of the
626
+ current project while filtering by running only the workspaces defined by
627
+ this configuration option.
628
+
629
+ Valid values for the \`workspace\` config are either:
630
+
631
+ * Workspace names
632
+ * Path to a workspace directory
633
+ * Path to a parent workspace directory (will result in selecting all
634
+ workspaces within that folder)
635
+
636
+ When set for the \`npm init\` command, this may be set to the folder of
637
+ a workspace which does not yet exist, to create the folder and set it
638
+ up as a brand new workspace within the project.
639
+ `,flatten:r((e,t,n)=>{wt["user-agent"].flatten("user-agent",t,n)},"flatten")}),workspaces:new p("workspaces",{default:null,type:[null,Boolean],envExport:!1,description:`
640
+ Set to true to run the command in the context of **all** configured
641
+ workspaces.
642
+
643
+ Explicitly setting this to false will cause commands like \`install\` to
644
+ ignore workspaces altogether.
645
+ When not set explicitly:
646
+
647
+ - Commands that operate on the \`node_modules\` tree (install, update,
648
+ etc.) will link workspaces into the \`node_modules\` folder.
649
+ - Commands that do other things (test, exec, publish, etc.) will operate
650
+ on the root project, _unless_ one or more workspaces are specified in
651
+ the \`workspace\` config.
652
+ `,flatten:r((e,t,n)=>{wt["user-agent"].flatten("user-agent",t,n),n.workspacesEnabled=t[e]!==!1},"flatten")}),"workspaces-update":new p("workspaces-update",{default:!0,type:Boolean,description:`
653
+ If set to true, the npm cli will run an update after operations that may
654
+ possibly change the workspaces installed to the \`node_modules\` folder.
655
+ `,flatten:I}),yes:new p("yes",{default:null,type:[null,Boolean],short:"y",description:`
656
+ Automatically answer "yes" to any prompts that npm might print on
657
+ the command line.
658
+ `})};Tp.exports=wt});var Rp=ft((j_,Op)=>{var Pa=_p(),th=r((e,t={})=>{for(let[n,o]of Object.entries(e)){let s=Pa[n];s&&s.flatten?s.flatten(n,e,t):(/@.*:registry$/i.test(n)||/^\/\//.test(n))&&(t[n]=o)}return t},"flatten"),Ap=Object.entries(Pa).reduce((e,[t,{short:n=[],default:o}])=>{for(let s of[].concat(n))e.shorthands[s]=[`--${t}`];return e.defaults[t]=o,e},{shorthands:{},defaults:{}}),nh={"enjoy-by":["--before"],d:["--loglevel","info"],dd:["--loglevel","verbose"],ddd:["--loglevel","silly"],quiet:["--loglevel","warn"],q:["--loglevel","warn"],s:["--loglevel","silent"],silent:["--loglevel","silent"],verbose:["--loglevel","verbose"],desc:["--description"],help:["--usage"],local:["--no-global"],n:["--no-yes"],no:["--no-yes"],porcelain:["--parseable"],readonly:["--read-only"],reg:["--registry"],iwr:["--include-workspace-root"],ws:["--workspaces"],...Ap.shorthands},oh=["_auth","_authToken","_password","certfile","email","keyfile","username"],rh=["http_proxy","https_proxy","proxy","no_proxy"];Op.exports={defaults:Ap.defaults,definitions:Pa,flatten:th,nerfDarts:oh,proxyEnv:rh,shorthands:nh}});var Tt={};R(Tt,{ID:()=>zm,WorkspaceV2:()=>Tt});var Sr={};R(Sr,{Event:()=>Xm,ID:()=>Km,Workspace:()=>Sr});var hr={};R(hr,{ConnectionStatus:()=>Ed,Definitions:()=>Jm,Failed:()=>kd,Ready:()=>Id,Status:()=>bd,WorkspaceEvent:()=>hr});import{Schema as Ds}from"effect";var Ed=Ds.Struct({workspaceID:ms,status:Ds.Literals(["connected","connecting","disconnected","error"])}).annotate({identifier:"WorkspaceEvent.ConnectionStatus"}),Id=dr.define({type:"workspace.ready",schema:{name:Ds.String}}),kd=dr.define({type:"workspace.failed",schema:{message:Ds.String}}),bd=dr.define({type:"workspace.status",schema:Ed.fields}),Jm=dr.inventory(Id,kd,bd);var Km=ms,Xm=hr;var zm=Sr.ID;var tt={};R(tt,{APIError:()=>ng,AbortedError:()=>Qm,AgentPart:()=>zl,AgentPartInput:()=>ud,Assistant:()=>md,AuthError:()=>Zm,CompactionPart:()=>Yl,ContentFilterError:()=>rg,ContextOverflowError:()=>og,Event:()=>Sd,FilePart:()=>Xl,FilePartInput:()=>pd,FilePartSource:()=>Kl,FileSource:()=>Gl,Format:()=>Ul,Info:()=>gd,MessageID:()=>Ll,OutputFormatJsonSchema:()=>$l,OutputFormatText:()=>jl,OutputLengthError:()=>Ym,Part:()=>ld,PartID:()=>Nl,PatchPart:()=>Fl,ProviderQuotaError:()=>eg,Range:()=>Wl,ReasoningPart:()=>Vl,ResourceSource:()=>Jl,RetryPart:()=>Ql,SessionInfo:()=>hd,SessionV1:()=>tt,SnapshotPart:()=>Bl,StepFinishPart:()=>td,StepStartPart:()=>ed,StructuredOutputError:()=>tg,SubtaskPart:()=>Zl,SubtaskPartInput:()=>fd,SymbolSource:()=>Hl,TextPart:()=>ql,TextPartInput:()=>dd,ToolPart:()=>ad,ToolState:()=>id,ToolStateCompleted:()=>rd,ToolStateError:()=>sd,ToolStatePending:()=>nd,ToolStateRunning:()=>od,User:()=>cd,WithParts:()=>yd});import{Schema as ie}from"effect";import{Schema as In}from"effect";var We=class e extends Error{static{r(this,"NamedError")}static hasName(t,n){return typeof t=="object"&&t!==null&&"name"in t&&t.name===n}static create(t,n){return e.createSchemaClass(t,In.isSchema(n)?n:In.Struct(n))}static createSchemaClass(t,n){let o=In.Struct({name:In.Literal(t),data:n}).annotate({identifier:t}),s=class extends e{constructor(a,c){super(t,c);this.data=a;this.name=t}data;static{r(this,"result")}static Schema=o;static EffectSchema=o;static tag=t;name=t;static isInstance(a){return e.hasName(a,t)}schema(){return o}toObject(){return{name:t,data:this.data}}};return Object.defineProperty(s,"name",{value:t}),s}static Unknown=e.create("UnknownError",{message:In.String,ref:In.optional(In.String)})};var Ym=We.create("MessageOutputLengthError",{}),Zm=We.create("ProviderAuthError",{providerID:ie.String,message:ie.String}),Qm=We.create("MessageAbortedError",{message:ie.String}),eg=We.create("ProviderQuotaError",{providerID:ie.String,message:ie.String,planType:ie.optional(ie.String),resetsAt:ie.optional(ie.Finite),statusCode:ie.optional(it),responseBody:ie.optional(ie.String)}),tg=We.create("StructuredOutputError",{message:ie.String,retries:it}),ng=We.create("APIError",{message:ie.String,statusCode:ie.optional(it),isRetryable:ie.Boolean,responseHeaders:ie.optional(ie.Record(ie.String,ie.String)),responseBody:ie.optional(ie.String),metadata:ie.optional(ie.Record(ie.String,ie.String))}),og=We.create("ContextOverflowError",{message:ie.String,responseBody:ie.optional(ie.String)}),rg=We.create("ContentFilterError",{message:ie.String});var ca={};R(ca,{Action:()=>jm,Approval:()=>Vm,AskInput:()=>Wm,CorrectedError:()=>sa,DeniedError:()=>ia,Event:()=>Hm,ID:()=>ta,NotFoundError:()=>aa,PermissionV1:()=>ca,RejectedError:()=>ra,Reply:()=>Fm,ReplyBody:()=>qm,ReplyInput:()=>Gm,Request:()=>Bm,Rule:()=>$m,Ruleset:()=>Um});import{Schema as go}from"effect";var ra=class extends go.TaggedErrorClass()("PermissionRejectedError",{}){static{r(this,"RejectedError")}get message(){return"The user rejected permission to use this specific tool call."}},sa=class extends go.TaggedErrorClass()("PermissionCorrectedError",{feedback:go.String}){static{r(this,"CorrectedError")}get message(){return`The user rejected permission to use this specific tool call with the following feedback: ${this.feedback}`}},ia=class extends go.TaggedErrorClass()("PermissionDeniedError",{ruleset:go.Any}){static{r(this,"DeniedError")}get message(){return`The user has specified a rule which prevents you from using this specific tool call. Here are some of the relevant rules ${JSON.stringify(this.ruleset)}`}},aa=class extends go.TaggedErrorClass()("Permission.NotFoundError",{requestID:ta}){static{r(this,"NotFoundError")}};import{sqliteTable as kn,text as Z,integer as Xe,index as xt,primaryKey as pg,real as ug,uniqueIndex as la}from"drizzle-orm/sqlite-core";var vr={};R(vr,{AgentV2:()=>vr,Color:()=>cg,ID:()=>xr,Info:()=>Od,Service:()=>ho,defaultID:()=>Ad,locationLayer:()=>lg,node:()=>dg});import{Array as _d,Context as ig,Effect as yo,Layer as ag}from"effect";var Vt={};R(Vt,{Agent:()=>Vt,Color:()=>Td,ID:()=>Dd,Info:()=>sg});import{Schema as St}from"effect";var Dd=St.String.pipe(St.brand("AgentV2.ID")),Td=St.Union([St.String.check(St.isPattern(/^#[0-9a-fA-F]{6}$/)),St.Literals(["primary","secondary","accent","success","warning","error","info"])]).annotate({identifier:"Agent.Color"}),sg=St.Struct({id:Dd,model:gs.Ref.pipe(Te),request:Sl.Request,system:St.String.pipe(Te),description:St.String.pipe(Te),mode:St.Literals(["subagent","primary","all"]),hidden:St.Boolean,color:Td.pipe(Te),steps:$t.pipe(Te),permissions:xl.Ruleset}).annotate({identifier:"AgentV2.Info"}).pipe(fs(e=>({empty:r(t=>e.make({id:t,request:{headers:{},body:{}},mode:"all",hidden:!1,permissions:[]}),"empty")})));var xr=Vt.ID,Ad=xr.make("build"),cg=Vt.Color,Od=Vt.Info,ho=class extends ig.Service()("@opencode/v2/Agent"){static{r(this,"Service")}},Rd=ag.effect(ho,yo.gen(function*(){let e=vl.create({initial:r(()=>({agents:new Map}),"initial"),draft:r(o=>({list:r(()=>_d.fromIterable(o.agents.values()),"list"),get:r(s=>o.agents.get(s),"get"),default:r(s=>{o.default=s},"default"),update:r((s,i)=>{let a=o.agents.get(s)??Od.empty(s);o.agents.has(s)||o.agents.set(s,a),i(a),a.id=s},"update"),remove:r(s=>{o.agents.delete(s)},"remove")}),"draft")}),t=r(o=>o&&o.mode!=="subagent"&&!o.hidden?o:void 0,"selectable"),n=r(()=>{let o=e.get(),s=o.default?t(o.agents.get(o.default)):void 0;if(s)return s;let i=t(o.agents.get(xr.make("build")));if(i)return i;for(let a of o.agents.values()){let c=t(a);if(c)return c}},"selectedDefault");return ho.of({transform:e.transform,reload:e.reload,get:yo.fn("AgentV2.get")(function*(o){return e.get().agents.get(o)}),default:yo.fn("AgentV2.default")(function*(){return n()}),resolve:yo.fn("AgentV2.resolve")(function*(o){return o!==void 0?e.get().agents.get(xr.make(o)):n()}),select:yo.fn("AgentV2.select")(function*(o){if(o!==void 0){let i=xr.make(o);return{id:i,info:e.get().agents.get(i)}}let s=n();return{id:s?.id??Ad,info:s}}),all:yo.fn("AgentV2.all")(function*(){return _d.fromIterable(e.get().agents.values())})})})),lg=Rd,dg=io({service:ho,layer:Rd,deps:[]});var $=kn("session",{id:Z().$type().primaryKey(),project_id:Z().$type().notNull().references(()=>mo.id,{onDelete:"cascade"}),workspace_id:Z().$type(),parent_id:Z().$type(),slug:Z().notNull(),directory:Cl().notNull(),path:Pl(),title:Z().notNull(),version:Z().notNull(),share_url:Z(),summary_additions:Xe(),summary_deletions:Xe(),summary_files:Xe(),summary_diffs:Z({mode:"json"}).$type(),metadata:Z({mode:"json"}).$type(),cost:ug().notNull().default(0),tokens_input:Xe().notNull().default(0),tokens_output:Xe().notNull().default(0),tokens_reasoning:Xe().notNull().default(0),tokens_cache_read:Xe().notNull().default(0),tokens_cache_write:Xe().notNull().default(0),revert:Z({mode:"json"}).$type(),permission:Z({mode:"json"}).$type(),agent:Z(),model:Z({mode:"json"}).$type(),...qt,time_compacting:Xe(),time_archived:Xe()},e=>[xt("session_project_idx").on(e.project_id),xt("session_workspace_idx").on(e.workspace_id),xt("session_parent_idx").on(e.parent_id)]),bn=kn("message",{id:Z().$type().primaryKey(),session_id:Z().$type().notNull().references(()=>$.id,{onDelete:"cascade"}),...qt,data:Z({mode:"json"}).notNull().$type()},e=>[xt("message_session_time_created_id_idx").on(e.session_id,e.time_created,e.id)]),nt=kn("part",{id:Z().$type().primaryKey(),message_id:Z().$type().notNull().references(()=>bn.id,{onDelete:"cascade"}),session_id:Z().$type().notNull(),...qt,data:Z({mode:"json"}).notNull().$type()},e=>[xt("part_message_id_id_idx").on(e.message_id,e.id),xt("part_session_idx").on(e.session_id)]),TD=kn("todo",{session_id:Z().$type().notNull().references(()=>$.id,{onDelete:"cascade"}),content:Z().notNull(),status:Z().notNull(),priority:Z().notNull(),position:Xe().notNull(),...qt},e=>[pg({columns:[e.session_id,e.position]}),xt("todo_session_idx").on(e.session_id)]),T=kn("session_message",{id:Z().$type().primaryKey(),session_id:Z().$type().notNull().references(()=>$.id,{onDelete:"cascade"}),type:Z().$type().notNull(),seq:Xe().notNull(),...qt,data:Z({mode:"json"}).notNull().$type()},e=>[la("session_message_session_seq_idx").on(e.session_id,e.seq),xt("session_message_session_type_seq_idx").on(e.session_id,e.type,e.seq),xt("session_message_session_time_created_id_idx").on(e.session_id,e.time_created,e.id),xt("session_message_time_created_idx").on(e.time_created)]),oe=kn("session_input",{id:Z().$type().primaryKey(),session_id:Z().$type().notNull().references(()=>$.id,{onDelete:"cascade"}),prompt:Z({mode:"json"}).notNull().$type(),delivery:Z().$type().notNull(),admitted_seq:Xe().notNull(),promoted_seq:Xe(),time_created:Xe().notNull().$default(()=>Date.now())},e=>[xt("session_input_session_pending_delivery_seq_idx").on(e.session_id,e.promoted_seq,e.delivery,e.admitted_seq),la("session_input_session_admitted_seq_idx").on(e.session_id,e.admitted_seq),la("session_input_session_promoted_seq_idx").on(e.session_id,e.promoted_seq)]),Ts=kn("session_context_epoch",{session_id:Z().$type().primaryKey().references(()=>$.id,{onDelete:"cascade"}),baseline:Z().notNull(),snapshot:Z({mode:"json"}).notNull().$type(),baseline_seq:Xe().notNull()});var vo={};R(vo,{SessionAlreadyProjected:()=>Ns,SessionProjector:()=>vo,node:()=>Lg});import{and as vt,desc as Bd,eq as ne,gt as ma,or as _g,sql as _n}from"drizzle-orm";import{DateTime as on,Effect as N,Layer as Ag,Schema as qd}from"effect";import{sqliteTable as fg,text as Dn,integer as mg}from"drizzle-orm/sqlite-core";var da=fg("workspace",{id:Dn().$type().primaryKey(),type:Dn().notNull(),name:Dn().notNull().default(""),branch:Dn(),directory:Dn(),extra:Dn({mode:"json"}),project_id:Dn().$type().notNull().references(()=>mo.id,{onDelete:"cascade"}),time_used:mg().notNull().$default(()=>Date.now())});var j={};R(j,{AgentSwitched:()=>xm,Assistant:()=>Mm,AssistantContent:()=>Pm,AssistantReasoning:()=>Cm,AssistantText:()=>Rm,AssistantTool:()=>Om,Compaction:()=>Lm,ID:()=>hm,Message:()=>Nm,ModelSwitched:()=>vm,SessionMessage:()=>j,Shell:()=>km,Synthetic:()=>Em,System:()=>Im,ToolState:()=>Am,ToolStateCompleted:()=>Tm,ToolStateError:()=>_m,ToolStatePending:()=>bm,ToolStateRunning:()=>Dm,UnknownError:()=>Sm,User:()=>wm});var wr={};R(wr,{SessionMessageUpdater:()=>wr,memory:()=>gg,update:()=>yg});import{castDraft as So,produce as pa}from"immer";import{Effect as je}from"effect";function gg(e){let t=r(s=>e.messages.findLastIndex(i=>i.id===s),"assistantIndex"),n=r(()=>e.messages.findLastIndex(s=>s.type==="assistant"),"latestAssistantIndex"),o=r(s=>e.messages.findLastIndex(i=>i.type==="shell"&&i.callID===s),"activeShellIndex");return{getCurrentAssistant(){return je.sync(()=>{let s=n();if(s<0)return;let i=e.messages[s];return i?.type==="assistant"&&!i.time.completed?i:void 0})},getAssistant(s){return je.sync(()=>{let i=t(s);if(i<0)return;let a=e.messages[i];return a?.type==="assistant"?a:void 0})},getCurrentShell(s){return je.sync(()=>{let i=o(s);if(i<0)return;let a=e.messages[i];return a?.type==="shell"?a:void 0})},updateAssistant(s){return je.sync(()=>{let i=t(s.id);i<0||e.messages[i]?.type!=="assistant"||(e.messages[i]=s)})},updateShell(s){return je.sync(()=>{let i=o(s.callID);i<0||e.messages[i]?.type!=="shell"||(e.messages[i]=s)})},appendMessage(s){return je.sync(()=>{e.messages.push(s)})}}}r(gg,"memory");function yg(e,t){let n=r((a,c)=>a?.content.findLast(l=>l.type==="tool"&&(c===void 0||l.id===c)),"latestTool"),o=r((a,c)=>a?.content.findLast(l=>l.type==="text"&&l.id===c),"latestText"),s=r((a,c)=>a?.content.findLast(l=>l.type==="reasoning"&&l.id===c),"latestReasoning"),i=r((a,c)=>je.gen(function*(){let l=yield*e.getAssistant(a);l&&(yield*e.updateAssistant(pa(l,c)))}),"updateOwnedAssistant");return je.gen(function*(){yield*V.All.match(t,{"session.next.agent.switched":r(a=>e.appendMessage(j.AgentSwitched.make({id:a.data.messageID,type:"agent-switched",metadata:a.metadata,agent:a.data.agent,time:{created:a.data.timestamp}})),"session.next.agent.switched"),"session.next.model.switched":r(a=>e.appendMessage(j.ModelSwitched.make({id:a.data.messageID,type:"model-switched",metadata:a.metadata,model:a.data.model,time:{created:a.data.timestamp}})),"session.next.model.switched"),"session.next.moved":r(()=>je.void,"session.next.moved"),"session.next.prompted":r(a=>e.appendMessage(j.User.make({id:a.data.messageID,type:"user",metadata:a.metadata,text:a.data.prompt.text,files:a.data.prompt.files,agents:a.data.prompt.agents,time:{created:a.data.timestamp}})),"session.next.prompted"),"session.next.prompt.admitted":r(()=>je.void,"session.next.prompt.admitted"),"session.next.context.updated":r(a=>e.appendMessage(j.System.make({id:a.data.messageID,type:"system",text:a.data.text,time:{created:a.data.timestamp}})),"session.next.context.updated"),"session.next.synthetic":r(a=>e.appendMessage(j.Synthetic.make({sessionID:a.data.sessionID,text:a.data.text,id:a.data.messageID,type:"synthetic",time:{created:a.data.timestamp}})),"session.next.synthetic"),"session.next.shell.started":r(a=>e.appendMessage(j.Shell.make({id:a.data.messageID,type:"shell",metadata:a.metadata,callID:a.data.callID,command:a.data.command,output:"",time:{created:a.data.timestamp}})),"session.next.shell.started"),"session.next.shell.ended":r(a=>je.gen(function*(){let c=yield*e.getCurrentShell(a.data.callID);c&&(yield*e.updateShell(pa(c,l=>{l.output=a.data.output,l.time.completed=a.data.timestamp})))}),"session.next.shell.ended"),"session.next.step.started":r(a=>je.gen(function*(){let c=yield*e.getCurrentAssistant();c&&(yield*e.updateAssistant(pa(c,l=>{l.time.completed=a.data.timestamp}))),yield*e.appendMessage(j.Assistant.make({id:a.data.assistantMessageID,type:"assistant",agent:a.data.agent,model:a.data.model,time:{created:a.data.timestamp},content:[],snapshot:a.data.snapshot?{start:a.data.snapshot}:void 0}))}),"session.next.step.started"),"session.next.step.ended":r(a=>i(a.data.assistantMessageID,c=>{c.time.completed=a.data.timestamp,c.finish=a.data.finish,c.cost=a.data.cost,c.tokens=a.data.tokens,(a.data.snapshot||a.data.files)&&(c.snapshot={...c.snapshot,end:a.data.snapshot,files:a.data.files?Array.from(a.data.files):void 0})}),"session.next.step.ended"),"session.next.step.failed":r(a=>i(a.data.assistantMessageID,c=>{c.time.completed=a.data.timestamp,c.finish="error",c.error=a.data.error}),"session.next.step.failed"),"session.next.text.started":r(a=>i(a.data.assistantMessageID,c=>{c.content.push(So(j.AssistantText.make({type:"text",id:a.data.textID,text:""})))}),"session.next.text.started"),"session.next.text.delta":r(a=>i(a.data.assistantMessageID,c=>{let l=o(c,a.data.textID);l&&(l.text+=a.data.delta)}),"session.next.text.delta"),"session.next.text.ended":r(a=>i(a.data.assistantMessageID,c=>{let l=o(c,a.data.textID);l&&(l.text=a.data.text)}),"session.next.text.ended"),"session.next.tool.input.started":r(a=>i(a.data.assistantMessageID,c=>{c.content.push(So(j.AssistantTool.make({type:"tool",id:a.data.callID,name:a.data.name,time:{created:a.data.timestamp},state:j.ToolStatePending.make({status:"pending",input:""})})))}),"session.next.tool.input.started"),"session.next.tool.input.delta":r(()=>je.void,"session.next.tool.input.delta"),"session.next.tool.input.ended":r(a=>i(a.data.assistantMessageID,c=>{let l=n(c,a.data.callID);l&&l.state.status==="pending"&&(l.state.input=a.data.text)}),"session.next.tool.input.ended"),"session.next.tool.called":r(a=>i(a.data.assistantMessageID,c=>{let l=n(c,a.data.callID);l&&(l.provider=a.data.provider,l.time.ran=a.data.timestamp,l.state=So(j.ToolStateRunning.make({status:"running",input:a.data.input,structured:{},content:[]})))}),"session.next.tool.called"),"session.next.tool.progress":r(a=>i(a.data.assistantMessageID,c=>{let l=n(c,a.data.callID);l&&l.state.status==="running"&&(l.state.structured=a.data.structured,l.state.content=[...a.data.content])}),"session.next.tool.progress"),"session.next.tool.success":r(a=>i(a.data.assistantMessageID,c=>{let l=n(c,a.data.callID);l&&l.state.status==="running"&&(l.provider={executed:a.data.provider.executed||l.provider?.executed===!0,metadata:l.provider?.metadata,resultMetadata:a.data.provider.metadata},l.time.completed=a.data.timestamp,l.state=So(j.ToolStateCompleted.make({status:"completed",input:l.state.input,structured:a.data.structured,content:[...a.data.content],outputPaths:a.data.outputPaths?[...a.data.outputPaths]:[],result:a.data.result})))}),"session.next.tool.success"),"session.next.tool.failed":r(a=>i(a.data.assistantMessageID,c=>{let l=n(c,a.data.callID);l&&(l.state.status==="pending"||l.state.status==="running")&&(l.provider={executed:a.data.provider.executed||l.provider?.executed===!0,metadata:l.provider?.metadata,resultMetadata:a.data.provider.metadata},l.time.completed=a.data.timestamp,l.state=So(j.ToolStateError.make({status:"error",error:a.data.error,input:typeof l.state.input=="string"?{}:l.state.input,structured:l.state.status==="running"?l.state.structured:{},content:l.state.status==="running"?l.state.content:[],result:a.data.result})))}),"session.next.tool.failed"),"session.next.reasoning.started":r(a=>i(a.data.assistantMessageID,c=>{c.content.push(So(j.AssistantReasoning.make({type:"reasoning",id:a.data.reasoningID,text:"",providerMetadata:a.data.providerMetadata,time:{created:a.data.timestamp}})))}),"session.next.reasoning.started"),"session.next.reasoning.delta":r(a=>i(a.data.assistantMessageID,c=>{let l=s(c,a.data.reasoningID);l&&(l.text+=a.data.delta)}),"session.next.reasoning.delta"),"session.next.reasoning.ended":r(a=>i(a.data.assistantMessageID,c=>{let l=s(c,a.data.reasoningID);l&&(l.text=a.data.text,l.time={created:l.time?.created??a.data.timestamp,completed:a.data.timestamp},a.data.providerMetadata!==void 0&&(l.providerMetadata=a.data.providerMetadata))}),"session.next.reasoning.ended"),"session.next.retried":r(()=>je.void,"session.next.retried"),"session.next.compaction.started":r(()=>je.void,"session.next.compaction.started"),"session.next.compaction.delta":r(()=>je.void,"session.next.compaction.delta"),"session.next.compaction.ended":r(a=>e.appendMessage(j.Compaction.make({id:a.data.messageID,type:"compaction",metadata:a.metadata,reason:a.data.reason,summary:a.data.text,recent:a.data.recent,time:{created:a.data.timestamp}})),"session.next.compaction.ended"),"session.next.revert.staged":r(()=>je.void,"session.next.revert.staged"),"session.next.revert.cleared":r(()=>je.void,"session.next.revert.cleared"),"session.next.revert.committed":r(()=>je.void,"session.next.revert.committed")})})}r(yg,"update");var At={};R(At,{Admitted:()=>Er,Delivery:()=>_s,LifecycleConflict:()=>nn,SessionInput:()=>At,admit:()=>wg,equivalent:()=>$d,find:()=>Ir,hasPending:()=>kg,projectAdmitted:()=>Eg,projectPrompted:()=>Ig,promoteNextQueued:()=>Tg,promoteSteers:()=>Dg});import{and as Cs,asc as Ld,eq as _t,isNull as Ps,lte as vg}from"drizzle-orm";import{DateTime as Tn,Effect as ee,Schema as fa}from"effect";var ua={};R(ua,{Admitted:()=>Er,Delivery:()=>_s,SessionInput:()=>ua});import{Schema as hg}from"effect";var _s=Ml.Delivery,Er=hg.Struct({admittedSeq:it,id:Ol.ID,sessionID:ys,prompt:Qt,delivery:_s,timeCreated:ao,promotedSeq:it.pipe(Te)}).annotate({identifier:"SessionInput.Admitted"});var fe={};R(fe,{ID:()=>Cd,Info:()=>Pd,SessionSchema:()=>fe});var xo={};R(xo,{Event:()=>Sg,ID:()=>As,Info:()=>xg,ListAnchor:()=>Os,Session:()=>xo});import{Schema as ot}from"effect";var As=ys,Sg=V,xg=ot.Struct({id:As,parentID:As.pipe(Te),projectID:Rl.ID,agent:Vt.ID.pipe(Te),model:gs.Ref.pipe(Te),cost:ot.Finite,tokens:ot.Struct({input:ot.Finite,output:ot.Finite,reasoning:ot.Finite,cache:ot.Struct({read:ot.Finite,write:ot.Finite})}),time:ot.Struct({created:ao,updated:ao,archived:ao.pipe(Te)}),title:ot.String,location:hl.Ref,subpath:zt.pipe(Te),revert:Es.State.pipe(Te)}).annotate({identifier:"SessionV2.Info"}),Os=ot.Struct({id:As,time:ot.Finite,direction:ot.Literals(["previous","next"])}).annotate({identifier:"Session.ListAnchor"});var Cd=xo.ID,Pd=xo.Info;var Nd=fa.decodeUnknownSync(Qt),Rs=fa.encodeSync(Qt),jd=r(e=>Er.make({admittedSeq:e.admitted_seq,id:j.ID.make(e.id),sessionID:fe.ID.make(e.session_id),prompt:Nd(e.prompt),delivery:e.delivery,timeCreated:Tn.makeUnsafe(e.time_created),...e.promoted_seq===null?{}:{promotedSeq:e.promoted_seq}}),"fromRow"),Ir=ee.fn("SessionInput.find")(function*(e,t){let n=yield*e.select().from(oe).where(_t(oe.id,t)).get().pipe(ee.orDie);return n===void 0?void 0:jd(n)}),nn=class extends fa.TaggedErrorClass()("SessionInput.LifecycleConflict",{id:j.ID}){static{r(this,"LifecycleConflict")}},wg=ee.fn("SessionInput.admit")(function*(e,t,n){let o=yield*Ir(e,n.id);if(o!==void 0)return o;let s=yield*Tn.now;return yield*t.publish(V.PromptAdmitted,{messageID:n.id,sessionID:n.sessionID,timestamp:s,prompt:n.prompt,delivery:n.delivery}).pipe(ee.flatMap(i=>i.durable===void 0?ee.die("Prompt admission event is missing aggregate sequence"):ee.succeed(Er.make({admittedSeq:i.durable.seq,id:n.id,sessionID:n.sessionID,prompt:n.prompt,delivery:n.delivery,timeCreated:s}))),ee.catchDefect(i=>Ir(e,n.id).pipe(ee.flatMap(a=>a?ee.succeed(a):ee.die(i)))))}),Eg=ee.fn("SessionInput.projectAdmitted")(function*(e,t){if((yield*e.select({id:T.id}).from(T).where(_t(T.id,t.id)).get().pipe(ee.orDie))!==void 0)return yield*ee.die(new nn({id:t.id}));if(!(yield*e.insert(oe).values({id:t.id,session_id:t.sessionID,admitted_seq:t.admittedSeq,prompt:Rs(t.prompt),delivery:t.delivery,time_created:Tn.toEpochMillis(t.timeCreated)}).onConflictDoNothing().returning({id:oe.id}).get().pipe(ee.orDie)))return yield*ee.die(new nn({id:t.id}))}),Ig=ee.fn("SessionInput.projectPrompted")(function*(e,t){let n=yield*e.update(oe).set({promoted_seq:t.promotedSeq}).where(Cs(_t(oe.id,t.id),_t(oe.session_id,t.sessionID),Ps(oe.promoted_seq))).returning().get().pipe(ee.orDie);if(n){let s=jd(n);return Md(s,t)?void 0:yield*ee.die(new nn({id:t.id}))}let o=yield*Ir(e,t.id);if(o)return!Md(o,t)||o.promotedSeq!==t.promotedSeq?yield*ee.die(new nn({id:t.id})):void 0;yield*e.insert(oe).values({id:t.id,session_id:t.sessionID,prompt:Rs(t.prompt),delivery:t.delivery,admitted_seq:t.promotedSeq,promoted_seq:t.promotedSeq,time_created:Tn.toEpochMillis(t.timeCreated)}).run().pipe(ee.orDie)}),kg=ee.fn("SessionInput.hasPending")(function*(e,t,n){return(yield*e.select({id:oe.id}).from(oe).where(Cs(_t(oe.session_id,t),Ps(oe.promoted_seq),_t(oe.delivery,n))).limit(1).get().pipe(ee.orDie))!==void 0}),$d=r((e,t)=>e.delivery===t.delivery&&bg(e,t),"equivalent"),bg=r((e,t)=>e.sessionID===t.sessionID&&JSON.stringify(Rs(e.prompt))===JSON.stringify(Rs(t.prompt)),"matchesPrompt"),Md=r((e,t)=>$d(e,t)&&Tn.toEpochMillis(e.timeCreated)===Tn.toEpochMillis(t.timeCreated),"matchesProjection"),Ud=ee.fn("SessionInput.publish")(function*(e,t,n,o){for(let s of o){let i=j.ID.make(s.id);yield*t.publish(V.Prompted,{sessionID:n,timestamp:Tn.makeUnsafe(s.time_created),messageID:i,prompt:Nd(s.prompt),delivery:s.delivery}).pipe(ee.catchDefect(a=>a instanceof nn?Ir(e,i).pipe(ee.flatMap(c=>c?.promotedSeq===void 0?ee.die(a):ee.void)):ee.die(a)))}return o.length}),Dg=ee.fn("SessionInput.promoteSteers")(function*(e,t,n,o){let s=yield*e.select().from(oe).where(Cs(_t(oe.session_id,n),Ps(oe.promoted_seq),_t(oe.delivery,"steer"),vg(oe.admitted_seq,o))).orderBy(Ld(oe.admitted_seq)).all().pipe(ee.orDie);return yield*Ud(e,t,n,s)}),Tg=ee.fn("SessionInput.promoteNextQueued")(function*(e,t,n){let o=yield*e.select().from(oe).where(Cs(_t(oe.session_id,n),Ps(oe.promoted_seq),_t(oe.delivery,"queue"))).orderBy(Ld(oe.admitted_seq)).limit(1).get().pipe(ee.orDie);return o===void 0?!1:yield*Ud(e,t,n,[o]).pipe(ee.as(!0))});var Og=qd.decodeUnknownSync(j.Message),Vd=qd.encodeSync(j.Message),Ns=class extends Error{static{r(this,"SessionAlreadyProjected")}};function Ms(e){if(typeof e!="object"||e===null)return;let t=e;if(t.type==="step-finish"&&!(!("cost"in t)||!("tokens"in t)))return{cost:t.cost,tokens:t.tokens}}r(Ms,"usage");function Fd(e){return{id:e.id,project_id:e.projectID,workspace_id:e.workspaceID??null,parent_id:e.parentID,slug:e.slug,directory:e.directory,path:e.path,title:e.title,agent:e.agent,model:e.model,version:e.version,share_url:e.share?.url,summary_additions:e.summary?.additions,summary_deletions:e.summary?.deletions,summary_files:e.summary?.files,summary_diffs:e.summary?.diffs?[...e.summary.diffs]:void 0,metadata:e.metadata,cost:e.cost??0,tokens_input:(e.tokens??{input:0}).input,tokens_output:(e.tokens??{output:0}).output,tokens_reasoning:(e.tokens??{reasoning:0}).reasoning,tokens_cache_read:(e.tokens??{cache:{read:0}}).cache.read,tokens_cache_write:(e.tokens??{cache:{write:0}}).cache.write,revert:e.revert?{...e.revert,messageID:j.ID.make(e.revert.messageID)}:null,permission:e.permission?[...e.permission]:void 0,time_created:e.time.created,time_updated:e.time.updated,time_compacting:e.time.compacting,time_archived:e.time.archived}}r(Fd,"sessionRow");function Rg(e){let{id:t,sessionID:n,...o}=e;return o}r(Rg,"messageData");function Cg(e){let{id:t,messageID:n,sessionID:o,...s}=e;return s}r(Cg,"partData");function Ls(e,t,n,o=1){return e.update($).set({cost:_n`${$.cost} + ${n.cost*o}`,tokens_input:_n`${$.tokens_input} + ${n.tokens.input*o}`,tokens_output:_n`${$.tokens_output} + ${n.tokens.output*o}`,tokens_reasoning:_n`${$.tokens_reasoning} + ${n.tokens.reasoning*o}`,tokens_cache_read:_n`${$.tokens_cache_read} + ${n.tokens.cache.read*o}`,tokens_cache_write:_n`${$.tokens_cache_write} + ${n.tokens.cache.write*o}`,time_updated:_n`${$.time_updated}`}).where(ne($.id,t)).run().pipe(N.orDie)}r(Ls,"applyUsage");function _e(e,t){return N.gen(function*(){let n=r(a=>Og({...a.data,id:a.id,type:a.type}),"decodeRow"),o=r(a=>{if(t.durable===void 0)return N.die("Durable Session event is missing aggregate sequence");let c=Vd(a),{id:l,type:f,...g}=c;return e.update(T).set({type:f,time_created:on.toEpochMillis(a.time.created),data:g}).where(vt(ne(T.id,j.ID.make(l)),ne(T.session_id,t.data.sessionID))).run().pipe(N.orDie)},"updateMessage"),i={getCurrentAssistant(){return N.gen(function*(){let a=yield*e.select().from(T).where(vt(ne(T.session_id,t.data.sessionID),ne(T.type,"assistant"))).orderBy(Bd(T.seq)).limit(1).get().pipe(N.orDie);if(!a)return;let c=n(a);return c.type==="assistant"&&!c.time.completed?c:void 0})},getAssistant(a){return N.gen(function*(){let c=yield*e.select().from(T).where(vt(ne(T.id,a),ne(T.session_id,t.data.sessionID),ne(T.type,"assistant"))).get().pipe(N.orDie);if(!c)return;let l=n(c);return l.type==="assistant"?l:void 0})},getCurrentShell(a){return N.gen(function*(){return(yield*e.select().from(T).where(vt(ne(T.session_id,t.data.sessionID),ne(T.type,"shell"))).orderBy(Bd(T.seq)).all().pipe(N.orDie)).map(n).find(l=>l.type==="shell"&&l.callID===a)})},updateAssistant:o,updateShell:o,appendMessage:r(a=>Pg(e,t,a),"appendMessage")};yield*wr.update(i,t)})}r(_e,"run");function Pg(e,t,n){if(t.durable===void 0)return N.die("Durable Session event is missing aggregate sequence");let o=Vd(n),{id:s,type:i,...a}=o;return e.insert(T).values({id:j.ID.make(s),session_id:t.data.sessionID,type:i,seq:t.durable.seq,time_created:on.toEpochMillis(n.time.created),data:a}).run().pipe(N.orDie)}r(Pg,"insertMessage");var Mg=Ag.effectDiscard(N.gen(function*(){let e=yield*Fe.Service,{db:t}=yield*Qe.Service;yield*e.project(tt.Event.Created,n=>N.gen(function*(){if(!(yield*t.insert($).values(Fd(n.data.info)).onConflictDoNothing().returning({sessionID:$.id}).get().pipe(N.orDie)))return yield*N.die(new Ns);n.data.info.workspaceID&&(yield*t.update(da).set({time_used:Date.now()}).where(ne(da.id,n.data.info.workspaceID)).run().pipe(N.orDie))})),yield*e.project(tt.Event.Updated,n=>t.update($).set(Fd(n.data.info)).where(ne($.id,n.data.sessionID)).run().pipe(N.orDie)),yield*e.project(V.Moved,n=>N.gen(function*(){yield*t.update($).set({directory:n.data.location.directory,path:n.data.subdirectory,workspace_id:n.data.location.workspaceID?Tt.ID.make(n.data.location.workspaceID):null,time_updated:on.toEpochMillis(n.data.timestamp)}).where(ne($.id,n.data.sessionID)).run().pipe(N.orDie)})),yield*e.project(tt.Event.Deleted,n=>t.delete($).where(ne($.id,n.data.sessionID)).run().pipe(N.orDie)),yield*e.project(tt.Event.MessageUpdated,n=>N.gen(function*(){let o=n.data.info.time.created,s=n.data.info.id,i=n.data.info.sessionID,a=Rg(n.data.info);yield*t.insert(bn).values({id:s,session_id:i,time_created:o,data:a}).onConflictDoUpdate({target:bn.id,set:{data:a}}).run().pipe(N.orDie)})),yield*e.project(tt.Event.MessageRemoved,n=>N.gen(function*(){let o=yield*t.select().from(nt).where(vt(ne(nt.message_id,n.data.messageID),ne(nt.session_id,n.data.sessionID))).all().pipe(N.orDie);for(let s of o){let i=Ms(s.data);i&&(yield*Ls(t,n.data.sessionID,i,-1))}yield*t.delete(bn).where(vt(ne(bn.id,n.data.messageID),ne(bn.session_id,n.data.sessionID))).run().pipe(N.orDie)})),yield*e.project(tt.Event.PartRemoved,n=>N.gen(function*(){let o=yield*t.select().from(nt).where(vt(ne(nt.id,n.data.partID),ne(nt.session_id,n.data.sessionID))).get().pipe(N.orDie),s=o&&Ms(o.data);s&&(yield*Ls(t,n.data.sessionID,s,-1)),yield*t.delete(nt).where(vt(ne(nt.id,n.data.partID),ne(nt.session_id,n.data.sessionID))).run().pipe(N.orDie)})),yield*e.project(tt.Event.PartUpdated,n=>N.gen(function*(){let o=n.data.part.id,s=n.data.part.messageID,i=n.data.part.sessionID,a=Cg(n.data.part),c=yield*t.select().from(nt).where(ne(nt.id,o)).get().pipe(N.orDie);yield*t.insert(nt).values({id:o,message_id:s,session_id:i,time_created:n.data.time,data:a}).onConflictDoUpdate({target:nt.id,set:{data:a}}).run().pipe(N.orDie);let l=c&&Ms(c.data),f=Ms(n.data.part);l&&(yield*Ls(t,c.session_id,l,-1)),f&&(yield*Ls(t,i,f))})),yield*e.project(V.AgentSwitched,n=>t.update($).set({agent:n.data.agent,time_updated:on.toEpochMillis(n.data.timestamp)}).where(ne($.id,n.data.sessionID)).run().pipe(N.orDie,N.andThen(_e(t,n)))),yield*e.project(V.ModelSwitched,n=>N.gen(function*(){yield*t.update($).set({model:n.data.model,time_updated:on.toEpochMillis(n.data.timestamp)}).where(ne($.id,n.data.sessionID)).run().pipe(N.orDie),yield*_e(t,n)})),yield*e.project(V.Prompted,n=>N.gen(function*(){if(n.durable===void 0)return yield*N.die("Durable Session event is missing aggregate sequence");yield*At.projectPrompted(t,{id:n.data.messageID,sessionID:n.data.sessionID,prompt:n.data.prompt,delivery:n.data.delivery,timeCreated:n.data.timestamp,promotedSeq:n.durable.seq}),yield*_e(t,n)})),yield*e.project(V.PromptAdmitted,n=>N.gen(function*(){if(n.durable===void 0)return yield*N.die("Durable Session event is missing aggregate sequence");yield*At.projectAdmitted(t,{admittedSeq:n.durable.seq,id:n.data.messageID,sessionID:n.data.sessionID,prompt:n.data.prompt,delivery:n.data.delivery,timeCreated:n.data.timestamp})})),yield*e.project(V.ContextUpdated,n=>_e(t,n)),yield*e.project(V.Synthetic,n=>_e(t,n)),yield*e.project(V.Shell.Started,n=>_e(t,n)),yield*e.project(V.Shell.Ended,n=>_e(t,n)),yield*e.project(V.Step.Started,n=>_e(t,n)),yield*e.project(V.Step.Ended,n=>_e(t,n)),yield*e.project(V.Step.Failed,n=>_e(t,n)),yield*e.project(V.Text.Started,n=>_e(t,n)),yield*e.project(V.Text.Ended,n=>_e(t,n)),yield*e.project(V.Tool.Input.Started,n=>_e(t,n)),yield*e.project(V.Tool.Input.Ended,n=>_e(t,n)),yield*e.project(V.Tool.Called,n=>_e(t,n)),yield*e.project(V.Tool.Progress,n=>_e(t,n)),yield*e.project(V.Tool.Success,n=>_e(t,n)),yield*e.project(V.Tool.Failed,n=>_e(t,n)),yield*e.project(V.Reasoning.Started,n=>_e(t,n)),yield*e.project(V.Reasoning.Ended,n=>_e(t,n)),yield*e.project(V.Compaction.Ended,n=>_e(t,n)),yield*e.project(V.RevertEvent.Staged,n=>t.update($).set({revert:{...n.data.revert,files:n.data.revert.files?[...n.data.revert.files]:void 0},time_updated:on.toEpochMillis(n.data.timestamp)}).where(ne($.id,n.data.sessionID)).run().pipe(N.orDie,N.asVoid)),yield*e.project(V.RevertEvent.Cleared,n=>t.update($).set({revert:null,time_updated:on.toEpochMillis(n.data.timestamp)}).where(ne($.id,n.data.sessionID)).run().pipe(N.orDie,N.asVoid)),yield*e.project(V.RevertEvent.Committed,n=>N.gen(function*(){let o=yield*t.select({seq:T.seq}).from(T).where(vt(ne(T.session_id,n.data.sessionID),ne(T.id,n.data.messageID))).get().pipe(N.orDie);if(!o)return yield*N.die(`Revert boundary message not found: ${n.data.messageID}`);yield*t.delete(T).where(vt(ne(T.session_id,n.data.sessionID),ma(T.seq,o.seq))).run().pipe(N.orDie),yield*t.delete(oe).where(vt(ne(oe.session_id,n.data.sessionID),_g(ma(oe.admitted_seq,o.seq),ma(oe.promoted_seq,o.seq)))).run().pipe(N.orDie),yield*t.update($).set({revert:null,time_updated:on.toEpochMillis(n.data.timestamp)}).where(ne($.id,n.data.sessionID)).run().pipe(N.orDie)}))})),Lg=kt({name:"session-projector",layer:Mg,deps:[Fe.node,Qe.node]});var ga;(o=>{let e=["brave","calm","clever","cosmic","crisp","curious","eager","gentle","glowing","happy","hidden","jolly","kind","lucky","mighty","misty","neon","nimble","playful","proud","quick","quiet","shiny","silent","stellar","sunny","swift","tidy","witty"],t=["cabin","cactus","canyon","circuit","comet","eagle","engine","falcon","forest","garden","harbor","island","knight","lagoon","meadow","moon","mountain","nebula","orchid","otter","panda","pixel","planet","river","rocket","sailor","squid","star","tiger","wizard","wolf"];function n(){return[e[Math.floor(Math.random()*e.length)],t[Math.floor(Math.random()*t.length)]].join("-")}o.create=n,r(n,"create")})(ga||={});import{Layer as Ng}from"effect";var Wd=Ng.makeMemoMapUnsafe();var kr={};R(kr,{Observability:()=>kr,layer:()=>Xd,node:()=>Qg});import{NodeFileSystem as Kg}from"@effect/platform-node";import{Effect as Kd,Layer as rn,Logger as Xg,References as zg}from"effect";import{FetchHttpClient as Yg}from"effect/unstable/http";import{OtlpSerialization as Zg}from"effect/unstable/observability";var Eo={};R(Eo,{Logging:()=>Eo,fileLogger:()=>ya,loggers:()=>qg,minimumLogLevel:()=>Fg});import{Formatter as jg,Logger as $s}from"effect";import $g from"path";var wo=crypto.randomUUID().slice(0,8);function Gd(e=wo){return $s.map($s.formatStructured,t=>{let n=Array.isArray(t.message)?t.message:[t.message];return[["timestamp",t.timestamp],["level",t.level],["run",e],...n.flatMap(o=>Hd(o)?js(o):[["message",o]]),...t.cause===void 0?[]:[["cause",t.cause]],...js(t.spans),...js(t.annotations)].map(([o,s])=>`${o}=${Ug(s)}`).join(" ")})}r(Gd,"formatter");function js(e,t="",n=new WeakSet){if(n.has(e))return[[t,"[Circular]"]];n.add(e);let o=Object.entries(e);return o.length===0&&t?[[t,e]]:o.flatMap(([s,i])=>{let a=t?`${t}.${s}`:s;return Hd(i)?js(i,a,n):[[a,i]]})}r(js,"flatten");function Hd(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}r(Hd,"plain");function Ug(e){let t=typeof e=="string"?e:jg.format(e);return/^[^\s="\\]+$/.test(t)?t:JSON.stringify(t)}r(Ug,"format");function ya(e=$g.join(he.Path.log,"opencode.log"),t=wo){return $s.toFile(Gd(t),e,{flag:"a"})}r(ya,"fileLogger");var Bg=$s.make(e=>process.stderr.write(Gd().log(e)+`
659
+ `));function Fg(){let e=process.env.OPENCODE_LOG_LEVEL?.toUpperCase(),t={DEBUG:"Debug",INFO:"Info",WARN:"Warn",ERROR:"Error"};return e&&e in t?t[e]:t.INFO}r(Fg,"minimumLogLevel");function qg(){return process.env.OPENCODE_PRINT_LOGS==="1"?[ya(),Bg]:[ya()]}r(qg,"loggers");var Io={};R(Io,{Otlp:()=>Io,loggers:()=>Hg,resource:()=>ha,tracingLayer:()=>Jg});import{Layer as Vg}from"effect";import{OtlpLogger as Wg}from"effect/unstable/observability";var Us=le.OTEL_EXPORTER_OTLP_ENDPOINT,Jd=le.OTEL_EXPORTER_OTLP_HEADERS?le.OTEL_EXPORTER_OTLP_HEADERS.split(",").reduce((e,t)=>{let[n,...o]=t.split("=");return e[n]=o.join("="),e},{}):void 0;function Gg(){let e=process.env.OTEL_RESOURCE_ATTRIBUTES;if(!e)return{};try{return Object.fromEntries(e.split(",").map(t=>{let n=t.indexOf("=");if(n<1)throw new Error("Invalid OTEL_RESOURCE_ATTRIBUTES entry");return[decodeURIComponent(t.slice(0,n)),decodeURIComponent(t.slice(n+1))]}))}catch{return{}}}r(Gg,"resourceAttributes");function ha(){return{serviceName:"opencode",serviceVersion:lo,attributes:{...Gg(),"deployment.environment.name":wl,"opencode.client":le.OPENCODE_CLIENT,"opencode.run":wo,"service.instance.id":wo}}}r(ha,"resource");function Hg(){return Us?[Wg.make({url:`${Us}/v1/logs`,resource:ha(),headers:Jd})]:[]}r(Hg,"loggers");async function Jg(){if(!Us)return Vg.empty;let e=await import("@effect/opentelemetry/NodeSdk"),t=await import("@opentelemetry/exporter-trace-otlp-http"),n=await import("@opentelemetry/sdk-trace-base"),{AsyncLocalStorageContextManager:o}=await import("@opentelemetry/context-async-hooks"),{context:s}=await import("@opentelemetry/api"),i=new o;return i.enable(),s.setGlobalContextManager(i),e.layer(()=>({resource:ha(),spanProcessor:new n.BatchSpanProcessor(new t.OTLPTraceExporter({url:`${Us}/v1/traces`,headers:Jd}))}))}r(Jg,"tracingLayer");var Xd=rn.unwrap(Kd.gen(function*(){let e=Xg.layer([...Eo.loggers(),...Io.loggers()],{mergeWithExisting:!1}).pipe(rn.provide(Kg.layer),rn.provide(Zg.layerJson),rn.provide(Yg.layer),rn.orDie,rn.merge(rn.succeed(zg.MinimumLogLevel,Eo.minimumLogLevel())));return rn.merge(e,yield*Kd.promise(Io.tracingLayer))})),Qg=xe.make({name:"observability",layer:Xd,deps:[]});var cn={};R(cn,{InstallFailedError:()=>Cr,Npm:()=>cn,Service:()=>Rn,add:()=>hh,install:()=>yh,node:()=>Np,sanitize:()=>Lp,which:()=>Sh});import at from"path";import{realpathSync as ch}from"fs";import{createRequire as lh}from"module";import{pathToFileURL as dh}from"url";import ph from"npm-package-arg";import{Effect as me,Schema as On,Context as uh,Layer as fh,Option as He,FileSystem as mh}from"effect";import"@effect/platform-node";import Bs from"path";import ey from"os";import{randomUUID as ty}from"crypto";import{Context as ny,Effect as H,Function as oy,Layer as ry,Option as sy,Schedule as ko,Schema as Ge}from"effect";var Fs;(L=>{class e extends Ge.TaggedErrorClass()("LockTimeoutError",{key:Ge.String}){static{r(this,"LockTimeoutError")}}L.LockTimeoutError=e;class t extends Ge.TaggedErrorClass()("LockCompromisedError",{detail:Ge.String}){static{r(this,"LockCompromisedError")}}L.LockCompromisedError=t;class n extends Ge.TaggedErrorClass()("ReleaseError",{detail:Ge.String,cause:Ge.optional(Ge.Defect())}){static{r(this,"ReleaseError")}get message(){return this.detail}}class o extends Ge.TaggedErrorClass()("NotAcquired",{}){static{r(this,"NotAcquired")}}let s=6e4,i=5*6e4,a=100,c=2e3,l=Math.max(100,Math.floor(s/3)),f=ko.exponential(a,1.7).pipe(ko.either(ko.spaced(c)),ko.jittered,ko.while(G=>G.elapsed<i)),g=Ge.fromJsonString(Ge.Struct({token:Ge.String,pid:Ge.Number,hostname:Ge.String,createdAt:Ge.String})),d=Ge.decodeUnknownSync(g),h=Ge.encodeSync(g);class b extends ny.Service()("EffectFlock"){static{r(this,"Service")}}L.Service=b;function _(){return performance.timeOrigin+performance.now()}r(_,"wall");let P=r(G=>sy.getOrElse(G.mtime,()=>new Date(0)).getTime(),"mtimeMs"),C=r(G=>G.reason._tag==="NotFound"||G.reason._tag==="Unknown","isPathGone"),J=ry.effect(b,H.gen(function*(){let G=yield*he.Service,K=yield*de.Service,Me=Bs.join(G.state,"locks"),x=ey.hostname(),E=new Set,y=r(F=>K.stat(F).pipe(H.catchIf(C,()=>H.void),H.orDie),"safeStat"),S=r(F=>K.remove(F,{recursive:!0}).pipe(H.ignore),"forceRemove"),v=r(F=>K.makeDirectory(F,{mode:448}).pipe(H.as(!0),H.catchIf(Ie=>Ie.reason._tag==="AlreadyExists",()=>H.succeed(!1)),H.orDie),"atomicMkdir"),O=r((F,Ie,Ne,A)=>K.writeFileString(F,Ie,{flag:"wx"}).pipe(H.catch(()=>H.gen(function*(){return yield*S(Ne),yield*new t({detail:A})}))),"exclusiveWrite"),Q=H.fnUntraced(function*(F){let Ie=yield*y(F);return Ie&&_()-P(Ie)>s&&(yield*S(F)),!1}),ae=H.fnUntraced(function*(F){E.has(F)||(yield*K.makeDirectory(F,{recursive:!0}).pipe(H.orDie),E.add(F))}),ue=H.fnUntraced(function*(F,Ie,Ne){let A=_(),X=yield*y(Ie);if(X)return A-P(X)>s;let ye=yield*y(Ne);if(ye)return A-P(ye)>s;let re=yield*y(F);return re?A-P(re)>s:!1}),Le=r((F,Ie)=>H.gen(function*(){let Ne=ty(),A=Bs.join(F,"meta.json"),X=Bs.join(F,"heartbeat");if(!(yield*v(F))){if(!(yield*ue(F,X,A)))return yield*new o;let Be=F+".breaker";if(!(yield*K.makeDirectory(Be,{mode:448}).pipe(H.as(!0),H.catchIf(vn=>vn.reason._tag==="AlreadyExists",()=>Q(Be)),H.catchIf(C,()=>H.succeed(!1)),H.orDie)))return yield*new o;if(!(yield*H.gen(function*(){return(yield*ue(F,X,A))?(yield*S(F),yield*v(F)):!1}).pipe(H.ensuring(S(Be)))))return yield*new o}yield*O(X,"",F,"heartbeat already existed");let re=h({token:Ne,pid:process.pid,hostname:x,createdAt:new Date().toISOString()});return yield*O(A,re,F,"meta.json already existed"),{token:Ne,metaPath:A,heartbeatPath:X,lockDir:F}}).pipe(H.withSpan("EffectFlock.tryAcquire",{attributes:{key:Ie}})),"tryAcquireLockDir"),Ze=r((F,Ie)=>Le(F,Ie).pipe(H.retry({while:r(Ne=>Ne._tag==="NotAcquired","while"),schedule:f}),H.catchTag("NotAcquired",()=>H.fail(new e({key:Ie})))),"acquireHandle"),ir=r(F=>H.gen(function*(){let Ie=yield*K.readFileString(F.metaPath).pipe(H.catch(A=>C(A)?H.die(new n({detail:"metadata missing"})):H.die(A)));if((yield*H.try({try:r(()=>d(Ie),"try"),catch:r(A=>new n({detail:"metadata invalid",cause:A}),"catch")}).pipe(H.orDie)).token!==F.token)return yield*H.die(new n({detail:"token mismatch"}));yield*S(F.lockDir)}),"release"),ar=H.fn("EffectFlock.acquire")(function*(F,Ie){let Ne=Ie??Me;yield*ae(Ne);let A=Bs.join(Ne,hs.fast(F)+".lock"),X=yield*H.acquireRelease(Ze(A,F),ye=>ir(ye));yield*K.utimes(X.heartbeatPath,new Date,new Date).pipe(H.ignore,H.repeat(ko.spaced(l)),H.forkScoped)}),ps=oy.dual(F=>H.isEffect(F[0]),(F,Ie,Ne)=>H.scoped(H.gen(function*(){return yield*ar(Ie,Ne),yield*F})));return b.of({acquire:ar,withLock:ps})}));L.node=kt({service:b,layer:J,deps:[he.node,de.node]})})(Fs||={});import{Layer as iy,ManagedRuntime as ay}from"effect";function zd(e,t){let n,o=r(()=>n??=ay.make(iy.provideMerge(t,kr.layer),{memoMap:Wd}),"getRuntime");return{runSync:r(s=>o().runSync(e.use(s)),"runSync"),runPromiseExit:r((s,i)=>o().runPromiseExit(e.use(s),i),"runPromiseExit"),runPromise:r((s,i)=>o().runPromise(e.use(s),i),"runPromise"),runFork:r(s=>o().runFork(e.use(s)),"runFork"),runCallback:r(s=>o().runCallback(e.use(s)),"runCallback")}}r(zd,"makeRuntime");var Rr={};R(Rr,{NpmConfig:()=>Rr,load:()=>Pp,registry:()=>ah});var Cp=yl(xp(),1),an=yl(Rp(),1);import{fileURLToPath as sh}from"url";import{Effect as Ma}from"effect";var ih=sh(new URL("..",import.meta.url)),Pp=r(e=>Ma.tryPromise({try:r(async()=>{let t=new Cp.default({npmPath:ih,cwd:e,env:{...process.env},argv:[process.execPath,process.execPath],execPath:process.execPath,platform:process.platform,definitions:an.definitions,flatten:an.flatten,nerfDarts:an.nerfDarts,shorthands:an.shorthands,warn:!1});return await t.load(),t.flat},"try"),catch:r(t=>t,"catch")}).pipe(Ma.orElseSucceed(()=>({}))),"load"),ah=r(e=>Pp(e).pipe(Ma.map(t=>{let n=typeof t.registry=="string"?t.registry:"https://registry.npmjs.org";return n.endsWith("/")?n.slice(0,-1):n})),"registry");var Cr=class extends On.TaggedErrorClass()("NpmInstallFailedError",{add:On.Array(On.String).pipe(On.optional),dir:On.String,cause:On.optional(On.Defect())}){static{r(this,"InstallFailedError")}},Rn=class extends uh.Service()("@opencode/Npm"){static{r(this,"Service")}},Mp=process.platform==="win32"?new Set(["<",">",":",'"',"|","?","*"]):void 0;function Lp(e){return Mp?Array.from(e,t=>Mp.has(t)||t.charCodeAt(0)<32?"_":t).join(""):e}r(Lp,"sanitize");var La=r((e,t)=>{let n;try{n=typeof Bun<"u"?import.meta.resolve(e,t):dh(lh(at.join(t,"package.json")).resolve(e)).href}catch{n=void 0}return{directory:t,entrypoint:n}},"resolveEntryPoint"),gh=fh.effect(Rn,me.gen(function*(){let e=yield*de.Service,t=yield*he.Service,n=yield*mh.FileSystem,o=yield*Fs.Service,s=(()=>{try{return ch(t.cache)}catch{return t.cache}})(),i=r(g=>at.join(s,"packages",Lp(g)),"directory"),a=r(g=>me.gen(function*(){yield*o.acquire(`npm-install:${g.dir}`);let{Arborist:d}=yield*me.promise(()=>import("@npmcli/arborist")),h=g.add??[],b=yield*Rr.load(g.dir),_=new d({...b,path:g.dir,binLinks:!0,progress:!1,savePrefix:"",ignoreScripts:!0});return yield*me.tryPromise({try:r(()=>_.reify({...b,add:h,save:!0,saveType:"prod"}),"try"),catch:r(P=>new Cr({cause:P,add:h,dir:g.dir}),"catch")})}).pipe(me.withSpan("Npm.reify",{attributes:g})),"reify"),c=me.fn("Npm.add")(function*(g){let d=i(g),h=(()=>{try{return ph(g).name??g}catch{return g}})();if(yield*e.existsSafe(at.join(d,"node_modules",h)))return La(h,at.join(d,"node_modules",h));let _=(yield*a({dir:d,add:[g]})).edgesOut.values().next().value?.to;if(!_){let P=La(h,at.join(d,"node_modules",h));return P.entrypoint?P:yield*new Cr({add:[g],dir:d})}return La(_.name,_.path)},me.scoped),l=me.fn("Npm.install")(function*(g,d){if(!(yield*e.access(g,{writable:!0}).pipe(me.as(!0),me.orElseSucceed(()=>!1))))return;let b=d?.add.map(_=>[_.name,_.version].filter(Boolean).join("@"))??[];(yield*me.gen(function*(){return(yield*e.existsSafe(at.join(g,"node_modules")))?!1:(yield*a({add:b,dir:g}),!0)}).pipe(me.withSpan("Npm.checkNodeModules")))||(yield*me.gen(function*(){let _=yield*e.readJson(at.join(g,"package.json")).pipe(me.orElseSucceed(()=>({}))),P=yield*e.readJson(at.join(g,"package-lock.json")).pipe(me.orElseSucceed(()=>({}))),C=_,J=P,te=new Set([...Object.keys(C?.dependencies||{}),...Object.keys(C?.devDependencies||{}),...Object.keys(C?.peerDependencies||{}),...Object.keys(C?.optionalDependencies||{}),...(d?.add||[]).map(K=>K.name)]),L=J?.packages?.[""]||{},G=new Set([...Object.keys(L?.dependencies||{}),...Object.keys(L?.devDependencies||{}),...Object.keys(L?.peerDependencies||{}),...Object.keys(L?.optionalDependencies||{})]);for(let K of te)if(!G.has(K)){yield*a({dir:g,add:b});return}}).pipe(me.withSpan("Npm.checkDirty")))},me.scoped),f=me.fn("Npm.which")(function*(g,d){let h=i(g),b=at.join(h,"node_modules",".bin"),_=me.fnUntraced(function*(){let P=yield*n.readDirectory(b).pipe(me.catch(()=>me.succeed([])));if(P.length===0)return He.none();if(d)return P.includes(d)?He.some(d):He.none();if(P.length===1)return He.some(P[0]);let C=yield*e.readJson(at.join(h,"node_modules",g,"package.json")).pipe(me.option);if(He.isSome(C)){let J=C.value;if(J?.bin){let te=g.startsWith("@")?g.split("/")[1]:g,L=J.bin;if(typeof L=="string")return He.some(te);let G=Object.keys(L);return G.length===1?He.some(G[0]):L[te]?He.some(te):He.some(G[0])}}return He.some(P[0])});return He.getOrUndefined(yield*me.gen(function*(){let P=yield*_();if(He.isSome(P))return He.some(at.join(b,P.value));yield*n.remove(at.join(h,"package-lock.json")).pipe(me.orElseSucceed(()=>{})),yield*c(g);let C=yield*_();return He.isNone(C)?He.none():He.some(at.join(b,C.value))}).pipe(me.scoped,me.orElseSucceed(()=>He.none())))});return Rn.of({add:c,install:l,which:f})})),Np=kt({service:Rn,layer:gh,deps:[de.node,he.node,Al,Fs.node]}),{runPromise:Na}=zd(Rn,xe.compile(Np));async function yh(...e){return Na(t=>t.install(...e))}r(yh,"install");async function hh(...e){return Na(t=>t.add(...e))}r(hh,"add");async function Sh(...e){return Na(t=>t.which(...e))}r(Sh,"which");var jo={};R(jo,{AccessToken:()=>Mr,Account:()=>jo,AccountID:()=>Pr,AccountRepoError:()=>Ro,AccountServiceError:()=>Rt,AccountTransportError:()=>Pn,DeviceCode:()=>Mo,Info:()=>Ao,Login:()=>Co,Org:()=>Oo,OrgID:()=>Hs,PollDenied:()=>$n,PollError:()=>Un,PollExpired:()=>jn,PollPending:()=>Ln,PollResult:()=>Gp,PollSlow:()=>Nn,PollSuccess:()=>Mn,RefreshToken:()=>Po,Service:()=>Vn,UserCode:()=>Lr,node:()=>Bh,use:()=>$h});import{Cache as Jp,Clock as Ks,Duration as qn,Effect as ge,Layer as Rh,Option as Ce,Schema as pe,SchemaGetter as Kp,Context as Ch}from"effect";import{HttpClient as Wa,HttpClientError as Ph,HttpClientRequest as Ue,HttpClientResponse as Fn}from"effect/unstable/http";import{Schedule as jp}from"effect";import{HttpClient as xh}from"effect/unstable/http";var Ws=r(e=>e.pipe(xh.retryTransient({retryOn:"errors-and-responses",times:2,schedule:jp.exponential(200).pipe(jp.jittered)})),"withTransientReadRetry");var No={};R(No,{AccountRepo:()=>No,Service:()=>Bn,node:()=>Oh,use:()=>_h});import{eq as Lo}from"drizzle-orm";import{Effect as $e,Layer as bh,Option as Nr,Schema as Dh,Context as Th}from"effect";import{sqliteTable as Va,text as Et,integer as Gs,primaryKey as kh}from"drizzle-orm/sqlite-core";import{Schema as U}from"effect";var vh=U.String.pipe(U.brand("AccountID")),Wp=U.String.pipe(U.brand("OrgID")),dA=U.String.pipe(U.brand("AccessToken")),pA=U.String.pipe(U.brand("RefreshToken")),wh=U.String.pipe(U.brand("DeviceCode")),Eh=U.String.pipe(U.brand("UserCode")),$p=class extends U.Class("Account")({id:vh,email:U.String,url:U.String,active_org_id:U.NullOr(Wp)}){static{r(this,"Info")}},Up=class extends U.Class("Org")({id:Wp,name:U.String}){static{r(this,"Org")}},Bp=class extends U.TaggedErrorClass()("AccountRepoError",{message:U.String,cause:U.optional(U.Defect())}){static{r(this,"AccountRepoError")}},Fp=class extends U.TaggedErrorClass()("AccountServiceError",{message:U.String,cause:U.optional(U.Defect())}){static{r(this,"AccountServiceError")}},qp=class e extends U.TaggedErrorClass()("AccountTransportError",{method:U.String,url:U.String,description:U.optional(U.String),cause:U.optional(U.Defect())}){static{r(this,"AccountTransportError")}static fromHttpClientError(t){return new e({method:t.request.method,url:t.request.url,description:t.description,cause:t.cause})}get message(){return[`Could not reach ${this.method} ${this.url}.`,"This failed before the server returned an HTTP response.",this.description,"Check your network, proxy, or VPN configuration and try again."].filter(Boolean).join(`
660
+ `)}},Vp=class extends U.Class("Login")({code:wh,user:Eh,url:U.String,server:U.String,expiry:U.Duration,interval:U.Duration}){static{r(this,"Login")}},ja=class extends U.TaggedClass()("PollSuccess",{email:U.String}){static{r(this,"PollSuccess")}},$a=class extends U.TaggedClass()("PollPending",{}){static{r(this,"PollPending")}},Ua=class extends U.TaggedClass()("PollSlow",{}){static{r(this,"PollSlow")}},Ba=class extends U.TaggedClass()("PollExpired",{}){static{r(this,"PollExpired")}},Fa=class extends U.TaggedClass()("PollDenied",{}){static{r(this,"PollDenied")}},qa=class extends U.TaggedClass()("PollError",{cause:U.Defect()}){static{r(this,"PollError")}},uA=U.Union([ja,$a,Ua,Ba,Fa,qa]);var ct=Va("account",{id:Et().$type().primaryKey(),email:Et().notNull(),url:Et().notNull(),access_token:Et().$type().notNull(),refresh_token:Et().$type().notNull(),token_expiry:Gs(),...qt}),Cn=Va("account_state",{id:Gs().primaryKey(),active_account_id:Et().$type().references(()=>ct.id,{onDelete:"set null"}),active_org_id:Et().$type()}),SA=Va("control_account",{email:Et().notNull(),url:Et().notNull(),access_token:Et().$type().notNull(),refresh_token:Et().$type().notNull(),token_expiry:Gs(),active:Gs({mode:"boolean"}).notNull().$default(()=>!1),...qt},e=>[kh({columns:[e.email,e.url]})]);import{Schema as B}from"effect";var Pr=B.String.pipe(B.brand("AccountID")),Hs=B.String.pipe(B.brand("OrgID")),Mr=B.String.pipe(B.brand("AccessToken")),Po=B.String.pipe(B.brand("RefreshToken")),Mo=B.String.pipe(B.brand("DeviceCode")),Lr=B.String.pipe(B.brand("UserCode")),Ao=class extends B.Class("Account")({id:Pr,email:B.String,url:B.String,active_org_id:B.NullOr(Hs)}){static{r(this,"Info")}},Oo=class extends B.Class("Org")({id:Hs,name:B.String}){static{r(this,"Org")}},Ro=class extends B.TaggedErrorClass()("AccountRepoError",{message:B.String,cause:B.optional(B.Defect())}){static{r(this,"AccountRepoError")}},Rt=class extends B.TaggedErrorClass()("AccountServiceError",{message:B.String,cause:B.optional(B.Defect())}){static{r(this,"AccountServiceError")}},Pn=class e extends B.TaggedErrorClass()("AccountTransportError",{method:B.String,url:B.String,description:B.optional(B.String),cause:B.optional(B.Defect())}){static{r(this,"AccountTransportError")}static fromHttpClientError(t){return new e({method:t.request.method,url:t.request.url,description:t.description,cause:t.cause})}get message(){return[`Could not reach ${this.method} ${this.url}.`,"This failed before the server returned an HTTP response.",this.description,"Check your network, proxy, or VPN configuration and try again."].filter(Boolean).join(`
661
+ `)}},Co=class extends B.Class("Login")({code:Mo,user:Lr,url:B.String,server:B.String,expiry:B.Duration,interval:B.Duration}){static{r(this,"Login")}},Mn=class extends B.TaggedClass()("PollSuccess",{email:B.String}){static{r(this,"PollSuccess")}},Ln=class extends B.TaggedClass()("PollPending",{}){static{r(this,"PollPending")}},Nn=class extends B.TaggedClass()("PollSlow",{}){static{r(this,"PollSlow")}},jn=class extends B.TaggedClass()("PollExpired",{}){static{r(this,"PollExpired")}},$n=class extends B.TaggedClass()("PollDenied",{}){static{r(this,"PollDenied")}},Un=class extends B.TaggedClass()("PollError",{cause:B.Defect()}){static{r(this,"PollError")}},Gp=B.Union([Mn,Ln,Nn,jn,$n,Un]);var Js=r(e=>{let t=new URL(e);t.search="",t.hash="";let n=t.pathname.replace(/\/+$/,"");return n.length===0?t.origin:`${t.origin}${n}`},"normalizeServerUrl");var Hp=1,Bn=class extends Th.Service()("@opencode/AccountRepo"){static{r(this,"Service")}},_h=Yt(Bn),Ah=bh.effect(Bn,$e.gen(function*(){let{db:e}=yield*Qe.Service,t=Dh.decodeUnknownSync(Ao),n=r(h=>h.pipe($e.mapError(b=>new Ro({message:"Database operation failed",cause:b}))),"query"),o=$e.fnUntraced(function*(){let h=yield*e.select().from(Cn).where(Lo(Cn.id,Hp)).get();if(!h?.active_account_id)return;let b=yield*e.select().from(ct).where(Lo(ct.id,h.active_account_id)).get();if(b)return{...b,active_org_id:h.active_org_id??null}}),s=r((h,b)=>{let _=Nr.getOrNull(b);return e.insert(Cn).values({id:Hp,active_account_id:h,active_org_id:_}).onConflictDoUpdate({target:Cn.id,set:{active_account_id:h,active_org_id:_}}).run()},"state"),i=$e.fn("AccountRepo.active")(()=>n(o()).pipe($e.map(h=>h?Nr.some(t(h)):Nr.none()))),a=$e.fn("AccountRepo.list")(()=>n(e.select().from(ct).all().pipe($e.map(h=>h.map(b=>t({...b,active_org_id:null})))))),c=$e.fn("AccountRepo.remove")(h=>n(e.transaction(b=>$e.gen(function*(){yield*b.update(Cn).set({active_account_id:null,active_org_id:null}).where(Lo(Cn.active_account_id,h)).run(),yield*b.delete(ct).where(Lo(ct.id,h)).run()}))).pipe($e.asVoid)),l=$e.fn("AccountRepo.use")((h,b)=>n(s(h,b)).pipe($e.asVoid)),f=$e.fn("AccountRepo.getRow")(h=>n(e.select().from(ct).where(Lo(ct.id,h)).get()).pipe($e.map(Nr.fromNullishOr))),g=$e.fn("AccountRepo.persistToken")(h=>n(e.update(ct).set({access_token:h.accessToken,refresh_token:h.refreshToken,token_expiry:Nr.getOrNull(h.expiry)}).where(Lo(ct.id,h.accountID)).run()).pipe($e.asVoid)),d=$e.fn("AccountRepo.persistAccount")(h=>n(e.transaction(b=>$e.gen(function*(){let _=Js(h.url);yield*b.insert(ct).values({id:h.id,email:h.email,url:_,access_token:h.accessToken,refresh_token:h.refreshToken,token_expiry:h.expiry}).onConflictDoUpdate({target:ct.id,set:{email:h.email,url:_,access_token:h.accessToken,refresh_token:h.refreshToken,token_expiry:h.expiry}}).run(),yield*s(h.id,h.orgID)}))).pipe($e.asVoid));return Bn.of({active:i,list:a,remove:c,use:l,getRow:f,persistToken:g,persistAccount:d})})),Oh=xe.make({service:Bn,layer:Ah,deps:[Qe.node]});var Ha=class extends pe.Class("RemoteConfig")({config:pe.Record(pe.String,pe.Json)}){static{r(this,"RemoteConfig")}},Xs=pe.Number.pipe(pe.decodeTo(pe.Duration,{decode:Kp.transform(e=>qn.seconds(e)),encode:Kp.transform(e=>qn.toSeconds(e))})),Ja=class extends pe.Class("TokenRefresh")({access_token:Mr,refresh_token:Po,expires_in:Xs}){static{r(this,"TokenRefresh")}},Ka=class extends pe.Class("DeviceAuth")({device_code:Mo,user_code:Lr,verification_uri_complete:pe.String,expires_in:Xs,interval:Xs}){static{r(this,"DeviceAuth")}},Xa=class extends pe.Class("DeviceTokenSuccess")({access_token:Mr,refresh_token:Po,token_type:pe.Literal("Bearer"),expires_in:Xs}){static{r(this,"DeviceTokenSuccess")}},zs=class extends pe.Class("DeviceTokenError")({error:pe.String,error_description:pe.String}){static{r(this,"DeviceTokenError")}toPollResult(){return this.error==="authorization_pending"?new Ln:this.error==="slow_down"?new Nn:this.error==="expired_token"?new jn:this.error==="access_denied"?new $n:new Un({cause:this.error})}},Mh=pe.Union([Xa,zs]),za=class extends pe.Class("User")({id:Pr,email:pe.String}){static{r(this,"User")}},Ys=class extends pe.Class("ClientId")({client_id:pe.String}){static{r(this,"ClientId")}},Zs=class extends pe.Class("DeviceTokenRequest")({grant_type:pe.String,device_code:Mo,client_id:pe.String}){static{r(this,"DeviceTokenRequest")}},Qs=class extends pe.Class("TokenRefreshRequest")({grant_type:pe.String,refresh_token:Po,client_id:pe.String}){static{r(this,"TokenRefreshRequest")}},Ga="opencode-cli",Lh=qn.minutes(5),Nh=qn.toMillis(Lh),Xp=r((e,t)=>e!=null&&e>t+Nh,"isTokenFresh"),It=r((e="Account service operation failed")=>t=>t.pipe(ge.mapError(n=>jh(n,e))),"mapAccountServiceError"),jh=r((e,t)=>e instanceof Rt||e instanceof Pn?e:Ph.isHttpClientError(e)?e.reason._tag==="TransportError"?Pn.fromHttpClientError(e.reason):new Rt({message:t,cause:e}):new Rt({message:t,cause:e}),"accountErrorFromCause"),Vn=class extends Ch.Service()("@opencode/Account"){static{r(this,"Service")}},$h=Yt(Vn),Uh=Rh.effect(Vn,ge.gen(function*(){let e=yield*No.Service,t=yield*Wa.HttpClient,n=Ws(t),o=Wa.filterStatusOk(t),s=Wa.filterStatusOk(n),i=r(x=>n.execute(x).pipe(It("HTTP request failed")),"executeRead"),a=r(x=>s.execute(x).pipe(It("HTTP request failed")),"executeReadOk"),c=r(x=>x.pipe(ge.flatMap(E=>o.execute(E)),It("HTTP request failed")),"executeEffectOk"),l=r(x=>x.pipe(ge.flatMap(E=>t.execute(E)),It("HTTP request failed")),"executeEffect"),f=ge.fnUntraced(function*(x){let E=yield*Ks.currentTimeMillis,y=yield*c(Ue.post(`${x.url}/auth/device/token`).pipe(Ue.acceptJson,Ue.schemaBodyJson(Qs)(new Qs({grant_type:"refresh_token",refresh_token:x.refresh_token,client_id:Ga})))),S=yield*Fn.schemaBodyJson(Ja)(y).pipe(It("Failed to decode response")),v=Ce.some(E+qn.toMillis(S.expires_in));return yield*e.persistToken({accountID:x.id,accessToken:S.access_token,refreshToken:S.refresh_token,expiry:v}),S.access_token}),g=yield*Jp.make({capacity:Number.POSITIVE_INFINITY,timeToLive:qn.zero,lookup:ge.fnUntraced(function*(x){let E=yield*e.getRow(x);if(Ce.isNone(E))return yield*ge.fail(new Rt({message:"Account not found during token refresh"}));let y=E.value,S=yield*Ks.currentTimeMillis;return Xp(y.token_expiry,S)?y.access_token:yield*f(y)})}),d=ge.fnUntraced(function*(x){let E=yield*Ks.currentTimeMillis;return Xp(x.token_expiry,E)?x.access_token:yield*Jp.get(g,x.id)}),h=ge.fnUntraced(function*(x){let E=yield*e.getRow(x);if(Ce.isNone(E))return Ce.none();let y=E.value,S=yield*d(y);return Ce.some({account:y,accessToken:S})}),b=ge.fnUntraced(function*(x,E){let y=yield*a(Ue.get(`${x}/api/orgs`).pipe(Ue.acceptJson,Ue.bearerToken(E)));return yield*Fn.schemaBodyJson(pe.Array(Oo))(y).pipe(It("Failed to decode response"))}),_=ge.fnUntraced(function*(x,E){let y=yield*a(Ue.get(`${x}/api/user`).pipe(Ue.acceptJson,Ue.bearerToken(E)));return yield*Fn.schemaBodyJson(za)(y).pipe(It("Failed to decode response"))}),P=ge.fn("Account.token")(x=>h(x).pipe(ge.map(Ce.map(E=>E.accessToken)))),C=ge.fn("Account.activeOrg")(function*(){let x=yield*e.active();if(Ce.isNone(x))return Ce.none();let E=x.value;if(!E.active_org_id)return Ce.none();let S=(yield*te(E.id)).find(v=>v.id===E.active_org_id);return S?Ce.some({account:E,org:S}):Ce.none()}),J=ge.fn("Account.orgsByAccount")(function*(){let x=yield*e.list();return yield*ge.forEach(x,E=>te(E.id).pipe(ge.catch(()=>ge.succeed([])),ge.map(y=>({account:E,orgs:y}))),{concurrency:3})}),te=ge.fn("Account.orgs")(function*(x){let E=yield*h(x);if(Ce.isNone(E))return[];let{account:y,accessToken:S}=E.value;return yield*b(y.url,S)}),L=ge.fn("Account.remove")(function*(x){let E=yield*e.active();if(yield*e.remove(x),Ce.isNone(E)||E.value.id!==x)return;let y=(yield*J()).flatMap(S=>S.orgs.map(v=>({accountID:S.account.id,orgID:v.id})))[0];y&&(yield*e.use(y.accountID,Ce.some(y.orgID)))}),G=ge.fn("Account.config")(function*(x,E){let y=yield*h(x);if(Ce.isNone(y))return Ce.none();let{account:S,accessToken:v}=y.value,O=yield*i(Ue.get(`${S.url}/api/config`).pipe(Ue.acceptJson,Ue.bearerToken(v),Ue.setHeaders({"x-org-id":E})));if(O.status===404)return Ce.none();let Q=yield*Fn.filterStatusOk(O).pipe(It()),ae=yield*Fn.schemaBodyJson(Ha)(Q).pipe(It("Failed to decode response"));return Ce.some(ae.config)}),K=ge.fn("Account.login")(function*(x){let E=Js(x),y=yield*c(Ue.post(`${E}/auth/device/code`).pipe(Ue.acceptJson,Ue.schemaBodyJson(Ys)(new Ys({client_id:Ga})))),S=yield*Fn.schemaBodyJson(Ka)(y).pipe(It("Failed to decode response")),v=yield*ge.try({try:r(()=>{let O=new URL(S.verification_uri_complete,`${E}/`);if(O.protocol!=="http:"&&O.protocol!=="https:")throw new Error("expected HTTP(S)");return O.href},"try"),catch:r(O=>new Rt({message:"Invalid device verification URL",cause:O}),"catch")});return new Co({code:S.device_code,user:S.user_code,url:v,server:E,expiry:S.expires_in,interval:S.interval})}),Me=ge.fn("Account.poll")(function*(x){let E=yield*l(Ue.post(`${x.server}/auth/device/token`).pipe(Ue.acceptJson,Ue.schemaBodyJson(Zs)(new Zs({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:x.code,client_id:Ga})))),y=yield*Fn.schemaBodyJson(Mh)(E).pipe(It("Failed to decode response"));if(y instanceof zs)return y.toPollResult();let S=y.access_token,v=_(x.server,S),O=b(x.server,S),[Q,ae]=yield*ge.all([v,O],{concurrency:2}),ue=ae.length>0?Ce.some(ae[0].id):Ce.none(),Ze=(yield*Ks.currentTimeMillis)+qn.toMillis(y.expires_in),ir=y.refresh_token;return yield*e.persistAccount({id:Q.id,email:Q.email,url:x.server,accessToken:S,refreshToken:ir,expiry:Ze,orgID:ue}),new Mn({email:Q.email})});return Vn.of({active:e.active,activeOrg:C,list:e.list,orgsByAccount:J,remove:L,use:e.use,orgs:te,config:G,token:P,login:K,poll:Me})})),Bh=xe.make({service:Vn,layer:Uh,deps:[No.node,ws]});var Uo={};R(Uo,{Api:()=>ni,Auth:()=>Uo,AuthError:()=>ri,Info:()=>zp,OAUTH_DUMMY_KEY:()=>Hh,Oauth:()=>ti,Service:()=>$o,WellKnown:()=>oi,node:()=>Kh});import Fh from"path";import{Effect as gt,Layer as qh,Record as Vh,Result as Wh,Schema as Se,Context as Gh}from"effect";var Hh="opencode-oauth-dummy-key",ei=Fh.join(he.Path.globalData,"auth.json"),Ya=r(e=>t=>new ri({message:e,cause:t}),"fail"),ti=class extends Se.Class("OAuth")({type:Se.Literal("oauth"),refresh:Se.String,access:Se.String,expires:it,accountId:Se.optional(Se.String),enterpriseUrl:Se.optional(Se.String)}){static{r(this,"Oauth")}},ni=class extends Se.Class("ApiAuth")({type:Se.Literal("api"),key:Se.String,metadata:Se.optional(Se.Record(Se.String,Se.String))}){static{r(this,"Api")}},oi=class extends Se.Class("WellKnownAuth")({type:Se.Literal("wellknown"),key:Se.String,token:Se.String}){static{r(this,"WellKnown")}},zp=Se.Union([ti,ni,oi]).annotate({discriminator:"type",identifier:"Auth"}),ri=class extends Se.TaggedErrorClass()("AuthError",{message:Se.String,cause:Se.optional(Se.Defect())}){static{r(this,"AuthError")}},$o=class extends Gh.Service()("@opencode/Auth"){static{r(this,"Service")}},Jh=qh.effect($o,gt.gen(function*(){let e=yield*de.Service,t=Se.decodeUnknownOption(zp),n=gt.fn("Auth.all")(function*(){if(process.env.OPENCODE_AUTH_CONTENT)try{return JSON.parse(process.env.OPENCODE_AUTH_CONTENT)}catch{}let c=yield*e.readJson(ei).pipe(gt.orElseSucceed(()=>({})));return Vh.filterMap(c,l=>Wh.fromOption(t(l),()=>{}))}),o=gt.fn("Auth.rawAll")(function*(){return yield*e.readJson(ei).pipe(gt.catchIf(c=>c?.reason?._tag==="NotFound"||c?.cause?.reason?._tag==="NotFound",()=>gt.succeed({})),gt.mapError(Ya("Refusing to write auth data: existing auth.json could not be read")))}),s=gt.fn("Auth.get")(function*(c){return(yield*n())[c]}),i=gt.fn("Auth.set")(function*(c,l){let f=c.replace(/\/+$/,""),g=yield*o();f!==c&&delete g[c],delete g[f+"/"],yield*e.writeJson(ei,{...g,[f]:l},384).pipe(gt.mapError(Ya("Failed to write auth data")))}),a=gt.fn("Auth.remove")(function*(c){let l=c.replace(/\/+$/,""),f=yield*o();delete f[c],delete f[l],yield*e.writeJson(ei,f,384).pipe(gt.mapError(Ya("Failed to write auth data")))});return $o.of({get:s,all:n,set:i,remove:a})})),Kh=xe.make({service:$o,layer:Jh,deps:[de.node]});var ze={};R(ze,{InstanceState:()=>ze,context:()=>ec,directory:()=>ii,get:()=>tc,has:()=>tS,invalidate:()=>nS,make:()=>Zh,use:()=>Qh,useEffect:()=>eS,workspaceID:()=>Yh});import{Effect as rt,ScopedCache as Ur}from"effect";import{Context as Yp}from"effect";var jr=Yp.Reference("~opencode/InstanceRef",{defaultValue:r(()=>{},"defaultValue")}),$r=Yp.Reference("~opencode/WorkspaceRef",{defaultValue:r(()=>{},"defaultValue")});var Za=new Set;function Zp(e){return Za.add(e),()=>{Za.delete(e)}}r(Zp,"registerDisposer");async function cO(e){await Promise.allSettled([...Za].map(t=>t(e)))}r(cO,"disposeInstance");var Wn={};R(Wn,{LocalContext:()=>Wn,NotFound:()=>si,create:()=>zh});import{AsyncLocalStorage as Xh}from"async_hooks";var si=class extends Error{constructor(n){super(`No context found for ${n}`);this.name=n}name;static{r(this,"NotFound")}};function zh(e){let t=new Xh;return{use(){let n=t.getStore();if(!n)throw new si(e);return n},provide(n,o){return t.run(n,o)}}}r(zh,"create");var Qa=Wn.create("instance"),Qp={async provide(e){return Qa.provide({workspaceID:e.workspaceID},()=>e.fn())},restore(e,t){return Qa.provide({workspaceID:e},t)},get workspaceID(){try{return Qa.use().workspaceID}catch{return}}};var eu="~opencode/InstanceState",ec=rt.gen(function*(){let e=yield*jr;return e||(yield*rt.die(new Error("InstanceRef not provided")))}),Yh=rt.gen(function*(){return(yield*$r)??Qp.workspaceID}),ii=rt.map(ec,e=>e.directory),Zh=r(e=>rt.gen(function*(){let t=yield*Ur.make({capacity:Number.POSITIVE_INFINITY,lookup:r(()=>rt.gen(function*(){return yield*e(yield*ec)}),"lookup")}),n=Zp(o=>rt.runPromise(Ur.invalidate(t,o)));return yield*rt.addFinalizer(()=>rt.sync(n)),{[eu]:eu,cache:t}}),"make"),tc=r(e=>rt.gen(function*(){return yield*Ur.get(e.cache,yield*ii)}),"get"),Qh=r((e,t)=>rt.map(tc(e),t),"use"),eS=r((e,t)=>rt.flatMap(tc(e),t),"useEffect"),tS=r(e=>rt.gen(function*(){return yield*Ur.has(e.cache,yield*ii)}),"has"),nS=r(e=>rt.gen(function*(){return yield*Ur.invalidate(e.cache,yield*ii)}),"invalidate");function be(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}r(be,"isRecord");function Br(e){if(e instanceof Error)return e.stack??`${e.name}: ${e.message}`;if(typeof e=="object"&&e!==null)try{let t=JSON.stringify(e,null,2);if(t==="{}"){let n=String(e);if(n&&n!=="[object Object]")return n;let o=e.constructor?.name,s=o&&o!=="Object"?o:"Error",i=Object.getOwnPropertyNames(e);return i.length===0?`${s} (no message)`:`${s} { ${i.join(", ")} }`}return t}catch{return"Unexpected error (unserializable)"}return String(e)}r(Br,"errorFormat");function Fr(e){if(e instanceof Error){if(e.message)return e.message;if(e.name)return e.name}if(be(e)&&typeof e.message=="string"&&e.message)return e.message;if(be(e)&&be(e.data)&&typeof e.data.message=="string"&&e.data.message)return e.data.message;let t=String(e);if(t&&t!=="[object Object]")return t;let n=Br(e);return n||"unknown error"}r(Fr,"errorMessage");function kO(e){if(e instanceof Error)return{type:e.name,message:Fr(e),stack:e.stack,cause:e.cause===void 0?void 0:Br(e.cause),formatted:Br(e)};if(!be(e))return{type:typeof e,message:Fr(e),formatted:Br(e)};let t=Object.getOwnPropertyNames(e).reduce((n,o)=>{let s=e[o];return s===void 0?n:typeof s=="string"||typeof s=="number"||typeof s=="boolean"?(n[o]=s,n):(n[o]=s instanceof Error?s.message:String(s),n)},{});return typeof t.message!="string"&&(t.message=Fr(e)),typeof t.type!="string"&&(t.type=e.constructor?.name),t.formatted=Br(e),t}r(kO,"errorData");var Pc={};R(Pc,{Config:()=>Pc,Service:()=>Zn,node:()=>Mv,use:()=>Rv});import dt from"path";import{pathToFileURL as vv}from"url";import wv from"os";import{mergeDeep as Mt}from"remeda";import Gu from"fs/promises";var Bo={};R(Bo,{Env:()=>Bo,Service:()=>Hn,node:()=>aS,use:()=>sS});import{Context as oS,Effect as Gn,Layer as rS}from"effect";var Hn=class extends oS.Service()("@opencode/Env"){static{r(this,"Service")}},sS=Yt(Hn),iS=rS.effect(Hn,Gn.gen(function*(){let e=yield*ze.make(Gn.fn("Env.state")(()=>Gn.succeed({...process.env}))),t=Gn.fn("Env.get")(i=>ze.use(e,a=>a[i])),n=Gn.fn("Env.all")(()=>ze.get(e)),o=Gn.fn("Env.set")(function*(i,a){let c=yield*ze.get(e);c[i]=a}),s=Gn.fn("Env.remove")(function*(i){let a=yield*ze.get(e);delete a[i]});return Hn.of({get:t,all:n,set:o,remove:s})})),aS=xe.make({service:Hn,layer:iS,deps:[]});import{applyEdits as Ev,modify as Iv}from"jsonc-parser";import{existsSync as xi}from"fs";import{Context as kv,Duration as bv,Effect as D,Exit as Dv,Fiber as Tv,Layer as _v,Option as Si,Schema as Rc}from"effect";import{HttpClient as Hu,HttpClientRequest as Cc}from"effect/unstable/http";var $O=Wn.create("instance");function tu(e,t){return de.contains(t.directory,e)?!0:t.worktree==="/"?!1:de.contains(t.worktree,e)}r(tu,"containsPath");var rc={};R(rc,{ConfigErrorV1:()=>rc,DirectoryTypoError:()=>lS,FrontmatterError:()=>ai,InvalidError:()=>Ct,JsonError:()=>nc,RemoteAuthError:()=>oc});import{Schema as we}from"effect";var cS=we.StructWithRest(we.Struct({message:we.String,path:we.Array(we.String)}),[we.Record(we.String,we.Unknown)]),nc=We.create("ConfigJsonError",{path:we.String,message:we.optional(we.String)}),Ct=We.create("ConfigInvalidError",{path:we.String,issues:we.optional(we.Array(cS)),message:we.optional(we.String)}),ai=We.create("ConfigFrontmatterError",{path:we.String,message:we.String}),lS=We.create("ConfigDirectoryTypoError",{path:we.String,dir:we.String,suggestion:we.String}),oc=We.create("ConfigRemoteAuthError",{url:we.String,remote:we.String});var Kn={};R(Kn,{ConfigAgent:()=>Kn,load:()=>zS,loadAlchemy:()=>YS,loadMode:()=>ZS});import dc from"path";import{readFile as JS}from"fs/promises";import{Exit as KS,Schema as XS}from"effect";import nu from"path";function dS(e,t){let n=e.replaceAll("\\","/");for(let o of t)if(n.startsWith(o))return n.slice(o.length)}r(dS,"stripPrefix");function qr(e,t){let n=dS(e,t)??nu.basename(e),o=nu.extname(n);return o.length?n.slice(0,-o.length):n}r(qr,"configEntryNameFromPath");var Gr={};R(Gr,{ConfigMarkdown:()=>Gr,FILE_REGEX:()=>mu,SHELL_REGEX:()=>gu,fallbackSanitization:()=>US,files:()=>jS,parse:()=>Fo,parseText:()=>lc,shell:()=>$S});var Je={};R(Je,{Filesystem:()=>Je,contains:()=>CS,exists:()=>ic,findUp:()=>PS,globUp:()=>LS,isDir:()=>SS,mimeType:()=>TS,normalizePath:()=>Vr,normalizePathPattern:()=>_S,overlaps:()=>RS,readArrayBuffer:()=>kS,readBytes:()=>IS,readJson:()=>ES,readText:()=>wS,resolve:()=>AS,resolveFilePath:()=>OS,size:()=>vS,stat:()=>lu,statAsync:()=>xS,up:()=>MS,windowsPath:()=>cc,write:()=>du,writeJson:()=>bS,writeStream:()=>DS});import{chmod as pS,mkdir as ru,readFile as li,stat as uS,writeFile as ci}from"fs/promises";import{createWriteStream as fS,existsSync as su,statSync as iu}from"fs";import{realpathSync as au}from"fs";import{dirname as Wr,isAbsolute as mS,join as sc,resolve as cu,win32 as ou}from"path";import{Readable as gS}from"stream";import{pipeline as yS}from"stream/promises";import{fileURLToPath as hS}from"url";async function ic(e){return su(e)}r(ic,"exists");async function SS(e){try{return iu(e).isDirectory()}catch{return!1}}r(SS,"isDir");function lu(e){return iu(e,{throwIfNoEntry:!1})??void 0}r(lu,"stat");async function xS(e){return uS(e).catch(t=>{if(!ac(t))throw t})}r(xS,"statAsync");async function vS(e){let t=lu(e)?.size??0;return typeof t=="bigint"?Number(t):t}r(vS,"size");async function wS(e){return li(e,"utf-8")}r(wS,"readText");async function ES(e){return JSON.parse(await li(e,"utf-8"))}r(ES,"readJson");async function IS(e){return li(e)}r(IS,"readBytes");async function kS(e){let t=await li(e);return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}r(kS,"readArrayBuffer");function ac(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}r(ac,"isEnoent");async function du(e,t,n){pr.assert(e,"write");try{n?await ci(e,t,{mode:n}):await ci(e,t)}catch(o){if(ac(o)){await ru(Wr(e),{recursive:!0}),n?await ci(e,t,{mode:n}):await ci(e,t);return}throw o}}r(du,"write");async function bS(e,t,n){return du(e,JSON.stringify(t,null,2),n)}r(bS,"writeJson");async function DS(e,t,n){pr.assert(e,"write");let o=Wr(e);su(o)||await ru(o,{recursive:!0});let s=t instanceof ReadableStream?gS.fromWeb(t):t,i=fS(e);await yS(s,i),n&&await pS(e,n)}r(DS,"writeStream");async function TS(e){let{lookup:t}=await import("mime-types");return t(e)||"application/octet-stream"}r(TS,"mimeType");function Vr(e){if(process.platform!=="win32")return e;let t=ou.normalize(ou.resolve(cc(e)));try{return au.native(t)}catch{return t}}r(Vr,"normalizePath");function _S(e){if(process.platform!=="win32"||e==="*")return e;let t=e.match(/^(.*)[\\/]\*$/);if(!t)return Vr(e);let n=/^[A-Za-z]:$/.test(t[1])?t[1]+"\\":t[1];return sc(Vr(n),"*")}r(_S,"normalizePathPattern");function AS(e){let t=cu(cc(e));try{return Vr(au(t))}catch(n){if(ac(n))return Vr(t);throw n}}r(AS,"resolve");function OS(e,t){let n=t.startsWith("file://")?hS(t):t;return mS(n)?n:cu(e,n)}r(OS,"resolveFilePath");function cc(e){return process.platform!=="win32"?e:e.replace(/^\/([a-zA-Z]):(?:[\\/]|$)/,(t,n)=>`${n.toUpperCase()}:/`).replace(/^\/([a-zA-Z])(?:\/|$)/,(t,n)=>`${n.toUpperCase()}:/`).replace(/^\/cygdrive\/([a-zA-Z])(?:\/|$)/,(t,n)=>`${n.toUpperCase()}:/`).replace(/^\/mnt\/([a-zA-Z])(?:\/|$)/,(t,n)=>`${n.toUpperCase()}:/`)}r(cc,"windowsPath");function RS(e,t){return de.overlaps(e,t)}r(RS,"overlaps");function CS(e,t){return de.contains(e,t)}r(CS,"contains");async function PS(e,t,n,o){let s=[t],i=t;for(;n!==i;){let l=Wr(i);if(l===i)break;s.push(l),i=l}let a=Array.isArray(e)?e:[e],c=[];for(let l of o?.rootFirst?s.toReversed():s)for(let f of a){let g=sc(l,f);await ic(g)&&c.push(g)}return c}r(PS,"findUp");async function*MS(e){let{targets:t,start:n,stop:o}=e,s=n;for(;;){for(let a of t){let c=sc(s,a);await ic(c)&&(yield c)}if(o===s)break;let i=Wr(s);if(i===s)break;s=i}}r(MS,"up");async function LS(e,t,n){let o=t,s=[];for(;;){try{let a=await Ut.scan(e,{cwd:o,absolute:!0,include:"file",dot:!0});s.push(...a)}catch{}if(n===o)break;let i=Wr(o);if(i===o)break;o=i}return s}r(LS,"globUp");var Jn={};R(Jn,{ConfigMarkdown:()=>Jn,parse:()=>uu,parseOption:()=>NS,sanitize:()=>fu});import pu from"gray-matter";function uu(e){try{return pu(e)}catch{return pu(fu(e))}}r(uu,"parse");function NS(e){try{return uu(e)}catch{return}}r(NS,"parseOption");function fu(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return e;let n=t[1],o=n.split(/\r?\n/).flatMap(s=>{if(s.trim().startsWith("#")||s.trim()===""||/^\s+/.test(s))return[s];let i=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*:\s*(.*)$/);if(!i)return[s];let a=i[2].trim();return a===""||a===">"||a==="|"||a.startsWith('"')||a.startsWith("'")?[s]:a.includes(":")?[`${i[1]}: |-`,` ${a}`]:[s]});return e.replace(n,()=>o.join(`
662
+ `))}r(fu,"sanitize");var mu=/(?<![\w`])@(\.?[^\s`,.]*(?:\.[^\s`,.]+)*)/g,gu=/!`([^`]+)`/g;function jS(e){return Array.from(e.matchAll(mu))}r(jS,"files");function $S(e){return Array.from(e.matchAll(gu))}r($S,"shell");var US=Jn.sanitize;async function Fo(e){let t=await Je.readText(e);try{return Jn.parse(t)}catch(n){throw new ai({path:e,message:`${e}: Failed to parse YAML frontmatter: ${n instanceof Error?n.message:String(n)}`},{cause:n})}}r(Fo,"parse");function lc(e,t){try{return Jn.parse(e)}catch(n){throw new ai({path:t,message:`${t}: Failed to parse YAML frontmatter: ${n instanceof Error?n.message:String(n)}`},{cause:n})}}r(lc,"parseText");var lt={};R(lt,{ConfigParse:()=>lt,jsonc:()=>GS,schema:()=>HS});import{parse as BS,printParseErrorCode as FS}from"jsonc-parser";import{Cause as qS,Exit as VS,Schema as yu,SchemaIssue as WS}from"effect";function GS(e,t){let n=[],o=BS(e,n,{allowTrailingComma:!0});if(n.length){let s=e.split(`
663
+ `),i=n.map(a=>{let c=e.substring(0,a.offset).split(`
664
+ `),l=c.length,f=c[c.length-1].length+1,g=s[l-1],d=`${FS(a.error)} at line ${l}, column ${f}`;return g?`${d}
665
+ Line ${l}: ${g}
666
+ ${"".padStart(f+9)}^`:d}).join(`
667
+ `);throw new nc({path:t,message:`
668
+ --- JSONC Input ---
669
+ ${e}
670
+ --- Errors ---
671
+ ${i}
672
+ --- End ---`})}return o}r(GS,"jsonc");function HS(e,t,n){let o=yu.decodeUnknownExit(e)(t,{errors:"all",onExcessProperty:"ignore",propertyOrder:"original"});if(VS.isSuccess(o))return o.value;let s=qS.squash(o.cause);throw new Ct({path:n,issues:yu.isSchemaError(s)?WS.makeFormatterStandardSchemaV1()(s.issue).issues.map(i=>({...i,message:i.message,path:i.path?.map(String)??[]})):[{message:String(s),path:[]}]},{cause:s})}r(HS,"schema");async function zS(e){let t={};for(let n of await Ut.scan("{agent,agents}/**/*.md",{cwd:e,absolute:!0,dot:!0,symlink:!0})){let o=await Fo(n).catch(()=>{});if(!o)continue;let i={name:qr(dc.relative(e,n),["agent/","agents/"]),...o.data,prompt:o.content.trim()};t[i.name]=lt.schema(ks.Info,i,n)}return t}r(zS,"load");async function YS(e,t){let n={},o=dc.join(e,".alchemy_lab","action-server.json"),s,i;for(let c=0;c<20&&!s;c++)try{let l=JSON.parse(await JS(o,"utf8"));l?.port&&(s=l.port),typeof l?.secret=="string"&&(i=l.secret)}catch{await new Promise(l=>setTimeout(l,500))}if(!s)return t("alchemy agents: no action-server.json; agents unavailable until config reload"),n;let a=[];try{let c=await fetch(`http://127.0.0.1:${s}/api/agents/markdown`,{signal:AbortSignal.timeout(8e3),headers:i?{"x-alchemy-local":i}:{}});if(!c.ok)throw new Error(`HTTP ${c.status}`);a=(await c.json()).data??[]}catch(c){return t("alchemy agents: fetch failed",{port:s,err:String(c)}),n}for(let c of a)try{let l=lc(c.markdown,`alchemy agent ${c.name}`),f={name:c.name,...l.data,prompt:l.content.trim()};n[c.name]=lt.schema(ks.Info,f,`alchemy agent ${c.name}`)}catch(l){t("invalid alchemy agent",{agent:c.name,err:String(l)})}return n}r(YS,"loadAlchemy");async function ZS(e){let t={};for(let n of await Ut.scan("{mode,modes}/*.md",{cwd:e,absolute:!0,dot:!0,symlink:!0})){let o=await Fo(n).catch(()=>{});if(!o)continue;let s={name:qr(dc.relative(e,n),["mode/","modes/"]),...o.data,prompt:o.content.trim()},i=XS.decodeUnknownExit(ks.Info)(s,{errors:"all",propertyOrder:"original"});KS.isSuccess(i)&&(t[s.name]={...i.value,mode:"primary"})}return t}r(ZS,"loadMode");var Kr={};R(Kr,{AnthropicCompaction:()=>Kr,BETA:()=>uc,HEADER:()=>fc,IDENTITY:()=>Hr,LOG:()=>wu,METADATA_KEY:()=>vu,THINKING_BETA:()=>xu,configure:()=>ox,cut:()=>ix,hasBlock:()=>_u,log:()=>mc,newest:()=>pi,newestStored:()=>hx,on:()=>gc,put:()=>lx,relocate:()=>mx,remember:()=>ax,restoreBlocks:()=>Au,send:()=>fx,shape:()=>Ou,stored:()=>ku,storedOf:()=>Jr,supports:()=>Iu,supportsID:()=>yc,take:()=>cx,validCut:()=>Tu,view:()=>yx,withSystem:()=>gx});import{mkdirSync as QS,writeFileSync as ex}from"node:fs";import tx from"node:path";var uc="compact-2026-09-04",xu="thinking-binding-controls-2026-08-01",fc="x-alchemylab-anthropic-compaction",vu="anthropicCompaction",wu="anthcomp",Hr="You are Claude Code, Anthropic's official CLI for Claude.",nx=new Set(["claude-fable-5-1","claude-mythos-5-1","claude-fable-5","claude-mythos-5","claude-mythos-preview","claude-opus-5-5","claude-opus-5","claude-opus-4-8","claude-opus-4-7","claude-opus-4-6","claude-sonnet-5-5","claude-sonnet-5","claude-sonnet-4-6","claude-haiku-5-5"]),Eu=!1;function ox(e){Eu=e.compaction?.anthropic===!0}r(ox,"configure");function gc(){return le.ALCHEMYLAB_ANTHROPIC_COMPACTION??Eu}r(gc,"on");function yc(e){return typeof e!="string"?!1:nx.has(e.replace(/-\d{8}$/,""))}r(yc,"supportsID");function Iu(e){return e.api.npm==="@ai-sdk/anthropic"&&yc(e.api.id)}r(Iu,"supports");function mc(e,t){try{process.stderr.write(`level=INFO service=session.anthropic-compaction message=${JSON.stringify(`${wu} ${e}`)} ${JSON.stringify(t??{})}
673
+ `)}catch{}}r(mc,"log");function ku(e){if(!e||e.type!=="text")return;let t=e.metadata?.[vu];if(!(!t||typeof t!="object"||t.block?.type!=="compaction")&&typeof t.block.content=="string")return t}r(ku,"stored");function Jr(e){if(!(e.info.role!=="assistant"||!e.info.summary))for(let t of e.parts){let n=ku(t);if(n&&t.type==="text")return{part:t,value:n}}}r(Jr,"storedOf");var bu=r(e=>e.parts.some(t=>t.type==="tool"),"hasTools"),Du=r(e=>e.info.role==="user"&&e.parts.some(t=>t.type==="compaction"),"isCompactionUser");function pc(e){let t=e.info;return t.role!=="assistant"||t.summary||t.aside||t.error||!t.finish?!1:e.parts.some(n=>n.type==="text"||n.type==="reasoning"||n.type==="tool")}r(pc,"cleanStep");function hu(e){return e.info.role!=="user"||Du(e)?!1:e.parts.some(t=>t.type==="text"&&!t.ignored&&t.text!==""||t.type==="file"&&t.mime!=="text/plain")}r(hu,"realUser");function rx(e){if(!bu(e))return!1;let t;for(let n of e.parts)(n.type==="text"||n.type==="reasoning"||n.type==="tool")&&(t=n);return!t||t.type!=="tool"?!1:e.parts.every(n=>n.type!=="tool"||n.state.status==="completed"||n.state.status==="error")}r(rx,"endsOnResults");function sx(e){if(bu(e))return!1;let n=e.parts.filter(o=>o.type==="text"&&o.text!=="").at(-1);return!!n&&n.text===n.text.trimEnd()}r(sx,"endsOnText");function Tu(e,t){if(t<=0||t>=e.length)return!1;let n=e[t],o=e[t-1];return hu(n)?pc(o)&&sx(o):pc(n)?hu(o)||pc(o)&&rx(o):!1}r(Tu,"validCut");function ix(e,t,n){if(n<=0||e.length<2)return;let o=e.filter(f=>f.info.role==="assistant"&&f.info.summary),s=pi(o),i=s?e.indexOf(s)+2:1,a=e.flatMap((f,g)=>f.info.role==="user"&&!Du(f)?[g]:[]),c=Math.max(i,a.length>=2?a[a.length-2]:0,1),l=new Array(e.length+1).fill(0);for(let f=e.length-1;f>=0;f--)l[f]=l[f+1]+(t[f]??0);for(let f=c;f<e.length;f++)if(!(l[f]>n)&&Tu(e,f))return{index:f,id:e[f].info.id,tokens:l[f]}}r(ix,"cut");var qo=new Map;function ax(e){for(qo.delete(e.content),qo.set(e.content,e);qo.size>256;)qo.delete(qo.keys().next().value)}r(ax,"remember");function _u(e){let t=e.find(o=>o.role!=="system");if(!t||t.role!=="assistant"||!Array.isArray(t.content))return!1;let n=t.content[0];return n?.type==="text"&&n.providerOptions?.anthropic?.type==="compaction"}r(_u,"hasBlock");function Au(e){let t=0,n=0;if(!Array.isArray(e?.messages))return{restored:t,missing:n};for(let s of e.messages)Array.isArray(s?.content)&&(s.content=s.content.map(i=>{if(i?.type!=="compaction"||i.signature!==void 0)return i;let a=qo.get(i.content);return a?(t++,{...a,...i.cache_control?{cache_control:i.cache_control}:{}}):(n++,i)}));let o=e.messages[0];return o?.role==="assistant"&&Array.isArray(o.content)&&o.content[0]?.type==="compaction"&&o.content.length>1&&e.messages.splice(0,1,{role:"assistant",content:[o.content[0]]},{...o,content:o.content.slice(1)}),{restored:t,missing:n}}r(Au,"restoreBlocks");var di=new Map;function cx(e){let t=di.get(e);return di.delete(e),t}r(cx,"take");function lx(e,t){di.set(e,t)}r(lx,"put");function Su(e,t){for(let n of t.split(`
674
+ `)){if(!n.startsWith("data:"))continue;let o;try{o=JSON.parse(n.slice(5).trim())}catch{continue}o?.type==="message_start"&&(Array.isArray(o.message?.input_transformations)&&(e.inputTransformations=o.message.input_transformations),e.usage=o.message?.usage??e.usage),o?.type==="content_block_start"&&o.content_block?.type==="compaction"&&(e.block=o.content_block),o?.type==="message_delta"&&(e.stopReason=o.delta?.stop_reason??e.stopReason,o.usage&&(e.usage={...e.usage,...o.usage})),o?.type==="error"&&(e.error=JSON.stringify(o.error??o).slice(0,1e3))}}r(Su,"readEvent");function dx(e,t){let n={status:e.status};if(di.set(t,n),!e.ok)return e.clone().text().then(a=>n.error=a.slice(0,2e3)).catch(()=>{}),e;if(!e.body)return e;if(!(e.headers.get("content-type")??"").includes("event-stream"))return e.clone().json().then(a=>{n.block=(a?.content??[]).find(c=>c?.type==="compaction"),n.stopReason=a?.stop_reason,n.usage=a?.usage,n.inputTransformations=a?.input_transformations}).catch(()=>{}),e;let o=new TextDecoder,s="",i=new TransformStream({transform(a,c){s+=o.decode(a,{stream:!0});let l;for(;(l=s.indexOf(`
675
+
676
+ `))!==-1;)Su(n,s.slice(0,l)),s=s.slice(l+2);c.enqueue(a)},flush(){s&&Su(n,s)}});return new Response(e.body.pipeThrough(i),{status:e.status,statusText:e.statusText,headers:e.headers})}r(dx,"capture");function px(e){let t={};if(!e)return t;if(e instanceof Headers)e.forEach((n,o)=>t[o]=n);else if(Array.isArray(e))for(let[n,o]of e)t[String(n)]=String(o);else for(let[n,o]of Object.entries(e))o!==void 0&&(t[n]=String(o));return t}r(px,"headerRecord");function Ou(e){let t=r(s=>Array.isArray(s)?s.map(i=>i?.type+(i?.type==="compaction"&&i.signature?"+sig":"")).join(","):"text","kinds"),n=Array.isArray(e?.system)?e.system.length:e?.system?1:0,o=(e?.messages??[]).map(s=>`${s.role}[${t(s.content)}]`);return`system:${n} `+o.join(" ")}r(Ou,"shape");function ux(e,t){let n=process.env.ALCHEMYLAB_ANTHROPIC_COMPACTION_DUMP;if(n)try{QS(n,{recursive:!0}),ex(tx.join(n,`${Date.now()}-${Math.random().toString(36).slice(2,6)}-${e}.json`),JSON.stringify(t,null,1))}catch{}}r(ux,"dump");async function fx(e,t,n){if(!gc()||typeof n?.body!="string"||n?.method!=="POST")return e(t,n);let o;try{o=JSON.parse(n.body)}catch{return e(t,n)}if(!yc(o?.model)||!Array.isArray(o?.messages))return e(t,n);let s=px(n.headers),i=s[fc];delete s[fc];let a=Object.keys(s).find(b=>b.toLowerCase()==="anthropic-beta")??"anthropic-beta",c=new Set((s[a]??"").split(",").map(b=>b.trim()).filter(Boolean)),{restored:l,missing:f}=Au(o);(l||f)&&c.add(uc),i&&(o.compaction={type:"summarize"},c.add(uc),delete o.stop_sequences,delete o.context_management,o.tool_choice&&(o.tool_choice.type==="any"||o.tool_choice.type==="tool")&&delete o.tool_choice,o.output_config&&(delete o.output_config.format,delete o.output_config.task_budget));let g=o.thinking;g&&(g.type==="adaptive"||g.type==="enabled")&&(g.block_binding||(g.block_binding={prefix_mismatch_behavior:"drop_block"}),c.add(xu)),s[a]=[...c].join(","),mc(i?"compaction request":"request",{model:o.model,shape:Ou(o),restored:l,missing:f,thinking:o.thinking}),f&&mc("block without its signature",{missing:f});let d={...n,body:JSON.stringify(o),headers:s};ux(i?"compaction-request":"request",o);let h=await e(t,d);return i?dx(h,i):h}r(fx,"send");function mx(e){if(!_u(e.messages))return;let t=[],n=[];for(let l of e.system)if(l===Hr)t.push(l);else if(l.startsWith(Hr)){t.push(Hr);let f=l.slice(Hr.length).replace(/^\n+/,"");f&&n.push(f)}else l&&n.push(l);if(t.length===0)return;let o=n.join(`
677
+
678
+ `),s=e.messages.findLast(l=>l.role==="system"),i=s&&typeof s.content=="string"?s.content:void 0;if(!o||o===i||e.append===!1)return{system:t,messages:e.messages};let a=e.messages.length;for(;a>0&&e.messages[a-1].role==="assistant";)a--;let c=[...e.messages.slice(0,a),{role:"system",content:o},...e.messages.slice(a)];return{system:t,messages:c,added:o}}r(mx,"relocate");function gx(e,t){return{...e,system:[...e.system??[],t]}}r(gx,"withSystem");function yx(e,t){if(!gc()||!Iu(t))return;let n={blocks:new Map,drop:new Set,skip:new Set,after:new Map},o=e.filter(i=>i.info.role!=="assistant"||!i.info.summary||!i.info.finish||i.info.error||i.info.providerID!==t.providerID||i.info.modelID!==t.id?!1:!!Jr(i)),s=pi(o);if(s){for(let i of o){let a=Jr(i);i===s?n.blocks.set(i.info.id,a.value.block):n.drop.add(i.info.id),i.info.role==="assistant"&&n.skip.add(i.info.parentID);for(let c of a.value.system??[])n.after.set(c.after,[...n.after.get(c.after)??[],c.text])}return n}}r(yx,"view");function pi(e){let t;for(let n of e)t?(n.info.time.created>t.info.time.created||n.info.time.created===t.info.time.created&&n.info.id>t.info.id)&&(t=n):t=n;return t}r(pi,"newest");function hx(e){let t=pi(e.filter(n=>!!Jr(n)));return t?Jr(t):void 0}r(hx,"newestStored");var Xr={};R(Xr,{ConfigCommand:()=>Xr,load:()=>Ex});import Sx from"path";import{Cause as Ru,Exit as xx,Schema as vx}from"effect";var wx=vx.decodeUnknownExit(wd.Info);async function Ex(e){let t={};for(let n of await Ut.scan("{command,commands}/**/*.md",{cwd:e,absolute:!0,dot:!0,symlink:!0})){let o=await Fo(n).catch(()=>{});if(!o)continue;let i={name:qr(Sx.relative(e,n),["command/","commands/"]),...o.data,template:o.content.trim()},a=wx(i,{errors:"all",propertyOrder:"original"});if(xx.isSuccess(a)){t[i.name]=a.value;continue}throw new Ct({path:n,message:Ru.pretty(a.cause)},{cause:Ru.squash(a.cause)})}return t}r(Ex,"load");var Vo={};R(Vo,{ConfigManaged:()=>Vo,managedConfigDir:()=>Ox,parseManagedPlist:()=>Nu,readManagedPreferences:()=>Rx});import{existsSync as Dx}from"fs";import Tx from"os";import Sc from"path";var zr={};R(zr,{Process:()=>zr,RunFailedError:()=>ui,lines:()=>bx,run:()=>hc,spawn:()=>Pu,stop:()=>kx,text:()=>Mu});import Ix from"cross-spawn";import{buffer as Cu}from"node:stream/consumers";var ui=class extends Error{static{r(this,"RunFailedError")}cmd;code;stdout;stderr;constructor(t,n,o,s){let i=s.toString().trim();super(i?`Command failed with code ${n}: ${t.join(" ")}
679
+ ${i}`:`Command failed with code ${n}: ${t.join(" ")}`),this.name="ProcessRunFailedError",this.cmd=[...t],this.code=n,this.stdout=o,this.stderr=s}};function Pu(e,t={}){if(e.length===0)throw new Error("Command is required");t.abort?.throwIfAborted();let n=Ix(e[0],e.slice(1),{cwd:t.cwd,shell:t.shell,env:t.env===null?{}:t.env?{...process.env,...t.env}:void 0,stdio:[t.stdin??"ignore",t.stdout??"ignore",t.stderr??"ignore"],windowsHide:process.platform==="win32"}),o=!1,s,i=r(()=>{if(o||n.exitCode!==null||n.signalCode!==null)return;o=!0,n.kill(t.kill??"SIGTERM");let l=t.timeout??5e3;l<=0||(s=setTimeout(()=>n.kill("SIGKILL"),l))},"abort"),a=new Promise((l,f)=>{let g=r(()=>{t.abort?.removeEventListener("abort",i),s&&clearTimeout(s)},"done");n.once("exit",(d,h)=>{g(),l(d??(h?1:0))}),n.once("error",d=>{g(),f(d)})});a.catch(()=>{}),t.abort&&(t.abort.addEventListener("abort",i,{once:!0}),t.abort.aborted&&i());let c=n;return c.exited=a,c}r(Pu,"spawn");async function hc(e,t={}){let n=Pu(e,{cwd:t.cwd,env:t.env,stdin:t.stdin,shell:t.shell,abort:t.abort,kill:t.kill,timeout:t.timeout,stdout:"pipe",stderr:"pipe"});if(!n.stdout||!n.stderr)throw new Error("Process output not available");let o=await Promise.all([n.exited,Cu(n.stdout),Cu(n.stderr)]).then(([s,i,a])=>({code:s,stdout:i,stderr:a})).catch(s=>{if(!t.nothrow)throw s;return{code:1,stdout:Buffer.alloc(0),stderr:Buffer.from(Fr(s))}});if(o.code===0||t.nothrow)return o;throw new ui(e,o.code,o.stdout,o.stderr)}r(hc,"run");async function kx(e){if(e.exitCode!==null||e.signalCode!==null)return;if(process.platform!=="win32"||!e.pid){e.kill();return}(await hc(["taskkill","/pid",String(e.pid),"/T","/F"],{nothrow:!0})).code!==0&&e.kill()}r(kx,"stop");async function Mu(e,t={}){let n=await hc(e,t);return{...n,text:n.stdout.toString()}}r(Mu,"text");async function bx(e,t={}){return(await Mu(e,t)).text.split(/\r?\n/).filter(Boolean)}r(bx,"lines");var Lu="ai.opencode.managed",_x=new Set(["PayloadDisplayName","PayloadIdentifier","PayloadType","PayloadUUID","PayloadVersion","_manualProfile"]);function Ax(){switch(process.platform){case"darwin":return"/Library/Application Support/opencode";case"win32":return Sc.join(process.env.ProgramData||"C:\\ProgramData","opencode");default:return"/etc/opencode"}}r(Ax,"systemManagedConfigDir");function Ox(){return process.env.OPENCODE_TEST_MANAGED_CONFIG_DIR||Ax()}r(Ox,"managedConfigDir");function Nu(e){let t=JSON.parse(e);for(let n of Object.keys(t))_x.has(n)&&delete t[n];return JSON.stringify(t)}r(Nu,"parseManagedPlist");async function Rx(){if(process.platform!=="darwin")return;let e=(()=>{try{return Tx.userInfo().username||"user"}catch{return"user"}})(),t=[Sc.join("/Library/Managed Preferences",e,`${Lu}.plist`),Sc.join("/Library/Managed Preferences",`${Lu}.plist`)];for(let n of t){if(!Dx(n))continue;let o=await zr.run(["plutil","-convert","json","-o","-",n],{nothrow:!0});if(o.code===0)return{source:`mobileconfig:${n}`,text:Nu(o.stdout.toString())}}}r(Rx,"readManagedPreferences");var Wo={};R(Wo,{ConfigPaths:()=>Wo,directories:()=>Mx,fileInDirectory:()=>Lx,files:()=>Px});import ju from"path";import{unique as Cx}from"remeda";import*as xc from"effect/Effect";var Px=xc.fn("ConfigPaths.projectFiles")(function*(e,t,n){return(yield*(yield*de.Service).up({targets:[`${e}.jsonc`,`${e}.json`],start:t,stop:n})).toReversed()}),Mx=xc.fn("ConfigPaths.directories")(function*(e,t){let n=yield*de.Service;return Cx([he.Path.config,...le.OPENCODE_DISABLE_PROJECT_CONFIG?[]:yield*n.up({targets:[".opencode"],start:e,stop:t}),...yield*n.up({targets:[".opencode"],start:he.Path.home,stop:he.Path.home}),...le.OPENCODE_CONFIG_DIR?[le.OPENCODE_CONFIG_DIR]:[]])});function Lx(e,t){return[ju.join(e,`${t}.json`),ju.join(e,`${t}.jsonc`)]}r(Lx,"fileInDirectory");var Xn={};R(Xn,{ConfigPlugin:()=>Xn,deduplicatePluginOrigins:()=>Yx,load:()=>Kx,pluginOptions:()=>Xx,pluginSpecifier:()=>bc,resolvePluginSpec:()=>zx});import{pathToFileURL as kc}from"url";import Pt from"path";import{fileURLToPath as fi,pathToFileURL as Go}from"url";import Nx from"npm-package-arg";import vc from"semver";var jx=["opencode-openai-codex-auth","opencode-copilot-auth"];function eC(e){return jx.some(t=>e.includes(t))}r(eC,"isDeprecatedPlugin");function Uu(e){try{return Nx(e)}catch{}}r(Uu,"parse");function Bu(e){let t=Uu(e);if(t?.type==="alias"&&!t.name){let n=t.subSpec;if(n?.name){let o=!n.rawSpec||n.rawSpec==="*"?"latest":n.rawSpec;return{pkg:n.name,version:o}}}return t?.name?t.raw===t.name?{pkg:t.name,version:"latest"}:{pkg:t.name,version:t.rawSpec}:{pkg:e,version:""}}r(Bu,"parsePluginSpecifier");var $x=["index.ts","index.tsx","index.js","index.mjs","index.cjs"];function Fu(e){return mi(e)?"file":"npm"}r(Fu,"pluginSource");function Ux(e,t){return e.startsWith("file://")?fi(e):Pt.isAbsolute(e)?e:Pt.resolve(t,e)}r(Ux,"resolveExportPath");function Bx(e){return Pt.isAbsolute(e)||/^[A-Za-z]:[\\/]/.test(e)}r(Bx,"isAbsolutePath");function Fx(e){if(typeof e=="string")return e;if(be(e))for(let t of["import","default"]){let n=e[t];if(typeof n=="string")return n}}r(Fx,"extractExportValue");function qx(e){let t=e.json.main;if(typeof t!="string")return;let n=t.trim();if(n)return n}r(qx,"packageMain");function Vx(e,t,n,o){let s=Ux(t,o.dir),i=Je.resolve(o.dir),a=Je.resolve(s);if(!Je.contains(i,a))throw new Error(`Plugin ${e} resolved ${n} entry outside plugin directory`);return a}r(Vx,"resolvePackageFile");function $u(e,t,n,o){return Go(Vx(e,t,n,o)).href}r($u,"resolvePackagePath");function Wx(e,t,n){let o=n.json.exports;if(be(o)){let i=Fx(o[`./${t}`]);if(i)return $u(e,i,t,n)}if(t!=="server")return;let s=qx(n);if(s)return $u(e,s,t,n)}r(Wx,"resolvePackageEntrypoint");function Gx(e){if(e.startsWith("file://"))return fi(e);if(Pt.isAbsolute(e))return e}r(Gx,"targetPath");async function wc(e){for(let t of $x){let n=Pt.join(e,t);if(await Je.exists(n))return n}}r(wc,"resolveDirectoryIndex");async function Hx(e){let t=Gx(e);if(!(!t||!(await Je.statAsync(t))?.isDirectory()))return t}r(Hx,"resolveTargetDirectory");async function Jx(e,t,n,o){let s=Fu(e),i=o??(s==="npm"?await Ho(t):await Ho(t).catch(()=>{}));if(!i)return t;let a=Wx(e,n,i);if(a)return a;let c=await Hx(t);if(n==="tui"){if(s==="file"&&c){let l=await wc(c);if(l)return Go(l).href}return s==="npm"||c?void 0:t}if(c&&be(i.json.exports)){if(s==="file"){let l=await wc(c);if(l)return Go(l).href}return}return t}r(Jx,"resolvePluginEntrypoint");function mi(e){return e.startsWith("file://")||e.startsWith(".")||Bx(e)}r(mi,"isPathPluginSpec");async function Ec(e){let t=e.startsWith("file://")?fi(e):e,n=Pt.isAbsolute(t)||/^[A-Za-z]:[\\/]/.test(t)?t:Pt.resolve(t);if(!(await Je.statAsync(n))?.isDirectory())return e.startsWith("file://")?e:Go(n).href;if(await Je.exists(Pt.join(n,"package.json")))return Go(n).href;let s=await wc(n);if(s)return Go(s).href;throw new Error(`Plugin directory ${n} is missing package.json or index file`)}r(Ec,"resolvePathPluginTarget");async function tC(e,t,n){if(!vc.valid(t)||vc.major(t)===0)return;let o=n??await Ho(e).catch(()=>{});if(!o)return;let s=o.json.engines;if(!be(s))return;let i=s.opencode;if(typeof i=="string"&&!vc.satisfies(t,i))throw new Error(`Plugin requires opencode ${i} but running ${t}`)}r(tC,"checkPluginCompatibility");async function nC(e){if(mi(e))return Ec(e);let t=Uu(e),n=t?.name&&t.raw===t.name?`${t.name}@latest`:e;return(await cn.add(n)).directory}r(nC,"resolvePluginTarget");async function Ho(e){let t=e.startsWith("file://")?fi(e):e,o=(await Je.statAsync(t))?.isDirectory()?t:Pt.dirname(t),s=Pt.join(o,"package.json"),i=await Je.readJson(s);return{dir:o,pkg:s,json:i}}r(Ho,"readPluginPackage");async function oC(e,t,n){let o=Fu(e),s=o==="npm"?await Ho(t):await Ho(t).catch(()=>{}),i=await Jx(e,t,n,s);return{spec:e,source:o,target:t,pkg:s,entry:i}}r(oC,"createPluginEntry");function rC(e,t){if(e===void 0)return;if(typeof e!="string")throw new TypeError(`Plugin ${t} has invalid id type ${typeof e}`);let n=e.trim();if(!n)throw new TypeError(`Plugin ${t} has an empty id`);return n}r(rC,"readPluginId");function sC(e,t,n,o="strict"){let s=e.default;if(!be(s)){if(o==="detect")return;throw new TypeError(`Plugin ${t} must default export an object with ${n}()`)}if(o==="detect"&&!("id"in s)&&!("server"in s)&&!("tui"in s))return;let i="server"in s?s.server:void 0,a="tui"in s?s.tui:void 0;if(i!==void 0&&typeof i!="function")throw new TypeError(`Plugin ${t} has invalid server export`);if(a!==void 0&&typeof a!="function")throw new TypeError(`Plugin ${t} has invalid tui export`);if(i!==void 0&&a!==void 0)throw new TypeError(`Plugin ${t} must default export either server() or tui(), not both`);if(n==="server"&&i===void 0)throw new TypeError(`Plugin ${t} must default export an object with server()`);if(n==="tui"&&a===void 0)throw new TypeError(`Plugin ${t} must default export an object with tui()`);return s}r(sC,"readV1Plugin");async function iC(e,t,n,o,s){if(e==="file"){if(o)return o;throw new TypeError(`Path plugin ${t} must export id`)}if(o)return o;let i=s??await Ho(n);if(typeof i.json.name!="string"||!i.json.name.trim())throw new TypeError(`Plugin package ${i.pkg} is missing name`);return i.json.name.trim()}r(iC,"resolvePluginId");import Ic from"path";async function Kx(e){let t=[];for(let n of await Ut.scan("{plugin,plugins}/*.{ts,js}",{cwd:e,absolute:!0,dot:!0,symlink:!0}))t.push(kc(n).href);return t}r(Kx,"load");function bc(e){return Array.isArray(e)?e[0]:e}r(bc,"pluginSpecifier");function Xx(e){return Array.isArray(e)?e[1]:void 0}r(Xx,"pluginOptions");async function zx(e,t){let n=bc(e);if(!mi(n))return e;let o=Ic.dirname(t),s=n.startsWith("file://")?n:Ic.isAbsolute(n)||/^[A-Za-z]:[\\/]/.test(n)?kc(n).href:kc(Ic.resolve(o,n)).href,i=await Ec(s).catch(()=>s);return Array.isArray(e)?[i,e[1]]:i}r(zx,"resolvePluginSpec");function Yx(e){let t=new Set,n=[];for(let o of e.toReversed()){let s=bc(o.spec),i=s.startsWith("file://")?s:Bu(s).pkg;t.has(i)||(t.add(i),n.push(o))}return n.toReversed()}r(Yx,"deduplicatePluginOrigins");var zn={};R(zn,{ConfigVariable:()=>zn,substitute:()=>tv});import gi from"path";import Zx from"os";function Qx(e){return e.type==="path"?e.path:e.source}r(Qx,"source");function ev(e){return e.type==="path"?gi.dirname(e.path):e.dir}r(ev,"dir");async function tv(e){let t=e.missing??"error",n=e.text.replace(/\{env:([^}]+)\}/g,(l,f)=>(e.env?.[f]??process.env[f])||""),o=Array.from(n.matchAll(/\{file:[^}]+\}/g));if(!o.length)return n;let s=ev(e),i=Qx(e),a="",c=0;for(let l of o){let f=l[0],g=l.index;a+=n.slice(c,g);let d=n.lastIndexOf(`
680
+ `,g-1)+1;if(n.slice(d,g).trimStart().startsWith("//")){a+=f,c=g+f.length;continue}let b=f.replace(/^\{file:/,"").replace(/\}$/,"");b.startsWith("~/")&&(b=gi.join(Zx.homedir(),b.slice(2)));let _=gi.isAbsolute(b)?b:gi.resolve(s,b),P=(await Je.readText(_).catch(C=>{if(t==="empty")return"";let J=`bad file reference: "${f}"`;throw C.code==="ENOENT"?new Ct({path:i,message:J+` ${_} does not exist`},{cause:C}):new Ct({path:i,message:J},{cause:C})})).trim();a+=JSON.stringify(P).slice(1,-1),c=g+f.length}return a+=n.slice(c),a}r(tv,"substitute");var Jo={};R(Jo,{ConfigV2Compat:()=>Jo,lower:()=>cv});import{isDeepStrictEqual as Tc}from"node:util";import{Option as ce,Schema as w}from"effect";var Zr={errors:"all",onExcessProperty:"ignore",propertyOrder:"original"},yi=w.Record(w.String,w.Unknown),Dc=w.Struct({startup:w.optional($t),catalog:w.optional($t),execution:w.optional($t)}),nv=w.Struct({client_id:w.optional(w.String),client_secret:w.optional(w.String),scope:w.optional(w.String),callback_port:w.optional(w.Int.check(w.isBetween({minimum:1,maximum:65535}))),redirect_uri:w.optional(w.String)}),ov=w.Union([w.Struct({type:w.Literal("local"),command:w.Array(w.String),cwd:w.optional(w.String),environment:w.optional(w.Record(w.String,w.String)),disabled:w.optional(w.Boolean),codemode:w.optional(w.Boolean),timeout:w.optional(Dc)}),w.Struct({type:w.Literal("remote"),url:w.String,headers:w.optional(w.Record(w.String,w.String)),oauth:w.optional(w.Union([nv,w.Literal(!1)])),disabled:w.optional(w.Boolean),codemode:w.optional(w.Boolean),timeout:w.optional(Dc)})]),_c=w.Union([w.String.check(w.isPattern(/^[^/#]+\/[^#]+(?:#[^#]+)?$/)),w.Struct({providerID:w.String.check(w.isPattern(/^[^/#]+$/)),model:w.String.check(w.isPattern(/^[^#]+$/)),variant:w.optional(w.String.check(w.isPattern(/^[^#]+$/)))})]),rv=w.Struct({model:w.optional(_c),request:w.optional(w.Struct({headers:w.optional(w.Record(w.String,w.String)),body:w.optional(w.Record(w.String,w.Json))})),system:w.optional(w.String),description:w.optional(w.String),mode:w.optional(w.Literals(["subagent","primary","all"])),hidden:w.optional(w.Boolean),color:w.optional(w.String.check(w.isPattern(/^#[0-9a-fA-F]{6}$/))),steps:w.optional($t),disabled:w.optional(w.Boolean)}),sv=w.Struct({template:w.String,description:w.optional(w.String),agent:w.optional(w.String),model:w.optional(_c),subtask:w.optional(w.Boolean)}),Ye=w.decodeUnknownOption(yi,Zr),iv=w.decodeUnknownOption(oa.Entry,Zr),av=new Set(oa.builtinServerIds);function cv(e,t="configuration"){let n=Ye(e);if(ce.isNone(n))return{value:e,diagnostics:[]};let o=[...Object.hasOwn(n.value,"permissions")?[["permissions"]]:[],...["agents","agent","mode"].flatMap(a=>{let c=Ye(n.value[a]);return ce.isNone(c)?[]:Object.entries(c.value).flatMap(([l,f])=>{let g=Ye(f);return ce.isSome(g)&&Object.hasOwn(g.value,"permissions")?[[a,l,"permissions"]]:[]})})];if(o.length)throw new Ct({path:t,issues:o.map(a=>({path:a,message:'V2 permissions are not supported by OpenCode V1. Use V1 "permission" rules or run opencode2.'}))});let s={...n.value},i=[];for(let a of["plugins","providers","websearch","warming"])Object.hasOwn(n.value,a)&&ln([a],i);return lv(n.value,s,i),dv(n.value,s,i),pv(n.value,s,i),uv(n.value,s,i),fv(n.value,s,i),mv(n.value,s,i),gv(n.value,s,i),yv(n.value,s,i),hv(n.value,s,i),{value:s,diagnostics:i}}r(cv,"lower");function lv(e,t,n){if(Object.hasOwn(e,"snapshots")){let o=yt(w.Boolean,e.snapshots,["snapshots"],n);o!==void 0&&Yn(t,"snapshot",o,["snapshots"],n)}if(Object.hasOwn(e,"media")){let o=yt(vd.Info,e.media,["media"],n);o!==void 0&&Yn(t,"attachment",o,["media"],n)}}r(lv,"normalizeSettings");function dv(e,t,n){if(!Object.hasOwn(e,"model"))return;let o=w.decodeUnknownOption(_c,Zr)(e.model);if(ce.isNone(o))return;let s=Ac(o.value);t.model=s.model,s.variant!==void 0&&ln(["model","variant"],n)}r(dv,"normalizeModel");function pv(e,t,n){if(!Array.isArray(e.skills))return;let o=yt(w.Array(w.String),e.skills,["skills"],n);o!==void 0&&(t.skills={paths:o.filter(s=>!/^https?:\/\//i.test(s)),urls:o.filter(s=>/^https?:\/\//i.test(s))})}r(pv,"normalizeSkills");function uv(e,t,n){let o=Ye(e.compaction);if(ce.isNone(o))return;let s={...o.value};if(Object.hasOwn(s,"keep")){let i=yt(yi,s.keep,["compaction","keep"],n);if(i!==void 0&&Object.hasOwn(i,"tokens")){let a=yt(it,i.tokens,["compaction","keep","tokens"],n);a!==void 0&&Yn(s,"preserve_recent_tokens",a,["compaction","keep","tokens"],n)}}if(Object.hasOwn(s,"buffer")){let i=yt(it,s.buffer,["compaction","buffer"],n);i!==void 0&&Yn(s,"reserved",i,["compaction","buffer"],n)}t.compaction=s}r(uv,"normalizeCompaction");function fv(e,t,n){let o=Ye(e.experimental);if(ce.isNone(o)||(Object.hasOwn(o.value,"portable_shell_scanner")&&ln(["experimental","portable_shell_scanner"],n),!Object.hasOwn(o.value,"subagent_depth")))return;let s=yt(it,o.value.subagent_depth,["experimental","subagent_depth"],n);s!==void 0&&Yn(t,"subagent_depth",s,["experimental","subagent_depth"],n)}r(fv,"normalizeExperimental");function mv(e,t,n){if(!Object.hasOwn(e,"agents"))return;let o=yt(yi,e.agents,["agents"],n);if(o===void 0)return;let s=Ye(t.agent),i=ce.isSome(s)?{...s.value}:{};for(let[a,c]of Object.entries(o)){let l=["agents",a];if(Object.hasOwn(i,a)){Tc(i[a],c)||hi(l,n);continue}let f=yt(rv,c,l,n);f!==void 0&&(f.request?.headers!==void 0&&ln([...l,"request","headers"],n),Yr(i,a,Sv(f)))}Object.hasOwn(t,"agent")&&ce.isNone(s)||(Object.keys(i).length>0||ce.isSome(s))&&(t.agent=i)}r(mv,"normalizeAgents");function gv(e,t,n){if(!Object.hasOwn(e,"commands"))return;let o=yt(yi,e.commands,["commands"],n);if(o===void 0)return;let s=Ye(t.command);if(Object.hasOwn(t,"command")&&ce.isNone(s))return;let i=ce.isSome(s)?{...s.value}:{};for(let[a,c]of Object.entries(o)){let l=["commands",a],f=yt(sv,c,l,n);f!==void 0&&Yn(i,a,xv(f),l,n)}(Object.keys(i).length>0||ce.isSome(s))&&(t.command=i)}r(gv,"normalizeCommands");function yv(e,t,n){let o=Ye(e.mcp);if(ce.isNone(o))return;let s={},i=Ye(o.value.servers),a=ce.isSome(i)&&!qu(i.value),c=Ye(o.value.timeout),l=w.decodeUnknownOption(Dc,Zr)(o.value.timeout),f=ce.isSome(l)&&ce.isSome(c)&&!qu(c.value)&&(Object.keys(c.value).length===0||["startup","catalog","execution"].some(b=>Object.hasOwn(c.value,b)));for(let[b,_]of Object.entries(o.value)){if(b==="servers"&&a||b==="timeout"&&f)continue;let P=["mcp",b],C=Ye(_),J=ce.isSome(C)?Ye(C.value.oauth):ce.none(),te=ce.isSome(C)&&(Object.hasOwn(C.value,"disabled")||Object.hasOwn(C.value,"codemode")||typeof C.value.timeout=="object"||ce.isSome(J)&&["client_id","client_secret","callback_port","redirect_uri"].some(L=>Object.hasOwn(J.value,L)));Yr(s,b,te?Vu(_,P,n)??_:_)}if(a&&ce.isSome(i))for(let[b,_]of Object.entries(i.value)){let P=["mcp","servers",b];if(Object.hasOwn(s,b)){Tc(s[b],_)||hi(P,n);continue}let C=Ye(_);if(ce.isSome(C)&&typeof C.value.enabled=="boolean"&&!Object.hasOwn(C.value,"disabled")){Yr(s,b,_);continue}let J=Vu(_,P,n);J!==void 0&&Yr(s,b,J)}if(t.mcp=s,!f||ce.isNone(l))return;let g=Oc(l.value);if(g===void 0){Object.keys(l.value).length&&ln(["mcp","timeout"],n);return}let d=Ye(t.experimental);if(Object.hasOwn(t,"experimental")&&ce.isNone(d))return;let h=ce.isSome(d)?{...d.value}:{};Yn(h,"mcp_timeout",g,["mcp","timeout"],n),t.experimental=h}r(yv,"normalizeMcp");function qu(e){return["type","enabled"].some(t=>Object.hasOwn(e,t)&&(e[t]===null||typeof e[t]!="object"||Array.isArray(e[t])))}r(qu,"isDirectServer");function Vu(e,t,n){let o=yt(ov,e,t,n);if(o===void 0)return;o.codemode!==void 0&&ln([...t,"codemode"],n),o.timeout&&Oc(o.timeout)===void 0&&Object.keys(o.timeout).length&&ln([...t,"timeout"],n);let s=Ye(e);return ce.isNone(s)||!Object.hasOwn(s.value,"enabled")?Wu(o):(o.disabled!==void 0&&s.value.enabled===o.disabled&&hi([...t,"disabled"],n),{...Wu(o),enabled:s.value.enabled})}r(Vu,"normalizeServer");function hv(e,t,n){let o=Ye(e.lsp);ce.isNone(o)||(t.lsp=Object.fromEntries(Object.entries(o.value).filter(([s,i])=>{if(av.has(s))return!0;let a=iv(i);return ce.isNone(a)||a.value.disabled===!0||"extensions"in a.value&&a.value.extensions!==void 0?!0:(ln(["lsp",s],n),!1)})))}r(hv,"normalizeLsp");function Ac(e){if(typeof e!="string")return{model:`${e.providerID}/${e.model}`,...e.variant!==void 0?{variant:e.variant}:{}};let t=e.indexOf("#");return t===-1?{model:e}:{model:e.slice(0,t),variant:e.slice(t+1)}}r(Ac,"lowerSelection");function Oc(e){if(e.startup===void 0&&!(e.catalog===void 0||e.execution===void 0)&&e.catalog===e.execution)return e.catalog}r(Oc,"lowerTimeout");function Wu(e){let t={...e,enabled:e.disabled!==!0};if(delete t.disabled,delete t.codemode,delete t.timeout,e.timeout){let n=Oc(e.timeout);n!==void 0&&(t.timeout=n)}if(e.type==="remote"&&e.oauth&&typeof e.oauth=="object"){let n={};e.oauth.client_id!==void 0&&(n.clientId=e.oauth.client_id),e.oauth.client_secret!==void 0&&(n.clientSecret=e.oauth.client_secret),e.oauth.scope!==void 0&&(n.scope=e.oauth.scope),e.oauth.callback_port!==void 0&&(n.callbackPort=e.oauth.callback_port),e.oauth.redirect_uri!==void 0&&(n.redirectUri=e.oauth.redirect_uri),t.oauth=n}return t}r(Wu,"lowerServer");function Sv(e){let t={};for(let n of["description","mode","hidden","color","steps"])e[n]!==void 0&&(t[n]=e[n]);return e.system!==void 0&&(t.prompt=e.system),e.disabled!==void 0&&(t.disable=e.disabled),e.model!==void 0&&Object.assign(t,Ac(e.model)),e.request?.body!==void 0&&(t.options=e.request.body),t}r(Sv,"lowerAgent");function xv(e){return{...e,...e.model!==void 0?Ac(e.model):{}}}r(xv,"lowerCommand");function yt(e,t,n,o){let s=w.decodeUnknownOption(e,Zr)(t);if(ce.isSome(s))return s.value;o.push({kind:"invalid",path:n,message:"Native setting could not be lowered because it is malformed"})}r(yt,"decodeValue");function Yn(e,t,n,o,s){if(Object.hasOwn(e,t)){Tc(e[t],n)||hi(o,s);return}Yr(e,t,n)}r(Yn,"preferLegacy");function Yr(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})}r(Yr,"setOwn");function ln(e,t){t.push({kind:"unsupported",path:e,message:"Omitted native setting that cannot be represented in V1"})}r(ln,"unsupported");function hi(e,t){t.push({kind:"conflict",path:e,message:"Retained legacy value over native value"})}r(hi,"conflict");function Ko(e,t){return Mt(e,t)}r(Ko,"mergeConfig");function Ju(e,t){let n=Ko(e,t);return e.instructions&&t.instructions&&(n.instructions=Array.from(new Set([...e.instructions,...t.instructions]))),n}r(Ju,"mergeConfigConcatArrays");function Ku(e){if(!be(e))return e;let t={...e};return("theme"in t||"keybinds"in t||"tui"in t)&&(delete t.theme,delete t.keybinds,delete t.tui),t}r(Ku,"normalizeLoadedConfig");async function Av(e){if(!be(e.value)||typeof e.value.url!="string")return;let t=await zn.substitute({text:e.value.url,type:"virtual",dir:e.dir,source:e.source,env:e.env}),n=be(e.value.headers)?Object.fromEntries(await Promise.all(Object.entries(e.value.headers).filter(o=>typeof o[1]=="string").map(async([o,s])=>[o,await zn.substitute({text:s,type:"virtual",dir:e.dir,source:e.source,env:e.env})]))):void 0;return{url:t,headers:n}}r(Av,"substituteWellKnownRemoteConfig");async function Ov(e,t){if(!e.plugin)return e;for(let n=0;n<e.plugin.length;n++)e.plugin[n]=await Xn.resolvePluginSpec(e.plugin[n],t);return e}r(Ov,"resolveLoadedPlugins");var Zn=class extends kv.Service()("@opencode/Config"){static{r(this,"Service")}},Rv=Yt(Zn);function Xu(){let e=["opencode.jsonc","opencode.json","config.json"].map(t=>dt.join(he.Path.config,t));for(let t of e)if(xi(t))return t;return e[0]}r(Xu,"globalConfigFile");function zu(e,t,n=[]){if(!be(t)){let o=Iv(e,n,t,{formattingOptions:{insertSpaces:!0,tabSize:2}});return Ev(e,o)}return Object.entries(t).reduce((o,[s,i])=>zu(o,i,[...n,s]),e)}r(zu,"patchJsonc");function vi(e){let{plugin_origins:t,...n}=e;return n}r(vi,"writable");function Cv(e){let t=vi(e);return"shell"in t&&t.shell===""?{...t,shell:void 0}:t}r(Cv,"writableGlobal");var Pv=_v.effect(Zn,D.gen(function*(){let e=yield*de.Service,t=yield*Uo.Service,n=yield*jo.Service,o=yield*Bo.Service,s=yield*cn.Service,i=yield*Hu.HttpClient,a=r(y=>e.readFileStringSafe(y).pipe(D.orDie),"readConfigFile"),c=D.fnUntraced(function*(y,S){let v=Jo.lower(Ku(y),S);return yield*D.forEach(v.diagnostics,O=>D.logWarning("configuration compatibility diagnostic",{source:S,path:O.path,kind:O.kind,action:O.message})),lt.schema(bs.Info,v.value,S)}),l=D.fnUntraced(function*(y,S,v,O){let Q=yield*Hu.filterStatusOk(Ws(i)).execute(Cc.get(y).pipe(Cc.acceptJson,Cc.setHeaders(S??{}))).pipe(D.catch(Le=>D.die(new Error(`failed to fetch remote config from ${y}: ${String(Le)}`)))),ae=yield*Q.text.pipe(D.catch(Le=>D.die(new Error(`failed to read remote config from ${y}: ${String(Le)}`))));return(Q.headers["content-type"]??"").toLowerCase().includes("html")||/^\s*<!doctype|^\s*<html/i.test(ae)?yield*D.die(new oc({url:O,remote:y})):yield*Rc.decodeEffect(Rc.fromJsonString(v))(ae).pipe(D.catch(Le=>D.die(new Error(`failed to decode remote config from ${y}: ${String(Le)}`))))}),f=D.fnUntraced(function*(y,S,v){let O="path"in S?S.path:S.source,Q=yield*D.promise(()=>zn.substitute("path"in S?{text:y,type:"path",path:S.path,env:v}:{text:y,type:"virtual",...S,env:v})),ae=lt.jsonc(Q,O),ue=yield*c(ae,O);if(!("path"in S))return ue;if(yield*D.promise(()=>Ov(ue,S.path)),!ue.$schema){ue.$schema="https://opencode.ai/config.json";let Le=y.replace(/^\s*\{/,`{
681
+ "$schema": "https://opencode.ai/config.json",`);yield*e.writeFileString(S.path,Le).pipe(D.catch(()=>D.void))}return ue}),g=D.fnUntraced(function*(y,S){yield*D.logInfo("loading",{path:y});let v=yield*a(y);return v?yield*f(v,{path:y},S):{}}),d=D.fnUntraced(function*(y){let S={};if(!le.OPENCODE_CONFIG&&!le.OPENCODE_CONFIG_DIR&&!le.OPENCODE_CONFIG_CONTENT){let O=Xu();xi(O)||(yield*e.writeWithDirs(O,JSON.stringify({$schema:"https://opencode.ai/config.json"},null,2)).pipe(D.catch(()=>D.void)))}S=Ko(S,yield*g(dt.join(he.Path.config,"config.json"),y)),S=Ko(S,yield*g(dt.join(he.Path.config,"opencode.json"),y)),S=Ko(S,yield*g(dt.join(he.Path.config,"opencode.jsonc"),y));let v=dt.join(he.Path.config,"config");return xi(v)&&(yield*D.promise(()=>import(vv(v).href,{with:{type:"toml"}}).then(async O=>{let{provider:Q,model:ae,...ue}=O.default;Q&&ae&&(S.model=`${Q}/${ae}`),S.$schema="https://opencode.ai/config.json",S=Ko(S,ue),await Gu.writeFile(dt.join(he.Path.config,"config.json"),JSON.stringify(S,null,2)),await Gu.unlink(v)}).catch(()=>{}))),S}),[h,b]=yield*D.cachedInvalidateWithTTL(d().pipe(D.tapError(y=>D.logError("failed to load global config, using defaults",{error:String(y)})),D.orElseSucceed(()=>({}))),bv.infinity),_=D.fn("Config.getGlobal")(function*(){return yield*h}),P=D.fn("Config.ensureGitignore")(function*(y){yield*e.ensureDir(y);let S=dt.join(y,".gitignore");(yield*e.existsSafe(S))||(yield*e.writeFileString(S,["node_modules","package.json","package-lock.json","bun.lock",".gitignore"].join(`
682
+ `)).pipe(D.catchIf(O=>O.reason._tag==="PermissionDenied",()=>D.void)))}),C=D.fn("Config.loadInstanceState")(function*(y){let S=yield*t.all().pipe(D.orDie),v={},O={},Q=new Set,ae,ue=D.fnUntraced(function*(A){return A.startsWith("http://")||A.startsWith("https://")?"global":A==="OPENCODE_CONFIG_CONTENT"||tu(A,y)?"local":"global"}),Le=D.fnUntraced(function*(A,X,ye){if(!X?.length)return;let re=ye??(yield*ue(A)),Be=Xn.deduplicatePluginOrigins([...v.plugin_origins??[],...X.map(et=>({spec:et,source:A,scope:re}))]);v.plugin=Be.map(et=>et.spec),v.plugin_origins=Be}),Ze=r((A,X,ye)=>(v=Ju(v,X),Le(A,X.plugin,ye)),"merge");for(let[A,X]of Object.entries(S))if(X.type==="wellknown"){let ye=A.replace(/\/+$/,"");O[X.key]=X.token;let re=`${ye}/.well-known/opencode`;yield*D.logDebug("fetching remote config",{url:re});let Be=yield*l(re,void 0,bs.WellKnown,ye),et=yield*D.promise(()=>Av({value:Be.remote_config,dir:ye,source:re,env:O})),cr=et?yield*D.gen(function*(){yield*D.logDebug("fetching remote config",{url:et.url});let lr=yield*l(et.url,et.headers,Rc.Json,ye);return be(lr)&&be(lr.config)?lr.config:be(lr)?lr:yield*D.die(new Error(`failed to decode remote config from ${et.url}: expected object`))}):{},vn=Ko(be(Be.config)?Be.config:{},cr);vn.$schema||(vn.$schema="https://opencode.ai/config.json");let Gi=re,ym=yield*f(JSON.stringify(vn),{dir:dt.dirname(Gi),source:Gi},O);yield*Ze(Gi,ym,"global"),yield*D.logDebug("loaded remote config from well-known",{url:ye})}let ir=Object.keys(O).length?yield*d(O):yield*_();if(yield*Ze(he.Path.config,ir,"global"),le.OPENCODE_CONFIG&&(yield*Ze(le.OPENCODE_CONFIG,yield*g(le.OPENCODE_CONFIG,O)),yield*D.logDebug("loaded custom config",{path:le.OPENCODE_CONFIG})),!le.OPENCODE_DISABLE_PROJECT_CONFIG)for(let A of yield*Wo.files("opencode",y.directory,y.worktree).pipe(D.orDie))yield*Ze(A,yield*g(A,O),"local");v.agent=v.agent||{},v.mode=v.mode||{},v.plugin=v.plugin||[];let ar=yield*Wo.directories(y.directory,y.worktree);le.OPENCODE_CONFIG_DIR&&(yield*D.logDebug("loading config from OPENCODE_CONFIG_DIR",{path:le.OPENCODE_CONFIG_DIR}));let ps=[];for(let A of ar){if(A.endsWith(".opencode")||A===le.OPENCODE_CONFIG_DIR)for(let re of["opencode.json","opencode.jsonc"]){let Be=dt.join(A,re);yield*D.logDebug(`loading config from ${Be}`),yield*Ze(Be,yield*g(Be,O)),v.agent??={},v.mode??={},v.plugin??=[]}yield*P(A).pipe(D.orDie);let X=yield*s.install(A,{add:[{name:"@opencode-ai/plugin",version:El?void 0:lo}]}).pipe(D.exit,D.tap(re=>Dv.isFailure(re)?D.logWarning("background dependency install failed",{dir:A,error:String(re.cause)}):D.void),D.asVoid,D.forkDetach);ps.push(X),v.command=Mt(v.command??{},yield*D.promise(()=>Xr.load(A))),v.agent=Mt(v.agent??{},yield*D.promise(()=>Kn.load(A))),v.agent=Mt(v.agent??{},yield*D.promise(()=>Kn.loadMode(A)));let ye=yield*D.promise(()=>Xn.load(A));yield*Le(A,ye)}if(le.ALCHEMYLAB){let A=[],X=yield*D.promise(()=>Kn.loadAlchemy(y.directory,(ye,re)=>A.push([ye,re])));for(let[ye,re]of A)yield*D.logWarning(ye,re??{});Object.keys(X).length>0&&(v.agent=Mt(v.agent??{},X),yield*D.logInfo("alchemy agents loaded in memory",{count:Object.keys(X).length}))}if(process.env.OPENCODE_CONFIG_CONTENT){let A="OPENCODE_CONFIG_CONTENT",X=yield*f(process.env.OPENCODE_CONFIG_CONTENT,{dir:y.directory,source:A});yield*Ze(A,X,"local"),yield*D.logDebug("loaded custom config from OPENCODE_CONFIG_CONTENT")}let F=Si.getOrUndefined(yield*n.active().pipe(D.catch(()=>D.succeed(Si.none()))));if(F?.active_org_id){let A=F.id,X=F.active_org_id,ye=F.url;yield*D.gen(function*(){let[re,Be]=yield*D.all([n.config(A,X),n.token(A)],{concurrency:2});if(Si.isSome(Be)&&(process.env.OPENCODE_CONSOLE_TOKEN=Be.value,yield*o.set("OPENCODE_CONSOLE_TOKEN",Be.value)),Si.isSome(re)){let et=`${ye}/api/config`,cr=yield*f(JSON.stringify(re.value),{dir:dt.dirname(et),source:et});for(let vn of Object.keys(cr.provider??{}))Q.add(vn);yield*Ze(et,cr,"global")}}).pipe(D.withSpan("Config.loadActiveOrgConfig"),D.catch(re=>D.logDebug("failed to fetch remote account config",{error:re instanceof Error?re.message:String(re)})))}let Ie=Vo.managedConfigDir();if(xi(Ie))for(let A of["opencode.json","opencode.jsonc"]){let X=dt.join(Ie,A);yield*Ze(X,yield*g(X),"global")}let Ne=yield*D.promise(()=>Vo.readManagedPreferences());Ne&&(v=Ju(v,yield*f(Ne.text,{dir:dt.dirname(Ne.source),source:Ne.source})));for(let[A,X]of Object.entries(v.mode??{}))v.agent=Mt(v.agent??{},{[A]:{...X,mode:"primary"}});if(le.OPENCODE_PERMISSION)try{v.permission=Mt(v.permission??{},JSON.parse(le.OPENCODE_PERMISSION))}catch(A){yield*D.logWarning("OPENCODE_PERMISSION contains invalid JSON, skipping",{err:A})}if(v.tools){let A={};for(let[X,ye]of Object.entries(v.tools)){let re=ye?"allow":"deny";if(X==="write"||X==="edit"||X==="patch"){A.edit=re;continue}A[X]=re}v.permission=Mt(A,v.permission??{})}if(!v.username)try{v.username=wv.userInfo().username||"user"}catch(A){yield*D.logWarning("failed to read system username, using fallback",{err:A}),v.username="user"}return v.autoshare===!0&&!v.share&&(v.share="auto"),le.OPENCODE_DISABLE_AUTOCOMPACT&&(v.compaction={...v.compaction,auto:!1}),le.OPENCODE_DISABLE_PRUNE&&(v.compaction={...v.compaction,prune:!1}),Kr.configure(v),{config:v,directories:ar,deps:ps,consoleState:{consoleManagedProviders:Array.from(Q),activeOrgName:ae,switchableOrgCount:0}}},D.provideService(de.Service,e)),J=yield*ze.make(D.fn("Config.state")(function*(y){return yield*C(y).pipe(D.orDie)})),te=D.fn("Config.get")(function*(){return yield*ze.use(J,y=>y.config)}),L=D.fn("Config.directories")(function*(){return yield*ze.use(J,y=>y.directories)}),G=D.fn("Config.getConsoleState")(function*(){return yield*ze.use(J,y=>y.consoleState)}),K=D.fn("Config.waitForDependencies")(function*(){yield*ze.useEffect(J,y=>D.forEach(y.deps,Tv.join,{concurrency:"unbounded"}).pipe(D.asVoid))}),Me=D.fn("Config.update")(function*(y){let S=yield*ze.directory,v=dt.join(S,"config.json");pr.assert(v,"config update");let O=yield*g(v),Q=yield*a(v),ae=Q?lt.jsonc(Q,v):vi(O);yield*e.writeFileString(v,JSON.stringify(Mt(be(ae)?ae:vi(O),vi(y)),null,2)).pipe(D.orDie)}),x=D.fn("Config.invalidate")(function*(){yield*b}),E=D.fn("Config.updateGlobal")(function*(y){let S=Xu(),v=(yield*a(S))??"{}",O=Cv(y),Q,ae;if(S.endsWith(".jsonc")){let ue=zu(v,O);Q=yield*c(lt.jsonc(ue,S),S),ae=ue!==v,ae&&(yield*e.writeFileString(S,ue).pipe(D.orDie))}else{let ue=lt.jsonc(v,S);lt.schema(bs.Info,Jo.lower(Ku(ue),S).value,S);let Le=Mt(be(ue)?ue:{},O),Ze=JSON.stringify(Le,null,2);Q=yield*c(Le,S),ae=Ze!==v,ae&&(yield*e.writeFileString(S,Ze).pipe(D.orDie))}return ae&&(yield*x()),{info:Q,changed:ae}});return Zn.of({get:te,getGlobal:_,getConsoleState:G,update:Me,updateGlobal:E,invalidate:x,directories:L,waitForDependencies:K})})),Mv=xe.make({service:Zn,layer:Pv,deps:[de.node,Uo.node,jo.node,Bo.node,cn.node,ws]});import{EventEmitter as qv}from"events";var Qr={};R(Qr,{Identifier:()=>Qr,ascending:()=>jv,compareAscending:()=>Bv,create:()=>Qu,descending:()=>$v,timestamp:()=>Fv});import{randomBytes as Lv}from"crypto";var Mc={job:"job",event:"evt",session:"ses",message:"msg",permission:"per",question:"que",part:"prt",pty:"pty",tool:"tool",workspace:"wrk"},Nv=26,Yu=0,Lc=0;function jv(e,t){return Zu(e,"ascending",t)}r(jv,"ascending");function $v(e,t){return Zu(e,"descending",t)}r($v,"descending");function Zu(e,t,n){if(!n)return Qu(Mc[e],t);if(!n.startsWith(Mc[e]))throw new Error(`ID ${n} does not start with ${Mc[e]}`);return n}r(Zu,"generateID");function Uv(e){let t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",n="",o=Lv(e);for(let s=0;s<e;s++)n+=t[o[s]%62];return n}r(Uv,"randomBase62");function Qu(e,t,n){let o=n??Date.now();o!==Yu&&(Yu=o,Lc=0),Lc++;let s=BigInt(o)*BigInt(4096)+BigInt(Lc);s=t==="descending"?~s:s;let i=Buffer.alloc(6);for(let a=0;a<6;a++)i[a]=Number(s>>BigInt(40-8*a)&BigInt(255));return e+"_"+i.toString("hex")+Uv(Nv-12)}r(Qu,"create");function Bv(e,t){if(e===t)return 0;try{let n=BigInt("0x"+e.slice(e.indexOf("_")+1,e.indexOf("_")+13)),o=BigInt("0x"+t.slice(t.indexOf("_")+1,t.indexOf("_")+13));if(n!==o){let s=1n<<48n,i=1n<<47n,a=(n-o)%s;return a<0n&&(a+=s),a<i?1:-1}}catch{}return e<t?-1:1}r(Bv,"compareAscending");function Fv(e){let t=e.split("_")[0],n=e.slice(t.length+1,t.length+13),o=BigInt("0x"+n);return Number(o/BigInt(4096))}r(Fv,"timestamp");var Nc=class extends qv{static{r(this,"GlobalBusEmitter")}emit(t,n){return n.payload&&typeof n.payload=="object"&&!("id"in n.payload)&&(n.payload.id=n.payload.syncEvent?.id??Qr.create("evt","ascending")),super.emit(t,n)}},jc=new Nc;var $c={};R($c,{EventV2Bridge:()=>$c,Service:()=>Xo,node:()=>Hv});import{Context as Vv,Effect as wi,Layer as Wv}from"effect";var Xo=class extends Vv.Service()("@opencode/EventV2Bridge"){static{r(this,"Service")}},Gv=Wv.effect(Xo,wi.gen(function*(){let e=yield*Fe.Service,t=r((o,s,i)=>wi.gen(function*(){if(i?.location)return yield*e.publish(o,s,i);let a=yield*jr;if(!a)return yield*e.publish(o,s,i);let c=yield*$r;return yield*e.publish(o,s,{...i,location:new En.Info({directory:bt.make(a.directory),...c?{workspaceID:c}:{},project:{id:tn.ID.make(a.project.id),directory:bt.make(a.worktree)}})})}),"publish"),n=yield*e.listen(o=>wi.gen(function*(){let s=yield*jr,i=(yield*$r)??o.location?.workspaceID;jc.emit("event",{directory:o.location?.directory??s?.directory,project:s?.project.id,workspace:i,payload:{id:o.id,type:o.type,properties:o.data}}),o.durable!==void 0&&jc.emit("event",{directory:o.location?.directory??s?.directory,project:s?.project.id,workspace:i,payload:{type:"sync",syncEvent:{id:o.id,type:Fe.versionedType(o.type,o.durable.version),seq:o.durable.seq,aggregateID:o.durable.aggregateID,data:o.data}}})}));return yield*wi.addFinalizer(()=>n),Xo.of({...e,publish:t})})),Hv=xe.make({service:Xo,layer:Gv,deps:[Fe.node]});var Bc={};R(Bc,{Git:()=>Bc,Service:()=>zo,node:()=>ew});import{Effect as Ee,Layer as Jv,Context as Kv,Stream as Xv}from"effect";import{ChildProcess as zv}from"effect/unstable/process";var Yv=["--no-optional-locks","-c","core.autocrlf=false","-c","core.fsmonitor=false","-c","core.longpaths=true","-c","core.symlinks=true","-c","core.quotepath=false"],es=r(e=>e.text().trim(),"out"),Uc=r(e=>e.split("\0").filter(Boolean),"nuls"),Zv=r(e=>({exitCode:1,text:r(()=>"","text"),stdout:Buffer.alloc(0),stderr:Buffer.from(e instanceof Error?e.message:String(e)),truncated:!1}),"fail"),ef=r(e=>e==="??"?"added":e.includes("U")?"modified":e.includes("A")&&!e.includes("D")?"added":e.includes("D")&&!e.includes("A")?"deleted":"modified","kind"),zo=class extends Kv.Service()("@opencode/Git"){static{r(this,"Service")}},Qv=Jv.effect(zo,Ee.gen(function*(){let e=yield*Zi.Service,t=new TextEncoder,n=r(x=>Xv.make(t.encode(x)),"stdin"),o=Ee.fn("Git.run")(function*(x,E){let y=yield*e.run(zv.make("git",[...Yv,...x],{cwd:E.cwd,env:E.env,extendEnv:!0,stdin:E.stdin??"ignore",stdout:"pipe",stderr:"pipe"}),{maxOutputBytes:E.maxOutputBytes});return{exitCode:y.exitCode,text:r(()=>y.stdout.toString("utf8"),"text"),stdout:y.stdout,stderr:y.stderr,truncated:y.stdoutTruncated||y.stderrTruncated}},Ee.catch(x=>Ee.succeed(Zv(x)))),s=Ee.fn("Git.text")(function*(x,E){return(yield*o(x,E)).text()}),i=Ee.fn("Git.lines")(function*(x,E){return(yield*s(x,E)).split(/\r?\n/).map(y=>y.trim()).filter(Boolean)}),a=Ee.fnUntraced(function*(x){return yield*i(["for-each-ref","--format=%(refname:short)","refs/heads"],{cwd:x})}),c=Ee.fnUntraced(function*(x,E){let y=yield*o(["config","init.defaultBranch"],{cwd:x}),S=es(y);if(!(!S||!E.includes(S)))return{name:S,ref:S}}),l=Ee.fnUntraced(function*(x){let E=yield*i(["remote"],{cwd:x});return E.includes("origin")?"origin":E.length===1?E[0]:E.includes("upstream")?"upstream":E[0]}),f=Ee.fn("Git.branch")(function*(x){let E=yield*o(["symbolic-ref","--quiet","--short","HEAD"],{cwd:x});return E.exitCode!==0?void 0:es(E)||void 0}),g=Ee.fn("Git.prefix")(function*(x){let E=yield*o(["rev-parse","--show-prefix"],{cwd:x});return E.exitCode!==0?"":es(E)}),d=Ee.fn("Git.defaultBranch")(function*(x){let E=yield*l(x);if(E){let v=yield*o(["symbolic-ref",`refs/remotes/${E}/HEAD`],{cwd:x});if(v.exitCode===0){let O=es(v).replace(/^refs\/remotes\//,""),Q=O.startsWith(`${E}/`)?O.slice(`${E}/`.length):"";if(Q)return{name:Q,ref:O}}}let y=yield*a(x),S=yield*c(x,y);if(S)return S;if(y.includes("main"))return{name:"main",ref:"main"};if(y.includes("master"))return{name:"master",ref:"master"}}),h=Ee.fn("Git.hasHead")(function*(x){return(yield*o(["rev-parse","--verify","HEAD"],{cwd:x})).exitCode===0}),b=Ee.fn("Git.mergeBase")(function*(x,E,y="HEAD"){let S=yield*o(["merge-base",E,y],{cwd:x});return S.exitCode!==0?void 0:es(S)||void 0}),_=Ee.fn("Git.show")(function*(x,E,y,S=""){let v=S?`${S}${y}`:y,O=yield*o(["show",`${E}:${v}`],{cwd:x});return O.exitCode!==0||O.stdout.includes(0)?"":O.text()}),P=Ee.fn("Git.status")(function*(x){return Uc(yield*s(["status","--porcelain=v1","--untracked-files=all","--no-renames","-z","--","."],{cwd:x})).flatMap(E=>{let y=E.slice(3);if(!y)return[];let S=E.slice(0,2);return[{file:y,code:S,status:ef(S)}]})}),C=Ee.fn("Git.diff")(function*(x,E){let y=Uc(yield*s(["diff","--no-ext-diff","--no-renames","--name-status","-z",E,"--","."],{cwd:x}));return y.flatMap((S,v)=>{if(v%2!==0)return[];let O=y[v+1];return!S||!O?[]:[{file:O,code:S,status:ef(S)}]})}),J=Ee.fn("Git.stats")(function*(x,E){return Uc(yield*s(["diff","--no-ext-diff","--no-renames","--numstat","-z",E,"--","."],{cwd:x})).flatMap(y=>{let S=y.indexOf(" "),v=y.indexOf(" ",S+1);if(S===-1||v===-1)return[];let O=y.slice(v+1);if(!O)return[];let Q=y.slice(0,S),ae=y.slice(S+1,v),ue=Q==="-"?0:Number.parseInt(Q||"0",10),Le=ae==="-"?0:Number.parseInt(ae||"0",10);return[{file:O,additions:Number.isFinite(ue)?ue:0,deletions:Number.isFinite(Le)?Le:0}]})}),te=Ee.fn("Git.patch")(function*(x,E,y,S){let v=yield*o(["diff","--patch","--no-ext-diff","--no-renames",`--unified=${S?.context??3}`,E,"--",y],{cwd:x,maxOutputBytes:S?.maxOutputBytes});return{text:v.truncated?"":v.text(),truncated:v.truncated}}),L=Ee.fn("Git.patchAll")(function*(x,E,y){let S=yield*o(["diff","--patch","--no-ext-diff","--no-renames",`--unified=${y?.context??3}`,E,"--","."],{cwd:x,maxOutputBytes:y?.maxOutputBytes});return{text:S.text(),truncated:S.truncated}}),G=Ee.fn("Git.patchUntracked")(function*(x,E,y){let S=yield*o(["diff","--no-index","--patch","--no-ext-diff","--no-renames",`--unified=${y?.context??3}`,"--","/dev/null",E],{cwd:x,maxOutputBytes:y?.maxOutputBytes});return{text:S.truncated?"":S.text(),truncated:S.truncated}}),K=Ee.fn("Git.statUntracked")(function*(x,E){let y=yield*o(["diff","--no-index","--numstat","--","/dev/null",E],{cwd:x,maxOutputBytes:4096});if(y.truncated)return;let v=y.text().split(" ");if(v.length<2)return;let O=v[0]==="-"?0:Number.parseInt(v[0]||"0",10),Q=v[1]==="-"?0:Number.parseInt(v[1]||"0",10);return{file:E,additions:Number.isFinite(O)?O:0,deletions:Number.isFinite(Q)?Q:0}}),Me=Ee.fn("Git.applyPatch")(function*(x,E){return yield*o(["apply","-"],{cwd:x,stdin:n(E)})});return zo.of({run:o,branch:f,prefix:g,defaultBranch:d,hasHead:h,mergeBase:b,show:_,status:P,diff:C,stats:J,patch:te,patchAll:L,patchUntracked:G,statUntracked:K,applyPatch:Me})})),ew=xe.make({service:zo,layer:Qv,deps:[Zi.node]});var Fc={};R(Fc,{RuntimeFlags:()=>Fc,Service:()=>Ht,layer:()=>cw,node:()=>lw});import{Config as Pe,ConfigProvider as nf,Effect as sw,Layer as ns,Option as iw}from"effect";var ts={};R(ts,{ConfigService:()=>ts,Service:()=>rw});import{Config as tw,Context as nw,Effect as ow,Layer as tf}from"effect";var rw=r(()=>(e,t)=>{class n extends nw.Service()(e){static{r(this,"ConfigTag")}static configLayer(s){return tf.succeed(this,this.of(s))}static get layer(){let s=this;return tf.effect(s,ow.gen(function*(){let i=yield*tw.all(t);return s.of(i)}))}}return n},"Service");var Ae=r(e=>Pe.boolean(e).pipe(Pe.withDefault(!1)),"bool"),of=r(e=>Pe.number(e).pipe(Pe.map(t=>Number.isInteger(t)&&t>0?t:void 0),Pe.orElse(()=>Pe.succeed(void 0))),"positiveInteger"),rf=Ae("OPENCODE_EXPERIMENTAL"),Gt=r(e=>Pe.all({experimental:rf,enabled:Pe.boolean(e).pipe(Pe.option)}).pipe(Pe.map(t=>iw.getOrElse(t.enabled,()=>t.experimental))),"enabledByExperimental"),Ht=class extends ts.Service()("@opencode/RuntimeFlags",{autoShare:Ae("OPENCODE_AUTO_SHARE"),pure:Ae("OPENCODE_PURE"),disableDefaultPlugins:Ae("OPENCODE_DISABLE_DEFAULT_PLUGINS"),disableEmbeddedWebUi:Ae("OPENCODE_DISABLE_EMBEDDED_WEB_UI"),disableExternalSkills:Ae("OPENCODE_DISABLE_EXTERNAL_SKILLS"),disableLspDownload:Ae("OPENCODE_DISABLE_LSP_DOWNLOAD"),disableClaudeCodePrompt:Pe.all({broad:Ae("OPENCODE_DISABLE_CLAUDE_CODE"),direct:Ae("OPENCODE_DISABLE_CLAUDE_CODE_PROMPT")}).pipe(Pe.map(t=>t.broad||t.direct)),disableClaudeCodeSkills:Pe.all({broad:Ae("OPENCODE_DISABLE_CLAUDE_CODE"),direct:Ae("OPENCODE_DISABLE_CLAUDE_CODE_SKILLS")}).pipe(Pe.map(t=>t.broad||t.direct)),enableExa:Pe.all({experimental:rf,enabled:Ae("OPENCODE_ENABLE_EXA"),legacy:Ae("OPENCODE_EXPERIMENTAL_EXA")}).pipe(Pe.map(t=>t.experimental||t.enabled||t.legacy)),enableParallel:Pe.all({enabled:Ae("OPENCODE_ENABLE_PARALLEL"),legacy:Ae("OPENCODE_EXPERIMENTAL_PARALLEL")}).pipe(Pe.map(t=>t.enabled||t.legacy)),enableExperimentalModels:Ae("OPENCODE_ENABLE_EXPERIMENTAL_MODELS"),enableQuestionTool:Ae("OPENCODE_ENABLE_QUESTION_TOOL"),experimentalReferences:Gt("OPENCODE_EXPERIMENTAL_REFERENCES"),experimentalBackgroundSubagents:Gt("OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS"),experimentalLspTy:Ae("OPENCODE_EXPERIMENTAL_LSP_TY"),experimentalLspTool:Gt("OPENCODE_EXPERIMENTAL_LSP_TOOL"),experimentalOxfmt:Gt("OPENCODE_EXPERIMENTAL_OXFMT"),experimentalPlanMode:Gt("OPENCODE_EXPERIMENTAL_PLAN_MODE"),experimentalCodeMode:Gt("OPENCODE_EXPERIMENTAL_CODE_MODE"),experimentalEventSystem:Gt("OPENCODE_EXPERIMENTAL_EVENT_SYSTEM"),experimentalWorkspaces:Gt("OPENCODE_EXPERIMENTAL_WORKSPACES"),experimentalIconDiscovery:Gt("OPENCODE_EXPERIMENTAL_ICON_DISCOVERY"),outputTokenMax:of("OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX"),bashDefaultTimeoutMs:of("OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS"),experimentalNativeLlm:Ae("OPENCODE_EXPERIMENTAL_NATIVE_LLM"),experimentalWebSockets:Ae("OPENCODE_EXPERIMENTAL_WEBSOCKETS"),client:Pe.string("OPENCODE_CLIENT").pipe(Pe.withDefault("cli")),alchemyLab:Ae("ALCHEMYLAB")}){static{r(this,"Service")}},aw=Ht.layer.pipe(ns.provide(nf.layer(nf.fromUnknown({}))),ns.orDie),cw=r((e={})=>ns.effect(Ht,sw.gen(function*(){let t=yield*Ht;return Ht.of({...t,...e})})).pipe(ns.provide(aw)),"layer"),lw=xe.make({service:Ht,layer:Ht.layer.pipe(ns.orDie),deps:[]});var Yo={};R(Yo,{LocationServiceMap:()=>Yo,Service:()=>Ei,node:()=>fw});import{Context as dw,Effect as pw,Layer as uw}from"effect";var Ei=class e extends dw.Service()("@opencode/example/LocationServiceMap"){static{r(this,"Service")}static get(t){return uw.unwrap(pw.map(e,n=>n.get(t)))}},fw=xe.unbound(Ei,us.tags.values.global);var bi={};R(bi,{Tool:()=>bi,ToolFailure:()=>uo,make:()=>Ii,toDefinitions:()=>ki});import{Effect as af,Schema as os}from"effect";function Ii(e){return"jsonSchema"in e?{description:e.description,parameters:os.Unknown,success:os.Unknown,execute:e.execute,toModelOutput:e.toModelOutput,toStructuredOutput:e.toStructuredOutput,_decode:af.succeed,_encode:af.succeed,_project:r((t,n,o)=>lf(e.toModelOutput,e.toStructuredOutput,t,n,o),"_project"),_legacyResult:e.toModelOutput===void 0&&e.toStructuredOutput===void 0,_definition:new po({name:"",description:e.description,inputSchema:e.jsonSchema,outputSchema:e.outputSchema})}:{description:e.description,parameters:e.parameters,success:e.success,execute:e.execute,toModelOutput:e.toModelOutput,toStructuredOutput:e.toStructuredOutput,_decode:os.decodeUnknownEffect(e.parameters),_encode:os.encodeEffect(e.success),_project:r((t,n,o)=>lf(e.toModelOutput,e.toStructuredOutput,t,n,o),"_project"),_legacyResult:!1,_definition:new po({name:"",description:e.description,inputSchema:cf(e.parameters),outputSchema:cf(e.success)})}}r(Ii,"make");var ki=r(e=>Object.entries(e).map(([t,n])=>new po({name:t,description:n._definition.description,inputSchema:n._definition.inputSchema,outputSchema:n._definition.outputSchema})),"toDefinitions"),cf=r(e=>{let t=os.toJsonSchemaDocument(e);return Object.keys(t.definitions).length===0?t.schema:{...t.schema,$defs:t.definitions}},"toJsonSchema"),lf=r((e,t,n,o,s)=>ur.make(t?.(s)??s,e?.({callID:o,parameters:n,output:s})??(typeof s=="string"?[{type:"text",text:s}]:[])),"project");import{Effect as Lt}from"effect";var mw=r((e,t)=>{let n=e[t.name];return n?n.execute?gw(n,t).pipe(Lt.map(o=>Di(t,o)),Lt.catchTag("LLM.ToolFailure",o=>Lt.succeed(Di(t,{type:"error",value:o.message},o.error)))):Lt.succeed(Di(t,{type:"error",value:`Tool has no execute handler: ${t.name}`})):Lt.succeed(Di(t,{type:"error",value:`Unknown tool: ${t.name}`}))},"dispatch"),gw=r((e,t)=>e._decode(t.input).pipe(Lt.mapError(n=>new uo({message:`Invalid tool input: ${n.message}`})),Lt.flatMap(n=>e.execute(n,{id:t.id,name:t.name}).pipe(Lt.flatMap(o=>e._encode(o).pipe(Lt.mapError(s=>new uo({message:`Tool returned an invalid value for its success schema: ${s.message}`})))),Lt.map(o=>{if(e._legacyResult&&Ji.is(o))return{result:o,output:ur.fromResultValue(o)};let s=e._project(n,t.id,o),i=ur.toResultValue(s);return i.type==="error"?{result:i}:{result:i,output:s}})))),"decodeAndExecute"),Di=r((e,t,n)=>{let o=Ji.is(t)?{result:t}:t;return{result:o.result,output:o.output,events:o.result.type==="error"?[z.toolError({id:e.id,name:e.name,message:String(o.result.value),error:n}),z.toolResult({id:e.id,name:e.name,result:o.result})]:[z.toolResult({id:e.id,name:e.name,result:o.result,output:o.output})]}},"result"),yw={dispatch:mw};var ff={};R(ff,{GenerateObjectResponse:()=>Ai,generate:()=>Sw,generateObject:()=>ww,request:()=>qc,requestInput:()=>uf,stream:()=>xw,updateRequest:()=>vw});import{Effect as _i,Schema as hw}from"effect";var Sw=gr.generate,xw=gr.stream,uf=r(e=>({...Ss.input(e)}),"requestInput"),qc=r(e=>{let{system:t,prompt:n,messages:o,tools:s,toolChoice:i,generation:a,providerOptions:c,http:l,...f}=e;return new Ss({...f,system:Dl.content(t),messages:[...o?.map(Ki.make)??[],...n===void 0?[]:[Ki.user(n)]],tools:s?.map(po.make)??[],toolChoice:i?Xi.make(i):void 0,generation:a===void 0?void 0:bl.make(a),providerOptions:c,http:l===void 0?void 0:kl.make(l)})},"request"),vw=r((e,t)=>qc({...uf(e),...t}),"updateRequest"),Ti="generate_object",df="Return the structured result by calling this tool.",Ai=class{constructor(t,n){this.object=t;this.response=n}object;response;static{r(this,"GenerateObjectResponse")}get events(){return this.response.events}get usage(){return this.response.usage}},pf=_i.fn("LLM.generateObject")(function*(e,t){let n=qc(e),o=Ss.update(n,{tools:ki({[Ti]:t}),toolChoice:Xi.named(Ti)}),s=yield*gr.generate(o),i=s.toolCalls.find(c=>z.is.toolCall(c)&&c.name===Ti);if(!i||!z.is.toolCall(i))return yield*new fr({module:"LLM",method:"generateObject",reason:new zi({message:`generateObject: model did not call the forced \`${Ti}\` tool`})});let a=yield*t._decode(i.input).pipe(_i.mapError(c=>new fr({module:"LLM",method:"generateObject",reason:new zi({message:`generateObject: tool input failed schema decode: ${c.message}`})})));return new Ai(a,s)});function ww(e){if("schema"in e){let{schema:o,...s}=e;return pf(s,Ii({description:df,parameters:o,success:hw.Unknown,execute:r(()=>_i.void,"execute")}))}let{jsonSchema:t,...n}=e;return pf(n,Ii({description:df,jsonSchema:t,execute:r(()=>_i.void,"execute")}))}r(ww,"generateObject");var tr={};R(tr,{Service:()=>er,SessionExecution:()=>tr,node:()=>Zk,noopLayer:()=>Qk});import{Context as zk,Effect as Ui,Layer as Yk}from"effect";var nl={};R(nl,{Service:()=>tl,SessionRunner:()=>nl});import{Context as Xk}from"effect";var el={};R(el,{ModelNotSelectedError:()=>Li,ModelUnavailableError:()=>Ni,Service:()=>mn,SessionRunnerModel:()=>el,UnsupportedApiError:()=>$i,VariantUnavailableError:()=>ji,fromCatalogModel:()=>Zf,layerWith:()=>Wk,locationLayer:()=>em,node:()=>Kk,resolve:()=>Qf,supported:()=>Qc});import{Effect as Ke,Schema as m}from"effect";var mf=r(e=>({remaining:e,dropped:0}),"newBreakpoints"),gf=r(e=>e!==void 0&&e>=3600?"1h":void 0,"ttlBucket");var W={};R(W,{Lifecycle:()=>W,finish:()=>Aw,initial:()=>Iw,reasoningDelta:()=>bw,reasoningEnd:()=>Dw,reasoningStart:()=>yf,stepStart:()=>Zo,textDelta:()=>kw,textEnd:()=>Tw});var Iw=r(()=>({stepStarted:!1,text:new Set,reasoning:new Set}),"initial"),Zo=r((e,t)=>e.stepStarted?e:(t.push(z.stepStart({index:0})),{...e,stepStarted:!0}),"stepStart"),kw=r((e,t,n,o)=>{let s=Zo(e,t);return s.text.has(n)?(t.push(z.textDelta({id:n,text:o})),s):(t.push(z.textStart({id:n}),z.textDelta({id:n,text:o})),{...s,text:new Set([...s.text,n])})},"textDelta"),yf=r((e,t,n,o)=>{if(e.reasoning.has(n))return e;let s=Zo(e,t);return t.push(z.reasoningStart({id:n,providerMetadata:o})),{...s,reasoning:new Set([...s.reasoning,n])}},"reasoningStart"),bw=r((e,t,n,o,s)=>{let i=yf(e,t,n,s);return t.push(z.reasoningDelta({id:n,text:o})),i},"reasoningDelta"),Dw=r((e,t,n,o)=>{if(!e.reasoning.has(n))return e;let s=Zo(e,t);t.push(z.reasoningEnd({id:n,providerMetadata:o}));let i=new Set(s.reasoning);return i.delete(n),{...s,reasoning:i}},"reasoningEnd"),Tw=r((e,t,n,o)=>{if(!e.text.has(n))return e;let s=Zo(e,t);t.push(z.textEnd({id:n,providerMetadata:o}));let i=new Set(s.text);return i.delete(n),{...s,text:i}},"textEnd"),_w=r((e,t)=>{for(let n of e.reasoning)t.push(z.reasoningEnd({id:n}));for(let n of e.text)t.push(z.textEnd({id:n}));return{...e,text:new Set,reasoning:new Set}},"closeOpenBlocks"),Aw=r((e,t,n)=>{let o=_w(Zo(e,t),t);return t.push(z.stepFinish({index:0,reason:n.reason,usage:n.usage,providerMetadata:n.providerMetadata}),z.finish(n)),{...o,stepStarted:!1}},"finish");var rs={};R(rs,{GeminiToolSchema:()=>rs,convert:()=>Pw});var Ow=["type","properties","items","prefixItems","enum","const","$ref","additionalProperties","patternProperties","required","not","if","then","else"],Vc=r(e=>Re(e)&&(Array.isArray(e.anyOf)||Array.isArray(e.oneOf)||Array.isArray(e.allOf)),"hasCombiner"),Rw=r(e=>Re(e)&&(Vc(e)||Ow.some(t=>t in e)),"hasSchemaIntent"),Wc=r(e=>{if(!Re(e))return Array.isArray(e)?e.map(Wc):e;let t=Object.fromEntries(Object.entries(e).map(([o,s])=>[o,o==="enum"&&Array.isArray(s)?s.map(String):Wc(s)]));Array.isArray(t.enum)&&(t.type==="integer"||t.type==="number")&&(t.type="string");let n=t.properties;return t.type==="object"&&Re(n)&&Array.isArray(t.required)&&(t.required=t.required.filter(o=>typeof o=="string"&&o in n)),t.type==="array"&&!Vc(t)&&(t.items=t.items??{},Re(t.items)&&!Rw(t.items)&&(t.items={...t.items,type:"string"})),typeof t.type=="string"&&t.type!=="object"&&!Vc(t)&&(delete t.properties,delete t.required),t},"sanitizeNode"),Cw=r(e=>e.type==="object"&&(!Re(e.properties)||Object.keys(e.properties).length===0)&&!e.additionalProperties,"emptyObjectSchema"),Qn=r(e=>{if(Re(e)&&!Cw(e))return Object.fromEntries([["description",e.description],["required",e.required],["format",e.format],["type",Array.isArray(e.type)?e.type.filter(t=>t!=="null")[0]:e.type],["nullable",Array.isArray(e.type)&&e.type.includes("null")?!0:void 0],["enum",e.const!==void 0?[e.const]:e.enum],["properties",Re(e.properties)?Object.fromEntries(Object.entries(e.properties).map(([t,n])=>[t,Qn(n)])):void 0],["items",Array.isArray(e.items)?e.items.map(Qn):e.items===void 0?void 0:Qn(e.items)],["allOf",Array.isArray(e.allOf)?e.allOf.map(Qn):void 0],["anyOf",Array.isArray(e.anyOf)?e.anyOf.map(Qn):void 0],["oneOf",Array.isArray(e.oneOf)?e.oneOf.map(Qn):void 0],["minLength",e.minLength]].filter(t=>t[1]!==void 0))},"projectNode"),Pw=r(e=>Qn(Wc(e)),"convert");var Oi=r(e=>{if(Array.isArray(e))return e.map(Oi);if(!Re(e))return e;let t=Object.fromEntries(Object.entries(e).filter(([o])=>o!=="anyOf").map(([o,s])=>[o,Oi(s)]));if(!Array.isArray(e.anyOf))return t;let n=e.anyOf.filter(o=>!Re(o)||o.type!=="null").map(Oi);return n.length===1&&Re(n[0])?{...t,...n[0]}:{...t,anyOf:n}},"removeNullSchemas"),hf=r(e=>{let t=e.map(Ri);return t.length===0?{}:t.length===1?t[0]:{anyOf:t}},"tupleItemsSchema"),Ri=r(e=>Array.isArray(e)?e.map(Ri):Re(e)?typeof e.$ref=="string"?{$ref:e.$ref}:Object.fromEntries(Object.entries(e).flatMap(([t,n])=>t==="items"&&Array.isArray(n)?[[t,hf(n)]]:t==="prefixItems"?"items"in e?[]:[["items",hf(Array.isArray(n)?n:[])]]:t==="unevaluatedItems"?[]:[[t,Ri(n)]])):e,"moonshotNode"),Sf=r(e=>{let t=Ri(e);return Re(t)?t:{}},"moonshot"),Mw=r(e=>{let t=Array.isArray(e.anyOf)?e.anyOf.filter(Re):[],n=t.length===0?{...e,type:"object"}:{...Object.fromEntries(Object.entries(e).filter(([s])=>s!=="anyOf")),type:"object",properties:t.reduce((s,i)=>({...Re(i.properties)?i.properties:{},...s}),{}),additionalProperties:!1},o=Oi(n);return Re(o)?o:{type:"object"}},"openAI"),xf=r(e=>rs.convert(e)??{},"gemini"),Lw=r((e,t)=>{if(t===void 0)return e;switch(t){case"gemini":return xf(e);case"moonshot":return Sf(e)}},"modelCompatibility"),dn={gemini:xf,modelCompatibility:Lw,moonshot:Sf,openAI:Mw};var De={};R(De,{ToolStream:()=>De,appendExisting:()=>Fw,appendOrStart:()=>Bw,empty:()=>vf,finish:()=>qw,finishAll:()=>Ww,finishWithInput:()=>Vw,isError:()=>$w,start:()=>Uw});import{Effect as eo}from"effect";var vf=r(()=>({}),"empty"),wf=r((e,t,n)=>({...e,[t]:n}),"withTool"),Ef=r((e,t)=>{let n={...e};return delete n[t],n},"withoutTool"),Nw=r(e=>z.toolInputStart({id:e.id,name:e.name,providerMetadata:e.providerMetadata}),"inputStart"),jw=r((e,t)=>z.toolInputDelta({id:e.id,name:e.name,text:t}),"inputDelta"),Gc=r((e,t,n)=>Tl(e,t.name,n??t.input).pipe(eo.map(o=>z.toolCall({id:t.id,name:t.name,input:o,providerExecuted:t.providerExecuted?!0:void 0,providerMetadata:t.providerMetadata}))),"toolCall"),If=r((e,t,n,o)=>{let s=[];return e[t]||s.push(Nw(n)),o.length>0&&s.push(jw(n,o)),{tools:wf(e,t,n),tool:n,events:s}},"appendTool"),$w=r(e=>e instanceof fr,"isError"),Uw=r((e,t,n)=>wf(e,t,{...n,input:n.input??""}),"start"),Bw=r((e,t,n,o,s)=>{let i=t[n],a=o.id??i?.id,c=o.name??i?.name;if(!a||!c)return Yi(e,s);let l={id:a,name:c,input:`${i?.input??""}${o.text}`,providerExecuted:i?.providerExecuted,providerMetadata:i?.providerMetadata};return i&&o.text.length===0&&i.id===a&&i.name===c?{tools:t,tool:i,events:[]}:If(t,n,l,o.text)},"appendOrStart"),Fw=r((e,t,n,o,s)=>{let i=t[n];return i?o.length===0?{tools:t,tool:i,events:[]}:If(t,n,{...i,input:`${i.input}${o}`},o):Yi(e,s)},"appendExisting"),qw=r((e,t,n)=>eo.gen(function*(){let o=t[n];return o?{tools:Ef(t,n),events:[z.toolInputEnd({id:o.id,name:o.name,providerMetadata:o.providerMetadata}),yield*Gc(e,o)]}:{tools:t}}),"finish"),Vw=r((e,t,n,o)=>eo.gen(function*(){let s=t[n];return s?{tools:Ef(t,n),events:[z.toolInputEnd({id:s.id,name:s.name,providerMetadata:s.providerMetadata}),yield*Gc(e,s,o)]}:{tools:t}}),"finishWithInput"),Ww=r((e,t)=>eo.gen(function*(){let n=Object.values(t).filter(o=>o!==void 0);return{tools:vf(),events:yield*eo.forEach(n,o=>Gc(e,o).pipe(eo.map(s=>[z.toolInputEnd({id:o.id,name:o.name,providerMetadata:o.providerMetadata}),s]))).pipe(eo.map(o=>o.flat()))}}),"finishAll");var Pi="anthropic-messages",Gw="https://api.anthropic.com/v1",Hw="/messages",pn=m.Struct({type:m.tag("ephemeral"),ttl:m.optional(m.Literals(["5m","1h"]))}),ss=m.Struct({type:m.tag("text"),text:m.String,cache_control:m.optional(pn)}),Df=m.Struct({type:m.tag("image"),source:m.Struct({type:m.tag("base64"),media_type:m.String,data:m.String}),cache_control:m.optional(pn)}),Jw=m.Struct({type:m.tag("thinking"),thinking:m.String,signature:m.optional(m.String),cache_control:m.optional(pn)}),Kw=m.Struct({type:m.tag("tool_use"),id:m.String,name:m.String,input:m.Unknown,cache_control:m.optional(pn)}),Xw=m.Struct({type:m.tag("server_tool_use"),id:m.String,name:m.String,input:m.Unknown,cache_control:m.optional(pn)}),zw=m.Literals(["web_search_tool_result","code_execution_tool_result","web_fetch_tool_result"]),Yw=m.Struct({type:zw,tool_use_id:m.String,content:m.Unknown,cache_control:m.optional(pn)}),Zw=m.Union([ss,Df]),Qw=m.Struct({type:m.tag("tool_result"),tool_use_id:m.String,content:m.Union([m.String,m.Array(Zw)]),is_error:m.optional(m.Boolean),cache_control:m.optional(pn)}),eE=m.Union([ss,Df,Qw]),tE=m.Union([ss,Jw,Kw,Xw,Yw]),nE=m.Union([m.Struct({role:m.Literal("user"),content:m.Array(eE)}),m.Struct({role:m.Literal("assistant"),content:m.Array(tE)}),m.Struct({role:m.Literal("system"),content:m.Array(ss)})]).pipe(m.toTaggedUnion("role")),oE=m.Struct({name:m.String,description:m.String,input_schema:fo,cache_control:m.optional(pn)}),rE=m.Union([m.Struct({type:m.Literals(["auto","any"])}),m.Struct({type:m.tag("tool"),name:m.String})]),sE=m.Struct({type:m.tag("enabled"),budget_tokens:m.Number}),iE={model:m.String,system:ht(ss),messages:m.Array(nE),tools:ht(oE),tool_choice:m.optional(rE),stream:m.Literal(!0),max_tokens:m.Number,temperature:m.optional(m.Number),top_p:m.optional(m.Number),top_k:m.optional(m.Number),stop_sequences:ht(m.String),thinking:m.optional(sE)},aE=m.Struct(iE),kf=m.Struct({input_tokens:m.optional(m.Number),output_tokens:m.optional(m.Number),cache_creation_input_tokens:se(m.Number),cache_read_input_tokens:se(m.Number)}),cE=m.Struct({type:m.String,id:m.optional(m.String),name:m.optional(m.String),text:m.optional(m.String),thinking:m.optional(m.String),signature:m.optional(m.String),input:m.optional(m.Unknown),tool_use_id:m.optional(m.String),content:m.optional(m.Unknown)}),lE=m.Struct({type:m.optional(m.String),text:m.optional(m.String),thinking:m.optional(m.String),partial_json:m.optional(m.String),signature:m.optional(m.String),stop_reason:se(m.String),stop_sequence:se(m.String)}),dE=m.Struct({type:m.String,index:m.optional(m.Number),message:m.optional(m.Struct({usage:m.optional(kf)})),content_block:m.optional(cE),delta:m.optional(lE),usage:m.optional(kf),error:m.optional(m.Struct({type:m.optional(m.String),message:m.optional(m.String)}))}),Ci=M.invalidRequest,bf=4,pE={type:"ephemeral"},uE={type:"ephemeral",ttl:"1h"},to=r((e,t)=>{if(!(t?.type!=="ephemeral"&&t?.type!=="persistent")){if(e.remaining<=0){e.dropped+=1;return}return e.remaining-=1,gf(t.ttlSeconds)==="1h"?uE:pE}},"cacheControl"),Hc=r(e=>({anthropic:e}),"anthropicMetadata"),fE=r(e=>{let t=e?.anthropic;if(M.isRecord(t))return typeof t.signature=="string"?t.signature:void 0},"signatureFromMetadata"),mE=r((e,t,n)=>({name:t.name,description:t.description,input_schema:n,cache_control:to(e,t.cache)}),"lowerTool"),gE=r(e=>M.matchToolChoice("Anthropic Messages",e,{auto:r(()=>({type:"auto"}),"auto"),none:r(()=>{},"none"),required:r(()=>({type:"any"}),"required"),tool:r(t=>({type:"tool",name:t}),"tool")}),"lowerToolChoice"),yE=r(e=>({type:"tool_use",id:e.id,name:e.name,input:e.input}),"lowerToolCall"),hE=r(e=>({type:"server_tool_use",id:e.id,name:e.name,input:e.input}),"lowerServerToolCall"),SE=r(e=>{if(e==="web_search")return"web_search_tool_result";if(e==="code_execution")return"code_execution_tool_result";if(e==="web_fetch")return"web_fetch_tool_result"},"serverToolResultType"),xE=Ke.fn("AnthropicMessages.lowerServerToolResult")(function*(e){let t=SE(e.name);return t?{type:t,tool_use_id:e.id,content:e.result.value}:yield*Ci(`Anthropic Messages does not know how to round-trip server tool result for ${e.name}`)}),vE=Ke.fn("AnthropicMessages.lowerImage")(function*(e){let t=yield*M.validateMedia("Anthropic Messages",e,new Set(M.IMAGE_MIMES));return{type:"image",source:{type:"base64",media_type:t.mime,data:t.base64}}}),wE=Ke.fn("AnthropicMessages.lowerToolResultContentItem")(function*(e){if(e.type==="text")return{type:"text",text:e.text};let t=yield*M.validateToolFile("Anthropic Messages",e,new Set(M.IMAGE_MIMES));return{type:"image",source:{type:"base64",media_type:t.mime,data:t.base64}}}),EE=Ke.fn("AnthropicMessages.lowerToolResultContent")(function*(e){if(e.result.type!=="content")return M.toolResultText(e);let t=e.result.value;return yield*Ke.forEach(t,wE)}),IE=r(e=>String(e.model.id)==="claude-opus-4-8","supportsNativeSystemUpdates"),kE=r(e=>{let t=e.content.at(-1);return e.role==="assistant"&&t?.type==="tool-call"&&t.providerExecuted===!0},"endsInServerToolUse"),bE=r((e,t)=>{let n=e[t-1],o=e[t+1];return n!==void 0&&n.role!=="system"&&(n.role==="user"||n.role==="tool"||kE(n))&&o?.role!=="system"&&(o===void 0||o.role==="assistant")},"canUseNativeSystemUpdate"),DE=r((e,t)=>{let n=new Set;for(let o of e.slice(0,t))for(let s of o.content)o.role==="assistant"&&s.type==="tool-call"&&s.providerExecuted!==!0&&n.add(s.id),o.role==="tool"&&s.type==="tool-result"&&n.delete(s.id);return n.size>0},"splitsLocalToolResults"),TE=Ke.fn("AnthropicMessages.lowerNativeSystemUpdate")(function*(e,t){return{role:"system",content:(yield*M.systemUpdateText("Anthropic Messages",e)).map(o=>({type:"text",text:o.text,cache_control:to(t,o.cache)}))}}),_E=Ke.fn("AnthropicMessages.lowerMessages")(function*(e,t){let n=[];for(let[o,s]of e.messages.entries()){if(s.role==="system"){if(DE(e.messages,o))return yield*Ci("Anthropic Messages system updates cannot split a local tool call from its tool result");if(IE(e)&&bE(e.messages,o)){n.push(yield*TE(s,t));continue}let a=yield*M.wrappedSystemUpdate("Anthropic Messages",s),c={type:"text",text:a.text,cache_control:to(t,a.cache)},l=n.at(-1);l?.role==="user"?n[n.length-1]={role:"user",content:[...l.content,c]}:n.push({role:"user",content:[c]});continue}if(s.role==="user"){let a=[];for(let c of s.content){if(c.type==="text"){a.push({type:"text",text:c.text,cache_control:to(t,c.cache)});continue}if(c.type==="media"){a.push(yield*vE(c));continue}return yield*M.unsupportedContent("Anthropic Messages","user",["text","media"])}n.push({role:"user",content:a});continue}if(s.role==="assistant"){let a=[];for(let c of s.content){if(c.type==="text"){a.push({type:"text",text:c.text,cache_control:to(t,c.cache)});continue}if(c.type==="reasoning"){a.push({type:"thinking",thinking:c.text,signature:c.encrypted??fE(c.providerMetadata)});continue}if(c.type==="tool-call"){a.push(c.providerExecuted?hE(c):yE(c));continue}if(c.type==="tool-result"&&c.providerExecuted){a.push(yield*xE(c));continue}return yield*Ci("Anthropic Messages assistant messages only support text, reasoning, and tool-call content for now")}n.push({role:"assistant",content:a});continue}let i=[];for(let a of s.content){if(!M.supportsContent(a,["tool-result"]))return yield*M.unsupportedContent("Anthropic Messages","tool",["tool-result"]);i.push({type:"tool_result",tool_use_id:a.id,content:yield*EE(a),is_error:a.result.type==="error"?!0:void 0,cache_control:to(t,a.cache)})}n.push({role:"user",content:i})}return n}),AE=r(e=>e.providerOptions?.anthropic,"anthropicOptions"),OE=Ke.fn("AnthropicMessages.lowerThinking")(function*(e){let t=AE(e)?.thinking;if(!M.isRecord(t)||t.type!=="enabled")return;let n=typeof t.budgetTokens=="number"?t.budgetTokens:typeof t.budget_tokens=="number"?t.budget_tokens:void 0;return n===void 0?yield*Ci("Anthropic thinking provider option requires budgetTokens"):{type:"enabled",budget_tokens:n}}),RE=Ke.fn("AnthropicMessages.fromRequest")(function*(e){let t=e.toolChoice?yield*gE(e.toolChoice):void 0,n=e.generation,o=e.model.compatibility?.toolSchema,s=e.model.defaults?.limits?.output??e.model.route.defaults.limits?.output??4096,i=mf(bf),a=e.tools.length===0||e.toolChoice?.type==="none"?void 0:e.tools.map(f=>mE(i,f,dn.modelCompatibility(f.inputSchema,o))),c=e.system.length===0?void 0:e.system.map(f=>({type:"text",text:f.text,cache_control:to(i,f.cache)})),l=yield*_E(e,i);return i.dropped>0&&(yield*Ke.logWarning(`Anthropic Messages: dropped ${i.dropped} cache breakpoint(s); the API allows at most ${bf} per request.`)),{model:e.model.id,system:c,messages:l,tools:a,tool_choice:t,stream:!0,max_tokens:n?.maxTokens??s,temperature:n?.temperature,top_p:n?.topP,top_k:n?.topK,stop_sequences:n?.stop,thinking:yield*OE(e)}}),CE=r(e=>e==="end_turn"||e==="stop_sequence"||e==="pause_turn"?"stop":e==="max_tokens"?"length":e==="tool_use"?"tool-calls":e==="refusal"?"content-filter":"unknown","mapFinishReason"),Tf=r(e=>{if(!e)return;let t=e.input_tokens,n=e.cache_read_input_tokens??void 0,o=e.cache_creation_input_tokens??void 0,s=M.sumTokens(t,n,o);return new wn({inputTokens:s,outputTokens:e.output_tokens,nonCachedInputTokens:t,cacheReadInputTokens:n,cacheWriteInputTokens:o,totalTokens:M.totalTokens(s,e.output_tokens,void 0),providerMetadata:{anthropic:e}})},"mapUsage"),_f=r((e,t)=>{if(!e)return t;if(!t)return e;let n=t.nonCachedInputTokens??e.nonCachedInputTokens,o=t.cacheReadInputTokens??e.cacheReadInputTokens,s=t.cacheWriteInputTokens??e.cacheWriteInputTokens,i=M.sumTokens(n,o,s),a=t.outputTokens??e.outputTokens;return new wn({inputTokens:i,outputTokens:a,nonCachedInputTokens:n,cacheReadInputTokens:o,cacheWriteInputTokens:s,totalTokens:M.totalTokens(i,a,void 0),providerMetadata:{anthropic:{...e.providerMetadata?.anthropic,...t.providerMetadata?.anthropic}}})},"mergeUsage"),Af={web_search_tool_result:"web_search",code_execution_tool_result:"code_execution",web_fetch_tool_result:"web_fetch"},PE=r(e=>e in Af,"isServerToolResultType"),ME=r(e=>{if(!e.type||!PE(e.type))return;let n=(typeof e.content=="object"&&e.content!==null&&"type"in e.content?String(e.content.type):"").endsWith("_tool_result_error");return z.toolResult({id:e.tool_use_id??"",name:Af[e.type],result:n?{type:"error",value:e.content}:{type:"json",value:e.content},providerExecuted:!0,providerMetadata:Hc({blockType:e.type})})},"serverToolResultEvent"),no=[],LE=r((e,t)=>{let n=Tf(t.message?.usage);return[n?{...e,usage:_f(e.usage,n)}:e,no]},"onMessageStart"),NE=r((e,t)=>{let n=t.content_block;if(!n)return[e,no];if((n.type==="tool_use"||n.type==="server_tool_use")&&t.index!==void 0){let i=[],a=W.stepStart(e.lifecycle,i);return[{...e,lifecycle:a,tools:De.start(e.tools,t.index,{id:n.id??String(t.index),name:n.name??"",providerExecuted:n.type==="server_tool_use"})},[...i,z.toolInputStart({id:n.id??String(t.index),name:n.name??""})]]}if(n.type==="text"&&n.text){let i=[];return[{...e,lifecycle:W.textDelta(e.lifecycle,i,`text-${t.index??0}`,n.text)},i]}if(n.type==="thinking"&&n.thinking){let i=[];return[{...e,lifecycle:W.reasoningDelta(e.lifecycle,i,`reasoning-${t.index??0}`,n.thinking)},i]}let o=ME(n);if(!o)return[e,no];let s=[];return[{...e,lifecycle:W.stepStart(e.lifecycle,s)},[...s,o]]},"onContentBlockStart"),jE=Ke.fn("AnthropicMessages.onContentBlockDelta")(function*(e,t){let n=t.delta;if(n?.type==="text_delta"&&n.text){let o=[];return[{...e,lifecycle:W.textDelta(e.lifecycle,o,`text-${t.index??0}`,n.text)},o]}if(n?.type==="thinking_delta"&&n.thinking){let o=[];return[{...e,lifecycle:W.reasoningDelta(e.lifecycle,o,`reasoning-${t.index??0}`,n.thinking)},o]}if(n?.type==="signature_delta"&&n.signature){let o=[];return[{...e,lifecycle:W.reasoningEnd(e.lifecycle,o,`reasoning-${t.index??0}`,Hc({signature:n.signature}))},o]}if(n?.type==="input_json_delta"&&t.index!==void 0){if(!n.partial_json)return[e,no];let o=De.appendExisting(Pi,e.tools,t.index,n.partial_json,"Anthropic Messages tool argument delta is missing its tool call");if(De.isError(o))return yield*o;let s=[],i=o.events.length?W.stepStart(e.lifecycle,s):e.lifecycle;return s.push(...o.events),[{...e,lifecycle:i,tools:o.tools},s]}return[e,no]}),$E=Ke.fn("AnthropicMessages.onContentBlockStop")(function*(e,t){if(t.index===void 0)return[e,no];let n=yield*De.finish(Pi,e.tools,t.index),o=[],s=n.events??[],i=s.length?W.stepStart(e.lifecycle,o):W.reasoningEnd(W.textEnd(e.lifecycle,o,`text-${t.index}`),o,`reasoning-${t.index}`);return o.push(...s),[{...e,lifecycle:i,tools:n.tools},o]}),UE=r((e,t)=>{let n=_f(e.usage,Tf(t.usage)),o=[],s=W.finish(e.lifecycle,o,{reason:CE(t.delta?.stop_reason),usage:n,providerMetadata:t.delta?.stop_sequence?Hc({stopSequence:t.delta.stop_sequence}):void 0});return[{...e,lifecycle:s,usage:n},o]},"onMessageDelta"),BE=r(e=>{let t=e.error?.type,n=e.error?.message;return t&&n?`${t}: ${n}`:n||t||"Anthropic Messages stream error"},"providerErrorMessage"),FE=r((e,t)=>[e,[z.providerError({message:BE(t),classification:mr(t.error?.message??"")?"context-overflow":void 0})]],"onError"),qE=r((e,t)=>t.type==="message_start"?Ke.succeed(LE(e,t)):t.type==="content_block_start"?Ke.succeed(NE(e,t)):t.type==="content_block_delta"?jE(e,t):t.type==="content_block_stop"?$E(e,t):t.type==="message_delta"?Ke.succeed(UE(e,t)):t.type==="error"?Ke.succeed(FE(e,t)):Ke.succeed([e,no]),"step"),VE=Ft.make({id:Pi,body:{schema:aE,from:RE},stream:{event:Ft.jsonEvent(dE),initial:r(()=>({tools:De.empty(),lifecycle:W.initial()}),"initial"),step:qE}}),Of=Bt.make({id:Pi,provider:"anthropic",protocol:VE,endpoint:Zt.path(Hw,{baseURL:Gw}),auth:Ve.none,framing:xs.sse,headers:r(()=>({"anthropic-version":"2023-06-01"}),"headers")});import{Effect as Nt,Schema as k}from"effect";var ve={};R(ve,{OpenAIOptions:()=>ve,OpenAIReasoningEffort:()=>XE,OpenAIReasoningEfforts:()=>Kc,OpenAIResponseIncludable:()=>YE,OpenAIResponseIncludables:()=>Xc,OpenAIServiceTier:()=>ZE,OpenAIServiceTiers:()=>zc,OpenAITextVerbosity:()=>zE,include:()=>sI,instructions:()=>lI,isReasoningEffort:()=>eI,promptCacheKey:()=>iI,reasoningEffort:()=>oI,reasoningSummary:()=>rI,serviceTier:()=>cI,store:()=>nI,textVerbosity:()=>aI});import{Schema as Jc}from"effect";var Kc=Hi.filter(e=>e!=="max"),Xc=["file_search_call.results","web_search_call.results","web_search_call.action.sources","message.input_image.image_url","computer_call_output.output.image_url","code_interpreter_call.outputs","reasoning.encrypted_content","message.output_text.logprobs"],zc=["auto","default","flex","priority"],WE=new Set(Hi),GE=new Set(Kc),HE=new Set(["low","medium","high"]),JE=new Set(Xc),KE=new Set(zc),XE=Jc.Literals(Kc),zE=Il,YE=Jc.Literals(Xc),ZE=Jc.Literals(zc),QE=r(e=>typeof e=="string"&&WE.has(e),"isAnyReasoningEffort"),eI=r(e=>typeof e=="string"&&GE.has(e),"isReasoningEffort"),tI=r(e=>typeof e=="string"&&HE.has(e),"isTextVerbosity"),un=r(e=>e.providerOptions?.openai,"options"),nI=r(e=>{let t=un(e)?.store;return typeof t=="boolean"?t:void 0},"store"),oI=r(e=>{let t=un(e)?.reasoningEffort;return QE(t)?t:void 0},"reasoningEffort"),rI=r(e=>un(e)?.reasoningSummary==="auto"?"auto":void 0,"reasoningSummary"),sI=r(e=>{let t=un(e)?.include;if(!Array.isArray(t))return;let n=t.filter(o=>JE.has(o));return n.length>0?n:void 0},"include"),iI=r(e=>{let t=un(e)?.promptCacheKey;return typeof t=="string"?t:void 0},"promptCacheKey"),aI=r(e=>{let t=un(e)?.textVerbosity;return tI(t)?t:void 0},"textVerbosity"),cI=r(e=>{let t=un(e)?.serviceTier;return typeof t=="string"&&KE.has(t)?t:void 0},"serviceTier"),lI=r(e=>{let t=un(e)?.instructions;return typeof t=="string"?t:void 0},"instructions");var Mi="openai-chat",dI=new Set(M.IMAGE_MIMES),pI="https://api.openai.com/v1",uI="/chat/completions",fI=k.Struct({name:k.String,description:k.String,parameters:fo}),mI=k.Struct({type:k.tag("function"),function:fI}),gI=k.Struct({id:k.String,type:k.tag("function"),function:k.Struct({name:k.String,arguments:k.String})}),yI=k.Union([k.Struct({type:k.Literal("text"),text:k.String}),k.Struct({type:k.Literal("image_url"),image_url:k.Struct({url:k.String})})]),hI=k.Union([k.Struct({role:k.Literal("system"),content:k.String}),k.Struct({role:k.Literal("user"),content:k.Union([k.String,k.Array(yI)])}),k.Struct({role:k.Literal("assistant"),content:k.NullOr(k.String),tool_calls:ht(gI),reasoning_content:k.optional(k.String)}),k.Struct({role:k.Literal("tool"),tool_call_id:k.String,content:k.String})]).pipe(k.toTaggedUnion("role")),SI=k.Union([k.Literals(["auto","none","required"]),k.Struct({type:k.tag("function"),function:k.Struct({name:k.String})})]),xI={model:k.String,messages:k.Array(hI),tools:ht(mI),tool_choice:k.optional(SI),stream:k.Literal(!0),stream_options:k.optional(k.Struct({include_usage:k.Boolean})),store:k.optional(k.Boolean),reasoning_effort:k.optional(ve.OpenAIReasoningEffort),max_tokens:k.optional(k.Number),temperature:k.optional(k.Number),top_p:k.optional(k.Number),frequency_penalty:k.optional(k.Number),presence_penalty:k.optional(k.Number),seed:k.optional(k.Number),stop:ht(k.String)},vI=k.Struct(xI),wI=k.Struct({prompt_tokens:k.optional(k.Number),completion_tokens:k.optional(k.Number),total_tokens:k.optional(k.Number),prompt_tokens_details:se(k.Struct({cached_tokens:k.optional(k.Number)})),completion_tokens_details:se(k.Struct({reasoning_tokens:k.optional(k.Number)}))}),EI=k.Struct({name:se(k.String),arguments:se(k.String)}),II=k.Struct({index:k.Number,id:se(k.String),function:se(EI)}),kI=k.Struct({content:se(k.String),reasoning_content:se(k.String),tool_calls:se(k.Array(II))}),bI=k.Struct({delta:se(kI),finish_reason:se(k.String)}),DI=k.Struct({choices:k.Array(bI),usage:se(wI)}),TI=M.invalidRequest,_I=r((e,t)=>({type:"function",function:{name:e.name,description:e.description,parameters:dn.openAI(t)}}),"lowerTool"),AI=r(e=>M.matchToolChoice("OpenAI Chat",e,{auto:r(()=>"auto","auto"),none:r(()=>"none","none"),required:r(()=>"required","required"),tool:r(t=>({type:"function",function:{name:t}}),"tool")}),"lowerToolChoice"),OI=r(e=>({id:e.id,type:"function",function:{name:e.name,arguments:M.encodeJson(e.input)}}),"lowerToolCall"),Cf=Nt.fn("OpenAIChat.lowerMedia")(function*(e){return{type:"image_url",image_url:{url:(yield*M.validateMedia("OpenAI Chat",e,dI)).dataUrl}}}),RI=r(e=>Re(e)&&typeof e.reasoning_content=="string"?e.reasoning_content:void 0,"openAICompatibleReasoningContent"),CI=Nt.fn("OpenAIChat.lowerUserMessage")(function*(e){let t=[];for(let n of e.content){if(n.type==="text"){t.push({type:"text",text:n.text});continue}if(n.type==="media"){t.push(yield*Cf(n));continue}return yield*M.unsupportedContent("OpenAI Chat","user",["text","media"])}return t.every(n=>n.type==="text")?{role:"user",content:t.map(n=>n.text).join("")}:{role:"user",content:t}}),PI=Nt.fn("OpenAIChat.lowerAssistantMessage")(function*(e){let t=[],n=[],o=[];for(let s of e.content){if(!M.supportsContent(s,["text","reasoning","tool-call"]))return yield*M.unsupportedContent("OpenAI Chat","assistant",["text","reasoning","tool-call"]);if(s.type==="text"){t.push(s);continue}if(s.type==="reasoning"){n.push(s);continue}if(s.type==="tool-call"){o.push(OI(s));continue}}return{role:"assistant",content:t.length===0?null:M.joinText(t),tool_calls:o.length===0?void 0:o,reasoning_content:n.length>0?n.map(s=>s.text).join(""):RI(e.native?.openaiCompatible)}}),Pf=Nt.fn("OpenAIChat.lowerToolMessages")(function*(e){let t=[],n=[];for(let o of e.content){if(!M.supportsContent(o,["tool-result"]))return yield*M.unsupportedContent("OpenAI Chat","tool",["tool-result"]);if(o.result.type!=="content"){t.push({role:"tool",tool_call_id:o.id,content:M.toolResultText(o)});continue}let s=o.result.value,i=s.filter(c=>c.type==="text").map(c=>c.text);t.push({role:"tool",tool_call_id:o.id,content:i.join(`
683
+ `)});let a=s.filter(c=>c.type==="file");n.push(...yield*Nt.forEach(a,c=>Cf({type:"media",mediaType:c.mime,data:c.uri,filename:c.name})))}return{messages:t,images:n}}),MI=Nt.fn("OpenAIChat.lowerMessage")(function*(e){return e.role==="user"?[yield*CI(e)]:e.role==="assistant"?[yield*PI(e)]:(yield*Pf(e)).messages}),LI=Nt.fn("OpenAIChat.lowerMessages")(function*(e){let n=[...e.system.length===0?[]:[{role:"system",content:M.joinText(e.system)}]],o=[],s=r(()=>{o.length!==0&&n.push({role:"user",content:o.splice(0)})},"flushImages");for(let i of e.messages){if(i.role==="system"){let a=yield*M.wrappedSystemUpdate("OpenAI Chat",i);if(o.length>0){n.push({role:"user",content:[...o.splice(0),{type:"text",text:a.text}]});continue}let c=n.at(-1);c?.role==="user"&&typeof c.content=="string"?n[n.length-1]={role:"user",content:`${c.content}
684
+ ${a.text}`}:c?.role==="user"&&Array.isArray(c.content)?n[n.length-1]={role:"user",content:[...c.content,{type:"text",text:a.text}]}:n.push({role:"user",content:a.text});continue}if(i.role==="tool"){let a=yield*Pf(i);n.push(...a.messages),o.push(...a.images);continue}s(),n.push(...yield*MI(i))}return s(),n}),NI=Nt.fn("OpenAIChat.lowerOptions")(function*(e){let t=ve.store(e),n=ve.reasoningEffort(e);return n&&!ve.isReasoningEffort(n)?yield*TI(`OpenAI Chat does not support reasoning effort ${n}`):{...t!==void 0?{store:t}:{},...n?{reasoning_effort:n}:{}}}),jI=Nt.fn("OpenAIChat.fromRequest")(function*(e){let t=e.generation,n=e.model.compatibility?.toolSchema;return{model:e.model.id,messages:yield*LI(e),tools:e.tools.length===0?void 0:e.tools.map(o=>_I(o,dn.modelCompatibility(o.inputSchema,n))),tool_choice:e.toolChoice?yield*AI(e.toolChoice):void 0,stream:!0,stream_options:{include_usage:!0},max_tokens:t?.maxTokens,temperature:t?.temperature,top_p:t?.topP,frequency_penalty:t?.frequencyPenalty,presence_penalty:t?.presencePenalty,seed:t?.seed,stop:t?.stop,...yield*NI(e)}}),$I=r(e=>e==="stop"?"stop":e==="length"?"length":e==="content_filter"?"content-filter":e==="function_call"||e==="tool_calls"?"tool-calls":"unknown","mapFinishReason"),UI=r(e=>{if(!e)return;let t=e.prompt_tokens_details?.cached_tokens,n=e.completion_tokens_details?.reasoning_tokens,o=M.subtractTokens(e.prompt_tokens,t);return new wn({inputTokens:e.prompt_tokens,outputTokens:e.completion_tokens,nonCachedInputTokens:o,cacheReadInputTokens:t,reasoningTokens:n,totalTokens:M.totalTokens(e.prompt_tokens,e.completion_tokens,e.total_tokens),providerMetadata:{openai:e}})},"mapUsage"),BI=r((e,t)=>Nt.gen(function*(){let n=[],o=UI(t.usage)??e.usage,s=t.choices[0],i=s?.finish_reason?$I(s.finish_reason):e.finishReason,a=s?.delta,c=a?.tool_calls??[],l=e.tools,f=e.lifecycle;a?.reasoning_content&&(f=W.reasoningDelta(f,n,"reasoning-0",a.reasoning_content)),a?.content&&(f=W.reasoningEnd(f,n,"reasoning-0"),f=W.textDelta(f,n,"text-0",a.content)),c.length&&(f=W.reasoningEnd(f,n,"reasoning-0"));for(let d of c){let h=De.appendOrStart(Mi,l,d.index,{id:d.id??void 0,name:d.function?.name??void 0,text:d.function?.arguments??""},"OpenAI Chat tool call delta is missing id or name");if(De.isError(h))return yield*h;l=h.tools,h.events.length&&(f=W.stepStart(f,n)),n.push(...h.events)}let g=i!==void 0&&e.finishReason===void 0&&Object.keys(l).length>0?yield*De.finishAll(Mi,l):void 0;return[{tools:g?.tools??l,toolCallEvents:g?.events??e.toolCallEvents,usage:o,finishReason:i,lifecycle:f},n]}),"step"),FI=r(e=>{let t=[],n=e.toolCallEvents.length>0,o=e.finishReason==="stop"&&n?"tool-calls":e.finishReason,s=e.toolCallEvents.length?W.stepStart(e.lifecycle,t):e.lifecycle;return t.push(...e.toolCallEvents),o&&W.finish(s,t,{reason:o,usage:e.usage}),t},"finishEvents"),Yc=Ft.make({id:Mi,body:{schema:vI,from:jI},stream:{event:Ft.jsonEvent(DI),initial:r(()=>({tools:De.empty(),toolCallEvents:[],lifecycle:W.initial()}),"initial"),step:BI,onHalt:FI}}),qI=vs.sseJson.with(),aL=Bt.make({id:Mi,provider:"openai",protocol:Yc,endpoint:Zt.path(uI,{baseURL:pI}),auth:Ve.none,transport:qI});var VI="openai-compatible-chat",Lf=Bt.make({id:VI,protocol:Yc,endpoint:Zt.path("/chat/completions"),framing:xs.sse});import{Effect as Oe,Schema as u}from"effect";var Qo="openai-responses",WI="https://api.openai.com/v1",GI="/responses",jf=u.Struct({type:u.tag("input_text"),text:u.String}),$f=u.Struct({type:u.tag("input_image"),image_url:u.String}),HI=u.Union([jf,$f]),JI=u.Struct({type:u.tag("output_text"),text:u.String}),KI=u.Struct({type:u.tag("summary_text"),text:u.String}),XI=u.Struct({type:u.tag("reasoning"),id:u.optionalKey(u.String),summary:u.Array(KI),encrypted_content:se(u.String)}),zI=u.Struct({type:u.tag("item_reference"),id:u.String}),YI=u.Union([jf,$f]),ZI=u.Union([u.String,u.Array(YI)]),QI=u.Union([u.Struct({role:u.tag("system"),content:u.String}),u.Struct({role:u.tag("user"),content:u.Array(HI)}),u.Struct({role:u.tag("assistant"),content:u.Array(JI)}),XI,zI,u.Struct({type:u.tag("function_call"),call_id:u.String,name:u.String,arguments:u.String}),u.Struct({type:u.tag("function_call_output"),call_id:u.String,output:ZI})]),ek=u.Struct({type:u.tag("function"),name:u.String,description:u.String,parameters:fo,strict:u.optional(u.Boolean)}),tk=u.Union([u.Literals(["auto","none","required"]),u.Struct({type:u.tag("function"),name:u.String})]),Uf={model:u.String,input:u.Array(QI),instructions:u.optional(u.String),tools:ht(ek),tool_choice:u.optional(tk),store:u.optional(u.Boolean),service_tier:u.optional(ve.OpenAIServiceTier),prompt_cache_key:u.optional(u.String),include:ht(ve.OpenAIResponseIncludable),reasoning:u.optional(u.Struct({effort:u.optional(ve.OpenAIReasoningEffort),summary:u.optional(u.Literal("auto"))})),text:u.optional(u.Struct({verbosity:u.optional(ve.OpenAITextVerbosity)})),max_output_tokens:u.optional(u.Number),temperature:u.optional(u.Number),top_p:u.optional(u.Number)},nk=u.Struct({...Uf,stream:u.Literal(!0)}),Bf=u.StructWithRest(u.Struct({type:u.tag("response.create"),...Uf}),[u.Record(u.String,u.Unknown)]),ok=u.encodeSync(u.fromJsonString(Bf)),rk=u.Struct({input_tokens:u.optional(u.Number),input_tokens_details:se(u.Struct({cached_tokens:u.optional(u.Number)})),output_tokens:u.optional(u.Number),output_tokens_details:se(u.Struct({reasoning_tokens:u.optional(u.Number)})),total_tokens:u.optional(u.Number)}),sk=u.Struct({type:u.String,id:u.optional(u.String),call_id:u.optional(u.String),name:u.optional(u.String),arguments:u.optional(u.String),status:u.optional(u.String),action:u.optional(u.Unknown),queries:u.optional(u.Unknown),results:u.optional(u.Unknown),code:u.optional(u.String),container_id:u.optional(u.String),outputs:u.optional(u.Unknown),server_label:u.optional(u.String),output:u.optional(u.Unknown),error:u.optional(u.Unknown),encrypted_content:se(u.String)}),ik=u.Struct({code:se(u.String),message:se(u.String),param:se(u.String)}),ak=u.Struct({type:u.String,delta:u.optional(u.String),item_id:u.optional(u.String),summary_index:u.optional(u.Number),item:u.optional(sk),response:u.optional(u.StructWithRest(u.Struct({id:u.optional(u.String),service_tier:se(u.String),incomplete_details:se(u.Struct({reason:u.String})),usage:se(rk),error:se(ik)}),[u.Record(u.String,u.Unknown)])),code:u.optional(u.String),message:u.optional(u.String),param:u.optional(u.String)}),ck=M.invalidRequest,lk=r((e,t)=>({type:"function",name:e.name,description:e.description,parameters:dn.openAI(t),strict:!1}),"lowerTool"),dk=r(e=>M.matchToolChoice("OpenAI Responses",e,{auto:r(()=>"auto","auto"),none:r(()=>"none","none"),required:r(()=>"required","required"),tool:r(t=>({type:"function",name:t}),"tool")}),"lowerToolChoice"),pk=r(e=>({type:"function_call",call_id:e.id,name:e.name,arguments:M.encodeJson(e.input)}),"lowerToolCall"),uk=r(e=>{let t=e.providerMetadata?.openai;if(!M.isRecord(t)||typeof t.itemId!="string"||t.itemId.length===0)return;let n=typeof t.reasoningEncryptedContent=="string"?t.reasoningEncryptedContent:t.reasoningEncryptedContent===null?null:void 0;return{type:"reasoning",id:t.itemId,summary:e.text.length>0?[{type:"summary_text",text:e.text}]:[],encrypted_content:n}},"lowerReasoning"),fk=r(e=>{let t=e.providerMetadata?.openai;return M.isRecord(t)&&typeof t.itemId=="string"&&t.itemId.length>0?t.itemId:void 0},"hostedToolItemID"),mk=Oe.fn("OpenAIResponses.lowerUserContent")(function*(e){return e.type==="text"?{type:"input_text",text:e.text}:e.type==="media"?{type:"input_image",image_url:(yield*M.validateMedia("OpenAI Responses",e,new Set(M.IMAGE_MIMES))).dataUrl}:yield*M.unsupportedContent("OpenAI Responses","user",["text","media"])}),gk=Oe.fn("OpenAIResponses.lowerToolResultContentItem")(function*(e){return e.type==="text"?{type:"input_text",text:e.text}:{type:"input_image",image_url:(yield*M.validateToolFile("OpenAI Responses",e,new Set(M.IMAGE_MIMES))).dataUrl}}),yk=Oe.fn("OpenAIResponses.lowerToolResultOutput")(function*(e){if(e.result.type!=="content")return M.toolResultText(e);let t=e.result.value;return yield*Oe.forEach(t,gk)}),hk=Oe.fn("OpenAIResponses.lowerMessages")(function*(e){let n=[...e.system.length===0?[]:[{role:"system",content:M.joinText(e.system)}]],o=ve.store(e);for(let s of e.messages){if(s.role==="system"){let i=yield*M.wrappedSystemUpdate("OpenAI Responses",s),a=n.at(-1);a&&"role"in a&&a.role==="user"?n[n.length-1]={role:"user",content:[...a.content,{type:"input_text",text:i.text}]}:n.push({role:"user",content:[{type:"input_text",text:i.text}]});continue}if(s.role==="user"){n.push({role:"user",content:yield*Oe.forEach(s.content,mk)});continue}if(s.role==="assistant"){let i=[],a={},c=new Set,l=new Set,f=r(()=>{i.length!==0&&(n.push({role:"assistant",content:i.map(g=>({type:"output_text",text:g.text}))}),i.splice(0,i.length))},"flushText");for(let g of s.content){if(g.type==="text"){i.push(g);continue}if(g.type==="reasoning"){f();let d=uk(g);if(!d)continue;if(o!==!1){c.has(d.id)||n.push({type:"item_reference",id:d.id}),c.add(d.id);continue}let h=a[d.id];if(h){h.summary.push(...d.summary),typeof d.encrypted_content=="string"&&(h.encrypted_content=d.encrypted_content);continue}let b={type:d.type,summary:d.summary,encrypted_content:d.encrypted_content};a[d.id]=b,n.push(b);continue}if(g.type==="tool-call"){if(f(),g.providerExecuted===!0)continue;n.push(pk(g));continue}if(g.type==="tool-result"&&g.providerExecuted===!0){f();let d=fk(g);o!==!1&&d&&!l.has(d)&&n.push({type:"item_reference",id:d}),d&&l.add(d);continue}return yield*M.unsupportedContent("OpenAI Responses","assistant",["text","reasoning","tool-call","tool-result"])}f();continue}for(let i of s.content){if(!M.supportsContent(i,["tool-result"]))return yield*M.unsupportedContent("OpenAI Responses","tool",["tool-result"]);n.push({type:"function_call_output",call_id:i.id,output:yield*yk(i)})}}return o===!1?n.filter(s=>!("type"in s)||s.type!=="reasoning"||typeof s.encrypted_content=="string"):n}),Sk=Oe.fn("OpenAIResponses.lowerOptions")(function*(e){let t=ve.store(e),n=ve.promptCacheKey(e),o=ve.reasoningEffort(e);if(o&&!ve.isReasoningEffort(o))return yield*ck(`OpenAI Responses does not support reasoning effort ${o}`);let s=ve.reasoningSummary(e),i=ve.include(e),a=ve.textVerbosity(e),c=ve.instructions(e),l=ve.serviceTier(e);return{...c?{instructions:c}:{},...t!==void 0?{store:t}:{},...n?{prompt_cache_key:n}:{},...i?{include:i}:{},...o||s?{reasoning:{effort:o,summary:s}}:{},...a?{text:{verbosity:a}}:{},...l?{service_tier:l}:{}}}),xk=Oe.fn("OpenAIResponses.fromRequest")(function*(e){let t=e.generation,n=yield*Sk(e),o=e.model.compatibility?.toolSchema;return{model:e.model.id,input:yield*hk(e),tools:e.tools.length===0?void 0:e.tools.map(s=>lk(s,dn.modelCompatibility(s.inputSchema,o))),tool_choice:e.toolChoice?yield*dk(e.toolChoice):void 0,stream:!0,max_output_tokens:t?.maxTokens,temperature:t?.temperature,top_p:t?.topP,...n}}),vk=r(e=>{if(!e)return;let t=e.input_tokens_details?.cached_tokens,n=e.output_tokens_details?.reasoning_tokens,o=M.subtractTokens(e.input_tokens,t);return new wn({inputTokens:e.input_tokens,outputTokens:e.output_tokens,nonCachedInputTokens:o,cacheReadInputTokens:t,reasoningTokens:n,totalTokens:M.totalTokens(e.input_tokens,e.output_tokens,e.total_tokens),providerMetadata:{openai:e}})},"mapUsage"),wk=r((e,t)=>{let n=e.response?.incomplete_details?.reason;return n==null?t?"tool-calls":"stop":n==="max_output_tokens"?"length":n==="content_filter"?"content-filter":t?"tool-calls":"unknown"},"mapFinishReason"),fn=r(e=>({openai:e}),"openaiMetadata"),Ff={web_search_call:{name:"web_search",input:r(e=>e.action??{},"input")},web_search_preview_call:{name:"web_search_preview",input:r(e=>e.action??{},"input")},file_search_call:{name:"file_search",input:r(e=>({queries:e.queries??[]}),"input")},code_interpreter_call:{name:"code_interpreter",input:r(e=>({code:e.code,container_id:e.container_id}),"input")},computer_use_call:{name:"computer_use",input:r(e=>e.action??{},"input")},image_generation_call:{name:"image_generation",input:r(()=>({}),"input")},mcp_call:{name:"mcp",input:r(e=>({server_label:e.server_label,name:e.name,arguments:e.arguments}),"input")},local_shell_call:{name:"local_shell",input:r(e=>e.action??{},"input")}},Ek=r(e=>e.type in Ff&&typeof e.id=="string"&&e.id.length>0,"isHostedToolItem"),qf=r(e=>e.type==="reasoning"&&typeof e.id=="string"&&e.id.length>0,"isReasoningItem"),Ik=r(e=>typeof e.error<"u"&&e.error!==null?{type:"error",value:e.error}:{type:"json",value:e},"hostedToolResult"),kk=r(e=>{let t=Ff[e.type],n=fn({itemId:e.id});return[z.toolCall({id:e.id,name:t.name,input:t.input(e),providerExecuted:!0,providerMetadata:n}),z.toolResult({id:e.id,name:t.name,result:Ik(e),providerExecuted:!0,providerMetadata:n})]},"hostedToolEvents"),pt=[],bk=new Set(["response.completed","response.incomplete","response.failed"]),Dk=r((e,t)=>{if(!t.delta)return[e,pt];let n=[];return[{...e,lifecycle:W.textDelta(e.lifecycle,n,t.item_id??"text-0",t.delta)},n]},"onOutputTextDelta"),Tk=r((e,t)=>{if(!t.delta)return[e,pt];let n=[],o=t.item_id??"reasoning-0",s=t.summary_index!==void 0||e.reasoningItems[o]?`${o}:${t.summary_index??0}`:o;return[{...e,lifecycle:W.reasoningDelta(e.lifecycle,n,s,t.delta)},n]},"onReasoningDelta"),_k=r((e,t)=>[e,pt],"onReasoningDone"),Vf=r(e=>fn({itemId:e.id,reasoningEncryptedContent:e.encrypted_content??null}),"reasoningMetadata"),Ak=r((e,t)=>{let n=t.item;if(n&&qf(n)){let a=[];return[{...e,lifecycle:W.reasoningStart(e.lifecycle,a,`${n.id}:0`,Vf(n)),reasoningItems:{...e.reasoningItems,[n.id]:{encryptedContent:n.encrypted_content,summaryParts:{0:"active"}}}},a]}if(n?.type!=="function_call"||!n.id)return[e,pt];let o=fn({itemId:n.id}),s=[],i=W.stepStart(e.lifecycle,s);return[{...e,lifecycle:i,hasFunctionCall:e.hasFunctionCall,tools:De.start(e.tools,n.id,{id:n.call_id??n.id,name:n.name??"",input:n.arguments??"",providerMetadata:o})},[...s,z.toolInputStart({id:n.call_id??n.id,name:n.name??"",providerMetadata:o})]]},"onOutputItemAdded"),Ok=r((e,t)=>{if(!t.item_id||t.summary_index===void 0)return[e,pt];let n=e.reasoningItems[t.item_id]??{encryptedContent:void 0,summaryParts:{}};if(t.summary_index===0){if(e.reasoningItems[t.item_id])return[e,pt];let i=[];return[{...e,lifecycle:W.reasoningStart(e.lifecycle,i,`${t.item_id}:0`,fn({itemId:t.item_id,reasoningEncryptedContent:null})),reasoningItems:{...e.reasoningItems,[t.item_id]:{...n,summaryParts:{0:"active"}}}},i]}let o=[],s=Object.entries(n.summaryParts).filter(i=>i[1]==="can-conclude").reduce((i,a)=>W.reasoningEnd(i,o,`${t.item_id}:${a[0]}`,fn({itemId:t.item_id})),e.lifecycle);return[{...e,lifecycle:W.reasoningStart(s,o,`${t.item_id}:${t.summary_index}`,fn({itemId:t.item_id,reasoningEncryptedContent:n.encryptedContent??null})),reasoningItems:{...e.reasoningItems,[t.item_id]:{...n,summaryParts:{...Object.fromEntries(Object.entries(n.summaryParts).map(i=>i[1]==="can-conclude"?[i[0],"concluded"]:i)),[t.summary_index]:"active"}}}},o]},"onReasoningSummaryPartAdded"),Rk=r((e,t)=>{if(!t.item_id||t.summary_index===void 0)return[e,pt];let n=e.reasoningItems[t.item_id];if(!n)return[e,pt];let o=[];return[{...e,lifecycle:e.store!==!1?W.reasoningEnd(e.lifecycle,o,`${t.item_id}:${t.summary_index}`,fn({itemId:t.item_id})):e.lifecycle,reasoningItems:{...e.reasoningItems,[t.item_id]:{...n,summaryParts:{...n.summaryParts,[t.summary_index]:e.store!==!1?"concluded":"can-conclude"}}}},o]},"onReasoningSummaryPartDone"),Ck=Oe.fn("OpenAIResponses.onFunctionCallArgumentsDelta")(function*(e,t){if(!t.item_id||!t.delta)return[e,pt];let n=De.appendExisting(Qo,e.tools,t.item_id,t.delta,"OpenAI Responses tool argument delta is missing its tool call");if(De.isError(n))return yield*n;let o=[],s=n.events.length?W.stepStart(e.lifecycle,o):e.lifecycle;return o.push(...n.events),[{...e,lifecycle:s,tools:n.tools},o]}),Pk=Oe.fn("OpenAIResponses.onOutputItemDone")(function*(e,t){let n=t.item;if(!n)return[e,pt];if(n.type==="function_call"){if(!n.id||!n.call_id||!n.name)return[e,pt];let o=e.tools[n.id]?e.tools:De.start(e.tools,n.id,{id:n.call_id,name:n.name}),s=n.arguments===void 0?yield*De.finish(Qo,o,n.id):yield*De.finishWithInput(Qo,o,n.id,n.arguments),i=[],a=s.events??[],c=a.length?W.stepStart(e.lifecycle,i):e.lifecycle;return i.push(...a),[{...e,lifecycle:c,hasFunctionCall:a.some(z.is.toolCall)?!0:e.hasFunctionCall,tools:s.tools},i]}if(Ek(n)){let o=[],s=W.stepStart(e.lifecycle,o);return o.push(...kk(n)),[{...e,lifecycle:s},o]}if(qf(n)){let o=[],s=Vf(n),i=e.reasoningItems[n.id];if(i){let a=Object.entries(i.summaryParts).filter(f=>f[1]==="active"||f[1]==="can-conclude").reduce((f,g)=>W.reasoningEnd(f,o,`${n.id}:${g[0]}`,s),e.lifecycle),{[n.id]:c,...l}=e.reasoningItems;return[{...e,lifecycle:a,reasoningItems:l},o]}if(!e.lifecycle.reasoning.has(n.id)){let a=W.stepStart(e.lifecycle,o);return o.push(z.reasoningStart({id:n.id,providerMetadata:s})),o.push(z.reasoningEnd({id:n.id,providerMetadata:s})),[{...e,lifecycle:a},o]}return[{...e,lifecycle:W.reasoningEnd(e.lifecycle,o,n.id,s)},o]}return[e,pt]}),Mk=r((e,t)=>{let n=[],o=W.finish(e.lifecycle,n,{reason:wk(t,e.hasFunctionCall),usage:vk(t.response?.usage),providerMetadata:t.response?.id||t.response?.service_tier?fn({responseId:t.response.id,serviceTier:t.response.service_tier}):void 0});return[{...e,lifecycle:o},n]},"onResponseFinish"),Lk=r((e,t)=>{let n=e.response?.error??void 0,o=e.message||n?.message||void 0,s=e.code||n?.code||void 0;return o&&s?`${s}: ${o}`:o||s||t},"providerErrorMessage"),Wf=r((e,t)=>{let n=e.code||e.response?.error?.code||void 0,o=Lk(e,t);return z.providerError({message:o,classification:n==="context_length_exceeded"||mr(o)?"context-overflow":void 0})},"providerError"),Nk=r((e,t)=>[e,[Wf(t,"OpenAI Responses response failed")]],"onResponseFailed"),jk=r((e,t)=>[e,[Wf(t,"OpenAI Responses stream error")]],"onError"),$k=r((e,t)=>t.type==="response.output_text.delta"?Oe.succeed(Dk(e,t)):t.type==="response.reasoning_text.delta"||t.type==="response.reasoning_summary.delta"||t.type==="response.reasoning_summary_text.delta"?Oe.succeed(Tk(e,t)):t.type==="response.reasoning_text.done"||t.type==="response.reasoning_summary.done"||t.type==="response.reasoning_summary_text.done"?Oe.succeed(_k(e,t)):t.type==="response.reasoning_summary_part.added"?Oe.succeed(Ok(e,t)):t.type==="response.reasoning_summary_part.done"?Oe.succeed(Rk(e,t)):t.type==="response.output_item.added"?Oe.succeed(Ak(e,t)):t.type==="response.function_call_arguments.delta"?Ck(e,t):t.type==="response.output_item.done"?Pk(e,t):t.type==="response.completed"||t.type==="response.incomplete"?Oe.succeed(Mk(e,t)):t.type==="response.failed"?Oe.succeed(Nk(e,t)):t.type==="error"?Oe.succeed(jk(e,t)):Oe.succeed([e,pt]),"step"),Gf=Ft.make({id:Qo,body:{schema:nk,from:xk},stream:{event:Ft.jsonEvent(ak),initial:r(e=>({hasFunctionCall:!1,tools:De.empty(),lifecycle:W.initial(),reasoningItems:{},store:ve.store(e)}),"initial"),step:$k,terminal:r(e=>bk.has(e.type),"terminal")}}),Hf=Zt.path(GI,{baseURL:WI}),Jf=Ve.none,Uk=vs.sseJson.with(),Kf=Bt.make({id:Qo,provider:"openai",protocol:Gf,endpoint:Hf,auth:Jf,transport:Uk,defaults:{providerOptions:{openai:{store:!1}}}}),Bk=M.validateWith(u.decodeUnknownEffect(Bf)),Fk=r(e=>Oe.gen(function*(){if(!M.isRecord(e))return yield*M.invalidRequest("OpenAI Responses WebSocket body must be a JSON object");let{stream:t,...n}=e;return yield*Bk({...n,type:"response.create"})}),"webSocketMessage"),qk=_l.jsonTransport.with({toMessage:Fk,encodeMessage:ok}),bL=Bt.make({id:`${Qo}-websocket`,provider:"openai",protocol:Gf,endpoint:Hf,auth:Jf,transport:qk,defaults:{providerOptions:{openai:{store:!1}}}});import{Context as Vk,Effect as Jt,Layer as zf,Schema as is}from"effect";import{produce as Yf}from"immer";var Li=class extends is.TaggedErrorClass()("SessionRunnerModel.ModelNotSelectedError",{sessionID:fe.ID}){static{r(this,"ModelNotSelectedError")}get message(){return`No model is available for session ${this.sessionID}`}},Ni=class extends is.TaggedErrorClass()("SessionRunnerModel.ModelUnavailableError",{providerID:co.ID,modelID:Dt.ID}){static{r(this,"ModelUnavailableError")}get message(){return`Model unavailable: ${this.providerID}/${this.modelID}`}},ji=class extends is.TaggedErrorClass()("SessionRunnerModel.VariantUnavailableError",{providerID:co.ID,modelID:Dt.ID,variant:Dt.VariantID}){static{r(this,"VariantUnavailableError")}get message(){return`Variant unavailable for ${this.providerID}/${this.modelID}: ${this.variant}`}},$i=class extends is.TaggedErrorClass()("SessionRunnerModel.UnsupportedApiError",{providerID:co.ID,modelID:Dt.ID,api:is.String}){static{r(this,"UnsupportedApiError")}get message(){return`Unsupported API for ${this.providerID}/${this.modelID}: ${this.api}`}},mn=class extends Vk.Service()("@opencode/v2/SessionRunnerModel"){static{r(this,"Service")}},Wk=r(e=>zf.succeed(mn,mn.of({resolve:e})),"layerWith"),Gk=r((e,t)=>{if(t?.type==="key")return Ve.value(t.key);if(t?.type==="oauth")return Ve.value(t.access);let n=e.request.body.apiKey??e.api.settings?.apiKey;if(typeof n=="string")return Ve.value(n)},"apiKey"),Zc=r((e,t)=>{let n=e.request.body,o=Object.hasOwn(n,"apiKey")?Object.fromEntries(Object.entries(n).filter(([s])=>s!=="apiKey")):n;return t.with({provider:e.providerID,endpoint:e.api.url===void 0?void 0:{baseURL:e.api.url},headers:e.request.headers,http:{body:o},limits:{context:e.limit.context,output:e.limit.output}})},"withDefaults"),Hk=r((e,t)=>{let n=t==="default"||t===void 0?e.request.variant:t,o=e.variants.find(s=>s.id===n);return!o&&t!==void 0&&t!=="default"?Jt.fail(new ji({providerID:e.providerID,modelID:e.id,variant:t})):Jt.succeed(o?Yf(e,s=>{Object.assign(s.request.headers,o.headers),Object.assign(s.request.body,o.body)}):e)},"withVariant"),Jk=r(e=>e.api.type==="aisdk"?`${e.api.type}:${e.api.package}`:e.api.type,"apiName"),Zf=r((e,t)=>{let n=t?.type!=="key"||t.metadata===void 0?e:Yf(e,s=>{Object.assign(s.request.body,t.metadata)}),o=Gk(n,t);return n.api.type==="aisdk"&&n.api.package==="@ai-sdk/openai"?Jt.succeed(Zc(n,Kf).with({auth:o===void 0?Ve.none:Ve.bearer(o)}).model({id:n.api.id})):n.api.type==="aisdk"&&n.api.package==="@ai-sdk/anthropic"?Jt.succeed(Zc(n,Of).with({auth:o===void 0?Ve.none:Ve.header("x-api-key",o)}).model({id:n.api.id})):n.api.type==="aisdk"&&n.api.package==="@ai-sdk/openai-compatible"&&n.api.url?Jt.succeed(Zc(n,Lf).with({auth:o===void 0?Ve.none:Ve.bearer(o)}).model({id:n.api.id})):Jt.fail(new $i({providerID:n.providerID,modelID:n.id,api:Jk(n)}))},"fromCatalogModel"),Qf=r((e,t,n)=>Hk(t,e.model?.variant).pipe(Jt.flatMap(o=>Zf(o,n))),"resolve"),Qc=r(e=>e.api.type==="aisdk"&&(e.api.package==="@ai-sdk/openai"||e.api.package==="@ai-sdk/anthropic"||e.api.package==="@ai-sdk/openai-compatible"&&e.api.url!==void 0),"supported"),em=zf.effect(mn,Jt.gen(function*(){let e=yield*na.Service,t=yield*Is.Service;return mn.of({resolve:Jt.fn("SessionRunnerModel.resolve")(function*(n){let o=n.model?void 0:yield*e.model.default(),s=n.model?(yield*e.model.available()).find(c=>c.providerID===n.model?.providerID&&c.id===n.model.id):o&&Qc(o)?o:(yield*e.model.available()).find(Qc);if(!s&&n.model)return yield*new Ni({providerID:n.model.providerID,modelID:n.model.id});if(!s)return yield*new Li({sessionID:n.id});let i=yield*e.provider.get(s.providerID),a=yield*t.connection.active(i?.integrationID??Is.ID.make(s.providerID));return yield*Qf(n,s,a?yield*t.connection.resolve(a):void 0)})})})),Kk=io({service:mn,layer:em,deps:[na.node,Is.node]});var tl=class extends Xk.Service()("@opencode/v2/SessionRunner"){static{r(this,"Service")}};var er=class extends zk.Service()("@opencode/v2/SessionExecution"){static{r(this,"Service")}},Zk=xe.unbound(er,us.tags.values.global),Qk=Yk.succeed(er,er.of({active:Ui.succeed(new Set),resume:r(()=>Ui.void,"resume"),wake:r(()=>Ui.void,"wake"),interrupt:r(()=>Ui.void,"interrupt")}));var gl={};R(gl,{ContextSnapshotDecodeError:()=>Fi,ID:()=>Cd,Info:()=>Pd,ListAnchor:()=>Os,ListInput:()=>Rb,MessageDecodeError:()=>hn,MessageNotFoundError:()=>Cb,NotFoundError:()=>Wi,OperationUnavailableError:()=>so,PromptConflictError:()=>ds,RevertState:()=>Tb,Service:()=>sr,SessionSchema:()=>fe,SessionV2:()=>gl,node:()=>Lb});import{DateTime as um,Effect as q,Layer as gm,Schema as qe,Context as kb,Stream as fm}from"effect";import{and as ls,asc as dl,desc as pl,eq as Xt,gt as ul,like as bb,lt as fl,or as mm}from"drizzle-orm";var ol={};R(ol,{FileAttachment:()=>tm,Prompt:()=>eb,PromptInput:()=>ol});import{Schema as gn}from"effect";var tm=gn.Struct({uri:gn.String,name:gn.String.pipe(Te),description:gn.String.pipe(Te),source:Qi.pipe(Te)}).annotate({identifier:"PromptInput.FileAttachment"}).pipe(fs(e=>({create:r(t=>e.make(t),"create")}))),eb=gn.Struct({text:gn.String,files:gn.Array(tm).pipe(Te),agents:gn.Array(ea).pipe(Te)}).annotate({identifier:"PromptInput"});import Db from"path";import{DateTime as sl}from"effect";var Kt={};R(Kt,{Error:()=>jt,ID:()=>nm,Service:()=>yn,Snapshot:()=>Kt,locationLayer:()=>nb,node:()=>ob,noopLayer:()=>rb});import as from"path";import{Context as tb,Effect as Y,Layer as rl,Schema as oo}from"effect";var nm=oo.String.pipe(oo.brand("Snapshot.ID")),jt=class extends oo.TaggedErrorClass()("Snapshot.Error",{operation:oo.Literals(["capture","files","diff","preview","restore"]),message:oo.String,cause:oo.optional(oo.Defect())}){static{r(this,"Error")}},yn=class extends tb.Service()("@opencode/v2/Snapshot"){static{r(this,"Service")}},om=rl.effect(yn,Y.gen(function*(){let e=yield*yr.Service,t=yield*de.Service,n=yield*en.Service,o=yield*he.Service,s=yield*En.Service,i=yield*n.repo.discover(s.project.directory),a=i?bt.make(yield*t.realPath(i.worktree).pipe(Y.orDie)):s.project.directory,c=bt.make(as.join(o.data,"snapshot",s.project.id,hs.fast(a))),l=Y.fnUntraced(function*(){let L=as.relative(a,s.directory);return L.startsWith("..")||as.isAbsolute(L)?yield*new jt({operation:"capture",message:"Location is outside the project"}):zt.make(L.replaceAll("\\","/")||".")}),f=Y.fnUntraced(function*(){return i?(yield*t.existsSafe(as.join(c,"HEAD")))?new en.Repository({worktree:a,gitDirectory:c,commonDirectory:c}):yield*n.repo.create({worktree:a,gitDirectory:c,seed:i}).pipe(Y.mapError(L=>st("capture",L))):yield*new jt({operation:"capture",message:"Project is not a Git repository"})}),g=Y.fnUntraced(function*(){return s.vcs?.type!=="git"?!1:yr.latest(yield*e.entries(),"snapshots")!==!1}),d=Y.fn("Snapshot.capture")(function*(){if(yield*g())return yield*Y.gen(function*(){let L=yield*f();return nm.make(yield*n.tree.capture({repository:L,scopes:[yield*l()],ignores:i,maximumUntrackedFileBytes:2*1024*1024}))}).pipe(Y.catch(L=>Y.logWarning("failed to capture snapshot",{cause:L}).pipe(Y.as(void 0))))}),h=Y.fnUntraced(function*(L,G){return{repository:yield*f().pipe(Y.mapError(Me=>st(L,Me))),from:en.TreeID.make(G.from),to:en.TreeID.make(G.to)}}),b=Y.fn("Snapshot.files")(function*(L){let G=yield*h("files",L),K=yield*n.tree.files(G).pipe(Y.mapError(x=>st("files",x)));if(!i)return K;let Me=yield*n.index.ignored({repository:i,paths:K}).pipe(Y.mapError(x=>st("files",x)));return K.filter(x=>!Me.has(x))}),_=Y.fn("Snapshot.diff")(function*(L){let G=yield*h("diff",L),K=yield*n.tree.files(G).pipe(Y.mapError(x=>st("diff",x))),Me=i?yield*n.index.ignored({repository:i,paths:K}).pipe(Y.mapError(x=>st("diff",x))):new Set;return yield*n.tree.diff({...G,context:L.context,paths:(L.paths??K).filter(x=>!Me.has(x))}).pipe(Y.mapError(x=>st("diff",x)))}),P=Y.fnUntraced(function*(L,G){let K=new Map;for(let[Me,x]of G.files){let E=as.resolve(a,Me);if(!de.contains(a,E))return yield*new jt({operation:L,message:`Path escapes the project: ${Me}`});K.set(Me,en.TreeID.make(x))}return K}),C=Y.fn("Snapshot.preview")(function*(L){if(!(yield*g()))return yield*new jt({operation:"preview",message:"Snapshots are disabled"});let G=yield*f().pipe(Y.mapError(x=>st("preview",x))),K=yield*P("preview",L),Me=yield*n.tree.capture({repository:G,scopes:Array.from(K.keys()),ignores:i,maximumUntrackedFileBytes:2*1024*1024}).pipe(Y.mapError(x=>st("preview",x)));return yield*n.tree.preview({repository:G,current:Me,files:K,context:L.context}).pipe(Y.mapError(x=>st("preview",x)))}),J=Y.fn("Snapshot.restore")(function*(L){if(!(yield*g()))return yield*new jt({operation:"restore",message:"Snapshots are disabled"});let G=yield*f().pipe(Y.mapError(K=>st("restore",K)));yield*n.tree.restore({repository:G,files:yield*P("restore",L)}).pipe(Y.mapError(K=>st("restore",K)))}),te=Y.fn("Snapshot.checkout")(function*(L){let G=yield*f().pipe(Y.mapError(K=>st("restore",K)));yield*n.tree.checkout({repository:G,tree:en.TreeID.make(L)}).pipe(Y.mapError(K=>st("restore",K)))});return yn.of({capture:d,files:b,diff:_,preview:C,restore:J,checkout:te})})),nb=om.pipe(rl.provideMerge(yr.locationLayer)),ob=io({service:yn,layer:om,deps:[yr.node,de.node,en.node,he.node,En.node]}),rb=rl.succeed(yn,yn.of({capture:r(()=>Y.succeed(void 0),"capture"),files:r(()=>Y.succeed([]),"files"),diff:r(()=>Y.succeed([]),"diff"),preview:r(()=>Y.succeed([]),"preview"),restore:r(()=>Y.void,"restore"),checkout:r(()=>Y.void,"checkout")}));function st(e,t){return t instanceof jt&&t.operation===e?t:new jt({operation:e,message:t instanceof globalThis.Error?t.message:String(t),cause:t})}r(st,"failure");function Bi(e){return fe.Info.make({id:fe.ID.make(e.id),projectID:tn.ID.make(e.project_id),title:e.title,parentID:e.parent_id?fe.ID.make(e.parent_id):void 0,agent:e.agent?vr.ID.make(e.agent):void 0,model:e.model?{id:Dt.ID.make(e.model.id),providerID:co.ID.make(e.model.providerID),variant:Dt.VariantID.make(e.model.variant??"default")}:void 0,cost:e.cost,tokens:{input:e.tokens_input,output:e.tokens_output,reasoning:e.tokens_reasoning,cache:{read:e.tokens_cache_read,write:e.tokens_cache_write}},location:En.Ref.make({directory:bt.make(e.directory),workspaceID:e.workspace_id?Tt.ID.make(e.workspace_id):void 0}),subpath:e.path?zt.make(e.path):void 0,revert:e.revert?{...e.revert,messageID:j.ID.make(e.revert.messageID)}:void 0,time:{created:sl.makeUnsafe(e.time_created),updated:sl.makeUnsafe(e.time_updated),archived:e.time_archived?sl.makeUnsafe(e.time_archived):void 0}})}r(Bi,"fromRow");var rr={};R(rr,{Service:()=>or,SessionStore:()=>rr,node:()=>hb});import{eq as lm}from"drizzle-orm";import{Context as fb,Effect as Sn,Layer as mb,Schema as gb}from"effect";var nr={};R(nr,{SessionHistory:()=>nr,entriesForRunner:()=>cm,latestCompaction:()=>cl,load:()=>pb,loadForRunner:()=>ub});import{and as al,asc as sb,desc as ib,eq as cs,gt as rm,gte as ab,ne as cb,or as sm}from"drizzle-orm";import{Effect as ut,Schema as lb}from"effect";import{Schema as il}from"effect";var hn=class extends il.TaggedErrorClass()("Session.MessageDecodeError",{sessionID:fe.ID,messageID:j.ID}){static{r(this,"MessageDecodeError")}get message(){return`Failed to decode message ${this.messageID} in session ${this.sessionID}`}},Fi=class extends il.TaggedErrorClass()("Session.ContextSnapshotDecodeError",{sessionID:fe.ID,details:il.String}){static{r(this,"ContextSnapshotDecodeError")}get message(){return`Failed to decode context snapshot for session ${this.sessionID}: ${this.details}`}};var db=lb.decodeUnknownEffect(j.Message),cl=ut.fnUntraced(function*(e,t){return yield*e.select({seq:T.seq}).from(T).where(al(cs(T.session_id,t),cs(T.type,"compaction"))).orderBy(ib(T.seq)).limit(1).get().pipe(ut.orDie)}),im=ut.fnUntraced(function*(e,t,n,o){return yield*e.select().from(T).where(al(cs(T.session_id,t),n?sm(ab(T.seq,n.seq),o===void 0?void 0:al(cs(T.type,"system"),rm(T.seq,o))):void 0,o===void 0?void 0:sm(cb(T.type,"system"),rm(T.seq,o)))).orderBy(sb(T.seq)).all().pipe(ut.orDie)}),am=r(e=>db({...e.data,id:e.id,type:e.type}).pipe(ut.mapError(()=>new hn({sessionID:fe.ID.make(e.session_id),messageID:j.ID.make(e.id)}))),"decodeMessageRow"),pb=ut.fn("SessionHistory.load")(function*(e,t){let[n,o]=yield*ut.all([e.select({baselineSeq:Ts.baseline_seq}).from(Ts).where(cs(Ts.session_id,t)).get().pipe(ut.orDie),cl(e,t)],{concurrency:"unbounded"});return yield*ut.forEach(yield*im(e,t,o,n?.baselineSeq),am)}),ub=ut.fn("SessionHistory.loadForRunner")(function*(e,t,n){return(yield*cm(e,t,n)).map(o=>o.message)}),cm=ut.fn("SessionHistory.entriesForRunner")(function*(e,t,n){let o=yield*im(e,t,yield*cl(e,t),n);return yield*ut.forEach(o,s=>am(s).pipe(ut.map(i=>({seq:s.seq,message:i}))))});var or=class extends fb.Service()("@opencode/v2/SessionStore"){static{r(this,"Service")}},yb=mb.effect(or,Sn.gen(function*(){let{db:e}=yield*Qe.Service,t=gb.decodeUnknownEffect(j.Message);return or.of({get:Sn.fn("SessionStore.get")(function*(n){let o=yield*e.select().from($).where(lm($.id,n)).get().pipe(Sn.orDie);return o?Bi(o):void 0}),context:Sn.fn("SessionStore.context")(function*(n){return yield*nr.load(e,n)}),runnerContext:Sn.fn("SessionStore.runnerContext")(function*(n,o){return yield*nr.loadForRunner(e,n,o)}),message:Sn.fn("SessionStore.message")(function*(n){let o=yield*e.select().from(T).where(lm(T.id,n)).get().pipe(Sn.orDie);return o?{sessionID:fe.ID.make(o.session_id),message:yield*t({...o.data,id:o.id,type:o.type}).pipe(Sn.orDie)}:void 0})})})),hb=kt({service:or,layer:yb,deps:[Qe.node]});var xn={};R(xn,{MessageNotFoundError:()=>Vi,SessionRevert:()=>xn,clear:()=>Eb,commit:()=>Ib,stage:()=>wb});import{and as dm,asc as Sb,eq as qi,gt as xb}from"drizzle-orm";import{DateTime as ll,Effect as ro,Schema as pm}from"effect";var Vi=class extends pm.TaggedErrorClass()("Session.MessageNotFoundError",{sessionID:fe.ID,messageID:j.ID}){static{r(this,"MessageNotFoundError")}},vb=ro.fn("SessionRevert.plan")(function*(e){let t=(yield*Qe.Service).db,n=yield*t.select({seq:T.seq}).from(T).where(dm(qi(T.session_id,e.sessionID),qi(T.id,e.messageID))).get().pipe(ro.orDie);if(!n)return yield*new Vi(e);let o=yield*t.select().from(T).where(dm(qi(T.session_id,e.sessionID),qi(T.type,"assistant"),xb(T.seq,n.seq))).orderBy(Sb(T.seq)).all().pipe(ro.orDie),s=pm.decodeUnknownEffect(j.Message),i=new Map;for(let a of o){let c=yield*s({...a.data,id:a.id,type:a.type}).pipe(ro.orDie);if(!(c.type!=="assistant"||!c.snapshot?.start))for(let l of c.snapshot.files??[])i.has(l)||i.set(l,Kt.ID.make(c.snapshot.start))}return i}),wb=ro.fn("SessionRevert.stage")(function*(e){let t=yield*Kt.Service,n=yield*Fe.Service,o=e.session.revert?.snapshot?Kt.ID.make(e.session.revert.snapshot):yield*t.capture(),s=yield*vb({sessionID:e.session.id,messageID:e.messageID}),i=new Map;if(o)for(let f of e.session.revert?.files??[])i.set(f.path,o);if(e.files!==!1)for(let[f,g]of s)i.set(f,g);i.size&&(yield*t.restore({files:i}));let a=e.files===!1?[]:Array.from(s.keys()),c=o?yield*t.diff({from:o,to:(yield*t.capture())??o,paths:a}):[],l={messageID:e.messageID,snapshot:o,diff:c.map(f=>f.patch).join("").trim(),files:c};return yield*n.publish(V.RevertEvent.Staged,{sessionID:e.session.id,timestamp:yield*ll.now,revert:l}),l}),Eb=ro.fn("SessionRevert.clear")(function*(e){if(!e.revert)return;let t=yield*Kt.Service,n=e.revert.snapshot?Kt.ID.make(e.revert.snapshot):void 0;n&&(yield*t.restore({files:new Map((e.revert.files??[]).map(s=>[s.path,n]))})),yield*(yield*Fe.Service).publish(V.RevertEvent.Cleared,{sessionID:e.id,timestamp:yield*ll.now})}),Ib=ro.fn("SessionRevert.commit")(function*(e){if(!e.revert)return;yield*(yield*Fe.Service).publish(V.RevertEvent.Committed,{sessionID:e.id,messageID:e.revert.messageID,timestamp:yield*ll.now})});var Tb=Es.State;var ml={workspaceID:Tt.ID.pipe(qe.optional),search:qe.String.pipe(qe.optional),limit:$t.pipe(qe.optional),order:qe.Literals(["asc","desc"]).pipe(qe.optional),anchor:Os.pipe(qe.optional)},_b=qe.Struct({...ml,directory:bt}),Ab=qe.Struct({...ml,project:tn.ID,subpath:zt.pipe(qe.optional)}),Ob=qe.Struct(ml),Rb=qe.Union([_b,Ab,Ob]),Wi=class extends qe.TaggedErrorClass()("Session.NotFoundError",{sessionID:fe.ID}){static{r(this,"NotFoundError")}},so=class extends qe.TaggedErrorClass()("Session.OperationUnavailableError",{operation:qe.Literals(["move","shell","skill","switchAgent","compact","wait"])}){static{r(this,"OperationUnavailableError")}},ds=class extends qe.TaggedErrorClass()("Session.PromptConflictError",{sessionID:fe.ID,messageID:j.ID}){static{r(this,"PromptConflictError")}},Cb=xn.MessageNotFoundError,sr=class extends kb.Service()("@opencode/v2/Session"){static{r(this,"Service")}},Pb=gm.effect(sr,q.gen(function*(){let e=yield*Qe.Service,t=e.db,n=yield*Fe.Service,o=yield*tn.Service,s=yield*tr.Service,i=yield*rr.Service,a=yield*Yo.Service,c=qe.decodeUnknownEffect(j.Message),l=qe.is(V.Durable),f=r(d=>c({...d.data,id:d.id,type:d.type}).pipe(q.mapError(()=>new hn({sessionID:fe.ID.make(d.session_id),messageID:j.ID.make(d.id)}))),"decode"),g=sr.of({create:q.fn("V2Session.create")(function*(d){let h=d.id??fe.ID.create(),b=yield*i.get(h);if(b)return b;let _=yield*o.resolve(d.location.directory);yield*t.insert(mo).values({id:_.id,worktree:_.directory,vcs:_.vcs?.type,sandboxes:[]}).onConflictDoNothing().run().pipe(q.orDie);let P=Date.now(),C=tt.SessionInfo.make({id:h,slug:ga.create(),version:lo,projectID:_.id,directory:d.location.directory,path:Db.relative(_.directory,d.location.directory).replaceAll("\\","/"),workspaceID:d.location.workspaceID?Tt.ID.make(d.location.workspaceID):void 0,title:`New session - ${new Date(P).toISOString()}`,agent:d.agent,model:d.model?{id:Dt.ID.make(d.model.id),providerID:d.model.providerID,variant:d.model.variant}:void 0,cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},time:{created:P,updated:P}}),J=yield*n.publish(tt.Event.Created,{sessionID:h,info:C},{location:d.location}).pipe(q.as({type:"created"}),q.catchDefect(te=>te instanceof vo.SessionAlreadyProjected?i.get(h).pipe(q.flatMap(L=>L?q.succeed({type:"existing",session:L}):q.die(te))):q.die(te)));return J.type==="existing"?J.session:yield*g.get(h).pipe(q.orDie)}),get:q.fn("V2Session.get")(function*(d){let h=yield*i.get(d);return h||(yield*new Wi({sessionID:d}))}),list:q.fn("V2Session.list")(function*(d={}){let h=d.anchor?.direction??"next",b=d.order??"desc",_=h==="previous"?b==="asc"?"desc":"asc":b,P=$.time_created,C=[];"directory"in d&&C.push(Xt($.directory,d.directory)),d.workspaceID&&C.push(Xt($.workspace_id,d.workspaceID)),"project"in d&&C.push(Xt($.project_id,d.project)),d.search&&C.push(bb($.title,`%${d.search}%`)),d.anchor&&C.push(_==="asc"?mm(ul(P,d.anchor.time),ls(Xt(P,d.anchor.time),ul($.id,d.anchor.id))):mm(fl(P,d.anchor.time),ls(Xt(P,d.anchor.time),fl($.id,d.anchor.id))));let J=t.select().from($).where(C.length>0?ls(...C):void 0).orderBy(_==="asc"?dl(P):pl(P),_==="asc"?dl($.id):pl($.id)),te=yield*(d.limit===void 0?J.all():J.limit(d.limit).all()).pipe(q.orDie);return(h==="previous"?te.toReversed():te).map(L=>Bi(L))}),messages:q.fn("V2Session.messages")(function*(d){yield*g.get(d.sessionID);let h=d.cursor?.direction??"next",b=d.order??"desc",_=h==="previous"?b==="asc"?"desc":"asc":b,P=d.cursor?yield*t.select({seq:T.seq}).from(T).where(ls(Xt(T.session_id,d.sessionID),Xt(T.id,d.cursor.id))).get().pipe(q.orDie):void 0;if(d.cursor&&!P)return[];let C=P?_==="asc"?ul(T.seq,P.seq):fl(T.seq,P.seq):void 0,J=C?ls(Xt(T.session_id,d.sessionID),C):Xt(T.session_id,d.sessionID),te=t.select().from(T).where(J).orderBy(_==="asc"?dl(T.seq):pl(T.seq)),L=yield*(d.limit===void 0?te.all():te.limit(d.limit).all()).pipe(q.orDie);return yield*q.forEach(h==="previous"?L.toReversed():L,f)}),message:q.fn("V2Session.message")(function*(d){let h=yield*i.message(d.messageID);return h?.sessionID===d.sessionID?h.message:void 0}),context:q.fn("V2Session.context")(function*(d){return yield*g.get(d),yield*i.context(d)}),events:r(d=>fm.unwrap(g.get(d.sessionID).pipe(q.as(n.durable({aggregateID:d.sessionID,after:d.after})))).pipe(fm.filter(h=>l(h))),"events"),history:q.fn("V2Session.history")(function*(d){return yield*g.get(d.sessionID),yield*Fe.readAggregate(t,{...d,aggregateID:d.sessionID,manifest:xd})}),prompt:q.fn("V2Session.prompt")(d=>q.uninterruptible(q.gen(function*(){yield*g.get(d.sessionID);let h=Mb(d.prompt),b=d.id??j.ID.create(),_=d.delivery??"steer",P={sessionID:d.sessionID,messageID:b,prompt:h,delivery:_},C=yield*At.admit(t,n,{id:b,sessionID:d.sessionID,prompt:h,delivery:_}).pipe(q.catchDefect(J=>J instanceof At.LifecycleConflict?new ds({sessionID:d.sessionID,messageID:b}):q.die(J)));return At.equivalent(C,P)?(d.resume!==!1&&(yield*s.wake(C.sessionID)),C):yield*new ds({sessionID:d.sessionID,messageID:b})}))),shell:q.fn("V2Session.shell")(function*(){return yield*new so({operation:"shell"})}),skill:q.fn("V2Session.skill")(function*(){return yield*new so({operation:"skill"})}),switchAgent:q.fn("V2Session.switchAgent")(function*(d){yield*g.get(d.sessionID),yield*n.publish(V.AgentSwitched,{sessionID:d.sessionID,messageID:j.ID.create(),timestamp:yield*um.now,agent:d.agent})}),switchModel:q.fn("V2Session.switchModel")(function*(d){let h=yield*g.get(d.sessionID);h.model?.providerID===d.model.providerID&&h.model.id===d.model.id&&(h.model.variant??"default")===(d.model.variant??"default")||(yield*n.publish(V.ModelSwitched,{sessionID:d.sessionID,messageID:j.ID.create(),timestamp:yield*um.now,model:d.model}))}),compact:q.fn("V2Session.compact")(function*(d){return yield*g.get(d.sessionID),yield*new so({operation:"compact"})}),wait:q.fn("V2Session.wait")(function*(d){return yield*g.get(d),yield*new so({operation:"wait"})}),active:s.active,resume:q.fn("V2Session.resume")(function*(d){yield*g.get(d),yield*s.resume(d)}),interrupt:q.fn("V2Session.interrupt")(d=>q.uninterruptible(s.interrupt(d))),revert:{stage:q.fn("V2Session.revert.stage")(function*(d){let h=yield*g.get(d.sessionID);return yield*xn.stage({session:h,messageID:d.messageID,files:d.files}).pipe(q.provideService(Qe.Service,e),q.provideService(Fe.Service,n),q.provide(a.get(h.location)))}),clear:q.fn("V2Session.revert.clear")(function*(d){let h=yield*g.get(d);yield*xn.clear(h).pipe(q.provideService(Fe.Service,n),q.provide(a.get(h.location)))}),commit:q.fn("V2Session.revert.commit")(function*(d){let h=yield*g.get(d);yield*xn.commit(h).pipe(q.provideService(Fe.Service,n))})}});return g})),Mb=r(e=>Qt.make({text:e.text,agents:e.agents,files:e.files?.map(t=>{let n=t.uri.match(/^data:([^;,]+)[;,]/i)?.[1],o=URL.canParse(t.uri)?new URL(t.uri).pathname:t.name??t.uri;return{...t,mime:n??(o.endsWith("/")?"application/x-directory":de.mimeType(o))}})}),"resolvePrompt"),Lb=kt({service:sr,layer:Pb.pipe(gm.orDie),deps:[Qe.node,Fe.node,tn.node,tr.node,rr.node,Yo.node,vo.node]});export{Vt as a,vr as b,Yo as c,xo as d,fe as e,hr as f,Sr as g,Tt as h,j as i,ol as j,We as k,Ym as l,Zm as m,Qm as n,eg as o,ng as p,og as q,tt as r,da as s,ua as t,ca as u,$ as v,bn as w,nt as x,TD as y,Ts as z,At as A,vo as B,ga as C,Kt as D,ki as E,bi as F,yw as G,ff as H,mf as I,gf as J,W as K,rs as L,dn as M,De as N,Of as O,xI as P,Yc as Q,aL as R,Lf as S,Kf as T,bL as U,el as V,tl as W,nl as X,Fi as Y,nr as Z,rr as _,tr as $,gl as aa,Fs as ba,Jn as ca,Wd as da,Xd as ea,zd as fa,Rr as ga,cn as ha,Ws as ia,Pr as ja,Hs as ka,jo as la,Hh as ma,Uo as na,jr as oa,$r as pa,Zp as qa,cO as ra,Qp as sa,ec as ta,Yh as ua,ze as va,Bo as wa,be as xa,tu as ya,ai as za,rc as Aa,Je as Ba,Gr as Ca,Kr as Da,Fr as Ea,kO as Fa,hc as Ga,zr as Ha,eC as Ia,Bu as Ja,Fu as Ka,tC as La,nC as Ma,oC as Na,rC as Oa,sC as Pa,iC as Qa,Xn as Ra,Pc as Sa,ts as Ta,Qr as Ua,jc as Va,$c as Wa,Bc as Xa,Fc as Ya};