@opencode/console 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +37 -2
- package/THIRD_PARTY_LICENSES.md +547 -0
- package/chunk-0krh2hdf.js +1 -0
- package/chunk-1c689590.js +1 -0
- package/chunk-1mfjsp5r.js +2 -0
- package/chunk-41p6m0xy.js +6 -0
- package/chunk-4v6awhyw.js +1 -0
- package/chunk-52p33kcn.js +1 -0
- package/chunk-5x5fc0mq.js +2 -0
- package/chunk-6tene1pb.js +2 -0
- package/chunk-9pcmbxq5.js +1 -0
- package/chunk-a85j5cz4.js +1 -0
- package/chunk-aesb1szb.js +3 -0
- package/chunk-bgqw45qt.js +2 -0
- package/chunk-dsk7ztf6.js +2 -0
- package/chunk-g6d8xejf.js +63 -0
- package/chunk-gtf5exm1.js +8 -0
- package/chunk-hf4hqs7y.js +3 -0
- package/chunk-jqhy4pzf.js +2 -0
- package/chunk-ke4nwx54.js +2 -0
- package/chunk-nva98fq1.js +32 -0
- package/chunk-p909n1zf.js +1 -0
- package/chunk-q3519h2y.js +1 -0
- package/chunk-r2y8x1nz.js +12 -0
- package/chunk-rea503jg.js +1 -0
- package/chunk-sbec97g3.js +2 -0
- package/chunk-vx37gkw9.js +1 -0
- package/chunk-wb6qf86j.js +1 -0
- package/chunk-yjw665b0.js +1 -0
- package/chunk-z2kmm4pm.js +2 -0
- package/index.js +81 -0
- package/package.json +44 -3
- package/pi-extension.js +2 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{$r,jr,cs,ri}from"./chunk-yjw665b0.js";export{ri as FetchHttpClient,cs as HttpClient,$r as HttpClientRequest,jr as HttpClientResponse};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ws,Ks,Ko,Go,Jo,Vn,Gs,Vo,Gi,Zo}from"./chunk-dsk7ztf6.js";import"./chunk-6tene1pb.js";import"./chunk-1mfjsp5r.js";import"./chunk-ke4nwx54.js";import"./chunk-yjw665b0.js";import"./chunk-5x5fc0mq.js";import"./chunk-jqhy4pzf.js";export{Ks as Info,Ws as MAX_AGE_MS,Zo as WorkspaceSnapshot,Jo as clear,Gi as models,Gs as policies,Ko as read,Vn as stale,Vo as workspace,Go as write};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import"./chunk-jqhy4pzf.js";import"./chunk-yjw665b0.js";import{er}from"./chunk-ke4nwx54.js";import{ze,he,Re,me}from"./chunk-5x5fc0mq.js";import{Je,Qt}from"./chunk-1mfjsp5r.js";import{Uo,Gt,Jt,Lo,Nr,Dr,$o,zs,Ct,jo,Bo,z,Vt,Zt,Kn,Gn,Jn}from"./chunk-gtf5exm1.js";import"./chunk-6tene1pb.js";import"./chunk-dsk7ztf6.js";import{Yt}from"./chunk-sbec97g3.js";import{Fr,Do,Ki}from"./chunk-z2kmm4pm.js";import{st}from"./chunk-bgqw45qt.js";import{w,D,T,L,J,C,t,E,n,y,f,wt,se}from"./chunk-nva98fq1.js";var U={};w(U,{ClaudeCode:()=>U,hookArgs:()=>O,manifest:()=>R,manifestFile:()=>A,models:()=>F,paths:()=>Z,refresh:()=>ne,remove:()=>oe,shellCommand:()=>N});import{createHash as Q}from"node:crypto";import{existsSync as v,rmSync as X}from"node:fs";import Y from"node:os";import m from"node:path";function Z(o=process.env,e=Y.homedir()){let r=o.CLAUDE_CONFIG_DIR?.trim(),i=r?m.resolve(r):m.join(e,".claude");return{config:i,settings:m.join(i,"settings.json"),global:r?m.join(i,".claude.json"):m.join(e,".claude.json"),skills:m.join(i,"skills"),memory:m.join(i,"CLAUDE.md")}}function F(o){let e=Fr(o),r=Ki(e);if(e.length===0||r===void 0)return;let i=(s)=>s.provider==="opencode"?s.id:`${s.provider}/${s.id}`,a=(...s)=>i(Do(e,...s));return{baseURL:`${r}/anthropic`,options:e.map((s)=>({model:i(s),label:Vt(s.entry.name)??s.id,...s.provider==="opencode"||s.providerName===void 0?{}:{description:s.providerName}})),tiers:{opus:a("opus","sonnet","haiku"),sonnet:a("sonnet","opus","haiku"),haiku:a("haiku","sonnet","opus")}}}var ee=n({baseURL:t,options:f(n({model:t,label:t,description:C(t)})),tiers:n({opus:t,sonnet:t,haiku:t})}),B=n({paths:n({config:t,settings:t,global:t,skills:t,memory:t}),command:f(t),harness:C(t),...Uo,servers:f(t),skills:y(t,t),memoryCreated:E,created:C(n({settings:E,global:E})),providers:C(t),models:C(wt(ee))}),A=(o)=>m.join(o.data,"claude-code.json");function R(o){let e=A(o),r=he(e);if(r===void 0)return;let i=D(J(se(B))(r));if(!i)throw Error(`${e} can't be read, so Claude Code was left as it is. Delete it and run setup again.`);return i}var ne=L("ClaudeCode.refresh")(function*(o,e){let r=R(o),i=e??r;if(!i)return;let a=yield*Qt(o),s=a&&Yt(o,Je(a));if(!a||!s?.config)return;let l=s.config,c=Zt(l),p=Q("sha256").update(JSON.stringify(l.providers??null)).digest("hex"),h=!e&&r?.providers===p&&r.models!==void 0?r.models??void 0:F(yield*er(a)),j=yield*Gn(a,i.paths.skills,c.skills,r?.skills??{});return yield*ze(o,T(()=>te(o,{paths:i.paths,command:i.command,harness:e?e.harness:r?.harness,models:h,servers:Object.fromEntries(Object.entries(Kn(l)).map(([M,g])=>[M,{url:g.url,gateway:g.headers!==void 0}])),instructions:c.instructions,skills:c.skills,bundles:j,providers:p,explicit:e!==void 0})))});function oe(o){let e=R(o);if(!e)return!1;let r=Gt(e.paths.settings),i=Gt(e.paths.global),a=he(e.paths.memory),s=e.created??{settings:!v(Ct(e.paths.settings)),global:!v(Ct(e.paths.global))};if(r)if(Object.keys(e.originals).forEach((l)=>Nr(r,l,e)),K(r,void 0),G(r),Object.keys(r).length===0&&s.settings)me(e.paths.settings);else Jt(e.paths.settings,r);if(i){let l=z(i.mcpServers);if(e.servers.forEach((c)=>delete l[c]),Object.keys(l).length===0)delete i.mcpServers;else i.mcpServers=l;if(Object.keys(i).length===0&&s.global)me(e.paths.global);else Jt(e.paths.global,i,384)}return Object.keys(e.skills).forEach((l)=>X(m.join(e.paths.skills,l),{recursive:!0,force:!0})),V(e.paths.memory,a,[],e.memoryCreated),[e.paths.settings,e.paths.global].forEach((l)=>me(Ct(l))),me(A(o)),!0}var O=["hook","claude-code"],W="x-opencode-plugin",b="<!-- opencode-console:start -->",x="<!-- opencode-console:end -->";function te(o,e){let r=R(o),i=r===void 0,a=v(e.paths.settings),s=v(e.paths.global),l=Gt(e.paths.settings)??{},c=Gt(e.paths.global)??{},p=he(e.paths.memory),u=r?.created??{settings:!a,global:!s},h=[];if(i)[e.paths.settings,e.paths.global].forEach(jo);let{originals:j,written:M}=Lo(l,re(e),r,e.explicit);K(l,e.models?`${W}: opencode-console/${st}`:void 0),G(l);let g=z(l.hooks);ie(e.command).forEach(([d,S])=>{g[d]=[...Array.isArray(g[d])?g[d]:[],S]}),l.hooks=g;let I=new Set(r?.servers??[]),k=z(c.mcpServers);I.forEach((d)=>{if(!(d in e.servers))delete k[d]});let _=Object.entries(e.servers).flatMap(([d,S])=>{if(S.url===void 0||!/^[a-z0-9_-]+$/i.test(d))return[];if(d in k&&!I.has(d))return h.push(d),[];return k[d]={type:"http",url:S.url,...S.gateway?{headersHelper:N([...e.command,"mcp-headers",d])}:{}},[d]});if(Object.keys(k).length>0)c.mcpServers=k;else delete c.mcpServers;if(Jt(e.paths.settings,l,384),s||_.length>0)Jt(e.paths.global,c,384);let H=Jn(e.paths.skills,e.skills,e.bundles,r?.skills??{});h.push(...H.skipped);let P=H.skills,q=V(e.paths.memory,p,e.instructions,r?.memoryCreated??!1);return Re(A(o),JSON.stringify(B.make({paths:e.paths,command:[...e.command],...e.harness===void 0?{}:{harness:e.harness},originals:j,written:M,servers:_,skills:P,memoryCreated:q,created:u,providers:e.providers,models:e.models??null}))),{models:e.models,servers:_,skills:Object.keys(P),instructions:e.instructions.length,skipped:h}}function re(o){let e=o.harness===void 0?{}:{"env.OPENCODE_CONSOLE_HARNESS":o.harness};if(!o.models)return e;return{...e,apiKeyHelper:N([...o.command,"token"]),"env.ANTHROPIC_BASE_URL":o.models.baseURL,"env.ANTHROPIC_DEFAULT_OPUS_MODEL":o.models.tiers.opus,"env.ANTHROPIC_DEFAULT_SONNET_MODEL":o.models.tiers.sonnet,"env.ANTHROPIC_DEFAULT_HAIKU_MODEL":o.models.tiers.haiku,modelPicker:{options:o.models.options,replaceBuiltInOptions:!0}}}function K(o,e){let r=Dr(o,"env.ANTHROPIC_CUSTOM_HEADERS"),a=[...(typeof r==="string"?r:"").split(`
|
|
2
|
+
`).filter((s)=>s.trim()!==""&&!s.toLowerCase().startsWith(`${W}:`)),...e===void 0?[]:[e]];if(a.length>0)$o(o,"env.ANTHROPIC_CUSTOM_HEADERS",a.join(`
|
|
3
|
+
`));else if(r!==void 0)zs(o,"env.ANTHROPIC_CUSTOM_HEADERS")}function ie(o){let e={type:"command",command:o[0],args:[...o.slice(1),...O]},r={...e,timeout:30,onFailure:"block"};return[["PreToolUse",{matcher:"*",hooks:[r]}],["UserPromptSubmit",{hooks:[r]}],["UserPromptExpansion",{hooks:[r]}],["SessionStart",{hooks:[{...e,timeout:10}]}]]}function G(o){let e=z(o.hooks);if(Object.entries(e).forEach(([r,i])=>{if(!Array.isArray(i))return;let a=i.flatMap((s)=>{let l=z(s).hooks;if(!Array.isArray(l))return[s];let c=l.filter((p)=>!le(p));if(c.length===l.length)return[s];return c.length===0?[]:[{...z(s),hooks:c}]});if(a.length===0)delete e[r];else e[r]=a}),Object.keys(e).length===0)delete o.hooks;else o.hooks=e}function le(o){let e=z(o).args;return Array.isArray(e)&&e.slice(-O.length).join(" ")===O.join(" ")}function V(o,e,r,i){if(r.length===0&&!e?.includes(b))return i;let a=(e??"").replace(new RegExp(`\\n*${b}[\\s\\S]*?${x}\\n?`),`
|
|
4
|
+
`).trim(),s=(u)=>u.replaceAll(b,"<!-- opencode-console start -->").replaceAll(x,"<!-- opencode-console end -->"),l=r.length===0?"":[b,"# Workspace instructions from OpenCode Console",...r.map((u)=>`## ${s(u.name)}
|
|
5
|
+
|
|
6
|
+
${s(u.content.trim())}`),x].join(`
|
|
7
|
+
|
|
8
|
+
`),c=[a,l].filter((u)=>u!=="").join(`
|
|
9
|
+
|
|
10
|
+
`),p=i||e===void 0&&l!=="";if(c===""&&p)return me(o),!1;if(`${c}
|
|
11
|
+
`!==e)Bo(o,`${c}
|
|
12
|
+
`);return p}function N(o){return o.map((e)=>process.platform==="win32"?`"${e.replaceAll('"','""')}"`:/^[\w@%+=:,./-]+$/.test(e)?e:`'${e.replaceAll("'",`'"'"'`)}'`).join(" ")}export{U as ClaudeCode,O as hookArgs,R as manifest,A as manifestFile,F as models,Z as paths,ne as refresh,oe as remove,N as shellCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ho,qs,qo,Yt,Wo}from"./chunk-sbec97g3.js";import"./chunk-dsk7ztf6.js";import"./chunk-6tene1pb.js";import"./chunk-1mfjsp5r.js";import"./chunk-ke4nwx54.js";import"./chunk-yjw665b0.js";import"./chunk-5x5fc0mq.js";import"./chunk-jqhy4pzf.js";export{Wo as WorkspaceSync,Yt as current,Ho as identify,qo as sync,qs as userAgent};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{Xt,Ee,ti}from"./chunk-yjw665b0.js";import{Qn,An,ns}from"./chunk-ke4nwx54.js";import{ze}from"./chunk-5x5fc0mq.js";import{je,Je,In,Qt}from"./chunk-1mfjsp5r.js";import{Ko,Go,Jo,Vn}from"./chunk-dsk7ztf6.js";import{w,O,ee,at,r,T,u,Qr,g,L}from"./chunk-nva98fq1.js";var Wo={};w(Wo,{WorkspaceSync:()=>Wo,current:()=>Yt,identify:()=>Ho,sync:()=>qo,userAgent:()=>qs});function Ho(e){return ee(Ee,g(Ee,(o)=>ti(o,Xt({"user-agent":qs(e),"x-opencode-plugin":`opencode-console/${e.version}`}))))}function qs(e){return[e.harness?.replace(/[\r\n]/g,"").trim(),`opencode-console/${e.version}`].filter(Boolean).join(" ")}var qo=L("WorkspaceSync.sync")(function*(e,o={}){let n=je(e);if(!n)return yield*ze(e,T(()=>Jo(e))),{snapshot:void 0};let s=yield*at,i=Je(n),c=Yt(e,i);if(c&&!o.force&&!Vn(c,s))return{snapshot:c};let t=yield*Qt(e).pipe(u((a)=>a?ns(a).pipe(g((p)=>({credential:a,config:p}))):r(void 0)),Qr);if(O(t)){if(!t.success)return{snapshot:void 0};return{snapshot:yield*l(e,i,{owner:i,organization:In(t.success.credential),fetched:s,config:t.success.config})}}let f=m(t.failure);if(!f)return{snapshot:c,error:t.failure};let d=c??{owner:i,organization:In(n)};return{snapshot:yield*l(e,i,{...d,fetched:s,status:f}),error:t.failure}});function Yt(e,o){let n=Ko(e);return n?.owner===o?n:void 0}function l(e,o,n){return ze(e,T(()=>{let s=je(e);if(!s||Je(s)!==o)return;return Go(e,n),n}))}function m(e){if(e instanceof Qn)return{message:e.message,url:e.url};if(e instanceof An)return{message:e.message};return}
|
|
2
|
+
export{Ho,qs,qo,Yt,Wo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{je,Ur,Je,In,Ji,Qt,Vi,Qo}from"./chunk-1mfjsp5r.js";import"./chunk-ke4nwx54.js";import"./chunk-yjw665b0.js";import"./chunk-5x5fc0mq.js";import"./chunk-jqhy4pzf.js";export{Qo as ConsoleCredentials,Qt as fresh,Ji as login,Vi as logout,In as organization,Je as owner,je as read,Ur as stored};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Fo,No}from"./chunk-g6d8xejf.js";import"./chunk-6tene1pb.js";import"./chunk-yjw665b0.js";import"./chunk-5x5fc0mq.js";import"./chunk-jqhy4pzf.js";export{No as PolicyEvaluator,Fo as check};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{w,v,e,c,V,Te,Ot,Kr,s,ci,we,p,_,Z,ms,ke,X,ge,i,a,k,M,U,Ce,nr,D,P,ie,rn,Rt,I,h,Fe,S,O,B,on,pe,xe,ye,mt,rr,Pn,R,Rn,sn,Vr,Zr,bs,an,gt,ae,li,ee,sr,ir,un,ln,ar,Ze,fe,r,A,T,xt,o,Ye,H,cr,dn,u,mn,Ue,g,Qe,He,ur,vs,qe,lr,eo,Es,to,yt,ws,ks,Ut,Dn,Un,Cs,Ts,$t,ut,no,ro,oo,bt,Os,_s,Ps,jt,ce,hr,xr,gi,Sr,et,co,xi,yi,uo,lo,xn,bi,Bt,Si,vi,St,po,Ns,fo,Ei,zt,wi,We,wr,ki,Ci,Ii,Ai,Ti,Ht,mo,vt,Bn,qt,F,m,se,$s,Kt,Ge,Li,Or,bo,En,$i,So,ji,vo,Bi,zi,rt}from"./chunk-nva98fq1.js";var ri={};w(ri,{Fetch:()=>pt,RequestInit:()=>Br,StreamBodyFallback:()=>bn,layer:()=>zr});var cs={};w(cs,{HttpClient:()=>Ee,SpanNameGenerator:()=>hn,TracerDisabledWhen:()=>cn,TracerHeaderFilter:()=>pn,TracerPropagationEnabled:()=>fn,catch:()=>zs,catchTag:()=>Gs,catchTags:()=>Vs,circuitBreakerClassifier:()=>Ko,del:()=>Ws,execute:()=>As,filterOrElse:()=>Zs,filterOrFail:()=>Ks,filterStatus:()=>ta,filterStatusOk:()=>ei,followRedirects:()=>Ca,get:()=>Ds,head:()=>Fs,isHttpClient:()=>Zo,isTransientError:()=>Ir,isTransientResponse:()=>kr,layerMergedContext:()=>Mr,make:()=>Dr,makeWith:()=>nt,mapRequest:()=>ti,mapRequestEffect:()=>oa,mapRequestInput:()=>na,mapRequestInputEffect:()=>sa,options:()=>js,patch:()=>qs,post:()=>Ls,put:()=>Js,query:()=>Ms,retry:()=>aa,retryTransient:()=>ia,tap:()=>xa,tapError:()=>Sa,tapRequest:()=>ba,timeout:()=>ca,transform:()=>ue,transformResponse:()=>Ae,withCircuitBreaker:()=>fa,withCookiesRef:()=>Ha,withRateLimiter:()=>pa,withScope:()=>ni});var $r={};w($r,{accept:()=>yr,acceptJson:()=>tr,appendUrl:()=>Qn,appendUrlParam:()=>Kn,appendUrlParams:()=>Xn,basicAuth:()=>zn,bearerToken:()=>Qs,bodyFile:()=>ds,bodyFormData:()=>ps,bodyFormDataRecord:()=>fs,bodyJson:()=>ns,bodyJsonUnsafe:()=>Xs,bodyStream:()=>us,bodyText:()=>os,bodyUint8Array:()=>rs,bodyUrlParams:()=>is,compressBody:()=>es,delete:()=>Jn,empty:()=>Do,fromWeb:()=>ls,get:()=>as,head:()=>Wn,isHttpClientRequest:()=>Wt,make:()=>K,makeWith:()=>L,modify:()=>Er,options:()=>$n,patch:()=>vn,post:()=>Ys,prependUrl:()=>Vn,put:()=>qn,query:()=>Ln,removeHash:()=>ts,removeHeader:()=>lt,schemaBodyJson:()=>ss,setBody:()=>z,setHash:()=>No,setHeader:()=>Gt,setHeaders:()=>Xt,setMethod:()=>De,setUrl:()=>ko,setUrlParam:()=>Zn,setUrlParams:()=>Fo,toUrl:()=>oe,toWeb:()=>ys,toWebResult:()=>Lo,trace:()=>jn,updateHeaders:()=>Mo,updateUrl:()=>Yn,upgrade:()=>Gn});var jr={};w(jr,{TypeId:()=>ht,filterStatus:()=>Cr,filterStatusOk:()=>en,fromWeb:()=>Hr,matchStatus:()=>Us,schemaBodyJson:()=>Be,schemaBodyUrlParams:()=>qo,schemaHeaders:()=>Jo,schemaJson:()=>Ss,schemaNoBody:()=>Hs,stream:()=>Rs,toWeb:()=>xs});var Cn="~effect/Ref",Ba={[Cn]:{_A:c},...ge,toJSON(){return{_id:"Ref",ref:this.ref}}};var vr=(t)=>T(()=>t.ref.current);var qr=e(2,(t,n)=>T(()=>{t.ref.current=n(t.ref.current)}));var je="~effect/http/HttpBody";var Jr="~effect/http/HttpBody/HttpBodyError";class Ve extends R("HttpBodyError"){[Jr]=Jr}class Mt{[je];constructor(){this[je]=je}[_](){return this.toJSON()}toString(){return p(this,{ignoreToString:!0})}}class Xr extends Mt{_tag="Empty";toJSON(){return{_id:"effect/HttpBody",_tag:"Empty"}}}var kt=new Xr;class so extends Mt{_tag="Raw";body;contentType;contentLength;constructor(t,n,f){super();this.body=t,this.contentType=n,this.contentLength=f}toJSON(){return{_id:"effect/HttpBody",_tag:"Raw",body:this.body,contentType:this.contentType,contentLength:this.contentLength}}}var ao=(t,n)=>new so(t,n?.contentType,n?.contentLength);class me extends Mt{_tag="Uint8Array";contentType;contentLength;text;_body;constructor(t,n,f,d){super();this._body=t,this.text=d,this.contentType=n,this.contentLength=f}get body(){return this._body??=wn(this.text)}toJSON(){return{_id:"effect/HttpBody",_tag:"Uint8Array",body:this.contentType.startsWith("text/")||this.contentType.endsWith("json")?new TextDecoder().decode(this.body):`Uint8Array(${this.body.length})`,contentType:this.contentType,contentLength:this.contentLength}}}var Se=(t,n)=>new me(t,n??"application/octet-stream",t.length),io=new TextEncoder,le=globalThis.Buffer,wn=le!==void 0?(t)=>le.from(t,"utf8"):(t)=>io.encode(t),Yt=(t,n)=>{if(typeof t!=="string")t=t===void 0?"":String(t);if(le!==void 0)return new me(void 0,n??"text/plain",le.byteLength(t,"utf8"),t);let f=io.encode(t);return new me(f,n??"text/plain",f.length,t)},ho=(t,n)=>Yt(JSON.stringify(t),n??"application/json"),Ke=(t,n)=>H({try:()=>Yt(JSON.stringify(t),n??"application/json"),catch:(f)=>new Ve({reason:{_tag:"JsonError"},cause:f})}),go=(t,n)=>{let f=vt(Kt(t));return(d,l)=>f(d,n).pipe(qe((E)=>new Ve({reason:{_tag:"SchemaError",issue:E},cause:E})),u((E)=>Ke(E,l)))},Eo=(t,n)=>Yt(Ti(We(t)),n??"application/x-www-form-urlencoded");class yo extends Mt{_tag="FormData";contentType=void 0;contentLength=void 0;formData;constructor(t){super();this.formData=t}toJSON(){return{_id:"effect/HttpBody",_tag:"FormData",formData:this.formData}}}var Xe=(t)=>new yo(t),Wr=(t,n,f)=>{if(f==null)return;if(typeof f==="object"){t.append(n,f);return}t.append(n,String(f))},xo=(t)=>{let n=new globalThis.FormData;for(let[f,d]of Object.entries(t))if(Array.isArray(d))for(let l of d)Wr(n,f,l);else Wr(n,f,d);return Xe(n)};class Ho extends Mt{_tag="Stream";stream;contentType;contentLength;constructor(t,n,f){super();this.stream=t,this.contentType=n,this.contentLength=f}toJSON(){return{_id:"effect/HttpBody",_tag:"Stream",contentType:this.contentType,contentLength:this.contentLength}}}var Zt=(t,n,f)=>new Ho(t,n??"application/octet-stream",f),Gr=(t,n,f)=>{let d=Sr(t);return M(d)?r(d.value):o(Ge({module:"HttpBody",method:f,description:`Invalid ${n}: ${t}`}))},In=ce(function*(t,n,f){let d=f?.offset===void 0?gi:yield*Gr(f.offset,"offset",n),l=f?.bytesToRead===void 0?void 0:yield*Gr(f.bytesToRead,"bytesToRead",n),E=d>=t?BigInt("0"):t-d,y=l===void 0||l>E?E:l;if(y>BigInt(Number.MAX_SAFE_INTEGER))return yield*o(Ge({module:"HttpBody",method:n,description:`Content length exceeds Number.MAX_SAFE_INTEGER: ${y}`}));return Number(y)}),Co=(t,n)=>u(rt,(f)=>u(f.stat(t),(d)=>g(In(d.size,"file",n),(l)=>Zt(f.stream(t,n),n?.contentType,l))));var er="~effect/http/HttpClientError",te=(t)=>s(t,er);class q extends R("HttpClientError"){constructor(t){if("cause"in t.reason)super({...t,cause:t.reason.cause});else super(t)}[er]=er;get request(){return this.reason.request}get response(){return"response"in this.reason?this.reason.response:void 0}get message(){return this.reason.message}}var _t=(t)=>t.endsWith("Error")?t.slice(0,-5):t,Ft=(t,n,f)=>n?`${t}: ${n} (${f})`:`${t} error (${f})`,Nt=(t)=>`${t.method} ${Ht(t.url)}`,Lt=(t,n)=>({...n,request:{_id:"HttpClientRequest",method:t.request.method,url:Ht(t.request.url)},..."response"in t?{response:{_id:"HttpClientResponse",status:t.response.status}}:void 0});class Jt extends R("TransportError"){get methodAndUrl(){return Nt(this.request)}get message(){return Ft(_t(this._tag),this.description,this.methodAndUrl)}toJSON(){return Lt(this,super.toJSON())}}class Re extends R("EncodeError"){get methodAndUrl(){return Nt(this.request)}get message(){return Ft(_t(this._tag),this.description,this.methodAndUrl)}toJSON(){return Lt(this,super.toJSON())}}class or extends R("InvalidUrlError"){get methodAndUrl(){return Nt(this.request)}get message(){return Ft(_t(this._tag),this.description,this.methodAndUrl)}toJSON(){return Lt(this,super.toJSON())}}class Ct extends R("StatusCodeError"){get methodAndUrl(){return Nt(this.request)}get message(){let t=`${this.response.status} ${this.methodAndUrl}`;return Ft(_t(this._tag),this.description,t)}toJSON(){return Lt(this,super.toJSON())}}class Tt extends R("DecodeError"){get methodAndUrl(){return Nt(this.request)}get message(){let t=`${this.response.status} ${this.methodAndUrl}`;return Ft(_t(this._tag),this.description,t)}toJSON(){return Lt(this,super.toJSON())}}class pr extends R("EmptyBodyError"){get methodAndUrl(){return Nt(this.request)}get message(){let t=`${this.response.status} ${this.methodAndUrl}`;return Ft(_t(this._tag),this.description,t)}toJSON(){return Lt(this,super.toJSON())}}function fr(t){return t!=="GET"&&t!=="HEAD"&&t!=="OPTIONS"&&t!=="TRACE"}var Ro=[["GET","get"],["POST","post"],["PUT","put"],["DELETE","del"],["PATCH","patch"],["HEAD","head"],["OPTIONS","options"],["TRACE","trace"],["QUERY","query"]];var wo=(t)=>(n)=>n.pipeThrough(new CompressionStream(t)),On=(t)=>new ReadableStream({start(n){n.enqueue(t),n.close()}}),Uo=(t,n,f)=>{if(t._tag!=="Uint8Array"&&t._tag!=="Stream")return r(t);if(t.contentLength!==void 0&&t.contentLength<(f?.minSize??1024))return r(t);if(t._tag==="Uint8Array")return g(Ze(()=>new globalThis.Response(wo(n)(On(t.body))).arrayBuffer()),(d)=>Se(new Uint8Array(d),t.contentType));return r(Zt(bo({evaluate:()=>wo(n)(Bi(t.stream)),onError:c}),t.contentType))};var Po=(t,n)=>{if(n._tag==="Empty"||n._tag==="FormData")return St(St(t,"content-type"),"content-length");return t=n.contentType===void 0?St(t,"content-type"):Bt(t,"content-type",n.contentType),dr(t,n)},dr=(t,n)=>{let f=n._tag==="Empty"||n._tag==="FormData"?void 0:n.contentLength;return f===void 0?St(t,"content-length"):Bt(t,"content-length",f.toString())},Io=(t)=>{if(t===null||t===void 0||!/^\d+$/.test(t))return;let n=Number(t);return Number.isSafeInteger(n)?n:void 0};class Oe extends R("UrlError"){}var re=(t,n,f)=>Fe({try:()=>{let d=new URL(t,Fn());for(let l=0;l<n.params.length;l++){let[E,y]=n.params[l];if(y!==void 0)d.searchParams.append(E,zt(y))}if(f!==void 0)d.hash=f;return d},catch:(d)=>new Oe({cause:d})}),Fn=()=>{if("location"in globalThis&&globalThis.location!==void 0&&globalThis.location.origin!==void 0&&globalThis.location.pathname!==void 0){let t=location.origin+location.pathname;try{return new URL(t).href}catch{return}}return},Bo=(t,n)=>Fe({try:()=>new URL(t,n),catch:()=>new an(`Invalid URL: "${t}"${n!==void 0?` with base "${n}"`:""}`)});var gr="~effect/http/HttpClientRequest",Wt=(t)=>s(t,gr),Nn={[gr]:gr,...Z,toJSON(){return{_id:"HttpClientRequest",method:this.method,url:Ht(this.url),urlParams:this.urlParams,hash:this.hash,headers:we(this.headers),body:this.body.toJSON()}},pipe(){return v(this,arguments)}};function L(t,n,f,d,l,E){let y=Object.create(Nn);return y.method=t,y.url=n,y.urlParams=f,y.hash=d,y.headers=l,y.body=E,y}var Do=L("GET","",wr,i(),lo,kt),K=(t)=>(n,f)=>Er(Do,{method:t,url:n,...f??void 0}),as=K("GET"),Ln=K("QUERY"),Ys=K("POST"),vn=K("PATCH"),qn=K("PUT"),Jn=K("DELETE");var Wn=K("HEAD"),$n=K("OPTIONS"),jn=K("TRACE"),Er=e(2,(t,n)=>{let f=t;if(n.method)f=De(f,n.method);if(n.url)f=ko(f,n.url);if(n.headers)f=Xt(f,n.headers);if(n.urlParams)f=Fo(f,n.urlParams);if(n.hash)f=No(f,n.hash);if(n.body)f=z(f,n.body);if(n.accept)f=yr(f,n.accept);if(n.acceptJson)f=tr(f);return f}),De=e(2,(t,n)=>L(n,t.url,t.urlParams,t.hash,t.headers,t.body)),Gt=e(3,(t,n,f)=>L(t.method,t.url,t.urlParams,t.hash,Bt(t.headers,n,f),t.body)),Xt=e(2,(t,n)=>L(t.method,t.url,t.urlParams,t.hash,Si(t.headers,n),t.body)),Mo=e(2,(t,n)=>L(t.method,t.url,t.urlParams,t.hash,n(t.headers),t.body)),lt=e(2,(t,n)=>Mo(t,St(n))),zn=e(3,(t,n,f)=>Gt(t,"Authorization",`Basic ${et(`${uo(n)}:${uo(f)}`)}`)),Qs=e(2,(t,n)=>Gt(t,"Authorization",`Bearer ${uo(n)}`)),yr=e(2,(t,n)=>Gt(t,"Accept",n)),tr=yr("application/json"),Gn=e(2,(t,n)=>L(t.method,t.url,t.urlParams,t.hash,Bt(Bt(t.headers,"connection","Upgrade"),"upgrade",n),t.body)),ko=e(2,(t,n)=>{if(typeof n==="string")return L(t.method,n,t.urlParams,t.hash,t.headers,t.body);let f=new URL(n.toString()),d=We(f.searchParams),l=Ce(f.hash===""?void 0:f.hash.slice(1));return f.search="",f.hash="",L(t.method,f.toString(),d,l,t.headers,t.body)}),Vn=e(2,(t,n)=>{if(n==="")return t;return L(t.method,_o(n,t.url),t.urlParams,t.hash,t.headers,t.body)}),Qn=e(2,(t,n)=>{if(n==="")return t;return L(t.method,_o(t.url,n),t.urlParams,t.hash,t.headers,t.body)}),_o=(t,n)=>{let f=t.endsWith("/"),d=n.startsWith("/");return f&&d?t+n.slice(1):!f&&!d?t+"/"+n:t+n},Yn=e(2,(t,n)=>L(t.method,n(t.url),t.urlParams,t.hash,t.headers,t.body)),Zn=e(3,(t,n,f)=>L(t.method,t.url,ki(t.urlParams,n,f),t.hash,t.headers,t.body)),Fo=e(2,(t,n)=>L(t.method,t.url,Ci(t.urlParams,n),t.hash,t.headers,t.body)),Kn=e(3,(t,n,f)=>L(t.method,t.url,Ii(t.urlParams,n,f),t.hash,t.headers,t.body)),Xn=e(2,(t,n)=>L(t.method,t.url,Ai(t.urlParams,n),t.hash,t.headers,t.body)),No=e(2,(t,n)=>L(t.method,t.url,t.urlParams,a(n),t.headers,t.body)),ts=(t)=>L(t.method,t.url,t.urlParams,i(),t.headers,t.body),z=e(2,(t,n)=>L(t.method,t.url,t.urlParams,t.hash,Po(t.headers,n),n)),es=e((t)=>Wt(t[0]),(t,n,f)=>{if(t.headers["content-encoding"]!==void 0)return r(t);return g(Uo(t.body,n,f),(d)=>d===t.body?t:L(t.method,t.url,t.urlParams,t.hash,Bt(dr(t.headers,d),"content-encoding",n),d))}),rs=e((t)=>Wt(t[0]),(t,n,f)=>z(t,Se(n,f))),os=e((t)=>Wt(t[0]),(t,n,f)=>z(t,Yt(n,f))),ns=e(2,(t,n)=>g(Ke(n),(f)=>z(t,f))),Xs=e(2,(t,n)=>z(t,ho(n))),ss=(t,n)=>{let f=go(t,n);return e(2,(d,l)=>g(f(l),(E)=>z(d,E)))},is=e(2,(t,n)=>z(t,Eo(We(n)))),ps=e(2,(t,n)=>z(t,Xe(n))),fs=e(2,(t,n)=>z(t,xo(n))),us=e((t)=>Wt(t[0]),(t,n,f)=>z(t,Zt(n,f?.contentType,f?.contentLength))),ds=e((t)=>Wt(t[0]),(t,n,f)=>g(Co(n,f),(d)=>z(t,d)));function oe(t){let n=re(t.url,t.urlParams,D(t.hash));if(O(n))return a(n.success);return i()}var ls=(t)=>{let n=t.method.toUpperCase();return Er(L(n,"",wr,i(),lo,kt),{url:new URL(t.url),headers:t.headers,body:hs(t,n)})},hs=(t,n)=>{if(!fr(n)||t.body===null)return kt;return ao(t.body,{contentType:t.headers.get("content-type")??void 0,contentLength:Io(t.headers.get("content-length"))})},Lo=(t,n)=>{let f=re(t.url,t.urlParams,D(t.hash));if(S(f))return h(f.failure);let d={method:t.method,headers:t.headers};if(n?.signal)d.signal=n.signal;if(fr(t.method))switch(t.body._tag){case"Empty":break;case"Raw":{if(d.body=t.body.body,gs(t.body.body))d.duplex="half";break}case"Uint8Array":{d.body=t.body.body;break}case"FormData":{d.body=t.body.formData;break}case"Stream":{d.body=vo(t.body.stream,n?.context??ie()),d.duplex="half";break}}return Fe({try:()=>new Request(f.success,d),catch:(l)=>new Oe({cause:l})})},gs=(t)=>typeof ReadableStream<"u"&&t instanceof ReadableStream,ys=(t,n)=>Un((f)=>dn(Lo(t,{context:f,signal:n?.signal})));var Pt="~effect/http/HttpIncomingMessage";var Be=(t,n)=>{let f=qt(Kt(t)),d=n?.reviver===void 0?void 0:qt(se(Kt(t),n));return(l)=>d===void 0?u(l.json,(E)=>f(E,n)):u(l.text,(E)=>E===""?u(l.json,(y)=>f(y,n)):d(E,n))},qo=(t,n)=>{let f=$s.pipe(m(t),qt);return(d)=>u(d.urlParamsBody,(l)=>f(l,n))},Jo=(t,n)=>{let f=Bn(t);return(d)=>f(d.headers,n)};var Wo=(t,n)=>({...n,headers:we(t.headers),remoteAddress:t.remoteAddress});var Me="~effect/http/HttpClientResponse/WebSource",_e=(t)=>t["~effect/http/HttpClientResponse/WebSource"]?.();var ht="~effect/http/HttpClientResponse",Hr=(t,n)=>new jo(t,n),xs=(t)=>nr(_e(t)),Ss=(t,n)=>{let f=qt(Kt(t),n),d=Be(F,n);return(l)=>u(d(l),(E)=>f({status:l.status,headers:l.headers,body:E}))},Hs=(t,n)=>{let f=qt(t,n);return(d)=>f({status:d.status,headers:d.headers})},Rs=(t)=>En(g(t,(n)=>n.stream)),Us=e(2,(t,n)=>{let f=t.status;if(n[f])return n[f](t);else if(f>=200&&f<300&&n["2xx"])return n["2xx"](t);else if(f>=300&&f<400&&n["3xx"])return n["3xx"](t);else if(f>=400&&f<500&&n["4xx"])return n["4xx"](t);else if(f>=500&&f<600&&n["5xx"])return n["5xx"](t);return n.orElse(t)}),Cr=e(2,(t,n)=>A(()=>n(t.status)?r(t):o(new q({reason:new Ct({response:t,request:t.request,description:"invalid status code"})})))),en=(t)=>t.status>=200&&t.status<300?r(t):o(new q({reason:new Ct({response:t,request:t.request,description:"non 2xx status code"})}));class jo extends ms{[Pt];[ht];request;source;constructor(t,n){super();this.request=t,this.source=n,this[Pt]=Pt,this[ht]=ht}toJSON(){return Wo(this,{_id:"HttpClientResponse",request:this.request.toJSON(),status:this.status})}get status(){return this.source.status}get url(){if(this.source.url)return this.source.url.split("#")[0];let t=oe(this.request);if(k(t))return"";return t.value.hash="",t.value.href}get headers(){return xn(this.source.headers)}cachedCookies;get cookies(){if(this.cachedCookies)return this.cachedCookies;return this.cachedCookies=co(this.source.headers.getSetCookie?.()??[])}get remoteAddress(){return i()}[Me](){return this.source}get stream(){return this.source.body?bo({evaluate:()=>this.source.body,onError:(t)=>new q({reason:new Tt({request:this.request,response:this,cause:t})})}):Or(new q({reason:new pr({request:this.request,response:this,description:"can not create stream from empty body"})}))}get json(){return u(this.text,(t)=>H({try:()=>t===""?null:JSON.parse(t),catch:(n)=>new q({reason:new Tt({request:this.request,response:this,cause:n})})}))}textBody;get text(){return this.textBody??=g(this.arrayBuffer,(t)=>new TextDecoder().decode(t))}get urlParamsBody(){return u(this.arrayBuffer,(t)=>H({try:()=>We(wi(t)),catch:(n)=>new q({reason:new Tt({request:this.request,response:this,cause:n})})}))}formDataBody;get formData(){return this.formDataBody??=fe({try:()=>this.source.formData(),catch:(t)=>new q({reason:new Tt({request:this.request,response:this,cause:t})})}).pipe(no,jt)}arrayBufferBody;get arrayBuffer(){if(this.arrayBufferBody)return this.arrayBufferBody;return this.arrayBufferBody=fe({try:()=>this.source.arrayBuffer(),catch:(t)=>new q({reason:new Tt({request:this.request,response:this,cause:t})})}).pipe(no,jt),this.arrayBufferBody}get upgrade(){return o(new q({reason:new Ct({request:this.request,response:this,description:"fetch cannot hand over the connection of an HTTP upgrade"})}))}pipe(){return v(this,arguments)}}var zo=(t)=>bi({b3:`${t.traceId}-${t.spanId}-${t.sampled?"1":"0"}${U(t.parent,{onNone:()=>"",onSome:(n)=>`-${n.spanId}`})}`,traceparent:`00-${t.traceId.padStart(32,"0")}-${t.spanId}-${t.sampled?"01":"00"}`});var Is={"http:":80,"https:":443,"ws:":80,"wss:":443},Vo=(t,n,f)=>{let d=Ht(n.search,f).slice(1);if(t.attribute("url.full",Ht(n.href,f)),t.attribute("url.path",n.pathname),d!=="")t.attribute("url.query",d);if(t.attribute("url.scheme",n.protocol.slice(0,-1)),n.hostname!==""){t.attribute("server.address",n.hostname.startsWith("[")?n.hostname.slice(1,-1):n.hostname);let l=n.port===""?Is[n.protocol]:Number(n.port);if(l!==void 0)t.attribute("server.port",l)}},Qo=(t,n)=>{let f=t.params.filter(([,d])=>typeof d!=="string").map(([d])=>d);return f.length===0?n:[...n,...new URLSearchParams(f.map((d)=>[d,""])).keys()]},Rr=(t,n,f,d,l)=>{for(let E in f){if(!d(E,n))continue;t.attribute(`http.${n}.header.${E}`,po(E,l)?"<redacted>":f[E])}};var Ur="~effect/http/HttpClient",Zo=(t)=>s(t,Ur),Ee=P("effect/HttpClient"),ct=(t)=>(...n)=>u(Ee,(f)=>f[t](...n)),As=ct("execute"),Ds=ct("get"),Ms=ct("query"),Fs=ct("head"),Ls=ct("post"),qs=ct("patch"),Js=ct("put"),Ws=ct("del"),js=ct("options"),ue=e(2,(t,n)=>nt(u((f)=>n(t.postprocess(r(f)),f)),t.preprocess)),Ae=e(2,(t,n)=>nt((f)=>n(t.postprocess(f)),t.preprocess)),zs=e(2,(t,n)=>Ae(t,He(n)));var Gs=e(3,(t,n,f)=>Ae(t,(d)=>ur(d,n,f))),Vs=e(2,(t,n)=>Ae(t,vs(n))),Zs=e(3,(t,n,f)=>Ae(t,ws(n,f))),Ks=e(3,(t,n,f)=>Ae(t,ks(n,f))),ta=e(2,(t,n)=>Ae(t,u(Cr(n)))),ei=Ae(u(en)),nt=(t,n)=>{let f=Object.create(ea);return f.preprocess=n,f.postprocess=t,f.execute=function(d){return t(n(d))},f},ea={[Ur]:Ur,pipe(){return v(this,arguments)},...Z,toJSON(){return{_id:"effect/HttpClient"}},...Object.fromEntries(Ro.map(([t,n])=>[n,function(f,d){return this.execute(K(t)(f,d))}]))},Dr=(t)=>nt((n)=>u(n,(f)=>cr((d)=>{let l=Le.get(f),E=l??new AbortController,y=re(f.url,f.urlParams,D(f.hash));if(S(y))return o(new q({reason:new or({request:f,cause:y.failure})}));let b=y.success;if(d.getRef(Rn)||d.getRef(cn)(f)){let C=t(f,b,E.signal,d);if(l)return g(C,(N)=>Tr(N,E,!0));return bt((N)=>Ut(N(C),{onSuccess(x){return r(Tr(x,E,!1))},onFailure(x){if(Vr(x))E.abort();return Ye(x)}}))}return _s(d.getRef(hn)(f),{kind:"client"},(C)=>{C.attribute("http.request.method",f.method);let N=d.getRef(Ns);Vo(C,b,Qo(f.urlParams,d.getRef(mo)));let x=d.getRef(pn);return Rr(C,"request",f.headers,x,N),f=d.getRef(fn)?Xt(f,zo(C)):f,bt((G)=>G(t(f,b,E.signal,d)).pipe(Ps(C,{captureStackTrace:!1}),Ut({onSuccess:(J)=>{if(C.attribute("http.response.status_code",J.status),Rr(C,"response",J.headers,x,N),J.status>=400&&J.status<600)C.attribute("error.type",String(J.status)),ra(d,C,f,J);return r(Tr(J,E,l!==void 0))},onFailure(J){if(!l&&Vr(J))E.abort();return Ye(J)}})))})})),r),ra=(t,n,f,d)=>{let l=ke();X(0);let E;try{E=gt(new q({reason:new Ct({request:f,response:d})}))}finally{X(l)}n.end(t.getRef(li)?t.getRef(sr).currentTimeNanosUnsafe():BigInt(0),E)},ti=e(2,(t,n)=>nt(t.postprocess,(f)=>g(t.preprocess(f),n))),oa=e(2,(t,n)=>nt(t.postprocess,(f)=>u(t.preprocess(f),n))),na=e(2,(t,n)=>nt(t.postprocess,(f)=>t.preprocess(n(f)))),sa=e(2,(t,n)=>nt(t.postprocess,(f)=>u(n(f),t.preprocess))),aa=e(2,(t,n)=>Ae(t,eo(n))),ia=e(2,(t,n)=>{let f=ir(n),d=f?"errors-and-responses":n.retryOn??"errors-and-responses",l=Ta(f?n:n.schedule??ar),E=f?void 0:n.times;return Ae(t,Kr(d==="errors-only"?c:Os({schedule:l,times:E,while:kr}),d==="response-only"?c:eo({while:f||n.while===void 0?Ir:ci(Ir,n.while),schedule:l,times:E})))}),ca=e(2,(t,n)=>{let f=B(n),d=`timed out after ${Pn(f)}`;return ue(t,(l,E)=>Es(l,{duration:f,orElse:()=>o(new q({reason:new Jt({request:E,cause:new bs(`Operation ${d}`),description:d})}))}))}),pa=e(2,(t,n)=>{let f={initial:!0,limit:n.limit,window:mt(B(n.window),pe(1))},d=new Map,l=n.key,E=typeof l==="function"?l:V(l),y=n.tokens,b=typeof y==="function"?y:V(y??1),Y=!n.disableAdaptiveLearning,C=la(n.responseHeaders),N=(Q)=>{let W=d.get(Q);if(W!==void 0)return W;return d.set(Q,f),f},x=new Map,G=(Q)=>{let W=x.get(Q);if(W===void 0)W={sent:0,observed:0,remaining:0,resetAt:0},x.set(Q,W);return W},J=n.disableResponseInspection?void 0:(Q,W,at,It,Je)=>{let ft=N(W),st=ha(ft,Q,at,It,C);if(st.limit!==ft.limit||!rr(st.window,ft.window))d.set(W,st);let it=tn(at,C),tt=G(W);if(it===void 0||Je<=tt.observed)return;let Vt=Pr(Q,at,C);if(tt.observed=Je,tt.remaining=it,Vt!==void 0)tt.resetAt=Q.currentTimeMillisUnsafe()+ye(Vt)};return ue(t,function Q(W,at,It=0){let ft=xr().getRef(sr),st=E(at),it=Math.max(b(at),1),tt=G(st),Vt=ft.currentTimeMillisUnsafe();if(tt.resetAt>Vt&&tt.remaining-(tt.sent-tt.observed)<it)return u(yt(tt.resetAt-Vt),()=>Q(W,at,It));let Hn=tt.sent+=it,de=N(st),_r=n.times===void 0||It<n.times;function Fr(ot){return ot?u(yt(ot),()=>Q(W,at,It+1)):Q(W,at,It+1)}let Nr=(ot,At)=>{if(J?.(ft,st,ot.headers,it,Hn),n.disableResponseInspection||ot.status!==429)return r(void 0);let Qt=nn(ft.currentTimeMillisUnsafe(),ne(ot.headers,...C.retryAfter));if(Qt===void 0)return r(void 0);let j=Pr(ft,ot.headers,C)??Qt;if(At===void 0)return r(j);return Qe(n.limiter.adaptiveFeedback({key:st,epoch:At.epoch,tokens:it,status:ot.status,retryAfter:j}),j)};return u(n.limiter.consume({algorithm:n.algorithm,onExceeded:"delay",key:st,limit:de.limit,window:de.window,tokens:it}),({delay:ot})=>{let At=()=>{let Qt=(j)=>{let Lr=Dn(W,{onSuccess(dt){return u(Nr(dt,j),($e)=>{if(dt.status!==429||!_r)return r(dt);return Fr($e)})},onFailure(dt){if(wa(dt))return u(Nr(dt.reason.response,j),($e)=>_r?Fr($e):o(dt));return o(dt)}});return j===void 0||on(j.delay)?Lr:to(Lr,j.delay)};if(!Y)return Qt(void 0);return u(n.limiter.adaptiveConsume({key:st,tokens:it,fallbackLimit:de.limit,fallbackWindow:de.window}),(j)=>{if(!on(j.delay)&&j.phase==="cooldown")return u(yt(j.delay),At);return Qt(j)})};return on(ot)?At():u(yt(ot),At)})})}),fa=e(2,(t,n)=>{let f=n.key,d=typeof f==="function"?f:f===void 0?ua:V(f),l=n.classify??Ko;return ue(t,(E,y)=>n.breaker.execute(E,{key:d(y),classify:l}))}),ua=(t)=>U(oe(t),{onNone:()=>t.url,onSome:(n)=>n.origin}),Ko=(t)=>hr((n)=>r(da(t,n.currentTimeMillisUnsafe()))),da=(t,n)=>{if(ae(t)){let E=Xo(t.value.status);return E==="Failure"?Yo(Ar(t.value,n)):{_tag:E}}let f=!1,d=!1,l;for(let E of t.cause.reasons){if(!sn(E))continue;let y=ma(E.error);if(y==="Failure"){f=!0;let b=Ar(E.error,n);if(b!==void 0)l=l===void 0?b:mt(l,b)}else if(y==="Success")d=!0}return f?Yo(l):{_tag:d?"Success":"Ignored"}},Yo=(t)=>({_tag:"Failure",retryAfter:t}),ma=(t)=>{if(Zr(t))return"Failure";if(!te(t))return"Ignored";switch(t.reason._tag){case"TransportError":return"Failure";case"StatusCodeError":return Xo(t.reason.response.status);default:return"Ignored"}},Xo=(t)=>t===429?"Ignored":t===408||t===500||t===502||t===503||t===504?"Failure":"Success",la=(t)=>({limit:t?.limit===void 0?["ratelimit-limit","x-ratelimit-limit"]:[t.limit.toLowerCase()],remaining:t?.remaining===void 0?["ratelimit-remaining","x-ratelimit-remaining"]:[t.remaining.toLowerCase()],reset:t?.reset===void 0?["ratelimit-reset","x-ratelimit-reset"]:[t.reset.toLowerCase()],resetAfter:t?.resetAfter===void 0?["ratelimit-reset-after","x-ratelimit-reset-after"]:[t.resetAfter.toLowerCase()],retryAfter:t?.retryAfter===void 0?["retry-after"]:[t.retryAfter.toLowerCase()]}),ha=(t,n,f,d,l)=>{let E=ga(t,f,d,l)??t.limit,y=Pr(n,f,l)??t.window;if(E===t.limit&&rr(y,t.window))return t;return{limit:E,window:y,initial:!1}},ga=(t,n,f,d)=>{let l=ne(n,...d.limit),E=ve(l);if(E!==void 0&&E>0)return E;let y=tn(n,d);if(y===void 0)return;return t.initial?y+f:Math.max(y+f,t.limit)},tn=(t,n)=>{let f=ne(t,...n.remaining),d=ve(f);return d!==void 0&&d>=0?d:void 0},Pr=(t,n,f)=>{let d=Ea(ne(n,...f.resetAfter));if(d!==void 0)return d;return ya(t,ne(n,...f.reset))},nn=(t,n)=>{if(n===void 0)return;let f=fo(n);return O(f)?mt(Ei(f.success,t),pe(1)):void 0},Ea=(t)=>{let n=ve(t);if(n===void 0||n<=0)return;return mt(xe(n),pe(1))},ya=(t,n)=>{let f=ve(n);if(f===void 0||f<=0)return;let d=t.currentTimeMillisUnsafe();if(f>1000000000000)return pe(Math.max(f-d,1));if(f>1e9)return pe(Math.max(f*1000-d,1));return mt(xe(f),pe(1))},ve=(t)=>{if(t===void 0)return;let n=/-?\d+(?:\.\d+)?/.exec(t);if(n===null)return;let f=Number(n[0]);return Number.isFinite(f)?f:void 0},ne=(t,...n)=>{for(let f=0;f<n.length;f++){let d=t[n[f]];if(d!==void 0)return d}return},xa=e(2,(t,n)=>Ae(t,Ue(n))),Sa=e(2,(t,n)=>Ae(t,lr(n))),ba=e(2,(t,n)=>nt(t.postprocess,(f)=>Ue(t.preprocess(f),n))),Ha=e(2,(t,n)=>{let f=()=>xr().getRef(sr).currentTimeMillisUnsafe(),d=(l)=>g(vr(n),(E)=>{let y=yi(E,l.url,f());if(y===void 0)return l;let b=Gt(l,"cookie",y),Y=Le.get(l);if(Y!==void 0)Le.set(b,Y);return b});return nt((l)=>Ue(t.postprocess(u(l,d)),(E)=>qr(n,xi(E.url,E.cookies,f()))),t.preprocess)}),ni=(t)=>ue(t,(n,f)=>{let d=new AbortController;return Le.set(f,d),mn(Ts(()=>T(()=>d.abort())),n)}),Ca=e((t)=>Zo(t[0]),(t,n)=>nt((f)=>{let d=(l,E)=>A(()=>{let y;return u(t.postprocess(g(l,(b)=>(y=b,b))),(b)=>{if(b.status<300||b.status>=400||!b.headers.location||E>=(n??10))return r(b);let Y=Bo(b.headers.location,b.request.url);if(S(Y))return r(b);let C=Y.success,N=y??b.request,x=N;if((b.status===301||b.status===302)&&N.method==="POST"||b.status===303&&N.method!=="GET"&&N.method!=="HEAD")x=De(x,"GET"),x=z(x,kt),x=lt(x,"content-encoding"),x=lt(x,"content-language"),x=lt(x,"content-location");if(C.origin!==new URL(b.request.url).origin)x=lt(x,"authorization"),x=lt(x,"proxy-authorization"),x=lt(x,"cookie");let G=C.hash===""?i():a(C.hash.slice(1));return C.hash="",x=L(x.method,C.href,wr,G,x.headers,x.body),mn(T(()=>gn.get(b)?.abort()),d(r(x),E+1))})});return d(f,0)},t.preprocess)),cn=I("effect/http/HttpClient/TracerDisabledWhen",{defaultValue:()=>Ot}),pn=I("effect/http/HttpClient/TracerHeaderFilter",{defaultValue:()=>Ot}),fn=I("effect/http/HttpClient/TracerPropagationEnabled",{defaultValue:Te}),hn=I("effect/http/HttpClient/SpanNameGenerator",{defaultValue:()=>(t)=>t.method}),Mr=(t)=>ee(Ee)(Un((n)=>g(t,(f)=>Ae(f,Cs((d)=>Rt(n,d)))))),Ne=(()=>{if("FinalizationRegistry"in globalThis&&globalThis.FinalizationRegistry){let n=new FinalizationRegistry((f)=>{try{f.abort()}catch{}});return{register(f,d){n.register(f,d,f)},unregister(f){n.unregister(f)}}}let t=new WeakMap;return{register(n,f){t.set(n,setTimeout(()=>f.abort(),5000))},unregister(n){let f=t.get(n);if(f===void 0)return;clearTimeout(f),t.delete(n)}}})(),Le=new WeakMap,gn=new WeakMap,Tr=(t,n,f)=>{if(!f)Ne.register(t,n),t=new yn(t,n);return gn.set(t,n),t};class yn{original;controller;constructor(t,n){this.original=t,this.controller=n}[ht]=ht;[Pt]=Pt;applyInterrupt(t){return A(()=>(Ne.unregister(this.original),oo(t,()=>T(()=>{this.controller.abort()}))))}get request(){return this.original.request}get url(){return this.original.url}get status(){return this.original.status}get headers(){return this.original.headers}get cookies(){return this.original.cookies}get remoteAddress(){return this.original.remoteAddress}get formData(){return this.applyInterrupt(this.original.formData)}get text(){return this.applyInterrupt(this.original.text)}get json(){return this.applyInterrupt(this.original.json)}get urlParamsBody(){return this.applyInterrupt(this.original.urlParamsBody)}get arrayBuffer(){return this.applyInterrupt(this.original.arrayBuffer)}get upgrade(){return this.applyInterrupt(this.original.upgrade)}[Me](){let t=_e(this.original);if(t!==void 0)Ne.unregister(this.original);return t}get stream(){return Li(()=>(Ne.unregister(this.original),So(this.original.stream,T(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[_](){return this.original[_]()}pipe(){return v(this,arguments)}}var Ir=(t)=>Zr(t)||Ra(t),Ra=(t)=>te(t)&&(t.reason._tag==="TransportError"||t.reason._tag==="StatusCodeError"&&kr(t.reason.response)),Ar=(t,n)=>{let f=te(t)?t.response:s(t,ht)?t:void 0;return nn(n,f?.headers["retry-after"])},Ta=(t)=>un(g(ln(t),(n)=>(f,d)=>{let l=Ar(d,f);if(l===void 0)return n(f,d);return g(n(f,d),([E,y])=>[E,mt(y,l)])})),wa=(t)=>te(t)&&t.reason._tag==="StatusCodeError"&&t.reason.response.status===429,kr=(t)=>t.status===408||t.status===429||t.status===500||t.status===502||t.status===503||t.status===504;var pt=I("effect/http/FetchHttpClient/Fetch",{defaultValue:()=>globalThis.fetch}),bn=I("effect/http/FetchHttpClient/StreamBodyFallback",{defaultValue:()=>"error"});class Br extends P()("effect/http/FetchHttpClient/RequestInit"){}var Sn,Ua=()=>{try{let t=!1,n=new ReadableStream,f=new Request("https://example.com",{method:"POST",body:n,get duplex(){return t=!0,"half"}});return(t||f.body===n)&&!f.headers.has("Content-Type")}catch{return!1}},Pa=Dr((t,n,f,d)=>{if(t.headers.upgrade!==void 0)return o(new q({reason:new Jt({request:t,description:"fetch cannot send an HTTP upgrade request"})}));let l=d.getRef(pt),E=rn(d.context,Br)??{},y=E.headers?vi(xn(E.headers),t.headers):t.headers;if(y["content-length"])y=St(y,"content-length");let b,Y=T(()=>b?.abort()),C=(N)=>g(fe({try:()=>l(n,{...E,method:t.method,headers:y,body:N,duplex:typeof ReadableStream<"u"&&N instanceof ReadableStream?"half":void 0,signal:b?AbortSignal.any([f,b.signal]):f}),catch:(x)=>new q({reason:new Jt({request:t,cause:x})})}),(x)=>{let G=Hr(t,x);if(!b)return G;if(x.body===null)b.abort();return Object.create(G,{...Object.fromEntries(["arrayBuffer","text","json","formData","urlParamsBody"].map((J)=>[J,{get:()=>$t(G[J],Y)}])),stream:{get:()=>So(G.stream,Y)}})}).pipe(ut(()=>Y));switch(t.body._tag){case"Raw":case"Uint8Array":return C(t.body.body);case"FormData":return C(t.body.formData);case"Stream":{if(Sn??=Ua(),Sn){b=new AbortController;let N=AbortSignal.any([f,b.signal]),x=xt((G)=>{let J=()=>G(ro);if(N.aborted){J();return}return N.addEventListener("abort",J,{once:!0}),T(()=>N.removeEventListener("abort",J))});return u(zi($i(t.body.stream,x)),C)}if(d.getRef(bn)==="error")return o(new q({reason:new Re({request:t,description:"Streaming request bodies are not supported in this runtime"})}));return ji(t.body.stream).pipe(qe((N)=>new q({reason:new Re({request:t,cause:N})})),u(C))}}return C(void 0)}),zr=Mr(r(Pa));export{as,Ys,Xt,Qs,tr,Xs,$r,Be,en,jr,Ee,Ae,ei,ti,ni,cs,pt,Br,zr,ri};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{z,Vt}from"./chunk-gtf5exm1.js";function Fr(t){return Object.entries(t).toSorted(([e],[o])=>i(e)-i(o)).flatMap(([e,o])=>Object.entries(o.models).flatMap(([n,r])=>s(r)?[{provider:e,providerName:o.name,id:n,entry:r}]:[]))}function Do(t,...e){let o=(n)=>t.filter((r)=>r.id.toLowerCase().includes("claude")&&r.id.toLowerCase().includes(n)).toSorted((r,a)=>i(r.provider)-i(a.provider)||d(a).localeCompare(d(r)))[0];return e.map(o).find((n)=>n!==void 0)??t[0]}function Ki(t){return t.flatMap((e)=>Object.values(z(e.entry.api))).flatMap((e)=>Vt(z(e).base_url)??[]).map((e)=>e.match(/^(https?:\/\/.+?)\/(?:go\/)?(?:anthropic\/v1|openai\/v1|google\/v1beta|v1)\/?$/)?.[1]??e.match(/^(https?:\/\/.+?)\/custom\/[^/]+(?:\/.*)?$/)?.[1]).find((e)=>e!==void 0)}function s(t){let e=z(z(t.capabilities).tools).supported,o=z(t.modalities).output;return(t.type??"chat")==="chat"&&e!==!1&&(!Array.isArray(o)||o.includes("text")&&!o.includes("audio"))}function d(t){return Vt(t.entry.release_date)??""}function i(t){return t==="opencode"?0:t==="opencode-go"?1:2}
|
|
2
|
+
export{Fr,Do,Ki};
|
package/index.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{st}from"./chunk-bgqw45qt.js";import{spawn as U}from"node:child_process";import _ from"node:path";import{parseArgs as z}from"node:util";var E=z({allowPositionals:!0,strict:!1,options:{harness:{type:"string"},server:{type:"string"},json:{type:"boolean"},quiet:{type:"boolean"},remove:{type:"boolean"}}}),y=E.positionals[0],g=E.values,C=D("harness")??process.env.OPENCODE_CONSOLE_HARNESS,P="Not signed in. Run `npx @opencode/console login` or set OPENCODE_API_KEY.",R=["claude-code","pi"],j=["claude-code"],F={check:q,hook:J,login:V,logout:ee,"mcp-headers":X,setup:G,status:te,sync:oe,token:ne},x,H=y?F[y]:void 0;if(!H)process.stdout.write(ie()),process.exit(y&&!["help","--help","-h"].includes(y)?1:0);process.exitCode=await H().catch(async(t)=>{if(y==="hook")return I(`opencode-console couldn't check this: ${w(t)}`);if(process.stderr.write(`${w(t)}
|
|
3
|
+
`),y!=="check")return 1;return L(`opencode-console couldn't check this call: ${w(t)}`)});async function q(){let{Option:t,Schema:e}=await import("./chunk-1c689590.js"),o=e.decodeUnknownOption(e.fromJsonString(e.Struct({action:e.NonEmptyString,resources:e.NonEmptyArray(e.String),directory:e.optional(e.String),path:e.optional(e.String),shell:e.optional(e.String)})))(await Y());if(t.isNone(o))return process.stderr.write(`Expected JSON on stdin: {"action": "...", "resources": ["...", ...]}
|
|
4
|
+
`),L("opencode-console couldn't read this tool call, so it was blocked");let[i]=await K([o.value]);return process.stdout.write(`${JSON.stringify(i)}
|
|
5
|
+
`),i?.effect==="deny"?2:0}async function J(){let t=E.positionals[1];if(!t||!j.includes(t))return process.stderr.write(`Usage: opencode-console hook <${j.join("|")}>
|
|
6
|
+
`),2;let{Option:e}=await import("./chunk-1c689590.js"),{ClaudeCodeHook:o}=await import("./chunk-hf4hqs7y.js"),i=await Y();x=o.eventName(i);let r=o.decode(i);if(e.isNone(r))return I("opencode-console couldn't read this hook's input, so it was blocked");if(r.value.hook_event_name==="SessionStart")return B();let s=o.checks(r.value);if(s.length===0)return 0;let c=(await K(s)).find((n)=>n.effect==="deny");return c?.effect==="deny"?I(c.message):0}async function B(){let{ConsoleStore:t}=await import("./chunk-a85j5cz4.js"),{ConsoleCredentials:e}=await import("./chunk-vx37gkw9.js"),{WorkspaceSync:o}=await import("./chunk-rea503jg.js"),i=t.make(),r=e.read(i);if(!r)return 0;await A({always:!0,force:!0});let s=o.current(i,e.owner(r))?.status;if(s)process.stdout.write(`${JSON.stringify({systemMessage:`${s.message}${s.url?`: ${s.url}`:""}`})}
|
|
7
|
+
`);return 0}async function K(t){let{Effect:e}=await import("./chunk-1c689590.js"),{ConsoleStore:o}=await import("./chunk-a85j5cz4.js"),{ConsoleCredentials:i}=await import("./chunk-vx37gkw9.js"),{WorkspaceSnapshot:r}=await import("./chunk-q3519h2y.js"),{PolicyEvaluator:s}=await import("./chunk-wb6qf86j.js"),c=o.make(),n=i.read(c),a=n&&i.owner(n),d=n?r.read(c):void 0,p=a&&d?.owner!==a?await(async()=>(await A({always:!0}),se(()=>{let u=r.read(c);return u?.owner===a?u:void 0},3000)))():d&&r.stale(d,Date.now())?(await A(),d):d,l=r.workspace(n,p);return e.runPromise(e.forEach(t,(u)=>s.check(l,u)))}async function V(){if(!await W())return 1;if(process.env.OPENCODE_API_KEY)process.stderr.write(`OPENCODE_API_KEY is set, so opencode-console keeps using that key until it's unset
|
|
8
|
+
`);return 0}async function W(){let{Effect:t}=await import("./chunk-1c689590.js"),{openUrl:e}=await import("./chunk-aesb1szb.js"),{ConsoleClient:o}=await import("./chunk-4v6awhyw.js"),{ConsoleStore:i}=await import("./chunk-a85j5cz4.js"),{ConsoleCredentials:r}=await import("./chunk-vx37gkw9.js"),{WorkspaceSync:s}=await import("./chunk-rea503jg.js"),c=D("server")??process.env.OPENCODE_CONSOLE_SERVER??o.defaultServer,n=o.normalizeServer(c);if(!n){process.stderr.write(`Not a Console URL: ${c}
|
|
9
|
+
`);return}let a=i.make(),d=await f(r.login(a,{server:n,prompt:(l)=>t.promise(async()=>{if(process.stderr.write(`Open ${l.url} and confirm the code ${l.code}
|
|
10
|
+
`),process.stdout.isTTY)await e(l.url).catch(()=>{return})})})),p=await f(s.sync(a,{force:!0}));if(process.stdout.write(`Signed in to ${d.orgName??"OpenCode Console"}${d.email?` as ${d.email}`:""}
|
|
11
|
+
`),p.error)process.stderr.write(`Couldn't fetch the workspace config: ${w(p.error)}. Run the command again to retry.
|
|
12
|
+
`);return d}async function G(){let t=E.positionals[1];if(!t||!R.includes(t))return process.stderr.write(`Usage: opencode-console setup <${R.join("|")}> [--remove]
|
|
13
|
+
`),1;let e=t==="pi",o=e?"Pi":"Claude Code",{ConsoleStore:i}=await import("./chunk-a85j5cz4.js"),{ConsoleCredentials:r}=await import("./chunk-vx37gkw9.js"),{CliInstall:s}=await import("./chunk-9pcmbxq5.js"),{WorkspaceSync:c}=await import("./chunk-rea503jg.js"),n=i.make();if(g.remove===!0){let{Effect:O}=await import("./chunk-1c689590.js"),{ClaudeCode:v}=await import("./chunk-r2y8x1nz.js"),{Pi:S}=await import("./chunk-0krh2hdf.js"),N=await O.runPromise(i.locked(n,O.sync(()=>{let m=e?S.remove(n):v.remove(n);if(![v.manifestFile(n),S.manifestFile(n)].some((M)=>i.read(M)!==void 0))s.uninstall(n);return m})));return process.stdout.write(N?`Removed OpenCode Console from ${o} and restored its settings. You're still signed in; \`npx @opencode/console logout\` signs out.
|
|
14
|
+
`:`${o} wasn't set up with OpenCode Console
|
|
15
|
+
`),0}let{ConsoleClient:a}=await import("./chunk-4v6awhyw.js"),d=await re(e?"pi":"claude");if(d)C=e?`pi/${d}`:`claude-cli/${d}`;let p=r.read(n),l=D("server");if(!p||l!==void 0&&p.server!==a.normalizeServer(l)){if(!await W())return 1}if(process.env.OPENCODE_API_KEY)process.stderr.write(`OPENCODE_API_KEY is set, so setup used that key, and ${o} will use it instead of your sign-in wherever it's set.
|
|
16
|
+
`);let u=await f(c.sync(n,{force:!0}));if(!u.snapshot?.config)return process.stderr.write(`Couldn't fetch the workspace config${u.error?`: ${w(u.error)}`:""}. Run setup again.
|
|
17
|
+
`),1;if(e&&b())return process.stderr.write("Set up Pi with the npm package: `npx @opencode/console setup pi`\n"),1;let k=s.install(n,{execPath:process.execPath,entry:b()?void 0:process.argv[1],path:process.env.PATH});return e?Q(n,k,u.snapshot,d):Z(n,k,u.snapshot,d)}async function Z(t,e,o,i){let{ClaudeCode:r}=await import("./chunk-r2y8x1nz.js"),{WorkspaceSnapshot:s}=await import("./chunk-q3519h2y.js"),c=s.policies(o),n=await f(r.refresh(t,{paths:r.paths(),command:e,harness:i?`claude-cli/${i}`:void 0}));if(!n)return process.stderr.write(`Couldn't read the workspace config. Run setup again.
|
|
18
|
+
`),1;let d=[`Claude Code now uses ${o.organization??"your workspace"} through OpenCode Console.`,"",...n.models?[` Models ${h(n.models.options.length,"model","models")} in /model; opus is ${n.models.tiers.opus}, sonnet ${n.models.tiers.sonnet}, haiku ${n.models.tiers.haiku}`]:[" Models none from the workspace, so Claude Code keeps its own sign-in"],` Policies ${h(c?.length??0,"rule","rules")}, checked before every tool call`,...n.servers.length>0?[` MCP ${n.servers.join(", ")}`]:[],...T(n.instructions,n.skills.map((l)=>`/${l}`))];if(process.stdout.write(`${d.join(`
|
|
19
|
+
`)}
|
|
20
|
+
`),n.skipped.length>0)process.stderr.write(`
|
|
21
|
+
Kept your own ${n.skipped.join(", ")}, so the workspace's of the same name weren't added.
|
|
22
|
+
`);if(!i)process.stderr.write(`
|
|
23
|
+
Claude Code isn't on your PATH yet; these settings apply once it's installed.
|
|
24
|
+
`);let p=["ANTHROPIC_AUTH_TOKEN","ANTHROPIC_API_KEY"].filter((l)=>process.env[l]);if(n.models&&p.length>0)process.stderr.write(`
|
|
25
|
+
${p.join(" and ")} ${p.length===1?"is":"are"} set in your shell and Claude Code would use ${p.length===1?"it":"them"} instead of the workspace. Unset ${p.length===1?"it":"them"} before running claude.
|
|
26
|
+
`);return process.stdout.write(`
|
|
27
|
+
Run claude to start.
|
|
28
|
+
`),0}async function Q(t,e,o,i){let{Pi:r}=await import("./chunk-0krh2hdf.js"),{Library:s}=await import("./chunk-52p33kcn.js"),{WorkspaceSnapshot:c}=await import("./chunk-q3519h2y.js"),n=e.at(-1),a=_.join(_.dirname(n),`pi-extension${_.extname(n)}`),d=r.session({store:t,...C?{harness:C}:{}}),p=await r.models(d),l=p&&r.defaultModel(p);await r.skills(d).catch((m)=>{process.stderr.write(`Couldn't download the Library's skills yet (${w(m)}); Pi tries again when it starts.
|
|
29
|
+
`);return});let u=o.config??{},{Effect:k}=await import("./chunk-1c689590.js"),{ConsoleStore:O}=await import("./chunk-a85j5cz4.js");await k.runPromise(O.locked(t,k.sync(()=>r.setup(t,{paths:r.paths(),extension:a,...l?{model:l}:{}}))));let v=p?r.providers(p,()=>{return}).flatMap((m)=>m.models):[],S=Object.keys(s.servers(u)),N=[`Pi now uses ${o.organization??"your workspace"} through OpenCode Console.`,"",l?` Models ${h(v.length,"model","models")} in /model; new sessions start on ${l.provider}/${l.id}`:" Models none from the workspace, so Pi keeps its own providers",` Policies ${h(c.policies(o)?.length??0,"rule","rules")}, checked before every tool call and !command`,...S.length>0?[` MCP ${S.join(", ")}`]:[],...T(s.library(u).instructions.length,s.library(u).skills.map((m)=>`/skill:${m.slug}`))];if(process.stdout.write(`${N.join(`
|
|
30
|
+
`)}
|
|
31
|
+
`),!i)process.stderr.write(`
|
|
32
|
+
Pi isn't on your PATH yet; this applies once it's installed.
|
|
33
|
+
`);return process.stdout.write(`
|
|
34
|
+
Run pi to start.
|
|
35
|
+
`),0}function T(t,e){if(t+e.length===0)return[];return[` Library ${[...t>0?[h(t,"instruction","instructions")]:[],...e.length>0?[e.join(", ")]:[]].join(", ")}`]}async function X(){let t=E.positionals[1];if(!t)return process.stderr.write(`Usage: opencode-console mcp-headers <server>
|
|
36
|
+
`),1;let{Option:e,Schema:o}=await import("./chunk-1c689590.js"),{ConsoleStore:i}=await import("./chunk-a85j5cz4.js"),{WorkspaceSync:r}=await import("./chunk-rea503jg.js"),{snapshot:s}=await f(r.sync(i.make()));if(!s)return process.stderr.write(`${P}
|
|
37
|
+
`),1;let c=o.decodeUnknownOption(o.Struct({servers:o.Record(o.String,o.Struct({headers:o.optional(o.Record(o.String,o.String))}))}))(s.config?.mcp),n=e.getOrUndefined(c)?.servers[t];if(!n)return process.stderr.write(`The workspace doesn't offer the MCP server ${t} anymore
|
|
38
|
+
`),1;return process.stdout.write(`${JSON.stringify(n.headers??{})}
|
|
39
|
+
`),0}async function ee(){let{ConsoleStore:t}=await import("./chunk-a85j5cz4.js"),{ConsoleCredentials:e}=await import("./chunk-vx37gkw9.js"),o=await f(e.logout(t.make()));if(process.stdout.write(o?`Signed out of OpenCode Console
|
|
40
|
+
`:`Not signed in
|
|
41
|
+
`),process.env.OPENCODE_API_KEY)process.stdout.write(`OPENCODE_API_KEY is still set, so opencode-console keeps using that key
|
|
42
|
+
`);return 0}async function te(){let{ConsoleStore:t}=await import("./chunk-a85j5cz4.js"),{ConsoleCredentials:e}=await import("./chunk-vx37gkw9.js"),{WorkspaceSnapshot:o}=await import("./chunk-q3519h2y.js"),{WorkspaceSync:i}=await import("./chunk-rea503jg.js"),r=t.make(),s=e.read(r),c=s?(await f(i.sync(r))).snapshot:void 0,n=o.policies(c),a=s&&{server:s.server,credential:s.type==="key"?"OPENCODE_API_KEY":"device",email:s.type==="oauth"?s.email:void 0,workspace:c?.organization??e.organization(s),synced:n&&c?new Date(c.fetched).toISOString():void 0,policies:n?.length,models:o.models(c),needs:c?.status};if(g.json===!0)return process.stdout.write(`${JSON.stringify({signedIn:Boolean(a),...a})}
|
|
43
|
+
`),0;if(!a)return process.stdout.write(`${P}
|
|
44
|
+
`),0;let d=[["Signed in",a.credential==="OPENCODE_API_KEY"?"with OPENCODE_API_KEY":a.email??"yes"],...a.workspace?[["Workspace",a.workspace]]:[],["Console",a.server],["Policies",a.synced?`${h(a.policies??0,"policy","policies")}, synced at ${new Date(a.synced).toLocaleTimeString()}`:"not loaded yet, so tool calls are blocked"],["Models",a.models?`${a.models} from the workspace`:"none from the workspace"]];if(process.stdout.write(d.map(([p,l])=>`${p?.padEnd(10)} ${l}
|
|
45
|
+
`).join("")),a.needs)process.stdout.write(`
|
|
46
|
+
${a.needs.message}${a.needs.url?`: ${a.needs.url}`:""}
|
|
47
|
+
`);return 0}async function oe(){let{ConsoleStore:t}=await import("./chunk-a85j5cz4.js"),{WorkspaceSnapshot:e}=await import("./chunk-q3519h2y.js"),{WorkspaceSync:o}=await import("./chunk-rea503jg.js"),i=t.make(),r=e.read(i)?.fetched,s=await f(o.sync(i,{force:g.quiet!==!0||process.env.OPENCODE_CONSOLE_FORCE==="1"}));if(s.snapshot?.config&&!s.error&&s.snapshot.fetched!==r){let{ClaudeCode:a}=await import("./chunk-r2y8x1nz.js");await f(a.refresh(i)).catch((d)=>{if(g.quiet!==!0)process.stderr.write(`Couldn't update Claude Code: ${w(d)}
|
|
48
|
+
`)})}if(g.quiet===!0)return s.error?1:0;if(!s.snapshot&&!s.error)return process.stderr.write(`${P}
|
|
49
|
+
`),1;if(s.error){let a=e.policies(s.snapshot)?`
|
|
50
|
+
Policies from the last sync still apply.`:"";return process.stderr.write(`Couldn't sync: ${w(s.error)}${a}
|
|
51
|
+
`),1}let c=s.snapshot?.organization,n=e.policies(s.snapshot)?.length??0;return process.stdout.write(`Synced ${c?`${c}'s`:"the workspace"} config (${h(n,"policy","policies")})
|
|
52
|
+
`),0}async function ne(){let{ConsoleStore:t}=await import("./chunk-a85j5cz4.js"),{ConsoleCredentials:e}=await import("./chunk-vx37gkw9.js"),o=await f(e.fresh(t.make()));if(!o)return process.stderr.write(`${P}
|
|
53
|
+
`),1;return process.stdout.write(`${o.type==="key"?o.key:o.access}
|
|
54
|
+
`),0}async function f(t){let{Effect:e,Layer:o}=await import("./chunk-1c689590.js"),{FetchHttpClient:i}=await import("./chunk-p909n1zf.js"),{WorkspaceSync:r}=await import("./chunk-rea503jg.js");return e.runPromise(t.pipe(e.provide(r.identify({version:st,harness:C}).pipe(o.provide(i.layer)))))}async function A(t={}){let{ConsoleStore:e}=await import("./chunk-a85j5cz4.js"),o=e.syncClaimFile(e.make());try{let i=e.modified(o);if(!t.always&&i!==void 0&&Date.now()-i<30000)return;e.write(o,"");let r=b()?[process.execPath]:[process.execPath,process.argv[1]];U(r[0],[...r.slice(1),"sync","--quiet",...C?["--harness",C]:[]],{detached:!0,stdio:"ignore",env:{...process.env,...t.force?{OPENCODE_CONSOLE_FORCE:"1"}:{}}}).on("error",()=>{return}).unref()}catch{return}}async function se(t,e){let o=Date.now()+e;for(;;){let i=t();if(i!==void 0||Date.now()>=o)return i;await new Promise((r)=>setTimeout(r,25))}}async function I(t){let{ClaudeCodeHook:e}=await import("./chunk-hf4hqs7y.js"),o=e.denial(x,t);return process.stdout.write(o.stdout),process.stderr.write(o.stderr),o.code}async function re(t){let{execFile:e}=await import("node:child_process");return new Promise((o)=>e(t,["--version"],{timeout:1e4},(i,r)=>o(i?void 0:r.match(/\d+\.\d+\.\d+\S*/)?.[0])))}function L(t){return process.stdout.write(`${JSON.stringify({effect:"deny",message:t})}
|
|
55
|
+
`),2}function h(t,e,o){return`${t} ${t===1?e:o}`}function b(){return/^(\/\$bunfs\/|[A-Za-z]:[\\/]~BUN[\\/])/.test(process.argv[1]??"")}async function Y(){let t=[];for await(let e of process.stdin)t.push(Buffer.from(e));return Buffer.concat(t).toString("utf8")}function w(t){return t instanceof Error?t.message:String(t)}function D(t){let e=g[t];return typeof e==="string"?e:void 0}function ie(){return`opencode-console ${st}
|
|
56
|
+
Connect coding agents to an OpenCode Console workspace: its models, MCP servers, Library and policies.
|
|
57
|
+
|
|
58
|
+
Usage: opencode-console <command> [options]
|
|
59
|
+
|
|
60
|
+
Commands:
|
|
61
|
+
setup <claude-code|pi> Sign in if needed and set up Claude Code or Pi to use the workspace
|
|
62
|
+
(--remove undoes it)
|
|
63
|
+
login [--server <url>] Sign in to OpenCode Console and pick a workspace
|
|
64
|
+
logout Sign out and remove the stored workspace config
|
|
65
|
+
status [--json] Show the sign-in, workspace and config
|
|
66
|
+
sync Fetch the workspace config now
|
|
67
|
+
token Print an access token for auth helpers such as Claude Code's apiKeyHelper
|
|
68
|
+
check Check a tool call against the workspace's policies. Reads
|
|
69
|
+
{"action": "...", "resources": [...]} on stdin, with optional
|
|
70
|
+
"directory", "path" and "shell"; exits 0 to allow, 2 to deny
|
|
71
|
+
hook claude-code Answer a Claude Code hook (setup registers it)
|
|
72
|
+
mcp-headers <server> Print a workspace MCP server's headers (setup registers it)
|
|
73
|
+
|
|
74
|
+
Options:
|
|
75
|
+
--server <url> The Console to sign in to (or set OPENCODE_CONSOLE_SERVER)
|
|
76
|
+
--harness <name/version> Identify the calling agent to the Console, e.g. claude-cli/2.1.304
|
|
77
|
+
(or set OPENCODE_CONSOLE_HARNESS)
|
|
78
|
+
|
|
79
|
+
Set OPENCODE_API_KEY to use a personal or service account key instead of signing in.
|
|
80
|
+
Set OPENCODE_CONSOLE_SERVER to use a Console other than https://opencode.ai/console.
|
|
81
|
+
`}
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@opencode/console",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Connect Claude Code and Pi to an OpenCode Console workspace and enforce its policies",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"opencode",
|
|
7
|
+
"claude-code",
|
|
8
|
+
"pi-package",
|
|
9
|
+
"coding-agent",
|
|
10
|
+
"policy"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://opencode.ai/console/integrations/claude-code",
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/anomalyco/opencode-console.git",
|
|
16
|
+
"directory": "packages/cli"
|
|
17
|
+
},
|
|
18
|
+
"pi": {
|
|
19
|
+
"extensions": [
|
|
20
|
+
"./pi-extension.js"
|
|
21
|
+
]
|
|
22
|
+
},
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"@earendil-works/pi-ai": "*",
|
|
25
|
+
"@earendil-works/pi-coding-agent": "*"
|
|
26
|
+
},
|
|
27
|
+
"peerDependenciesMeta": {
|
|
28
|
+
"@earendil-works/pi-ai": {
|
|
29
|
+
"optional": true
|
|
30
|
+
},
|
|
31
|
+
"@earendil-works/pi-coding-agent": {
|
|
32
|
+
"optional": true
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"license": "MIT",
|
|
36
|
+
"type": "module",
|
|
37
|
+
"bin": {
|
|
38
|
+
"opencode-console": "index.js"
|
|
39
|
+
},
|
|
40
|
+
"files": [
|
|
41
|
+
"*.js",
|
|
42
|
+
"THIRD_PARTY_LICENSES.md"
|
|
43
|
+
],
|
|
44
|
+
"engines": {
|
|
45
|
+
"node": ">=22"
|
|
46
|
+
}
|
|
6
47
|
}
|
package/pi-extension.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import"./chunk-jqhy4pzf.js";import"./chunk-yjw665b0.js";import"./chunk-ke4nwx54.js";import"./chunk-5x5fc0mq.js";import{je,Qt}from"./chunk-1mfjsp5r.js";import{Zt,Kn}from"./chunk-gtf5exm1.js";import"./chunk-6tene1pb.js";import"./chunk-g6d8xejf.js";import"./chunk-dsk7ztf6.js";import"./chunk-sbec97g3.js";import{Eo,wo,ko,Co,Io,Ao,wn,Oo,kn,Wn,ot,Po,Ro}from"./chunk-41p6m0xy.js";import"./chunk-z2kmm4pm.js";import{w,H,Dt,pr,jt}from"./chunk-nva98fq1.js";var S={};w(S,{PiExtension:()=>S,default:()=>O,install:()=>R});import{existsSync as B}from"node:fs";import T from"node:path";import{anthropicMessagesApi as j,createProvider as K,googleGenerativeAIApi as q,openAICompletionsApi as D,openAIResponsesApi as F}from"@earendil-works/pi-ai/compat";import{getBuiltinModels as G,getBuiltinProviders as b}from"@earendil-works/pi-ai/providers/all";import{VERSION as J}from"@earendil-works/pi-coding-agent";async function O(e){await R(e,Oo({harness:`pi/${J}`}))}var L=(e,n,o)=>{let a=b();return[...a.filter((t)=>t===e),...a.filter((t)=>t==="opencode"&&t!==e),...a.filter((t)=>t!==e&&t!=="opencode")].flatMap((t)=>G(t).filter((f)=>f.id===n&&f.api===o)).at(0)},U="opencode_workspace_instructions";async function R(e,n){let o=new Set,a=new Map,d=new Map,t=p(n),f=t?await Po(n).catch(()=>{return}):void 0;if(Eo(f??{},L).forEach((s)=>{o.add(s.id),e.registerProvider(K({id:s.id,name:s.name,auth:{apiKey:{name:"OpenCode Console",resolve:()=>V(n)}},models:s.models,api:{"anthropic-messages":P(j()),"openai-responses":P(F()),"openai-completions":P(D()),"google-generative-ai":P(q())}}))}),t&&(await ot(n).catch(()=>{return}))?.config)["opencode","opencode-go"].filter((s)=>!o.has(s)).forEach((s)=>{o.add(s),e.registerProvider(s,{models:[]})});if(t)await M(e,n,d).catch(()=>{return});let m=f&&wo(f),h={},E=async(s)=>{let r=[...s.modelRegistry.getAll().map((c)=>c.provider),...b(),...s.modelRegistry.getRegisteredProviderIds(),...a.keys()],i=[...new Set(r)].filter((c)=>!o.has(c)),u=await Wn(n,i.map((c)=>({action:"provider.use",resources:[c]}))).catch(()=>{return});i.forEach((c,v)=>{let k=u?.[v]?.effect!=="allow";if(k&&!a.has(c)){let _=s.modelRegistry.getRegisteredNativeProvider(c);a.set(c,()=>{if(e.unregisterProvider(c),_)e.registerProvider(_)}),e.registerProvider(c,{models:[]})}let C=k?void 0:a.get(c);if(C)a.delete(c),C()}),h.fetched=(await ot(n).catch(()=>{return}))?.fetched;let l=s.model,g=m&&s.modelRegistry.find(m.provider,m.id);if(g&&(!l||a.has(l.provider)))await e.setModel(g)},x=async(s)=>{let r=await ot(n);if(r?.fetched!==h.fetched)await E(s);return r};e.on("session_start",async(s,r)=>{if(!p(n)){y(r,"OpenCode Console isn't signed in. Run `npx @opencode/console login`.","warning");return}let i=await ot(n).catch(()=>{return});if(i?.status)y(r,`${i.status.message}${i.status.url?`: ${i.status.url}`:""}`,"warning");await E(r)}),e.on("resources_discover",async()=>{if(!p(n))return;let s=await Ro(n).catch(()=>A(n));return B(s)?{skillPaths:[s]}:void 0}),e.on("before_agent_start",async(s,r)=>{if(!p(n))return;let i=s.systemPromptOptions,u=i.skills??[],l=await(async()=>{let g=await x(r),c=await Wn(n,u.map((v)=>({action:"skill",resources:[v.name]})));return{text:Ao(g?.config?Zt(g.config).instructions:[]),skills:u.filter((v,k)=>c[k]?.effect==="allow")}})().catch(()=>({text:void 0,skills:[]}));if(l.text)i.sections={...i.sections,[U]:l.text};i.skills=l.skills}),e.on("tool_call",async(s,r)=>{let i=e.getAllTools(),u=i.find((c)=>c.name===s.toolName)?.namespace?.aliases?.[0],l=[...new Set([...i.flatMap((c)=>c.namespace?.aliases?.slice(0,1)??[]),...e.getMcpServers().map((c)=>c.name)])],g=await kn(n,ko(s,{cwd:r.cwd,server:u,servers:l,skills:A(n)}));return g?.effect==="deny"?{block:!0,reason:g.message}:void 0}),e.on("user_bash",async(s,r)=>{let i=await kn(n,[Co(s)]);if(i?.effect!=="deny")return;return y(r,i.message,"error"),{result:{output:`${i.message}
|
|
2
|
+
`,exitCode:1,cancelled:!1,truncated:!1}}}),e.on("input",async(s,r)=>{if(p(n))await x(r).catch(()=>{return});let i=Io(s.text);if(!i)return{action:"continue"};let u=await kn(n,[{action:"skill",resources:[i]}]).catch((l)=>N(`/skill:${i}`,l));if(u?.effect!=="deny")return{action:"continue"};return y(r,u.message,"error"),{action:"handled"}}),e.on("before_provider_request",async(s,r)=>{let i=await I(n,r);if(i?.effect!=="deny")return;y(r,i.message,"error"),r.abort();return}),e.on("cache_warming_decision",async(s,r)=>(await I(n,r))?.effect==="deny"?{action:"stop"}:void 0),e.on("turn_start",()=>{if(p(n))M(e,n,d).catch(()=>{return})})}function p(e){return jt(H(()=>je(e.store)!==void 0).pipe(pr(()=>!0)))}async function I(e,n){let o=n.model?.provider;if(!o||!p(e))return;return kn(e,[{action:"provider.use",resources:[o]}]).catch((a)=>N(o,a))}function N(e,n){return{effect:"deny",message:`opencode-console couldn't check ${e}: ${n instanceof Error?n.message:String(n)}`}}var A=(e)=>T.join(wn(e.store),"skills");async function M(e,n,o){let a=await ot(n),d=a?.config?Kn(a.config):{};[...o.keys()].filter((t)=>!(t in d)).forEach((t)=>{o.delete(t),jt(H(()=>e.unregisterMcpServer(t)).pipe(Dt))}),Object.entries(d).forEach(([t,f])=>{let m={url:f.url,...f.headers?{headers:f.headers}:{}},h=JSON.stringify(m);if(o.get(t)===h)return;jt(H(()=>{e.registerMcpServer(t,m),o.set(t,h)}).pipe(Dt))})}async function V(e){let n=await e.run(Qt(e.store));if(!n)return;return{auth:{apiKey:n.type==="key"?n.key:n.access},source:"OpenCode Console"}}function P(e){let n=(o)=>o?.sessionId?{...o,headers:{...o.headers,"x-opencode-session":o.sessionId}}:o;return{...e,stream:(o,a,d)=>e.stream(o,a,n(d)),streamSimple:(o,a,d)=>e.streamSimple(o,a,n(d))}}function y(e,n,o){if(e.hasUI)e.ui.notify(n,o)}export{S as PiExtension,O as default,R as install};
|