alchemylab-opencode 1.0.24 → 1.0.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-SILEE7UA.js → chunk-5P5WLADX.js} +1 -1
- package/dist/chunk-A7EXZZPC.js +12 -0
- package/dist/chunk-G752V4OP.js +2187 -0
- package/dist/{chunk-VREN4JVV.js → chunk-GBXMNWYD.js} +3 -3
- package/dist/chunk-IR6PDN4W.js +13 -0
- package/dist/{session-FWLEEJPX.js → registry-ISXIFNPG.js} +1 -1
- package/dist/{run-VQUBMRCD.js → run-AUCA7EKA.js} +2 -2
- package/dist/{run-service-IUIOP7ZW.js → run-service-MT3LOWLS.js} +1 -1
- package/dist/run.js +1 -1
- package/dist/serve.js +1 -1
- package/dist/server-PIYRZLBG.js +12 -0
- package/dist/{mcp-3MLN7453.js → session-ACBIJ2VE.js} +1 -1
- package/dist/{registry-HM2N65IE.js → share-next-MPGA7EO4.js} +1 -1
- package/dist/{server-TLPVN3ZL.js → worktree-E4DGSBLJ.js} +1 -1
- package/package.json +5 -5
- package/dist/chunk-22MFGOA6.js +0 -75
- package/dist/chunk-GCMAFSDE.js +0 -12
- package/dist/chunk-MN5GIJ5E.js +0 -2260
- package/dist/chunk-N7PLTD3P.js +0 -13
- package/dist/share-next-PRCWHS3Z.js +0 -12
- package/dist/worktree-5G5VWN6L.js +0 -12
|
@@ -0,0 +1,2187 @@
|
|
|
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
|
+
|
|
12
|
+
import{A as Ke,a as Ei,b as qt,c as $o,d as tt,e as Ce,f as Bl,g as Wl,h as ge,i as kr,j as Xt,k as We,l as Ha,m as Xr,n as zt,o as lo,p as nr,q as Er,r as Ga,s as mt,t as Be,u as Ns,v as ut,w as uo,y as he}from"./chunk-IR6PDN4W.js";import{a as Nt,b as He,c as pt,d as It}from"./chunk-7KKA6WBY.js";import{a as An,b as Si}from"./chunk-LTCXIXYM.js";import{a as co,b as Ir,c as Ee,d as je,e as qe}from"./chunk-M4CB72HE.js";import{a as n,c as mm,e as kn,f as En}from"./chunk-MBZTOEAD.js";import gx from"zod";import hx from"path";import Im from"zod";import{Effect as km}from"effect";import{NodePath as bm}from"@effect/platform-node";import{Cause as wm,Duration as Ti,Effect as zn,Layer as Va,Schedule as xm,ServiceMap as vm}from"effect";import Ja from"path";import{sortBy as Hl,pipe as Gl}from"remeda";var Sr;(m=>{function e(y,p){y&&(y=y.replaceAll("\\","/")),p&&(p=p.replaceAll("\\","/"));let f=p.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");f.endsWith(" .*")&&(f=f.slice(0,-3)+"( .*)?");let b=process.platform==="win32"?"si":"s";return new RegExp("^"+f+"$",b).test(y)}m.match=e,n(e,"match");function t(y,p){let f=Gl(p,Object.entries,Hl([([d])=>d.length,"asc"],[([d])=>d,"asc"])),b;for(let[d,s]of f)if(e(y,d)){b=s;continue}return b}m.all=t,n(t,"all");function o(y,p){let f=Gl(p,Object.entries,Hl([([d])=>d.length,"asc"],[([d])=>d,"asc"])),b;for(let[d,s]of f){let c=d.split(/\s+/);if(e(y.head,c[0])&&(c.length===1||i(y.tail,c.slice(1)))){b=s;continue}}return b}m.allStructured=o,n(o,"allStructured");function i(y,p){if(p.length===0)return!0;let[f,...b]=p;if(f==="*")return i(y,b);for(let d=0;d<y.length;d++)if(e(y[d],f)&&i(y.slice(d+1),b))return!0;return!1}n(i,"matchSequence")})(Sr||={});function Di(e,t,...o){return o.flat().findLast(y=>Sr.match(e,y.permission)&&Sr.match(t,y.pattern))??{action:"ask",permission:e,pattern:"*"}}n(Di,"evaluate");import{Schema as Vl}from"effect";import gm from"zod";var hm=Vl.String.pipe(Vl.brand("ToolID")),Jl=hm.pipe(An(e=>({make:n(t=>e.makeUnsafe(t),"make"),ascending:n(t=>e.makeUnsafe(Nt.ascending("tool",t)),"ascending"),zod:Nt.schema("tool").pipe(gm.custom())})));import ym from"path";var Dr=ym.join(je.Path.data,"tool-output");var po;(l=>{let e=qe.create({service:"truncation"}),t=Ti.days(7);l.MAX_LINES=2e3,l.MAX_BYTES=50*1024,l.DIR=Dr,l.GLOB=Ja.join(Dr,"*");function p(g){return g?.permission?Di("task","*",g.permission).action!=="deny":!1}n(p,"hasTaskTool");class f extends vm.Service()("@opencode/Truncate"){static{n(this,"Service")}}l.Service=f,l.layer=Va.effect(f,zn.gen(function*(){let g=yield*ut.Service,u=zn.fn("Truncate.cleanup")(function*(){let w=Nt.timestamp(Nt.create("tool",!1,Date.now()-Ti.toMillis(t))),I=yield*g.readDirectory(Dr).pipe(zn.map(r=>r.filter(x=>x.startsWith("tool_"))),zn.catch(()=>zn.succeed([])));for(let r of I)Nt.timestamp(r)>=w||(yield*g.remove(Ja.join(Dr,r)).pipe(zn.catch(()=>zn.void)))}),a=zn.fn("Truncate.output")(function*(w,I={},r){let x=I.maxLines??l.MAX_LINES,h=I.maxBytes??l.MAX_BYTES,v=I.direction??"head",S=w.split(`
|
|
13
|
+
`),j=Buffer.byteLength(w,"utf-8");if(S.length<=x&&j<=h)return{content:w,truncated:!1};let O=[],k=0,E=0,D=!1;if(v==="head")for(k=0;k<S.length&&k<x;k++){let C=Buffer.byteLength(S[k],"utf-8")+(k>0?1:0);if(E+C>h){D=!0;break}O.push(S[k]),E+=C}else for(k=S.length-1;k>=0&&O.length<x;k--){let C=Buffer.byteLength(S[k],"utf-8")+(O.length>0?1:0);if(E+C>h){D=!0;break}O.unshift(S[k]),E+=C}let z=D?j-E:S.length-O.length,_=D?"bytes":"lines",B=O.join(`
|
|
14
|
+
`),$=Ja.join(Dr,Jl.ascending());yield*g.ensureDir(Dr).pipe(zn.orDie),yield*g.writeFileString($,w).pipe(zn.orDie);let M=p(r)?`The tool call succeeded but the output was truncated. Full output saved to: ${$}
|
|
15
|
+
Use the Task tool to have explore agent process this file with Grep and Read (with offset/limit). Do NOT read the full file yourself - delegate to save context.`:`The tool call succeeded but the output was truncated. Full output saved to: ${$}
|
|
16
|
+
Use Grep to search the full content or Read with offset/limit to view specific sections.`;return{content:v==="head"?`${B}
|
|
17
|
+
|
|
18
|
+
...${z} ${_} truncated...
|
|
19
|
+
|
|
20
|
+
${M}`:`...${z} ${_} truncated...
|
|
21
|
+
|
|
22
|
+
${M}
|
|
23
|
+
|
|
24
|
+
${B}`,truncated:!0,outputPath:$}});return yield*u().pipe(zn.catchCause(w=>(e.error("truncation cleanup failed",{cause:wm.pretty(w)}),zn.void)),zn.repeat(xm.spaced(Ti.hours(1))),zn.delay(Ti.minutes(1)),zn.forkScoped),f.of({cleanup:u,output:a})})),l.defaultLayer=l.layer.pipe(Va.provide(ut.defaultLayer),Va.provide(bm.layer));let{runPromise:s}=Ke(f,l.defaultLayer);async function c(g,u={},a){return s(w=>w.output(g,u,a))}l.output=c,n(c,"output")})(po||={});var Dt;(y=>{function e(p){if(p===null)return!0;if(p===void 0||typeof p!="object")return!1;if(Array.isArray(p)){for(let f of p)if(e(f))return!0;return!1}for(let f of Object.values(p))if(e(f))return!0;return!1}n(e,"hasNullsDeep");function t(p){if(!e(p))return p;if(p===null)return;if(Array.isArray(p))return p.map(t).filter(b=>b!==void 0);let f={};for(let[b,d]of Object.entries(p)){let s=t(d);s!==void 0&&(f[b]=s)}return f}n(t,"stripNullish");function o(p,f){return async b=>{let d=f instanceof Function?await f(b):{...f},s=d.execute;return d.execute=async(c,l)=>{c=t(c);try{d.parameters.parse(c)}catch(a){throw a instanceof Im.ZodError&&d.formatValidationError?new Error(d.formatValidationError(a),{cause:a}):new Error(`The ${p} tool was called with invalid arguments: ${a}.
|
|
25
|
+
Please rewrite the input so it satisfies the expected schema.`,{cause:a})}let g=await s(c,l);if(g.metadata.truncated!==void 0)return g;let u=await po.output(g.output,{},b?.agent);return{...g,output:u.content,metadata:{...g.metadata,truncated:u.truncated,...u.truncated&&{outputPath:u.outputPath}}}},d}}n(o,"wrap");function i(p,f){return{id:p,init:o(p,f)}}y.define=i,n(i,"define");function m(p,f){return km.map(f,b=>({id:p,init:o(p,b)}))}y.defineEffect=m,n(m,"defineEffect")})(Dt||={});import{Deferred as zs,Effect as Co,Layer as Kl,Schema as Pm,ServiceMap as _m}from"effect";import Yl from"zod";import{Effect as _n,Exit as Em,Layer as Sm,PubSub as or,Scope as Pi,ServiceMap as Dm,Stream as rr}from"effect";var Ve;(d=>{let e=qe.create({service:"bus"});d.InstanceDisposed=mt.define("server.instance.disposed",Yl.object({directory:Yl.string()}));class o extends Dm.Service()("@opencode/Bus"){static{n(this,"Service")}}d.Service=o,d.layer=Sm.effect(o,_n.gen(function*(){let s=yield*ge.make(_n.fn("Bus.state")(function*(r){let x=yield*or.unbounded(),h=new Map;return yield*_n.addFinalizer(()=>_n.gen(function*(){yield*or.publish(x,{type:d.InstanceDisposed.type,properties:{directory:r.directory}}),yield*or.shutdown(x);for(let v of h.values())yield*or.shutdown(v)})),{wildcard:x,typed:h}}));function c(r,x){return _n.gen(function*(){let h=r.typed.get(x.type);return h||(h=yield*or.unbounded(),r.typed.set(x.type,h)),h})}n(c,"getOrCreate");function l(r,x){return _n.gen(function*(){let h=yield*ge.get(s),v={type:r.type,properties:x};e.info("publishing",{type:r.type});let S=h.typed.get(r.type);S&&(yield*or.publish(S,v)),yield*or.publish(h.wildcard,v);let j=yield*ge.directory;Ei.emit("event",{directory:j,payload:v})})}n(l,"publish");function g(r){return e.info("subscribing",{type:r.type}),rr.unwrap(_n.gen(function*(){let x=yield*ge.get(s),h=yield*c(x,r);return rr.fromPubSub(h)})).pipe(rr.ensuring(_n.sync(()=>e.info("unsubscribing",{type:r.type}))))}n(g,"subscribe");function u(){return e.info("subscribing",{type:"*"}),rr.unwrap(_n.gen(function*(){let r=yield*ge.get(s);return rr.fromPubSub(r.wildcard)})).pipe(rr.ensuring(_n.sync(()=>e.info("unsubscribing",{type:"*"}))))}n(u,"subscribeAll");function a(r,x,h){return _n.gen(function*(){e.info("subscribing",{type:x});let v=yield*Pi.make(),S=yield*Pi.provide(v)(or.subscribe(r));return yield*Pi.provide(v)(rr.fromSubscription(S).pipe(rr.runForEach(j=>_n.tryPromise({try:n(()=>Promise.resolve().then(()=>h(j)),"try"),catch:n(O=>{e.error("subscriber failed",{type:x,cause:O})},"catch")}).pipe(_n.ignore)),_n.forkScoped)),()=>{e.info("unsubscribing",{type:x}),_n.runFork(Pi.close(v,Em.void))}})}n(a,"on");let w=_n.fn("Bus.subscribeCallback")(function*(r,x){let h=yield*ge.get(s),v=yield*c(h,r);return yield*a(v,r.type,x)}),I=_n.fn("Bus.subscribeAllCallback")(function*(r){let x=yield*ge.get(s);return yield*a(x.wildcard,"*",r)});return o.of({publish:l,subscribe:g,subscribeAll:u,subscribeCallback:w,subscribeAllCallback:I})}));let{runPromise:m,runSync:y}=Ke(o,d.layer);async function p(s,c){return m(l=>l.publish(s,c))}d.publish=p,n(p,"publish");function f(s,c){return y(l=>l.subscribeCallback(s,c))}d.subscribe=f,n(f,"subscribe");function b(s){return y(c=>c.subscribeAllCallback(s))}d.subscribeAll=b,n(b,"subscribeAll")})(Ve||={});import fn from"zod";import{Schema as Tm}from"effect";var Tr=class extends Si()("QuestionID",Tm.String){static{n(this,"QuestionID")}static make(t){return this.makeUnsafe(t)}static ascending(t){return this.makeUnsafe(Nt.ascending("question",t))}static zod=Nt.schema("question")};var Eo;(w=>{let e=qe.create({service:"question"});w.Option=fn.object({label:fn.string().describe("Display text (1-5 words, concise)"),description:fn.string().describe("Explanation of choice")}).meta({ref:"QuestionOption"}),w.Info=fn.object({question:fn.string().describe("Complete question"),header:fn.string().describe("Very short label (max 30 chars)"),options:fn.array(w.Option).describe("Available choices"),multiple:fn.boolean().optional().describe("Allow selecting multiple choices"),custom:fn.boolean().optional().describe("Allow typing a custom answer (default: true)")}).meta({ref:"QuestionInfo"}),w.Request=fn.object({id:Tr.zod,sessionID:He.zod,questions:fn.array(w.Info).describe("Questions to ask"),tool:fn.object({messageID:pt.zod,callID:fn.string()}).optional()}).meta({ref:"QuestionRequest"}),w.Answer=fn.array(fn.string()).meta({ref:"QuestionAnswer"}),w.Reply=fn.object({answers:fn.array(w.Answer).describe("User answers in order of questions (each answer is an array of selected labels)")}),w.Event={Asked:mt.define("question.asked",w.Request),Replied:mt.define("question.replied",fn.object({sessionID:He.zod,requestID:Tr.zod,answers:fn.array(w.Answer)})),Rejected:mt.define("question.rejected",fn.object({sessionID:He.zod,requestID:Tr.zod}))};class f extends Pm.TaggedErrorClass()("QuestionRejectedError",{}){static{n(this,"RejectedError")}get message(){return"The user dismissed this question"}}w.RejectedError=f;class b extends _m.Service()("@opencode/Question"){static{n(this,"Service")}}w.Service=b,w.layer=Kl.effect(b,Co.gen(function*(){let I=yield*Ve.Service,r=yield*ge.make(Co.fn("Question.state")(function*(){let j={pending:new Map};return yield*Co.addFinalizer(()=>Co.gen(function*(){for(let O of j.pending.values())yield*zs.fail(O.deferred,new f);j.pending.clear()})),j})),x=Co.fn("Question.ask")(function*(j){let O=(yield*ge.get(r)).pending,k=Tr.ascending();e.info("asking",{id:k,questions:j.questions.length});let E=yield*zs.make(),D={id:k,sessionID:j.sessionID,questions:j.questions,tool:j.tool};return O.set(k,{info:D,deferred:E}),yield*I.publish(w.Event.Asked,D),yield*Co.ensuring(zs.await(E),Co.sync(()=>{O.delete(k)}))}),h=Co.fn("Question.reply")(function*(j){let O=(yield*ge.get(r)).pending,k=O.get(j.requestID);if(!k){e.warn("reply for unknown request",{requestID:j.requestID});return}O.delete(j.requestID),e.info("replied",{requestID:j.requestID,answers:j.answers}),yield*I.publish(w.Event.Replied,{sessionID:k.info.sessionID,requestID:k.info.id,answers:j.answers}),yield*zs.succeed(k.deferred,j.answers)}),v=Co.fn("Question.reject")(function*(j){let O=(yield*ge.get(r)).pending,k=O.get(j);if(!k){e.warn("reject for unknown request",{requestID:j});return}O.delete(j),e.info("rejected",{requestID:j}),yield*I.publish(w.Event.Rejected,{sessionID:k.info.sessionID,requestID:k.info.id}),yield*zs.fail(k.deferred,new f)}),S=Co.fn("Question.list")(function*(){let j=(yield*ge.get(r)).pending;return Array.from(j.values(),O=>O.info)});return b.of({ask:x,reply:h,reject:v,list:S})})),w.defaultLayer=w.layer.pipe(Kl.provide(Ve.layer));let{runPromise:c}=Ke(b,w.defaultLayer);async function l(I){return c(r=>r.ask(I))}w.ask=l,n(l,"ask");async function g(I){return c(r=>r.reply(I))}w.reply=g,n(g,"reply");async function u(I){return c(r=>r.reject(I))}w.reject=u,n(u,"reject");async function a(){return c(I=>I.list())}w.list=a,n(a,"list")})(Eo||={});var Ya;(i=>{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 o(){return[e[Math.floor(Math.random()*e.length)],t[Math.floor(Math.random()*t.length)]].join("-")}i.create=o,n(o,"create")})(Ya||={});import xl from"path";import{Decimal as _s}from"decimal.js";import at from"zod";import en from"path";import{pathToFileURL as Xi}from"url";import Sd from"os";import Am from"cross-spawn";import{buffer as Xl}from"node:stream/consumers";function Ro(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}n(Ro,"isRecord");function Om(e){if(e instanceof Error)return e.stack??`${e.name}: ${e.message}`;if(typeof e=="object"&&e!==null)try{return JSON.stringify(e,null,2)}catch{return"Unexpected error (unserializable)"}return String(e)}n(Om,"errorFormat");function jo(e){if(e instanceof Error){if(e.message)return e.message;if(e.name)return e.name}if(Ro(e)&&typeof e.message=="string"&&e.message)return e.message;let t=String(e);if(t&&t!=="[object Object]")return t;let o=Om(e);return o&&o!=="{}"?o:"unknown error"}n(jo,"errorMessage");var St;(p=>{class e extends Error{static{n(this,"RunFailedError")}cmd;code;stdout;stderr;constructor(b,d,s,c){let l=c.toString().trim();super(l?`Command failed with code ${d}: ${b.join(" ")}
|
|
26
|
+
${l}`:`Command failed with code ${d}: ${b.join(" ")}`),this.name="ProcessRunFailedError",this.cmd=[...b],this.code=d,this.stdout=s,this.stderr=c}}p.RunFailedError=e;function t(f,b={}){if(f.length===0)throw new Error("Command is required");b.abort?.throwIfAborted();let d=Am(f[0],f.slice(1),{cwd:b.cwd,shell:b.shell,env:b.env===null?{}:b.env?{...process.env,...b.env}:void 0,stdio:[b.stdin??"ignore",b.stdout??"ignore",b.stderr??"ignore"],windowsHide:process.platform==="win32"}),s=!1,c,l=n(()=>{if(s||d.exitCode!==null||d.signalCode!==null)return;s=!0,d.kill(b.kill??"SIGTERM");let a=b.timeout??5e3;a<=0||(c=setTimeout(()=>d.kill("SIGKILL"),a))},"abort"),g=new Promise((a,w)=>{let I=n(()=>{b.abort?.removeEventListener("abort",l),c&&clearTimeout(c)},"done");d.once("exit",(r,x)=>{I(),a(r??(x?1:0))}),d.once("error",r=>{I(),w(r)})});g.catch(()=>{}),b.abort&&(b.abort.addEventListener("abort",l,{once:!0}),b.abort.aborted&&l());let u=d;return u.exited=g,u}p.spawn=t,n(t,"spawn");async function o(f,b={}){let d=t(f,{cwd:b.cwd,env:b.env,stdin:b.stdin,shell:b.shell,abort:b.abort,kill:b.kill,timeout:b.timeout,stdout:"pipe",stderr:"pipe"});if(!d.stdout||!d.stderr)throw new Error("Process output not available");let s=await Promise.all([d.exited,Xl(d.stdout),Xl(d.stderr)]).then(([c,l,g])=>({code:c,stdout:l,stderr:g})).catch(c=>{if(!b.nothrow)throw c;return{code:1,stdout:Buffer.alloc(0),stderr:Buffer.from(jo(c))}});if(s.code===0||b.nothrow)return s;throw new e(f,s.code,s.stdout,s.stderr)}p.run=o,n(o,"run");async function i(f){if(f.exitCode!==null||f.signalCode!==null)return;if(process.platform!=="win32"||!f.pid){f.kill();return}(await o(["taskkill","/pid",String(f.pid),"/T","/F"],{nothrow:!0})).code!==0&&f.kill()}p.stop=i,n(i,"stop");async function m(f,b={}){let d=await o(f,b);return{...d,text:d.stdout.toString()}}p.text=m,n(m,"text");async function y(f,b={}){return(await m(f,b)).text.split(/\r?\n/).filter(Boolean)}p.lines=y,n(y,"lines")})(St||={});import W from"zod";import qm from"path";import Ze from"zod";import{Effect as mn,Layer as Ka,Schema as un,ServiceMap as Rm,Stream as So}from"effect";import{FetchHttpClient as jm,HttpClient as Ql,HttpClientRequest as Do,HttpClientResponse as Fs}from"effect/unstable/http";import{Schedule as Zl}from"effect";import{HttpClient as Cm}from"effect/unstable/http";var sr=n(e=>e.pipe(Cm.retryTransient({retryOn:"errors-and-responses",times:2,schedule:Zl.exponential(200).pipe(Zl.jittered)})),"withTransientReadRetry");import{ChildProcess as Xa,ChildProcessSpawner as ed}from"effect/unstable/process";import td from"path";import Pr from"zod";import _i from"semver";var Ft;(j=>{let e=qe.create({service:"installation"});j.Event={Updated:mt.define("installation.updated",Pr.object({version:Pr.string()})),UpdateAvailable:mt.define("installation.update-available",Pr.object({version:Pr.string()}))};function o(O,k){let E=_i.major(O),D=_i.minor(O),z=_i.major(k),_=_i.minor(k);return z>E?"major":_>D?"minor":"patch"}j.getReleaseType=o,n(o,"getReleaseType"),j.Info=Pr.object({version:Pr.string(),latest:Pr.string()}).meta({ref:"InstallationInfo"}),j.VERSION=Bl,j.CHANNEL=Wl,j.USER_AGENT=`opencode/${j.CHANNEL}/${j.VERSION}/${Ce.OPENCODE_CLIENT}`;function f(){return j.CHANNEL!=="latest"}j.isPreview=f,n(f,"isPreview");function b(){return j.CHANNEL==="local"}j.isLocal=b,n(b,"isLocal");class d extends un.TaggedErrorClass()("UpgradeFailedError",{stderr:un.String}){static{n(this,"UpgradeFailedError")}}j.UpgradeFailedError=d;let s=un.Struct({tag_name:un.String}),c=un.Struct({version:un.String}),l=un.Struct({versions:un.Struct({stable:un.String})}),g=un.Struct({formulae:un.Array(un.Struct({versions:un.Struct({stable:un.String})}))}),u=un.Struct({d:un.Struct({results:un.Array(un.Struct({Version:un.String}))})}),a=c;class w extends Rm.Service()("@opencode/Installation"){static{n(this,"Service")}}j.Service=w,j.layer=Ka.effect(w,mn.gen(function*(){let O=yield*Ql.HttpClient,k=Ql.filterStatusOk(sr(O)),E=yield*ed.ChildProcessSpawner,D=mn.fnUntraced(function*(T,G){let N=Xa.make(T[0],T.slice(1),{cwd:G?.cwd,env:G?.env,extendEnv:!0}),A=yield*E.spawn(N),F=yield*So.mkString(So.decodeText(A.stdout));return yield*A.exitCode,F},mn.scoped,mn.catch(()=>mn.succeed(""))),z=mn.fnUntraced(function*(T,G){let N=Xa.make(T[0],T.slice(1),{cwd:G?.cwd,env:G?.env,extendEnv:!0}),A=yield*E.spawn(N),[F,V]=yield*mn.all([So.mkString(So.decodeText(A.stdout)),So.mkString(So.decodeText(A.stderr))],{concurrency:2});return{code:yield*A.exitCode,stdout:F,stderr:V}},mn.scoped,mn.catch(()=>mn.succeed({code:ed.ExitCode(1),stdout:"",stderr:""}))),_=mn.fnUntraced(function*(){return(yield*D(["brew","list","--formula","anomalyco/tap/opencode"])).includes("opencode")?"anomalyco/tap/opencode":((yield*D(["brew","list","--formula","opencode"])).includes("opencode"),"opencode")}),B=mn.fnUntraced(function*(T){let N=yield*(yield*k.execute(Do.get("https://opencode.ai/install"))).text,A=new TextEncoder().encode(N),F=Xa.make("bash",[],{stdin:So.make(A),env:{VERSION:T},extendEnv:!0}),V=yield*E.spawn(F),[Y,re]=yield*mn.all([So.mkString(So.decodeText(V.stdout)),So.mkString(So.decodeText(V.stderr))],{concurrency:2});return{code:yield*V.exitCode,stdout:Y,stderr:re}},mn.scoped,mn.orDie),$=mn.fn("Installation.method")(function*(){if(process.execPath.includes(td.join(".opencode","bin"))||process.execPath.includes(td.join(".local","bin")))return"curl";let T=process.execPath.toLowerCase(),G=[{name:"npm",command:n(()=>D(["npm","list","-g","--depth=0"]),"command")},{name:"yarn",command:n(()=>D(["yarn","global","list"]),"command")},{name:"pnpm",command:n(()=>D(["pnpm","list","-g","--depth=0"]),"command")},{name:"bun",command:n(()=>D(["bun","pm","ls","-g"]),"command")},{name:"brew",command:n(()=>D(["brew","list","--formula","opencode"]),"command")},{name:"scoop",command:n(()=>D(["scoop","list","opencode"]),"command")},{name:"choco",command:n(()=>D(["choco","list","--limit-output","opencode"]),"command")}];G.sort((N,A)=>{let F=T.includes(N.name),V=T.includes(A.name);return F&&!V?-1:!F&&V?1:0});for(let N of G){let A=yield*N.command(),F=N.name==="brew"||N.name==="choco"||N.name==="scoop"?"opencode":"opencode-ai";if(A.includes(F))return N.name}return"unknown"}),M=mn.fn("Installation.latest")(function*(T){let G=T||(yield*$());if(G==="brew"){let F=yield*_();if(F.includes("/")){let re=yield*D(["brew","info","--json=v2",F]);return(yield*un.decodeUnknownEffect(un.fromJsonString(g))(re)).formulae[0].versions.stable}let V=yield*k.execute(Do.get("https://formulae.brew.sh/api/formula/opencode.json").pipe(Do.acceptJson));return(yield*Fs.schemaBodyJson(l)(V)).versions.stable}if(G==="npm"||G==="bun"||G==="pnpm"){let V=(yield*D(["npm","config","get","registry"])).trim()||"https://registry.npmjs.org",Y=V.endsWith("/")?V.slice(0,-1):V,re=j.CHANNEL,ue=yield*k.execute(Do.get(`${Y}/opencode-ai/${re}`).pipe(Do.acceptJson));return(yield*Fs.schemaBodyJson(c)(ue)).version}if(G==="choco"){let F=yield*k.execute(Do.get("https://community.chocolatey.org/api/v2/Packages?$filter=Id%20eq%20%27opencode%27%20and%20IsLatestVersion&$select=Version").pipe(Do.setHeaders({Accept:"application/json;odata=verbose"})));return(yield*Fs.schemaBodyJson(u)(F)).d.results[0].Version}if(G==="scoop"){let F=yield*k.execute(Do.get("https://raw.githubusercontent.com/ScoopInstaller/Main/master/bucket/opencode.json").pipe(Do.setHeaders({Accept:"application/json"})));return(yield*Fs.schemaBodyJson(a)(F)).version}let N=yield*k.execute(Do.get("https://api.github.com/repos/anomalyco/opencode/releases/latest").pipe(Do.acceptJson));return(yield*Fs.schemaBodyJson(s)(N)).tag_name.replace(/^v/,"")},mn.orDie),C=mn.fn("Installation.upgrade")(function*(T,G){let N;switch(T){case"curl":N=yield*B(G);break;case"npm":N=yield*z(["npm","install","-g",`opencode-ai@${G}`]);break;case"pnpm":N=yield*z(["pnpm","install","-g",`opencode-ai@${G}`]);break;case"bun":N=yield*z(["bun","install","-g",`opencode-ai@${G}`]);break;case"brew":{let A=yield*_(),F={HOMEBREW_NO_AUTO_UPDATE:"1"};if(A.includes("/")){let V=yield*z(["brew","tap","anomalyco/tap"],{env:F});if(V.code!==0){N=V;break}let re=(yield*D(["brew","--repo","anomalyco/tap"])).trim();if(re){let ue=yield*z(["git","pull","--ff-only"],{cwd:re,env:F});if(ue.code!==0){N=ue;break}}}N=yield*z(["brew","upgrade",A],{env:F});break}case"choco":N=yield*z(["choco","upgrade","opencode",`--version=${G}`,"-y"]);break;case"scoop":N=yield*z(["scoop","install",`opencode@${G}`]);break;default:return yield*new d({stderr:`Unknown method: ${T}`})}if(!N||N.code!==0){let A=T==="choco"?"not running from an elevated command shell":N?.stderr||"";return yield*new d({stderr:A})}e.info("upgraded",{method:T,target:G,stdout:N.stdout,stderr:N.stderr}),yield*D([process.execPath,"--version"])});return w.of({info:mn.fn("Installation.info")(function*(){return{version:j.VERSION,latest:yield*M()}}),method:$,latest:M,upgrade:C})})),j.defaultLayer=j.layer.pipe(Ka.provide(jm.layer),Ka.provide(uo));let{runPromise:x}=Ke(w,j.defaultLayer);async function h(){return x(O=>O.method())}j.method=h,n(h,"method");async function v(O){return x(k=>k.latest(O))}j.latest=v,n(v,"latest");async function S(O,k){return x(E=>E.upgrade(O,k))}j.upgrade=S,n(S,"upgrade")})(Ft||={});import Oi from"path";import Lm from"os";import{randomBytes as Nm,randomUUID as zm}from"crypto";import{mkdir as Ai,readFile as Fm,rm as Zr,stat as Um,utimes as $m,writeFile as nd}from"fs/promises";import{createHash as Mm}from"crypto";var qo;(t=>{function e(o){return Mm("sha1").update(o).digest("hex")}t.fast=e,n(e,"fast")})(qo||={});var Bo;(g=>{let e=Oi.join(je.Path.state,"locks"),t={staleMs:6e4,timeoutMs:5*6e4,baseDelayMs:100,maxDelayMs:2e3};function o(u){if(typeof u!="object"||u===null||!("code"in u))return;let a=u.code;if(typeof a=="string")return a}n(o,"code");function i(u,a){return new Promise((w,I)=>{if(a?.aborted){I(a.reason??new Error("Aborted"));return}let r,x=n(()=>{a?.removeEventListener("abort",h),w()},"done"),h=n(()=>{r&&clearTimeout(r),a?.removeEventListener("abort",h),I(a?.reason??new Error("Aborted"))},"abort");a?.addEventListener("abort",h,{once:!0}),r=setTimeout(x,u)})}n(i,"sleep");function m(u){let a=Math.floor(u*.3),w=Math.floor(Math.random()*(2*a+1))-a;return Math.max(0,u+w)}n(m,"jitter");function y(){return performance.now()}n(y,"mono");function p(){return performance.timeOrigin+y()}n(p,"wall");async function f(u){try{return await Um(u)}catch(a){let w=o(a);if(w==="ENOENT"||w==="ENOTDIR")return;throw a}}n(f,"stats");async function b(u,a,w,I){let r=p(),x=await f(a);if(x)return r-x.mtimeMs>I;let h=await f(w);if(h)return r-h.mtimeMs>I;let v=await f(u);return v?r-v.mtimeMs>I:!1}n(b,"stale");async function d(u,a){let w=zm?.()??Nm(16).toString("hex"),I=Oi.join(u,"meta.json"),r=Oi.join(u,"heartbeat");try{await Ai(u,{mode:448})}catch(j){if(o(j)!=="EEXIST")throw j;if(!await b(u,r,I,a.staleMs))return{acquired:!1};let O=u+".breaker";try{await Ai(O,{mode:448})}catch(k){let E=o(k);if(E==="EEXIST"){let D=await f(O);return D&&p()-D.mtimeMs>a.staleMs&&await Zr(O,{recursive:!0,force:!0}).catch(()=>{}),{acquired:!1}}if(E==="ENOENT"||E==="ENOTDIR")return{acquired:!1};throw k}try{if(!await b(u,r,I,a.staleMs))return{acquired:!1};await Zr(u,{recursive:!0,force:!0});try{await Ai(u,{mode:448})}catch(k){let E=o(k);if(E==="EEXIST"||E==="ENOTEMPTY")return{acquired:!1};throw k}}finally{await Zr(O,{recursive:!0,force:!0}).catch(()=>{})}}let x={token:w,pid:process.pid,hostname:Lm.hostname(),createdAt:new Date().toISOString()};await nd(r,"",{flag:"wx"}).catch(async()=>{throw await Zr(u,{recursive:!0,force:!0}),new Error("Lock acquired but heartbeat already existed (possible compromise).")}),await nd(I,JSON.stringify(x,null,2),{flag:"wx"}).catch(async()=>{throw await Zr(u,{recursive:!0,force:!0}),new Error("Lock acquired but meta.json already existed (possible compromise).")});let h;return{acquired:!0,startHeartbeat:n((j=Math.max(100,Math.floor(a.staleMs/3)))=>{h||(h=setInterval(()=>{let O=new Date;$m(r,O,O).catch(()=>{})},j),h.unref?.())},"startHeartbeat"),release:n(async()=>{if(h&&(clearInterval(h),h=void 0),(await Fm(I,"utf8").then(O=>{let k=JSON.parse(O);return!k||typeof k!="object"?{}:{token:"token"in k&&typeof k.token=="string"?k.token:void 0}}).catch(O=>{let k=o(O);throw k==="ENOENT"||k==="ENOTDIR"?new Error("Refusing to release: lock is compromised (metadata missing)."):O instanceof SyntaxError?new Error("Refusing to release: lock is compromised (metadata invalid)."):O})).token!==w)throw new Error("Refusing to release: lock token mismatch (not the owner).");await Zr(u,{recursive:!0,force:!0})},"release")}}n(d,"tryAcquireLockDir");async function s(u,a,w){let I=y()+w.timeoutMs,r=0,x=0,h=w.baseDelayMs;for(;;){a.signal?.throwIfAborted();let v=await d(u,w);if(v.acquired)return v;if(y()>I)throw new Error(`Timed out waiting for lock: ${a.key}`);r+=1;let S=m(h);await a.onWait?.({key:a.key,attempt:r,delay:S,waited:x}),await i(S,a.signal),x+=S,h=Math.min(w.maxDelayMs,Math.floor(h*1.7))}}n(s,"acquireLockDir");async function c(u,a={}){a.signal?.throwIfAborted();let w={staleMs:a.staleMs??t.staleMs,timeoutMs:a.timeoutMs??t.timeoutMs,baseDelayMs:a.baseDelayMs??t.baseDelayMs,maxDelayMs:a.maxDelayMs??t.maxDelayMs},I=a.dir??e;await Ai(I,{recursive:!0});let r=Oi.join(I,qo.fast(u)+".lock"),x=await s(r,{key:u,onWait:a.onWait,signal:a.signal},w);x.startHeartbeat();let h=n(()=>x.release(),"release");return{release:h,[Symbol.asyncDispose](){return h()}}}g.acquire=c,n(c,"acquire");async function l(u,a,w={}){var r=[];try{let I=kn(r,await c(u,w),!0);w.signal?.throwIfAborted();return await a()}catch(x){var h=x,v=!0}finally{var S=En(r,h,v);S&&await S}}g.withLock=l,n(l,"withLock")})(Bo||={});var ir;(g=>{let e=qe.create({service:"models.dev"}),t=p(),o=qm.join(je.Path.cache,t==="https://models.dev"?"models.json":`models-${qo.fast(t)}.json`),i=300*1e3;g.Model=Ze.object({id:Ze.string(),name:Ze.string(),family:Ze.string().optional(),release_date:Ze.string(),attachment:Ze.boolean(),reasoning:Ze.boolean(),temperature:Ze.boolean(),tool_call:Ze.boolean(),interleaved:Ze.union([Ze.literal(!0),Ze.object({field:Ze.enum(["reasoning_content","reasoning_details"])}).strict()]).optional(),cost:Ze.object({input:Ze.number(),output:Ze.number(),cache_read:Ze.number().optional(),cache_write:Ze.number().optional(),context_over_200k:Ze.object({input:Ze.number(),output:Ze.number(),cache_read:Ze.number().optional(),cache_write:Ze.number().optional()}).optional()}).optional(),limit:Ze.object({context:Ze.number(),input:Ze.number().optional(),output:Ze.number()}),modalities:Ze.object({input:Ze.array(Ze.enum(["text","audio","image","video","pdf"])),output:Ze.array(Ze.enum(["text","audio","image","video","pdf"]))}).optional(),experimental:Ze.boolean().optional(),status:Ze.enum(["alpha","beta","deprecated"]).optional(),options:Ze.record(Ze.string(),Ze.any()),headers:Ze.record(Ze.string(),Ze.string()).optional(),provider:Ze.object({npm:Ze.string().optional(),api:Ze.string().optional()}).optional(),variants:Ze.record(Ze.string(),Ze.record(Ze.string(),Ze.any())).optional()}),g.Provider=Ze.object({api:Ze.string().optional(),name:Ze.string(),env:Ze.array(Ze.string()),id:Ze.string(),npm:Ze.string().optional(),models:Ze.record(Ze.string(),g.Model)});function p(){return Ce.OPENCODE_MODELS_URL||"https://models.dev"}n(p,"url");function f(){return Date.now()-Number(Ee.stat(o)?.mtimeMs??0)<i}n(f,"fresh");function b(u){return!u&&f()}n(b,"skip");let d=n(async()=>{let u=await fetch(`${p()}/api.json`,{headers:{"User-Agent":Ft.USER_AGENT},signal:AbortSignal.timeout(1e4)});return{ok:u.ok,text:await u.text()}},"fetchApi");g.Data=$o(async()=>{let u=await Ee.readJson(Ce.OPENCODE_MODELS_PATH??o).catch(()=>{});if(u)return u;let a=await import("./models-snapshot.js").then(w=>w.snapshot).catch(()=>{});return a||(Ce.OPENCODE_DISABLE_MODELS_FETCH?{}:Bo.withLock(`models-dev:${o}`,async()=>{let w=await Ee.readJson(Ce.OPENCODE_MODELS_PATH??o).catch(()=>{});if(w)return w;let I=await d();return I.ok&&await Ee.write(o,I.text).catch(r=>{e.error("Failed to write models cache",{error:r})}),JSON.parse(I.text)}))});async function c(){return await(0,g.Data)()}g.get=c,n(c,"get");async function l(u=!1){if(b(u))return g.Data.reset();await Bo.withLock(`models-dev:${o}`,async()=>{if(b(u))return g.Data.reset();let a=await d();a.ok&&(await Ee.write(o,a.text),g.Data.reset())}).catch(a=>{e.error("Failed to fetch models.dev",{error:a})})}g.refresh=l,n(l,"refresh")})(ir||={});!Ce.OPENCODE_DISABLE_MODELS_FETCH&&!process.argv.includes("--get-yargs-completions")&&(ir.refresh(),setInterval(async()=>{await ir.refresh()},60*1e3*60).unref());import{mergeDeep as Yn,pipe as Ag,unique as Cg}from"remeda";import pc from"fs/promises";import Ym from"path";import{Effect as Qn,Layer as rd,Record as Km,Result as Xm,Schema as Gt,ServiceMap as Zm}from"effect";import{SchemaAST as Ci}from"effect";import Cn from"zod";function od(e){return ar(e.ast)}n(od,"zod");function ar(e){let t=Bm(e),o=Ci.resolveDescription(e),i=Ci.resolveIdentifier(e),m=o?t.describe(o):t;return i?m.meta({ref:i}):m}n(ar,"walk");function Bm(e){if(Ci.isOptional(e))return Wm(e);switch(e._tag){case"String":return Cn.string();case"Number":return Cn.number();case"Boolean":return Cn.boolean();case"Null":return Cn.null();case"Undefined":return Cn.undefined();case"Any":case"Unknown":return Cn.unknown();case"Never":return Cn.never();case"Literal":return Cn.literal(e.literal);case"Union":return Hm(e);case"Objects":return Gm(e);case"Arrays":return Vm(e);case"Declaration":return Jm(e);default:return cr(e)}}n(Bm,"body");function Wm(e){if(e._tag!=="Union")return cr(e);let t=e.types.filter(o=>o._tag!=="Undefined");return t.length===1?ar(t[0]).optional():t.length>1?Cn.union(t.map(ar)).optional():Cn.undefined().optional()}n(Wm,"opt");function Hm(e){let t=e.types.map(ar);if(t.length===1)return t[0];if(t.length<2)return cr(e);let o=e.annotations?.discriminator;return o?Cn.discriminatedUnion(o,t):Cn.union(t)}n(Hm,"union");function Gm(e){if(e.propertySignatures.length===0&&e.indexSignatures.length===1){let t=e.indexSignatures[0];return t.parameter._tag!=="String"?cr(e):Cn.record(Cn.string(),ar(t.type))}return e.indexSignatures.length>0?cr(e):Cn.object(Object.fromEntries(e.propertySignatures.map(t=>[String(t.name),ar(t.type)])))}n(Gm,"object");function Vm(e){return e.elements.length>0||e.rest.length!==1?cr(e):Cn.array(ar(e.rest[0]))}n(Vm,"array");function Jm(e){return e.typeParameters.length!==1?cr(e):ar(e.typeParameters[0])}n(Jm,"decl");function cr(e){let t=Ci.resolveIdentifier(e);throw new Error(`unsupported effect schema: ${t??e._tag}`)}n(cr,"fail");var sd="opencode-oauth-dummy-key",Ri=Ym.join(je.Path.globalData,"auth.json"),ji=n(e=>t=>new Fn.AuthError({message:e,cause:t}),"fail"),Fn;(u=>{class e extends Gt.Class("OAuth")({type:Gt.Literal("oauth"),refresh:Gt.String,access:Gt.String,expires:Gt.Number,accountId:Gt.optional(Gt.String),enterpriseUrl:Gt.optional(Gt.String)}){static{n(this,"Oauth")}}u.Oauth=e;class t extends Gt.Class("ApiAuth")({type:Gt.Literal("api"),key:Gt.String,metadata:Gt.optional(Gt.Record(Gt.String,Gt.String))}){static{n(this,"Api")}}u.Api=t;class o extends Gt.Class("WellKnownAuth")({type:Gt.Literal("wellknown"),key:Gt.String,token:Gt.String}){static{n(this,"WellKnown")}}u.WellKnown=o;let i=Gt.Union([e,t,o]).annotate({discriminator:"type",identifier:"Auth"});u.Info=Object.assign(i,{zod:od(i)});class y extends Gt.TaggedErrorClass()("AuthError",{message:Gt.String,cause:Gt.optional(Gt.Defect)}){static{n(this,"AuthError")}}u.AuthError=y;class p extends Zm.Service()("@opencode/Auth"){static{n(this,"Service")}}u.Service=p,u.layer=rd.effect(p,Qn.gen(function*(){let a=yield*ut.Service,w=Gt.decodeUnknownOption(u.Info),I=Qn.fn("Auth.all")(function*(){let S=yield*a.readJson(Ri).pipe(Qn.orElseSucceed(()=>({})));return Km.filterMap(S,j=>Xm.fromOption(w(j),()=>{}))}),r=Qn.fn("Auth.rawAll")(function*(){return yield*a.readJson(Ri).pipe(Qn.catchIf(S=>S?.reason?._tag==="NotFound"||S?.cause?.reason?._tag==="NotFound",()=>Qn.succeed({})))}),x=Qn.fn("Auth.get")(function*(S){return(yield*I())[S]}),h=Qn.fn("Auth.set")(function*(S,j){let O=S.replace(/\/+$/,""),k=yield*r().pipe(Qn.mapError(ji("Refusing to write auth data: existing auth.json could not be read")));O!==S&&delete k[S],delete k[O+"/"],yield*a.writeJson(Ri,{...k,[O]:j},384).pipe(Qn.mapError(ji("Failed to write auth data")))}),v=Qn.fn("Auth.remove")(function*(S){let j=S.replace(/\/+$/,""),O=yield*r().pipe(Qn.mapError(ji("Refusing to write auth data: existing auth.json could not be read")));delete O[S],delete O[j],yield*a.writeJson(Ri,O,384).pipe(Qn.mapError(ji("Failed to write auth data")))});return p.of({get:x,all:I,set:h,remove:v})})),u.defaultLayer=u.layer.pipe(rd.provide(ut.defaultLayer));let{runPromise:d}=Ke(p,u.defaultLayer);async function s(a){return d(w=>w.get(a))}u.get=s,n(s,"get");async function c(){return d(a=>a.all())}u.all=c,n(c,"all");async function l(a,w){return d(I=>I.set(a,w))}u.set=l,n(l,"set");async function g(a){return d(w=>w.remove(a))}u.remove=g,n(g,"remove")})(Fn||={});var Tt;(y=>{let e=he.state(()=>({...process.env}));function t(p){return e()[p]}y.get=t,n(t,"get");function o(){return e()}y.all=o,n(o,"all");function i(p,f){let b=e();b[p]=f}y.set=i,n(i,"set");function m(p){let f=e();delete f[p]}y.remove=m,n(m,"remove")})(Tt||={});import{applyEdits as Rg,modify as jg,parse as Mg,printParseErrorCode as Lg}from"jsonc-parser";import Je from"path";import rg from"os";import{text as sg}from"node:stream/consumers";import jt from"fs/promises";import id from"path";var To;(t=>{async function e(o,i){if(process.platform==="win32"){let m=id.resolve(o),y=id.resolve(i),p=`$global:ProgressPreference = 'SilentlyContinue'; Expand-Archive -Path '${m}' -DestinationPath '${y}' -Force`;await St.run(["powershell","-NoProfile","-NonInteractive","-Command",p]);return}await St.run(["unzip","-o","-q",o,"-d",i])}t.extractZip=e,n(e,"extractZip")})(To||={});import{createRequire as Qm}from"node:module";import eg from"node:path";var Qr;(t=>{function e(o,i){try{return Qm(eg.join(i,"package.json")).resolve(o)}catch{}}t.resolve=e,n(e,"resolve")})(Qr||={});function ht(e,t,o){let i=Array.isArray(t)?[...t]:[],m=Array.isArray(t)?o:t,y=St.spawn([e,...i],{...m??{},stdin:"pipe",stdout:"pipe",stderr:"pipe"});if(!y.stdin||!y.stdout||!y.stderr)throw new Error("Process output not available");return y}n(ht,"spawn");import ad from"semver";import cd from"zod";import Wo from"path";import{readdir as tg,rm as ng}from"fs/promises";import{realpathSync as og}from"fs";import{Arborist as ld}from"@npmcli/arborist";var an;(c=>{let e=qe.create({service:"npm"}),t=process.platform==="win32"?new Set(["<",">",":",'"',"|","?","*"]):void 0;c.InstallFailedError=tt.create("NpmInstallFailedError",cd.object({pkg:cd.string()}));function i(l){return t?Array.from(l,g=>t.has(g)||g.charCodeAt(0)<32?"_":g).join(""):l}c.sanitize=i,n(i,"sanitize");function m(){try{return og(je.Path.cache)}catch{return je.Path.cache}}n(m,"cacheRoot");function y(l){return Wo.join(m(),"packages",i(l))}n(y,"directory");function p(l,g){let u;try{u=typeof Bun<"u"?import.meta.resolve(l,g):import.meta.resolve(g)}catch{}return{directory:g,entrypoint:u}}n(p,"resolveEntryPoint");async function f(l,g){let u=await fetch(`https://registry.npmjs.org/${l}`);if(!u.ok)return e.warn("Failed to resolve latest version, using cached",{pkg:l,cachedVersion:g}),!1;let w=(await u.json())?.["dist-tags"]?.latest;return w?/[\s^~*xX<>|=]/.test(g)?!ad.satisfies(w,g):ad.lt(g,w):(e.warn("No latest version found, using cached",{pkg:l,cachedVersion:g}),!1)}c.outdated=f,n(f,"outdated");async function b(l){var x=[];try{let g=y(l);let u=kn(x,await Bo.acquire(`npm-install:${Ee.resolve(g)}`),!0);e.info("installing package",{pkg:l});let a=new ld({path:g,binLinks:!0,progress:!1,savePrefix:"",ignoreScripts:!0});let w=await a.loadVirtual().catch(()=>{});if(w){let O=w.edgesOut.values().next().value?.to;if(O)return p(O.name,O.path)}let I=await a.reify({add:[l],save:!0,saveType:"prod"}).catch(O=>{throw new c.InstallFailedError({pkg:l},{cause:O})});let r=I.edgesOut.values().next().value?.to;if(!r)throw new c.InstallFailedError({pkg:l});return p(r.name,r.path)}catch(h){var v=h,S=!0}finally{var j=En(x,v,S);j&&await j}}c.add=b,n(b,"add");async function d(l){var h=[];try{let g=kn(h,await Bo.acquire(`npm-install:${l}`),!0);e.info("checking dependencies",{dir:l});let u=n(async()=>{await new ld({path:l,binLinks:!0,progress:!1,savePrefix:"",ignoreScripts:!0}).reify().catch(()=>{})},"reify");if(!await Ee.exists(Wo.join(l,"node_modules"))){e.info("node_modules missing, reifying"),await u();return}let a=await Ee.readJson(Wo.join(l,"package.json")).catch(()=>({}));let w=await Ee.readJson(Wo.join(l,"package-lock.json")).catch(()=>({}));let I=new Set([...Object.keys(a.dependencies||{}),...Object.keys(a.devDependencies||{}),...Object.keys(a.peerDependencies||{}),...Object.keys(a.optionalDependencies||{})]);let r=w.packages?.[""]||{};let x=new Set([...Object.keys(r.dependencies||{}),...Object.keys(r.devDependencies||{}),...Object.keys(r.peerDependencies||{}),...Object.keys(r.optionalDependencies||{})]);for(let k of I)if(!x.has(k)){e.info("dependency not in lock file, reifying",{name:k}),await u();return}e.info("dependencies in sync")}catch(v){var S=v,j=!0}finally{var O=En(h,S,j);O&&await O}}c.install=d,n(d,"install");async function s(l){let g=y(l),u=Wo.join(g,"node_modules",".bin"),a=n(async()=>{let r=await tg(u).catch(()=>[]);if(r.length===0)return;if(r.length===1)return r[0];let x=await Ee.readJson(Wo.join(g,"node_modules",l,"package.json")).catch(()=>{});if(x?.bin){let h=l.startsWith("@")?l.split("/")[1]:l,v=x.bin;if(typeof v=="string")return h;let S=Object.keys(v);return S.length===1?S[0]:v[h]?h:S[0]}return r[0]},"pick"),w=await a();if(w)return Wo.join(u,w);await ng(Wo.join(g,"package-lock.json"),{force:!0}),await b(l);let I=await a();if(I)return Wo.join(u,I)}c.which=s,n(s,"which")})(an||={});var $s;(ue=>{let e=qe.create({service:"lsp.server"}),t=n(async H=>jt.stat(H).then(()=>!0).catch(()=>!1),"pathExists"),o=n((H,R={})=>St.run(H,{...R,nothrow:!0}),"run"),i=n((H,R={})=>St.text(H,{...R,nothrow:!0}),"output"),m=n((H,R)=>async L=>{if(R){let ne=Ee.up({targets:R,start:Je.dirname(L),stop:he.directory}),Q=await ne.next();if(await ne.return(),Q.value)return}let q=Ee.up({targets:H,start:Je.dirname(L),stop:he.directory}),X=await q.next();return await q.return(),X.value?Je.dirname(X.value):he.directory},"NearestRoot");ue.Deno={id:"deno",root:n(async H=>{let R=Ee.up({targets:["deno.json","deno.jsonc"],start:Je.dirname(H),stop:he.directory}),L=await R.next();if(await R.return(),!!L.value)return Je.dirname(L.value)},"root"),extensions:[".ts",".tsx",".js",".jsx",".mjs"],async spawn(H){let R=Be("deno");if(!R){e.info("deno not found, please install deno first");return}return{process:ht(R,["lsp"],{cwd:H})}}},ue.Typescript={id:"typescript",root:m(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"],["deno.json","deno.jsonc"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],async spawn(H){let R=Qr.resolve("typescript/lib/tsserver.js",he.directory);if(e.info("typescript server",{tsserver:R}),!R)return;let L=await an.which("typescript-language-server");if(!L)return;let q=["--stdio","--tsserver-log-verbosity","off","--tsserver-path",R];return!await t(Je.join(H,"tsconfig.json"))&&!await t(Je.join(H,"jsconfig.json"))&&q.push("--ignore-node-modules"),{process:ht(L,q,{cwd:H,env:{...process.env}}),initialization:{tsserver:{path:R}}}}},ue.Vue={id:"vue",extensions:[".vue"],root:m(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(H){let R=Be("vue-language-server"),L=[];if(!R){if(Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;let X=await an.which("@vue/language-server");if(!X)return;R=X}return L.push("--stdio"),{process:ht(R,L,{cwd:H,env:{...process.env}}),initialization:{}}}},ue.ESLint={id:"eslint",root:m(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue"],async spawn(H){if(!Qr.resolve("eslint",he.directory))return;e.info("spawning eslint server");let L=Je.join(je.Path.bin,"vscode-eslint","server","out","eslintServer.js");if(!await Ee.exists(L)){if(Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;e.info("downloading and building VS Code ESLint server");let X=await fetch("https://github.com/microsoft/vscode-eslint/archive/refs/heads/main.zip");if(!X.ok)return;let ne=Je.join(je.Path.bin,"vscode-eslint.zip");if(X.body&&await Ee.writeStream(ne,X.body),!await To.extractZip(ne,je.Path.bin).then(()=>!0).catch(Oe=>(e.error("Failed to extract vscode-eslint archive",{error:Oe}),!1)))return;await jt.rm(ne,{force:!0});let oe=Je.join(je.Path.bin,"vscode-eslint-main"),ce=Je.join(je.Path.bin,"vscode-eslint");await jt.stat(ce).catch(()=>{})&&(e.info("removing old eslint installation",{path:ce}),await jt.rm(ce,{force:!0,recursive:!0})),await jt.rename(oe,ce);let De=process.platform==="win32"?"npm.cmd":"npm";await St.run([De,"install"],{cwd:ce}),await St.run([De,"run","compile"],{cwd:ce}),e.info("installed VS Code ESLint server",{serverPath:L})}return{process:ht("node",[L,"--stdio"],{cwd:H,env:{...process.env}})}}},ue.Oxlint={id:"oxlint",root:m([".oxlintrc.json","package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock","package.json"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue",".astro",".svelte"],async spawn(H){let R=process.platform==="win32"?".cmd":"",L=Je.join("node_modules",".bin","oxc_language_server"+R),q=Je.join("node_modules",".bin","oxlint"+R),X=n(async oe=>{let ce=Je.join(H,oe);if(await Ee.exists(ce))return ce;let pe=Ee.up({targets:[oe],start:H,stop:he.worktree}),De=await pe.next();if(await pe.return(),De.value)return De.value},"resolveBin"),ne=await X(q);if(!ne){let oe=Be("oxlint");oe&&(ne=oe)}if(ne){let oe=ht(ne,["--help"]);if(await oe.exited,oe.stdout&&(await sg(oe.stdout)).includes("--lsp"))return{process:ht(ne,["--lsp"],{cwd:H})}}let Q=await X(L);if(!Q){let oe=Be("oxc_language_server");oe&&(Q=oe)}if(Q)return{process:ht(Q,[],{cwd:H})};e.info("oxlint not found, please install oxlint")}},ue.Biome={id:"biome",root:m(["biome.json","biome.jsonc","package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".json",".jsonc",".vue",".astro",".svelte",".css",".graphql",".gql",".html"],async spawn(H){let R=Je.join(H,"node_modules",".bin","biome"),L;if(await Ee.exists(R)&&(L=R),!L){let ne=Be("biome");ne&&(L=ne)}let q=["lsp-proxy","--stdio"];if(!L){if(!Qr.resolve("biome",H)||(L=await an.which("biome"),!L))return;q=["lsp-proxy","--stdio"]}return{process:ht(L,q,{cwd:H,env:{...process.env}})}}},ue.Gopls={id:"gopls",root:n(async H=>{let R=await m(["go.work"])(H);return R||m(["go.mod","go.sum"])(H)},"root"),extensions:[".go"],async spawn(H){let R=Be("gopls");if(!R){if(!Be("go")||Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;if(e.info("installing gopls"),await St.spawn(["go","install","golang.org/x/tools/gopls@latest"],{env:{...process.env,GOBIN:je.Path.bin},stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0){e.error("Failed to install gopls");return}R=Je.join(je.Path.bin,"gopls"+(process.platform==="win32"?".exe":"")),e.info("installed gopls",{bin:R})}return{process:ht(R,{cwd:H})}}},ue.Rubocop={id:"ruby-lsp",root:m(["Gemfile"]),extensions:[".rb",".rake",".gemspec",".ru"],async spawn(H){let R=Be("rubocop");if(!R){let L=Be("ruby"),q=Be("gem");if(!L||!q){e.info("Ruby not found, please install Ruby first");return}if(Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;if(e.info("installing rubocop"),await St.spawn(["gem","install","rubocop","--bindir",je.Path.bin],{stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0){e.error("Failed to install rubocop");return}R=Je.join(je.Path.bin,"rubocop"+(process.platform==="win32"?".exe":"")),e.info("installed rubocop",{bin:R})}return{process:ht(R,["--lsp"],{cwd:H})}}},ue.Ty={id:"ty",extensions:[".py",".pyi"],root:m(["pyproject.toml","ty.toml","setup.py","setup.cfg","requirements.txt","Pipfile","pyrightconfig.json"]),async spawn(H){if(!Ce.OPENCODE_EXPERIMENTAL_LSP_TY)return;let R=Be("ty"),L={},q=[process.env.VIRTUAL_ENV,Je.join(H,".venv"),Je.join(H,"venv")].filter(ne=>ne!==void 0);for(let ne of q){let oe=process.platform==="win32"?Je.join(ne,"Scripts","python.exe"):Je.join(ne,"bin","python");if(await Ee.exists(oe)){L.pythonPath=oe;break}}if(!R)for(let ne of q){let oe=process.platform==="win32"?Je.join(ne,"Scripts","ty.exe"):Je.join(ne,"bin","ty");if(await Ee.exists(oe)){R=oe;break}}if(!R){e.error("ty not found, please install ty first");return}return{process:ht(R,["server"],{cwd:H}),initialization:L}}},ue.Pyright={id:"pyright",extensions:[".py",".pyi"],root:m(["pyproject.toml","setup.py","setup.cfg","requirements.txt","Pipfile","pyrightconfig.json"]),async spawn(H){let R=Be("pyright-langserver"),L=[];if(!R){if(Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;let Q=await an.which("pyright");if(!Q)return;R=Q}L.push("--stdio");let q={},X=[process.env.VIRTUAL_ENV,Je.join(H,".venv"),Je.join(H,"venv")].filter(Q=>Q!==void 0);for(let Q of X){let ce=process.platform==="win32"?Je.join(Q,"Scripts","python.exe"):Je.join(Q,"bin","python");if(await Ee.exists(ce)){q.pythonPath=ce;break}}return{process:ht(R,L,{cwd:H,env:{...process.env}}),initialization:q}}},ue.ElixirLS={id:"elixir-ls",extensions:[".ex",".exs"],root:m(["mix.exs","mix.lock"]),async spawn(H){let R=Be("elixir-ls");if(!R){let L=Je.join(je.Path.bin,"elixir-ls");if(R=Je.join(je.Path.bin,"elixir-ls-master","release",process.platform==="win32"?"language_server.bat":"language_server.sh"),!await Ee.exists(R)){if(!Be("elixir")){e.error("elixir is required to run elixir-ls");return}if(Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;e.info("downloading elixir-ls from GitHub releases");let X=await fetch("https://github.com/elixir-lsp/elixir-ls/archive/refs/heads/master.zip");if(!X.ok)return;let ne=Je.join(je.Path.bin,"elixir-ls.zip");if(X.body&&await Ee.writeStream(ne,X.body),!await To.extractZip(ne,je.Path.bin).then(()=>!0).catch(pe=>(e.error("Failed to extract elixir-ls archive",{error:pe}),!1)))return;await jt.rm(ne,{force:!0,recursive:!0});let oe=Je.join(je.Path.bin,"elixir-ls-master"),ce={MIX_ENV:"prod",...process.env};await St.run(["mix","deps.get"],{cwd:oe,env:ce}),await St.run(["mix","compile"],{cwd:oe,env:ce}),await St.run(["mix","elixir_ls.release2","-o","release"],{cwd:oe,env:ce}),e.info("installed elixir-ls",{path:L})}}return{process:ht(R,{cwd:H})}}},ue.Zls={id:"zls",extensions:[".zig",".zon"],root:m(["build.zig"]),async spawn(H){let R=Be("zls");if(!R){if(!Be("zig")){e.error("Zig is required to use zls. Please install Zig first.");return}if(Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;e.info("downloading zls from GitHub releases");let q=await fetch("https://api.github.com/repos/zigtools/zls/releases/latest");if(!q.ok){e.error("Failed to fetch zls release info");return}let X=await q.json(),ne=process.platform,Q=process.arch,oe="",ce=Q;Q==="arm64"?ce="aarch64":Q==="x64"?ce="x86_64":Q==="ia32"&&(ce="x86");let pe=ne;ne==="darwin"?pe="macos":ne==="win32"&&(pe="windows");let De=ne==="win32"?"zip":"tar.xz";if(oe=`zls-${ce}-${pe}.${De}`,!["zls-x86_64-linux.tar.xz","zls-x86_64-macos.tar.xz","zls-x86_64-windows.zip","zls-aarch64-linux.tar.xz","zls-aarch64-macos.tar.xz","zls-aarch64-windows.zip","zls-x86-linux.tar.xz","zls-x86-windows.zip"].includes(oe)){e.error(`Platform ${ne} and architecture ${Q} is not supported by zls`);return}let xe=X.assets.find(ve=>ve.name===oe);if(!xe){e.error(`Could not find asset ${oe} in latest zls release`);return}let ie=xe.browser_download_url,le=await fetch(ie);if(!le.ok){e.error("Failed to download zls");return}let Le=Je.join(je.Path.bin,oe);if(le.body&&await Ee.writeStream(Le,le.body),De==="zip"){if(!await To.extractZip(Le,je.Path.bin).then(()=>!0).catch(Te=>(e.error("Failed to extract zls archive",{error:Te}),!1)))return}else await o(["tar","-xf",Le],{cwd:je.Path.bin});if(await jt.rm(Le,{force:!0}),R=Je.join(je.Path.bin,"zls"+(ne==="win32"?".exe":"")),!await Ee.exists(R)){e.error("Failed to extract zls binary");return}ne!=="win32"&&await jt.chmod(R,493).catch(()=>{}),e.info("installed zls",{bin:R})}return{process:ht(R,{cwd:H})}}},ue.CSharp={id:"csharp",root:m([".slnx",".sln",".csproj","global.json"]),extensions:[".cs"],async spawn(H){let R=Be("csharp-ls");if(!R){if(!Be("dotnet")){e.error(".NET SDK is required to install csharp-ls");return}if(Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;if(e.info("installing csharp-ls via dotnet tool"),await St.spawn(["dotnet","tool","install","csharp-ls","--tool-path",je.Path.bin],{stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0){e.error("Failed to install csharp-ls");return}R=Je.join(je.Path.bin,"csharp-ls"+(process.platform==="win32"?".exe":"")),e.info("installed csharp-ls",{bin:R})}return{process:ht(R,{cwd:H})}}},ue.FSharp={id:"fsharp",root:m([".slnx",".sln",".fsproj","global.json"]),extensions:[".fs",".fsi",".fsx",".fsscript"],async spawn(H){let R=Be("fsautocomplete");if(!R){if(!Be("dotnet")){e.error(".NET SDK is required to install fsautocomplete");return}if(Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;if(e.info("installing fsautocomplete via dotnet tool"),await St.spawn(["dotnet","tool","install","fsautocomplete","--tool-path",je.Path.bin],{stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0){e.error("Failed to install fsautocomplete");return}R=Je.join(je.Path.bin,"fsautocomplete"+(process.platform==="win32"?".exe":"")),e.info("installed fsautocomplete",{bin:R})}return{process:ht(R,{cwd:H})}}},ue.SourceKit={id:"sourcekit-lsp",extensions:[".swift",".objc","objcpp"],root:m(["Package.swift","*.xcodeproj","*.xcworkspace"]),async spawn(H){let R=Be("sourcekit-lsp");if(R)return{process:ht(R,{cwd:H})};if(!Be("xcrun"))return;let L=await i(["xcrun","--find","sourcekit-lsp"]);if(L.code!==0)return;let q=L.text.trim();return{process:ht(q,{cwd:H})}}},ue.RustAnalyzer={id:"rust",root:n(async H=>{let R=await m(["Cargo.toml","Cargo.lock"])(H);if(R===void 0)return;let L=R;for(;L!==Je.dirname(L);){let q=Je.join(L,"Cargo.toml");try{if((await Ee.readText(q)).includes("[workspace]"))return L}catch{}let X=Je.dirname(L);if(X===L||(L=X,!L.startsWith(he.worktree)))break}return R},"root"),extensions:[".rs"],async spawn(H){let R=Be("rust-analyzer");if(!R){e.info("rust-analyzer not found in path, please install it");return}return{process:ht(R,{cwd:H})}}},ue.Clangd={id:"clangd",root:m(["compile_commands.json","compile_flags.txt",".clangd","CMakeLists.txt","Makefile"]),extensions:[".c",".cpp",".cc",".cxx",".c++",".h",".hpp",".hh",".hxx",".h++"],async spawn(H){let R=["--background-index","--clang-tidy"],L=Be("clangd");if(L)return{process:ht(L,R,{cwd:H})};let q=process.platform==="win32"?".exe":"",X=Je.join(je.Path.bin,"clangd"+q);if(await Ee.exists(X))return{process:ht(X,R,{cwd:H})};let ne=await jt.readdir(je.Path.bin,{withFileTypes:!0}).catch(()=>[]);for(let ae of ne){if(!ae.isDirectory()||!ae.name.startsWith("clangd_"))continue;let me=Je.join(je.Path.bin,ae.name,"bin","clangd"+q);if(await Ee.exists(me))return{process:ht(me,R,{cwd:H})}}if(Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;e.info("downloading clangd from GitHub releases");let Q=await fetch("https://api.github.com/repos/clangd/clangd/releases/latest");if(!Q.ok){e.error("Failed to fetch clangd release info");return}let oe=await Q.json(),ce=oe.tag_name;if(!ce){e.error("clangd release did not include a tag name");return}let pe=process.platform,Oe={darwin:"mac",linux:"linux",win32:"windows"}[pe];if(!Oe){e.error(`Platform ${pe} is not supported by clangd auto-download`);return}let xe=oe.assets??[],ie=n(ae=>!ae.name||!ae.browser_download_url||!ae.name.includes(Oe)?!1:ae.name.includes(ce),"valid"),le=xe.find(ae=>ie(ae)&&ae.name?.endsWith(".zip"))??xe.find(ae=>ie(ae)&&ae.name?.endsWith(".tar.xz"))??xe.find(ae=>ie(ae));if(!le?.name||!le.browser_download_url){e.error("clangd could not match release asset",{tag:ce,platform:pe});return}let Le=le.name,ve=await fetch(le.browser_download_url);if(!ve.ok){e.error("Failed to download clangd");return}let Te=Je.join(je.Path.bin,Le),it=await ve.arrayBuffer();if(it.byteLength===0){e.error("Failed to write clangd archive");return}await Ee.write(Te,Buffer.from(it));let Ie=Le.endsWith(".zip"),be=Le.endsWith(".tar.xz");if(!Ie&&!be){e.error("clangd encountered unsupported asset",{asset:Le});return}if(Ie&&!await To.extractZip(Te,je.Path.bin).then(()=>!0).catch(me=>(e.error("Failed to extract clangd archive",{error:me}),!1)))return;be&&await o(["tar","-xf",Te],{cwd:je.Path.bin}),await jt.rm(Te,{force:!0});let ye=Je.join(je.Path.bin,"clangd_"+ce,"bin","clangd"+q);if(!await Ee.exists(ye)){e.error("Failed to extract clangd binary");return}return pe!=="win32"&&await jt.chmod(ye,493).catch(()=>{}),await jt.unlink(Je.join(je.Path.bin,"clangd")).catch(()=>{}),await jt.symlink(ye,Je.join(je.Path.bin,"clangd")).catch(()=>{}),e.info("installed clangd",{bin:ye}),{process:ht(ye,R,{cwd:H})}}},ue.Svelte={id:"svelte",extensions:[".svelte"],root:m(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(H){let R=Be("svelteserver"),L=[];if(!R){if(Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;let X=await an.which("svelte-language-server");if(!X)return;R=X}return L.push("--stdio"),{process:ht(R,L,{cwd:H,env:{...process.env}}),initialization:{}}}},ue.Astro={id:"astro",extensions:[".astro"],root:m(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(H){let R=Qr.resolve("typescript/lib/tsserver.js",he.directory);if(!R){e.info("typescript not found, required for Astro language server");return}let L=Je.dirname(R),q=Be("astro-ls"),X=[];if(!q){if(Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;let Q=await an.which("@astrojs/language-server");if(!Q)return;q=Q}return X.push("--stdio"),{process:ht(q,X,{cwd:H,env:{...process.env}}),initialization:{typescript:{tsdk:L}}}}},ue.JDTLS={id:"jdtls",root:n(async H=>{let R=["settings.gradle","settings.gradle.kts"],L=["gradlew","gradlew.bat"],q=L.concat(R),[X,ne,Q]=await Promise.all([m(["pom.xml","build.gradle","build.gradle.kts",".project",".classpath"],q)(H),m(L,R)(H),m(R)(H)]);if(X)return X;if(ne)return ne;if(Q)return Q},"root"),extensions:[".java"],async spawn(H){let R=Be("java");if(!R){e.error("Java 21 or newer is required to run the JDTLS. Please install it first.");return}let L=await o(["java","-version"]).then(De=>{let Oe=/"(\d+)\.\d+\.\d+"/.exec(De.stderr.toString());return Oe?parseInt(Oe[1]):void 0});if(L==null||L<21){e.error("JDTLS requires at least Java 21.");return}let q=Je.join(je.Path.bin,"jdtls"),X=Je.join(q,"plugins");if(!await t(X)){if(Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;e.info("Downloading JDTLS LSP server."),await jt.mkdir(q,{recursive:!0});let De="https://www.eclipse.org/downloads/download.php?file=/jdtls/snapshots/jdt-language-server-latest.tar.gz",Oe="release.tar.gz";e.info("Downloading JDTLS archive",{url:De,dest:q});let xe=await fetch(De);if(!xe.ok||!xe.body){e.error("Failed to download JDTLS",{status:xe.status,statusText:xe.statusText});return}await Ee.writeStream(Je.join(q,Oe),xe.body),e.info("Extracting JDTLS archive");let ie=await o(["tar","-xzf",Oe],{cwd:q});if(ie.code!==0){e.error("Failed to extract JDTLS",{exitCode:ie.code,stderr:ie.stderr.toString()});return}await jt.rm(Je.join(q,Oe),{force:!0}),e.info("JDTLS download and extraction completed")}let Q=(await jt.readdir(X).catch(()=>[])).find(De=>/^org\.eclipse\.equinox\.launcher_.*\.jar$/.test(De))?.trim()??"",oe=Je.join(X,Q);if(!await t(oe)){e.error(`Failed to locate the JDTLS launcher module in the installed directory: ${q}.`);return}let ce=Je.join(q,(()=>{switch(process.platform){case"darwin":return"config_mac";case"linux":return"config_linux";case"win32":return"config_win";default:return"config_linux"}})()),pe=await jt.mkdtemp(Je.join(rg.tmpdir(),"opencode-jdtls-data"));return{process:ht(R,["-jar",oe,"-configuration",ce,"-data",pe,"-Declipse.application=org.eclipse.jdt.ls.core.id1","-Dosgi.bundles.defaultStartLevel=4","-Declipse.product=org.eclipse.jdt.ls.core.product","-Dlog.level=ALL","--add-modules=ALL-SYSTEM","--add-opens java.base/java.util=ALL-UNNAMED","--add-opens java.base/java.lang=ALL-UNNAMED"],{cwd:H})}}},ue.KotlinLS={id:"kotlin-ls",extensions:[".kt",".kts"],root:n(async H=>{let R=await m(["settings.gradle.kts","settings.gradle"])(H);if(R)return R;let L=await m(["gradlew","gradlew.bat"])(H);if(L)return L;let q=await m(["build.gradle.kts","build.gradle"])(H);return q||m(["pom.xml"])(H)},"root"),async spawn(H){let R=Je.join(je.Path.bin,"kotlin-ls"),L=process.platform==="win32"?Je.join(R,"kotlin-lsp.cmd"):Je.join(R,"kotlin-lsp.sh");if(!await Ee.exists(L)){if(Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;e.info("Downloading Kotlin Language Server from GitHub.");let X=await fetch("https://api.github.com/repos/Kotlin/kotlin-lsp/releases/latest");if(!X.ok){e.error("Failed to fetch kotlin-lsp release info");return}let Q=(await X.json()).name?.replace(/^v/,"");if(!Q){e.error("Could not determine Kotlin LSP version from release");return}let oe=process.platform,ce=process.arch,pe=ce;ce==="arm64"?pe="aarch64":ce==="x64"&&(pe="x64");let De=oe;oe==="darwin"?De="mac":oe==="linux"?De="linux":oe==="win32"&&(De="win");let Oe=["mac-x64","mac-aarch64","linux-x64","linux-aarch64","win-x64","win-aarch64"],xe=`${De}-${pe}`;if(!Oe.includes(xe)){e.error(`Platform ${oe}/${ce} is not supported by Kotlin LSP`);return}let ie=`kotlin-lsp-${Q}-${De}-${pe}.zip`,le=`https://download-cdn.jetbrains.com/kotlin-lsp/${Q}/${ie}`;await jt.mkdir(R,{recursive:!0});let Le=Je.join(R,"kotlin-ls.zip"),ve=await fetch(le);if(!ve.ok||!ve.body){e.error("Failed to download Kotlin Language Server",{status:ve.status,statusText:ve.statusText});return}if(await Ee.writeStream(Le,ve.body),!await To.extractZip(Le,R).then(()=>!0).catch(it=>(e.error("Failed to extract Kotlin LS archive",{error:it}),!1)))return;await jt.rm(Le,{force:!0}),process.platform!=="win32"&&await jt.chmod(L,493).catch(()=>{}),e.info("Installed Kotlin Language Server",{path:L})}if(!await Ee.exists(L)){e.error(`Failed to locate the Kotlin LS launcher script in the installed directory: ${R}.`);return}return{process:ht(L,["--stdio"],{cwd:H})}}},ue.YamlLS={id:"yaml-ls",extensions:[".yaml",".yml"],root:m(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(H){let R=Be("yaml-language-server"),L=[];if(!R){if(Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;let X=await an.which("yaml-language-server");if(!X)return;R=X}return L.push("--stdio"),{process:ht(R,L,{cwd:H,env:{...process.env}})}}},ue.LuaLS={id:"lua-ls",root:m([".luarc.json",".luarc.jsonc",".luacheckrc",".stylua.toml","stylua.toml","selene.toml","selene.yml"]),extensions:[".lua"],async spawn(H){let R=Be("lua-language-server");if(!R){if(Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;e.info("downloading lua-language-server from GitHub releases");let L=await fetch("https://api.github.com/repos/LuaLS/lua-language-server/releases/latest");if(!L.ok){e.error("Failed to fetch lua-language-server release info");return}let q=await L.json(),X=process.platform,ne=process.arch,Q="",oe=ne;ne==="arm64"?oe="arm64":ne==="x64"?oe="x64":ne==="ia32"&&(oe="ia32");let ce=X;X==="darwin"?ce="darwin":X==="linux"?ce="linux":X==="win32"&&(ce="win32");let pe=X==="win32"?"zip":"tar.gz";Q=`lua-language-server-${q.tag_name}-${ce}-${oe}.${pe}`;let De=["darwin-arm64.tar.gz","darwin-x64.tar.gz","linux-x64.tar.gz","linux-arm64.tar.gz","win32-x64.zip","win32-ia32.zip"],Oe=`${ce}-${oe}.${pe}`;if(!De.includes(Oe)){e.error(`Platform ${X} and architecture ${ne} is not supported by lua-language-server`);return}let xe=q.assets.find(it=>it.name===Q);if(!xe){e.error(`Could not find asset ${Q} in latest lua-language-server release`);return}let ie=xe.browser_download_url,le=await fetch(ie);if(!le.ok){e.error("Failed to download lua-language-server");return}let Le=Je.join(je.Path.bin,Q);le.body&&await Ee.writeStream(Le,le.body);let ve=Je.join(je.Path.bin,`lua-language-server-${oe}-${ce}`);if(await jt.stat(ve).catch(()=>{})&&await jt.rm(ve,{force:!0,recursive:!0}),await jt.mkdir(ve,{recursive:!0}),pe==="zip"){if(!await To.extractZip(Le,ve).then(()=>!0).catch(Ie=>(e.error("Failed to extract lua-language-server archive",{error:Ie}),!1)))return}else if(!await o(["tar","-xzf",Le,"-C",ve]).then(Ie=>Ie.code===0).catch(Ie=>(e.error("Failed to extract lua-language-server archive",{error:Ie}),!1)))return;if(await jt.rm(Le,{force:!0}),R=Je.join(ve,"bin","lua-language-server"+(X==="win32"?".exe":"")),!await Ee.exists(R)){e.error("Failed to extract lua-language-server binary");return}if(X!=="win32"&&!await jt.chmod(R,493).then(()=>!0).catch(Ie=>(e.error("Failed to set executable permission for lua-language-server binary",{error:Ie}),!1)))return;e.info("installed lua-language-server",{bin:R})}return{process:ht(R,{cwd:H})}}},ue.PHPIntelephense={id:"php intelephense",extensions:[".php"],root:m(["composer.json","composer.lock",".php-version"]),async spawn(H){let R=Be("intelephense"),L=[];if(!R){if(Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;let X=await an.which("intelephense");if(!X)return;R=X}return L.push("--stdio"),{process:ht(R,L,{cwd:H,env:{...process.env}}),initialization:{telemetry:{enabled:!1}}}}},ue.Prisma={id:"prisma",extensions:[".prisma"],root:m(["schema.prisma","prisma/schema.prisma","prisma"],["package.json"]),async spawn(H){let R=Be("prisma");if(!R){e.info("prisma not found, please install prisma");return}return{process:ht(R,["language-server"],{cwd:H})}}},ue.Dart={id:"dart",extensions:[".dart"],root:m(["pubspec.yaml","analysis_options.yaml"]),async spawn(H){let R=Be("dart");if(!R){e.info("dart not found, please install dart first");return}return{process:ht(R,["language-server","--lsp"],{cwd:H})}}},ue.Ocaml={id:"ocaml-lsp",extensions:[".ml",".mli"],root:m(["dune-project","dune-workspace",".merlin","opam"]),async spawn(H){let R=Be("ocamllsp");if(!R){e.info("ocamllsp not found, please install ocaml-lsp-server");return}return{process:ht(R,{cwd:H})}}},ue.BashLS={id:"bash",extensions:[".sh",".bash",".zsh",".ksh"],root:n(async()=>he.directory,"root"),async spawn(H){let R=Be("bash-language-server"),L=[];if(!R){if(Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;let X=await an.which("bash-language-server");if(!X)return;R=X}return L.push("start"),{process:ht(R,L,{cwd:H,env:{...process.env}})}}},ue.TerraformLS={id:"terraform",extensions:[".tf",".tfvars"],root:m([".terraform.lock.hcl","terraform.tfstate","*.tf"]),async spawn(H){let R=Be("terraform-ls");if(!R){if(Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;e.info("downloading terraform-ls from HashiCorp releases");let L=await fetch("https://api.releases.hashicorp.com/v1/releases/terraform-ls/latest");if(!L.ok){e.error("Failed to fetch terraform-ls release info");return}let q=await L.json(),X=process.platform,Q=process.arch==="arm64"?"arm64":"amd64",oe=X==="win32"?"windows":X,pe=(q.builds??[]).find(ie=>ie.arch===Q&&ie.os===oe);if(!pe?.url){e.error(`Could not find build for ${oe}/${Q} terraform-ls release version ${q.version}`);return}let De=await fetch(pe.url);if(!De.ok){e.error("Failed to download terraform-ls");return}let Oe=Je.join(je.Path.bin,"terraform-ls.zip");if(De.body&&await Ee.writeStream(Oe,De.body),!await To.extractZip(Oe,je.Path.bin).then(()=>!0).catch(ie=>(e.error("Failed to extract terraform-ls archive",{error:ie}),!1)))return;if(await jt.rm(Oe,{force:!0}),R=Je.join(je.Path.bin,"terraform-ls"+(X==="win32"?".exe":"")),!await Ee.exists(R)){e.error("Failed to extract terraform-ls binary");return}X!=="win32"&&await jt.chmod(R,493).catch(()=>{}),e.info("installed terraform-ls",{bin:R})}return{process:ht(R,["serve"],{cwd:H}),initialization:{experimentalFeatures:{prefillRequiredFields:!0,validateOnSave:!0}}}}},ue.TexLab={id:"texlab",extensions:[".tex",".bib"],root:m([".latexmkrc","latexmkrc",".texlabroot","texlabroot"]),async spawn(H){let R=Be("texlab");if(!R){if(Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;e.info("downloading texlab from GitHub releases");let L=await fetch("https://api.github.com/repos/latex-lsp/texlab/releases/latest");if(!L.ok){e.error("Failed to fetch texlab release info");return}let q=await L.json();if(!q.tag_name?.replace("v","")){e.error("texlab release did not include a version tag");return}let ne=process.platform,oe=process.arch==="arm64"?"aarch64":"x86_64",ce=ne==="darwin"?"macos":ne==="win32"?"windows":"linux",pe=ne==="win32"?"zip":"tar.gz",De=`texlab-${oe}-${ce}.${pe}`,xe=(q.assets??[]).find(Le=>Le.name===De);if(!xe?.browser_download_url){e.error(`Could not find asset ${De} in texlab release`);return}let ie=await fetch(xe.browser_download_url);if(!ie.ok){e.error("Failed to download texlab");return}let le=Je.join(je.Path.bin,De);if(ie.body&&await Ee.writeStream(le,ie.body),pe==="zip"&&!await To.extractZip(le,je.Path.bin).then(()=>!0).catch(ve=>(e.error("Failed to extract texlab archive",{error:ve}),!1)))return;if(pe==="tar.gz"&&await o(["tar","-xzf",le],{cwd:je.Path.bin}),await jt.rm(le,{force:!0}),R=Je.join(je.Path.bin,"texlab"+(ne==="win32"?".exe":"")),!await Ee.exists(R)){e.error("Failed to extract texlab binary");return}ne!=="win32"&&await jt.chmod(R,493).catch(()=>{}),e.info("installed texlab",{bin:R})}return{process:ht(R,{cwd:H})}}},ue.DockerfileLS={id:"dockerfile",extensions:[".dockerfile","Dockerfile"],root:n(async()=>he.directory,"root"),async spawn(H){let R=Be("docker-langserver"),L=[];if(!R){if(Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;let X=await an.which("dockerfile-language-server-nodejs");if(!X)return;R=X}return L.push("--stdio"),{process:ht(R,L,{cwd:H,env:{...process.env}})}}},ue.Gleam={id:"gleam",extensions:[".gleam"],root:m(["gleam.toml"]),async spawn(H){let R=Be("gleam");if(!R){e.info("gleam not found, please install gleam first");return}return{process:ht(R,["lsp"],{cwd:H})}}},ue.Clojure={id:"clojure-lsp",extensions:[".clj",".cljs",".cljc",".edn"],root:m(["deps.edn","project.clj","shadow-cljs.edn","bb.edn","build.boot"]),async spawn(H){let R=Be("clojure-lsp");if(!R&&process.platform==="win32"&&(R=Be("clojure-lsp.exe")),!R){e.info("clojure-lsp not found, please install clojure-lsp first");return}return{process:ht(R,["listen"],{cwd:H})}}},ue.Nixd={id:"nixd",extensions:[".nix"],root:n(async H=>{let R=await m(["flake.nix"])(H);return R&&R!==he.directory?R:he.worktree&&he.worktree!==he.directory?he.worktree:he.directory},"root"),async spawn(H){let R=Be("nixd");if(!R){e.info("nixd not found, please install nixd first");return}return{process:ht(R,[],{cwd:H,env:{...process.env}})}}},ue.Tinymist={id:"tinymist",extensions:[".typ",".typc"],root:m(["typst.toml"]),async spawn(H){let R=Be("tinymist");if(!R){if(Ce.OPENCODE_DISABLE_LSP_DOWNLOAD)return;e.info("downloading tinymist from GitHub releases");let L=await fetch("https://api.github.com/repos/Myriad-Dreamin/tinymist/releases/latest");if(!L.ok){e.error("Failed to fetch tinymist release info");return}let q=await L.json(),X=process.platform,Q=process.arch==="arm64"?"aarch64":"x86_64",oe,ce;X==="darwin"?(oe="apple-darwin",ce="tar.gz"):X==="win32"?(oe="pc-windows-msvc",ce="zip"):(oe="unknown-linux-gnu",ce="tar.gz");let pe=`tinymist-${Q}-${oe}.${ce}`,Oe=(q.assets??[]).find(le=>le.name===pe);if(!Oe?.browser_download_url){e.error(`Could not find asset ${pe} in tinymist release`);return}let xe=await fetch(Oe.browser_download_url);if(!xe.ok){e.error("Failed to download tinymist");return}let ie=Je.join(je.Path.bin,pe);if(xe.body&&await Ee.writeStream(ie,xe.body),ce==="zip"){if(!await To.extractZip(ie,je.Path.bin).then(()=>!0).catch(Le=>(e.error("Failed to extract tinymist archive",{error:Le}),!1)))return}else await o(["tar","-xzf",ie,"--strip-components=1"],{cwd:je.Path.bin});if(await jt.rm(ie,{force:!0}),R=Je.join(je.Path.bin,"tinymist"+(X==="win32"?".exe":"")),!await Ee.exists(R)){e.error("Failed to extract tinymist binary");return}X!=="win32"&&await jt.chmod(R,493).catch(()=>{}),e.info("installed tinymist",{bin:R})}return{process:ht(R,{cwd:H})}}},ue.HLS={id:"haskell-language-server",extensions:[".hs",".lhs"],root:m(["stack.yaml","cabal.project","hie.yaml","*.cabal"]),async spawn(H){let R=Be("haskell-language-server-wrapper");if(!R){e.info("haskell-language-server-wrapper not found, please install haskell-language-server");return}return{process:ht(R,["--lsp"],{cwd:H})}}},ue.JuliaLS={id:"julials",extensions:[".jl"],root:m(["Project.toml","Manifest.toml","*.jl"]),async spawn(H){let R=Be("julia");if(!R){e.info("julia not found, please install julia first (https://julialang.org/downloads/)");return}return{process:ht(R,["--startup-file=no","--history-file=no","-e","using LanguageServer; runserver()"],{cwd:H})}}}})($s||={});import Mi from"gray-matter";import{z as Za}from"zod";var Un;(b=>{b.FILE_REGEX=/(?<![\w`])@(\.?[^\s`,.]*(?:\.[^\s`,.]+)*)/g,b.SHELL_REGEX=/!`([^`]+)`/g;function o(d){return Array.from(d.matchAll(b.FILE_REGEX))}b.files=o,n(o,"files");function i(d){return Array.from(d.matchAll(b.SHELL_REGEX))}b.shell=i,n(i,"shell");function m(d){let s=d.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!s)return d;let c=s[1],l=c.split(/\r?\n/),g=[];for(let a of l){if(a.trim().startsWith("#")||a.trim()===""){g.push(a);continue}if(a.match(/^\s+/)){g.push(a);continue}let w=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*:\s*(.*)$/);if(!w){g.push(a);continue}let I=w[1],r=w[2].trim();if(r===""||r===">"||r==="|"||r.startsWith('"')||r.startsWith("'")){g.push(a);continue}if(r.includes(":")){g.push(`${I}: |-`),g.push(` ${r}`);continue}g.push(a)}let u=g.join(`
|
|
27
|
+
`);return d.replace(c,()=>u)}b.fallbackSanitization=m,n(m,"fallbackSanitization");async function y(d){let s=await Ee.readText(d);try{return Mi(s)}catch{try{return Mi(m(s))}catch(c){throw new b.FrontmatterError({path:d,message:`${d}: Failed to parse YAML frontmatter: ${c instanceof Error?c.message:String(c)}`},{cause:c})}}}b.parse=y,n(y,"parse");function p(d,s){try{return Mi(d)}catch{try{return Mi(m(d))}catch(c){throw new b.FrontmatterError({path:s,message:`${s}: Failed to parse YAML frontmatter: ${c instanceof Error?c.message:String(c)}`},{cause:c})}}}b.parseText=p,n(p,"parseText"),b.FrontmatterError=tt.create("ConfigFrontmatterError",Za.object({path:Za.string(),message:Za.string()}))})(Un||={});import{constants as Ng,existsSync as Zi}from"fs";import dd from"zod";var ud={Connected:mt.define("server.connected",dd.object({})),Disposed:mt.define("global.disposed",dd.object({}))};import{Cache as fd,Clock as Ui,Duration as Cr,Effect as Qt,Layer as tc,Option as cn,Schema as Bt,SchemaGetter as md,ServiceMap as ug}from"effect";import{FetchHttpClient as pg,HttpClient as nc,HttpClientRequest as vn,HttpClientResponse as Ar}from"effect/unstable/http";import{eq as as}from"drizzle-orm";import{Effect as Rn,Layer as cg,Option as Vs,Schema as lg,ServiceMap as dg}from"effect";import{sqliteTable as Qa,text as Po,integer as Li,primaryKey as ig}from"drizzle-orm/sqlite-core";var eo=Qa("account",{id:Po().$type().primaryKey(),email:Po().notNull(),url:Po().notNull(),access_token:Po().$type().notNull(),refresh_token:Po().$type().notNull(),token_expiry:Li(),...Ha}),_r=Qa("account_state",{id:Li().primaryKey(),active_account_id:Po().$type().references(()=>eo.id,{onDelete:"set null"}),active_org_id:Po().$type()}),PS=Qa("control_account",{email:Po().notNull(),url:Po().notNull(),access_token:Po().$type().notNull(),refresh_token:Po().$type().notNull(),token_expiry:Li(),active:Li({mode:"boolean"}).notNull().$default(()=>!1),...Ha},e=>[ig({columns:[e.email,e.url]})]);import{Schema as vt}from"effect";var Ni=vt.String.pipe(vt.brand("AccountID"),An(e=>({make:n(t=>e.makeUnsafe(t),"make")}))),ec=vt.String.pipe(vt.brand("OrgID"),An(e=>({make:n(t=>e.makeUnsafe(t),"make")}))),zi=vt.String.pipe(vt.brand("AccessToken"),An(e=>({make:n(t=>e.makeUnsafe(t),"make")}))),Hs=vt.String.pipe(vt.brand("RefreshToken"),An(e=>({make:n(t=>e.makeUnsafe(t),"make")}))),Gs=vt.String.pipe(vt.brand("DeviceCode"),An(e=>({make:n(t=>e.makeUnsafe(t),"make")}))),Fi=vt.String.pipe(vt.brand("UserCode"),An(e=>({make:n(t=>e.makeUnsafe(t),"make")}))),qs=class extends vt.Class("Account")({id:Ni,email:vt.String,url:vt.String,active_org_id:vt.NullOr(ec)}){static{n(this,"Info")}},Bs=class extends vt.Class("Org")({id:ec,name:vt.String}){static{n(this,"Org")}},es=class extends vt.TaggedErrorClass()("AccountRepoError",{message:vt.String,cause:vt.optional(vt.Defect)}){static{n(this,"AccountRepoError")}},Or=class extends vt.TaggedErrorClass()("AccountServiceError",{message:vt.String,cause:vt.optional(vt.Defect)}){static{n(this,"AccountServiceError")}},Ws=class extends vt.Class("Login")({code:Gs,user:Fi,url:vt.String,server:vt.String,expiry:vt.Duration,interval:vt.Duration}){static{n(this,"Login")}},ts=class extends vt.TaggedClass()("PollSuccess",{email:vt.String}){static{n(this,"PollSuccess")}},ns=class extends vt.TaggedClass()("PollPending",{}){static{n(this,"PollPending")}},os=class extends vt.TaggedClass()("PollSlow",{}){static{n(this,"PollSlow")}},rs=class extends vt.TaggedClass()("PollExpired",{}){static{n(this,"PollExpired")}},ss=class extends vt.TaggedClass()("PollDenied",{}){static{n(this,"PollDenied")}},is=class extends vt.TaggedClass()("PollError",{cause:vt.Defect}){static{n(this,"PollError")}},ag=vt.Union([ts,ns,os,rs,ss,is]);var pd=1,Js=class e extends dg.Service()("@opencode/AccountRepo"){static{n(this,"AccountRepo")}static layer=cg.effect(e,Rn.gen(function*(){let t=lg.decodeUnknownSync(qs),o=n(g=>Rn.try({try:n(()=>Xt.use(g),"try"),catch:n(u=>new es({message:"Database operation failed",cause:u}),"catch")}),"query"),i=n(g=>Rn.try({try:n(()=>Xt.transaction(g),"try"),catch:n(u=>new es({message:"Database operation failed",cause:u}),"catch")}),"tx"),m=n(g=>{let u=g.select().from(_r).where(as(_r.id,pd)).get();if(!u?.active_account_id)return;let a=g.select().from(eo).where(as(eo.id,u.active_account_id)).get();if(a)return{...a,active_org_id:u.active_org_id??null}},"current"),y=n((g,u,a)=>{let w=Vs.getOrNull(a);return g.insert(_r).values({id:pd,active_account_id:u,active_org_id:w}).onConflictDoUpdate({target:_r.id,set:{active_account_id:u,active_org_id:w}}).run()},"state"),p=Rn.fn("AccountRepo.active")(()=>o(g=>m(g)).pipe(Rn.map(g=>g?Vs.some(t(g)):Vs.none()))),f=Rn.fn("AccountRepo.list")(()=>o(g=>g.select().from(eo).all().map(u=>t({...u,active_org_id:null})))),b=Rn.fn("AccountRepo.remove")(g=>i(u=>{u.update(_r).set({active_account_id:null,active_org_id:null}).where(as(_r.active_account_id,g)).run(),u.delete(eo).where(as(eo.id,g)).run()}).pipe(Rn.asVoid)),d=Rn.fn("AccountRepo.use")((g,u)=>o(a=>y(a,g,u)).pipe(Rn.asVoid)),s=Rn.fn("AccountRepo.getRow")(g=>o(u=>u.select().from(eo).where(as(eo.id,g)).get()).pipe(Rn.map(Vs.fromNullishOr))),c=Rn.fn("AccountRepo.persistToken")(g=>o(u=>u.update(eo).set({access_token:g.accessToken,refresh_token:g.refreshToken,token_expiry:Vs.getOrNull(g.expiry)}).where(as(eo.id,g.accountID)).run()).pipe(Rn.asVoid)),l=Rn.fn("AccountRepo.persistAccount")(g=>i(u=>{u.insert(eo).values({id:g.id,email:g.email,url:g.url,access_token:g.accessToken,refresh_token:g.refreshToken,token_expiry:g.expiry}).onConflictDoUpdate({target:eo.id,set:{email:g.email,url:g.url,access_token:g.accessToken,refresh_token:g.refreshToken,token_expiry:g.expiry}}).run(),y(u,g.id,g.orgID)}).pipe(Rn.asVoid));return e.of({active:p,list:f,remove:b,use:d,getRow:s,persistToken:c,persistAccount:l})}))};var rc=class extends Bt.Class("RemoteConfig")({config:Bt.Record(Bt.String,Bt.Json)}){static{n(this,"RemoteConfig")}},$i=Bt.Number.pipe(Bt.decodeTo(Bt.Duration,{decode:md.transform(e=>Cr.seconds(e)),encode:md.transform(e=>Cr.toSeconds(e))})),sc=class extends Bt.Class("TokenRefresh")({access_token:zi,refresh_token:Hs,expires_in:$i}){static{n(this,"TokenRefresh")}},ic=class extends Bt.Class("DeviceAuth")({device_code:Gs,user_code:Fi,verification_uri_complete:Bt.String,expires_in:$i,interval:$i}){static{n(this,"DeviceAuth")}},ac=class extends Bt.Class("DeviceTokenSuccess")({access_token:zi,refresh_token:Hs,token_type:Bt.Literal("Bearer"),expires_in:$i}){static{n(this,"DeviceTokenSuccess")}},qi=class extends Bt.Class("DeviceTokenError")({error:Bt.String,error_description:Bt.String}){static{n(this,"DeviceTokenError")}toPollResult(){return this.error==="authorization_pending"?new ns:this.error==="slow_down"?new os:this.error==="expired_token"?new rs:this.error==="access_denied"?new ss:new is({cause:this.error})}},fg=Bt.Union([ac,qi]),cc=class extends Bt.Class("User")({id:Ni,email:Bt.String}){static{n(this,"User")}},Bi=class extends Bt.Class("ClientId")({client_id:Bt.String}){static{n(this,"ClientId")}},Wi=class extends Bt.Class("DeviceTokenRequest")({grant_type:Bt.String,device_code:Gs,client_id:Bt.String}){static{n(this,"DeviceTokenRequest")}},Hi=class extends Bt.Class("TokenRefreshRequest")({grant_type:Bt.String,refresh_token:Hs,client_id:Bt.String}){static{n(this,"TokenRefreshRequest")}},oc="opencode-cli",mg=Cr.minutes(5),gg=Cr.toMillis(mg),gd=n((e,t)=>e!=null&&e>t+gg,"isTokenFresh"),_o=n((e="Account service operation failed")=>t=>t.pipe(Qt.mapError(o=>o instanceof Or?o:new Or({message:e,cause:o}))),"mapAccountServiceError"),Gi;(c=>{class e extends ug.Service()("@opencode/Account"){static{n(this,"Service")}}c.Service=e,c.layer=tc.effect(e,Qt.gen(function*(){let l=yield*Js,g=yield*nc.HttpClient,u=sr(g),a=nc.filterStatusOk(g),w=nc.filterStatusOk(u),I=n(T=>u.execute(T).pipe(_o("HTTP request failed")),"executeRead"),r=n(T=>w.execute(T).pipe(_o("HTTP request failed")),"executeReadOk"),x=n(T=>T.pipe(Qt.flatMap(G=>a.execute(G)),_o("HTTP request failed")),"executeEffectOk"),h=n(T=>T.pipe(Qt.flatMap(G=>g.execute(G)),_o("HTTP request failed")),"executeEffect"),v=Qt.fnUntraced(function*(T){let G=yield*Ui.currentTimeMillis,N=yield*x(vn.post(`${T.url}/auth/device/token`).pipe(vn.acceptJson,vn.schemaBodyJson(Hi)(new Hi({grant_type:"refresh_token",refresh_token:T.refresh_token,client_id:oc})))),A=yield*Ar.schemaBodyJson(sc)(N).pipe(_o("Failed to decode response")),F=cn.some(G+Cr.toMillis(A.expires_in));return yield*l.persistToken({accountID:T.id,accessToken:A.access_token,refreshToken:A.refresh_token,expiry:F}),A.access_token}),S=yield*fd.make({capacity:Number.POSITIVE_INFINITY,timeToLive:Cr.zero,lookup:Qt.fnUntraced(function*(T){let G=yield*l.getRow(T);if(cn.isNone(G))return yield*Qt.fail(new Or({message:"Account not found during token refresh"}));let N=G.value,A=yield*Ui.currentTimeMillis;return gd(N.token_expiry,A)?N.access_token:yield*v(N)})}),j=Qt.fnUntraced(function*(T){let G=yield*Ui.currentTimeMillis;return gd(T.token_expiry,G)?T.access_token:yield*fd.get(S,T.id)}),O=Qt.fnUntraced(function*(T){let G=yield*l.getRow(T);if(cn.isNone(G))return cn.none();let N=G.value,A=yield*j(N);return cn.some({account:N,accessToken:A})}),k=Qt.fnUntraced(function*(T,G){let N=yield*r(vn.get(`${T}/api/orgs`).pipe(vn.acceptJson,vn.bearerToken(G)));return yield*Ar.schemaBodyJson(Bt.Array(Bs))(N).pipe(_o("Failed to decode response"))}),E=Qt.fnUntraced(function*(T,G){let N=yield*r(vn.get(`${T}/api/user`).pipe(vn.acceptJson,vn.bearerToken(G)));return yield*Ar.schemaBodyJson(cc)(N).pipe(_o("Failed to decode response"))}),D=Qt.fn("Account.token")(T=>O(T).pipe(Qt.map(cn.map(G=>G.accessToken)))),z=Qt.fn("Account.activeOrg")(function*(){let T=yield*l.active();if(cn.isNone(T))return cn.none();let G=T.value;if(!G.active_org_id)return cn.none();let A=(yield*B(G.id)).find(F=>F.id===G.active_org_id);return A?cn.some({account:G,org:A}):cn.none()}),_=Qt.fn("Account.orgsByAccount")(function*(){let T=yield*l.list();return yield*Qt.forEach(T,G=>B(G.id).pipe(Qt.catch(()=>Qt.succeed([])),Qt.map(N=>({account:G,orgs:N}))),{concurrency:3})}),B=Qt.fn("Account.orgs")(function*(T){let G=yield*O(T);if(cn.isNone(G))return[];let{account:N,accessToken:A}=G.value;return yield*k(N.url,A)}),$=Qt.fn("Account.config")(function*(T,G){let N=yield*O(T);if(cn.isNone(N))return cn.none();let{account:A,accessToken:F}=N.value,V=yield*I(vn.get(`${A.url}/api/config`).pipe(vn.acceptJson,vn.bearerToken(F),vn.setHeaders({"x-org-id":G})));if(V.status===404)return cn.none();let Y=yield*Ar.filterStatusOk(V).pipe(_o()),re=yield*Ar.schemaBodyJson(rc)(Y).pipe(_o("Failed to decode response"));return cn.some(re.config)}),M=Qt.fn("Account.login")(function*(T){let G=yield*x(vn.post(`${T}/auth/device/code`).pipe(vn.acceptJson,vn.schemaBodyJson(Bi)(new Bi({client_id:oc})))),N=yield*Ar.schemaBodyJson(ic)(G).pipe(_o("Failed to decode response"));return new Ws({code:N.device_code,user:N.user_code,url:`${T}${N.verification_uri_complete}`,server:T,expiry:N.expires_in,interval:N.interval})}),C=Qt.fn("Account.poll")(function*(T){let G=yield*h(vn.post(`${T.server}/auth/device/token`).pipe(vn.acceptJson,vn.schemaBodyJson(Wi)(new Wi({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:T.code,client_id:oc})))),N=yield*Ar.schemaBodyJson(fg)(G).pipe(_o("Failed to decode response"));if(N instanceof qi)return N.toPollResult();let A=N.access_token,F=E(T.server,A),V=k(T.server,A),[Y,re]=yield*Qt.all([F,V],{concurrency:2}),ue=re.length>0?cn.some(re[0].id):cn.none(),R=(yield*Ui.currentTimeMillis)+Cr.toMillis(N.expires_in),L=N.refresh_token;return yield*l.persistAccount({id:Y.id,email:Y.email,url:T.server,accessToken:A,refreshToken:L,expiry:R,orgID:ue}),new ts({email:Y.email})});return e.of({active:l.active,activeOrg:z,list:l.list,orgsByAccount:_,remove:l.remove,use:l.use,orgs:B,config:$,token:D,login:M,poll:C})})),c.defaultLayer=c.layer.pipe(tc.provide(Js.layer),tc.provide(pg.layer)),{runPromise:c.runPromise}=Ke(e,c.defaultLayer);async function m(){return cn.getOrUndefined(await(0,c.runPromise)(l=>l.active()))}c.active=m,n(m,"active");async function y(){return(0,c.runPromise)(l=>l.list())}c.list=y,n(y,"list");async function p(){return cn.getOrUndefined(await(0,c.runPromise)(l=>l.activeOrg()))}c.activeOrg=p,n(p,"activeOrg");async function f(){return(0,c.runPromise)(l=>l.orgsByAccount())}c.orgsByAccount=f,n(f,"orgsByAccount");async function b(l){return(0,c.runPromise)(g=>g.orgs(l))}c.orgs=b,n(b,"orgs");async function d(l,g){return(0,c.runPromise)(u=>u.use(l,cn.some(g)))}c.switchOrg=d,n(d,"switchOrg");async function s(l){let g=await(0,c.runPromise)(u=>u.token(l));return cn.getOrUndefined(g)}c.token=s,n(s,"token")})(Gi||={});import cs from"path";import hg from"os";import Rr from"zod";import{parse as yg,printParseErrorCode as bg}from"jsonc-parser";var ls;(s=>{async function e(c,l,g){return Ee.findUp([`${c}.json`,`${c}.jsonc`],l,g,{rootFirst:!0})}s.projectFiles=e,n(e,"projectFiles");async function t(c,l){return[je.Path.config,...Ce.OPENCODE_DISABLE_PROJECT_CONFIG?[]:await Array.fromAsync(Ee.up({targets:[".opencode"],start:c,stop:l})),...await Array.fromAsync(Ee.up({targets:[".opencode"],start:je.Path.home,stop:je.Path.home})),...Ce.OPENCODE_CONFIG_DIR?[Ce.OPENCODE_CONFIG_DIR]:[]]}s.directories=t,n(t,"directories");function o(c,l){return[cs.join(c,`${l}.json`),cs.join(c,`${l}.jsonc`)]}s.fileInDirectory=o,n(o,"fileInDirectory"),s.JsonError=tt.create("ConfigJsonError",Rr.object({path:Rr.string(),message:Rr.string().optional()})),s.InvalidError=tt.create("ConfigInvalidError",Rr.object({path:Rr.string(),issues:Rr.custom().optional(),message:Rr.string().optional()}));async function y(c){return Ee.readText(c).catch(l=>{if(l.code!=="ENOENT")throw new s.JsonError({path:c},{cause:l})})}s.readFile=y,n(y,"readFile");function p(c){return typeof c=="string"?c:c.source}n(p,"source");function f(c){return typeof c=="string"?cs.dirname(c):c.dir}n(f,"dir");async function b(c,l,g="error"){c=c.replace(/\{env:([^}]+)\}/g,(x,h)=>process.env[h]||"");let u=Array.from(c.matchAll(/\{file:[^}]+\}/g));if(!u.length)return c;let a=f(l),w=p(l),I="",r=0;for(let x of u){let h=x[0],v=x.index;I+=c.slice(r,v);let S=c.lastIndexOf(`
|
|
28
|
+
`,v-1)+1;if(c.slice(S,v).trimStart().startsWith("//")){I+=h,r=v+h.length;continue}let O=h.replace(/^\{file:/,"").replace(/\}$/,"");O.startsWith("~/")&&(O=cs.join(hg.homedir(),O.slice(2)));let k=cs.isAbsolute(O)?O:cs.resolve(a,O),E=(await Ee.readText(k).catch(D=>{if(g==="empty")return"";let z=`bad file reference: "${h}"`;throw D.code==="ENOENT"?new s.InvalidError({path:w,message:z+` ${k} does not exist`},{cause:D}):new s.InvalidError({path:w,message:z},{cause:D})})).trim();I+=JSON.stringify(E).slice(1,-1),r=v+h.length}return I+=c.slice(r),I}n(b,"substitute");async function d(c,l,g="error"){let u=p(l);c=await b(c,l,g);let a=[],w=yg(c,a,{allowTrailingComma:!0});if(a.length){let I=c.split(`
|
|
29
|
+
`),r=a.map(x=>{let h=c.substring(0,x.offset).split(`
|
|
30
|
+
`),v=h.length,S=h[h.length-1].length+1,j=I[v-1],O=`${bg(x.error)} at line ${v}, column ${S}`;return j?`${O}
|
|
31
|
+
Line ${v}: ${j}
|
|
32
|
+
${"".padStart(S+9)}^`:O}).join(`
|
|
33
|
+
`);throw new s.JsonError({path:u,message:`
|
|
34
|
+
--- JSONC Input ---
|
|
35
|
+
${c}
|
|
36
|
+
--- Errors ---
|
|
37
|
+
${r}
|
|
38
|
+
--- End ---`})}return w}s.parseText=d,n(d,"parseText")})(ls||={});import{Duration as zg,Effect as ct,Layer as Qi,Option as ea,ServiceMap as Fg}from"effect";import Mo from"path";import{fileURLToPath as Vi,pathToFileURL as ds}from"url";import wg from"npm-package-arg";import lc from"semver";var xg=["opencode-openai-codex-auth","opencode-copilot-auth"];function yd(e){return xg.some(t=>e.includes(t))}n(yd,"isDeprecatedPlugin");function bd(e){try{return wg(e)}catch{}}n(bd,"parse");function Ji(e){let t=bd(e);if(t?.type==="alias"&&!t.name){let o=t.subSpec;if(o?.name){let i=!o.rawSpec||o.rawSpec==="*"?"latest":o.rawSpec;return{pkg:o.name,version:i}}}return t?.name?t.raw===t.name?{pkg:t.name,version:"latest"}:{pkg:t.name,version:t.rawSpec}:{pkg:e,version:""}}n(Ji,"parsePluginSpecifier");var vg=["index.ts","index.tsx","index.js","index.mjs","index.cjs"];function Yi(e){return Ki(e)?"file":"npm"}n(Yi,"pluginSource");function Ig(e,t){return e.startsWith("file://")?Vi(e):Mo.isAbsolute(e)?e:Mo.resolve(t,e)}n(Ig,"resolveExportPath");function kg(e){return Mo.isAbsolute(e)||/^[A-Za-z]:[\\/]/.test(e)}n(kg,"isAbsolutePath");function Eg(e){if(typeof e=="string")return e;if(Ro(e))for(let t of["import","default"]){let o=e[t];if(typeof o=="string")return o}}n(Eg,"extractExportValue");function Sg(e){let t=e.json.main;if(typeof t!="string")return;let o=t.trim();if(o)return o}n(Sg,"packageMain");function Dg(e,t,o,i){let m=Ig(t,i.dir),y=Ee.resolve(i.dir),p=Ee.resolve(m);if(!Ee.contains(y,p))throw new Error(`Plugin ${e} resolved ${o} entry outside plugin directory`);return p}n(Dg,"resolvePackageFile");function hd(e,t,o,i){return ds(Dg(e,t,o,i)).href}n(hd,"resolvePackagePath");function Tg(e,t,o){let i=o.json.exports;if(Ro(i)){let y=Eg(i[`./${t}`]);if(y)return hd(e,y,t,o)}if(t!=="server")return;let m=Sg(o);if(m)return hd(e,m,t,o)}n(Tg,"resolvePackageEntrypoint");function Pg(e){if(e.startsWith("file://"))return Vi(e);if(Mo.isAbsolute(e))return e}n(Pg,"targetPath");async function dc(e){for(let t of vg){let o=Mo.join(e,t);if(await Ee.exists(o))return o}}n(dc,"resolveDirectoryIndex");async function _g(e){let t=Pg(e);if(!(!t||!(await Ee.statAsync(t))?.isDirectory()))return t}n(_g,"resolveTargetDirectory");async function Og(e,t,o,i){let m=Yi(e),y=i??(m==="npm"?await us(t):await us(t).catch(()=>{}));if(!y)return t;let p=Tg(e,o,y);if(p)return p;let f=await _g(t);if(o==="tui"){if(m==="file"&&f){let b=await dc(f);if(b)return ds(b).href}return m==="npm"||f?void 0:t}if(f&&Ro(y.json.exports)){if(m==="file"){let b=await dc(f);if(b)return ds(b).href}return}return t}n(Og,"resolvePluginEntrypoint");function Ki(e){return e.startsWith("file://")||e.startsWith(".")||kg(e)}n(Ki,"isPathPluginSpec");async function uc(e){let t=e.startsWith("file://")?Vi(e):e,o=Mo.isAbsolute(t)||/^[A-Za-z]:[\\/]/.test(t)?t:Mo.resolve(t);if(!(await Ee.statAsync(o))?.isDirectory())return e.startsWith("file://")?e:ds(o).href;if(await Ee.exists(Mo.join(o,"package.json")))return ds(o).href;let m=await dc(o);if(m)return ds(m).href;throw new Error(`Plugin directory ${o} is missing package.json or index file`)}n(uc,"resolvePathPluginTarget");async function wd(e,t,o){if(!lc.valid(t)||lc.major(t)===0)return;let i=o??await us(e).catch(()=>{});if(!i)return;let m=i.json.engines;if(!Ro(m))return;let y=m.opencode;if(typeof y=="string"&&!lc.satisfies(t,y))throw new Error(`Plugin requires opencode ${y} but running ${t}`)}n(wd,"checkPluginCompatibility");async function xd(e){if(Ki(e))return uc(e);let t=bd(e),o=t?.name&&t.raw===t.name?`${t.name}@latest`:e;return(await an.add(o)).directory}n(xd,"resolvePluginTarget");async function us(e){let t=e.startsWith("file://")?Vi(e):e,i=(await Ee.statAsync(t))?.isDirectory()?t:Mo.dirname(t),m=Mo.join(i,"package.json"),y=await Ee.readJson(m);return{dir:i,pkg:m,json:y}}n(us,"readPluginPackage");async function vd(e,t,o){let i=Yi(e),m=i==="npm"?await us(t):await us(t).catch(()=>{}),y=await Og(e,t,o,m);return{spec:e,source:i,target:t,pkg:m,entry:y}}n(vd,"createPluginEntry");function Id(e,t){if(e===void 0)return;if(typeof e!="string")throw new TypeError(`Plugin ${t} has invalid id type ${typeof e}`);let o=e.trim();if(!o)throw new TypeError(`Plugin ${t} has an empty id`);return o}n(Id,"readPluginId");function kd(e,t,o,i="strict"){let m=e.default;if(!Ro(m)){if(i==="detect")return;throw new TypeError(`Plugin ${t} must default export an object with ${o}()`)}if(i==="detect"&&!("id"in m)&&!("server"in m)&&!("tui"in m))return;let y="server"in m?m.server:void 0,p="tui"in m?m.tui:void 0;if(y!==void 0&&typeof y!="function")throw new TypeError(`Plugin ${t} has invalid server export`);if(p!==void 0&&typeof p!="function")throw new TypeError(`Plugin ${t} has invalid tui export`);if(y!==void 0&&p!==void 0)throw new TypeError(`Plugin ${t} must default export either server() or tui(), not both`);if(o==="server"&&y===void 0)throw new TypeError(`Plugin ${t} must default export an object with server()`);if(o==="tui"&&p===void 0)throw new TypeError(`Plugin ${t} must default export an object with tui()`);return m}n(kd,"readV1Plugin");async function Ed(e,t,o,i,m){if(e==="file"){if(i)return i;throw new TypeError(`Path plugin ${t} must export id`)}if(i)return i;let y=m??await us(o);if(typeof y.json.name!="string"||!y.json.name.trim())throw new TypeError(`Plugin package ${y.pkg} is missing name`);return y.json.name.trim()}n(Ed,"resolvePluginId");var rt;(Ie=>{let e=W.string().meta({$ref:"https://models.dev/model-schema.json#/$defs/Model"}),t=W.record(W.string(),W.unknown());Ie.PluginSpec=W.union([W.string(),W.tuple([W.string(),t])]);let i=qe.create({service:"config"});function m(){switch(process.platform){case"darwin":return"/Library/Application Support/opencode";case"win32":return en.join(process.env.ProgramData||"C:\\ProgramData","opencode");default:return"/etc/opencode"}}n(m,"systemManagedConfigDir");function y(){return process.env.OPENCODE_TEST_MANAGED_CONFIG_DIR||m()}Ie.managedConfigDir=y,n(y,"managedConfigDir");let p=y(),f="ai.opencode.managed",b=new Set(["PayloadDisplayName","PayloadIdentifier","PayloadType","PayloadUUID","PayloadVersion","_manualProfile"]);function d(be,ye){let ae=JSON.parse(be);for(let me of Object.keys(ae))b.has(me)&&delete ae[me];return X(JSON.stringify(ae),ye)}Ie.parseManagedPlist=d,n(d,"parseManagedPlist");async function s(){if(process.platform!=="darwin")return{};let be=f,ye=Sd.userInfo().username,ae=[en.join("/Library/Managed Preferences",ye,`${be}.plist`),en.join("/Library/Managed Preferences",`${be}.plist`)];for(let me of ae){if(!Zi(me))continue;i.info("reading macOS managed preferences",{path:me});let P=await St.run(["plutil","-convert","json","-o","-",me],{nothrow:!0});if(P.code!==0){i.warn("failed to convert managed preferences plist",{path:me});continue}return d(P.stdout.toString(),`mobileconfig:${me}`)}return{}}n(s,"readManagedPreferences");function c(be,ye){let ae=Yn(be,ye);return be.instructions&&ye.instructions&&(ae.instructions=Array.from(new Set([...be.instructions,...ye.instructions]))),ae}n(c,"mergeConfigConcatArrays");async function l(be,ye){var _e=[];try{if(!await g(be))return;let ae=kn(_e,await Bo.acquire(`config-install:${Ee.resolve(be)}`,{signal:ye?.signal,onWait:n(de=>ye?.waitTick?.({dir:be,attempt:de.attempt,delay:de.delay,waited:de.waited}),"onWait")}),!0);ye?.signal?.throwIfAborted();let me=en.join(be,"package.json");let P=Ft.isLocal()?"*":Ft.VERSION;let Z=await Ee.readJson(me).catch(()=>({dependencies:{}}));Z.dependencies={...Z.dependencies,"@opencode-ai/plugin":P};await Ee.writeJson(me,Z);let J=en.join(be,".gitignore");let fe=await Ee.exists(J);fe||await Ee.write(J,["node_modules","package.json","package-lock.json","bun.lock",".gitignore"].join(`
|
|
39
|
+
`));await an.install(be)}catch(te){var we=te,$e=!0}finally{var ee=En(_e,we,$e);ee&&await ee}}Ie.installDependencies=l,n(l,"installDependencies");async function g(be){try{return await pc.access(be,Ng.W_OK),!0}catch{return!1}}n(g,"isWritable");function u(be,ye){let ae=be.replaceAll("\\","/");for(let me of ye){let P=ae.indexOf(me);if(P!==-1)return ae.slice(P+me.length)}}n(u,"rel");function a(be){let ye=en.extname(be);return ye.length?be.slice(0,-ye.length):be}n(a,"trim");async function w(be){let ye={};for(let ae of await co.scan("{command,commands}/**/*.md",{cwd:be,absolute:!0,dot:!0,symlink:!0})){let me=await Un.parse(ae).catch(async te=>{let we=Un.FrontmatterError.isInstance(te)?te.data.message:`Failed to parse command ${ae}`,{Session:$e}=await import("./session-ACBIJ2VE.js");Ve.publish($e.Event.Error,{error:new tt.Unknown({message:we}).toObject()}),i.error("failed to load command",{command:ae,err:te})});if(!me)continue;let Z=u(ae,["/.opencode/command/","/.opencode/commands/","/command/","/commands/"])??en.basename(ae),fe={name:a(Z),...me.data,template:me.content.trim()},_e=Ie.Command.safeParse(fe);if(_e.success){ye[fe.name]=_e.data;continue}throw new Ie.InvalidError({path:ae,issues:_e.error.issues},{cause:_e.error})}return ye}n(w,"loadCommand");async function I(be){let ye={};for(let ae of await co.scan("{agent,agents}/**/*.md",{cwd:be,absolute:!0,dot:!0,symlink:!0})){let me=await Un.parse(ae).catch(async te=>{let we=Un.FrontmatterError.isInstance(te)?te.data.message:`Failed to parse agent ${ae}`,{Session:$e}=await import("./session-ACBIJ2VE.js");Ve.publish($e.Event.Error,{error:new tt.Unknown({message:we}).toObject()}),i.error("failed to load agent",{agent:ae,err:te})});if(!me)continue;let Z=u(ae,["/.opencode/agent/","/.opencode/agents/","/agent/","/agents/"])??en.basename(ae),fe={name:a(Z),...me.data,prompt:me.content.trim()},_e=Ie.Agent.safeParse(fe);if(_e.success){ye[fe.name]=_e.data;continue}throw new Ie.InvalidError({path:ae,issues:_e.error.issues},{cause:_e.error})}return ye}n(I,"loadAgent");async function r(be){let ye={};if(!Ce.ALCHEMYLAB)return ye;let ae=en.join(be,".alchemy_lab","action-server.json"),me,P;for(let J=0;J<20&&!me;J++)try{let fe=JSON.parse(await Ee.readText(ae));fe?.port&&(me=fe.port),typeof fe?.secret=="string"&&(P=fe.secret)}catch{await new Promise(fe=>setTimeout(fe,500))}if(!me)return i.warn("alchemy agents: no action-server.json; agents unavailable until config reload"),ye;let Z=[];try{let J=await fetch(`http://127.0.0.1:${me}/api/agents/markdown`,{signal:AbortSignal.timeout(8e3),headers:P?{"x-alchemy-local":P}:{}});if(!J.ok)throw new Error(`HTTP ${J.status}`);Z=(await J.json()).data??[]}catch(J){return i.warn("alchemy agents: fetch failed",{port:me,err:J}),ye}for(let J of Z){let fe;try{fe=Un.parseText(J.markdown,`alchemy agent ${J.name}`)}catch(we){i.error("failed to parse alchemy agent",{agent:J.name,err:we});continue}let _e={name:J.name,...fe.data,prompt:fe.content.trim()},te=Ie.Agent.safeParse(_e);te.success?ye[J.name]=te.data:i.error("invalid alchemy agent",{agent:J.name,issues:te.error.issues})}return i.info("alchemy agents loaded in memory",{count:Object.keys(ye).length,port:me}),ye}n(r,"loadAlchemyAgents");async function x(be){let ye={};for(let ae of await co.scan("{mode,modes}/*.md",{cwd:be,absolute:!0,dot:!0,symlink:!0})){let me=await Un.parse(ae).catch(async J=>{let fe=Un.FrontmatterError.isInstance(J)?J.data.message:`Failed to parse mode ${ae}`,{Session:_e}=await import("./session-ACBIJ2VE.js");Ve.publish(_e.Event.Error,{error:new tt.Unknown({message:fe}).toObject()}),i.error("failed to load mode",{mode:ae,err:J})});if(!me)continue;let P={name:en.basename(ae,".md"),...me.data,prompt:me.content.trim()},Z=Ie.Agent.safeParse(P);if(Z.success){ye[P.name]={...Z.data,mode:"primary"};continue}}return ye}n(x,"loadMode");async function h(be){let ye=[];for(let ae of await co.scan("{plugin,plugins}/*.{ts,js}",{cwd:be,absolute:!0,dot:!0,symlink:!0}))ye.push(Xi(ae).href);return ye}n(h,"loadPlugin");function v(be){return Array.isArray(be)?be[0]:be}Ie.pluginSpecifier=v,n(v,"pluginSpecifier");function S(be){return Array.isArray(be)?be[1]:void 0}Ie.pluginOptions=S,n(S,"pluginOptions");async function j(be,ye){let ae=v(be);if(!Ki(ae))return be;let me=en.dirname(ye),P=ae.startsWith("file://")?ae:en.isAbsolute(ae)||/^[A-Za-z]:[\\/]/.test(ae)?Xi(ae).href:Xi(en.resolve(me,ae)).href,Z=await uc(P).catch(()=>P);return Array.isArray(be)?[Z,be[1]]:Z}Ie.resolvePluginSpec=j,n(j,"resolvePluginSpec");function O(be){let ye=new Set,ae=[];for(let me of be.toReversed()){let P=v(me.spec),Z=P.startsWith("file://")?P:Ji(P).pkg;ye.has(Z)||(ye.add(Z),ae.push(me))}return ae.toReversed()}Ie.deduplicatePluginOrigins=O,n(O,"deduplicatePluginOrigins"),Ie.McpLocal=W.object({type:W.literal("local").describe("Type of MCP server connection"),command:W.string().array().describe("Command and arguments to run the MCP server"),environment:W.record(W.string(),W.string()).optional().describe("Environment variables to set when running the MCP server"),enabled:W.boolean().optional().describe("Enable or disable the MCP server on startup"),timeout:W.number().int().positive().optional().describe("Timeout in ms for MCP server requests. Defaults to 5000 (5 seconds) if not specified.")}).strict().meta({ref:"McpLocalConfig"}),Ie.McpOAuth=W.object({clientId:W.string().optional().describe("OAuth client ID. If not provided, dynamic client registration (RFC 7591) will be attempted."),clientSecret:W.string().optional().describe("OAuth client secret (if required by the authorization server)"),scope:W.string().optional().describe("OAuth scopes to request during authorization")}).strict().meta({ref:"McpOAuthConfig"}),Ie.McpRemote=W.object({type:W.literal("remote").describe("Type of MCP server connection"),url:W.string().describe("URL of the remote MCP server"),enabled:W.boolean().optional().describe("Enable or disable the MCP server on startup"),headers:W.record(W.string(),W.string()).optional().describe("Headers to send with the request"),oauth:W.union([Ie.McpOAuth,W.literal(!1)]).optional().describe("OAuth authentication configuration for the MCP server. Set to false to disable OAuth auto-detection."),timeout:W.number().int().positive().optional().describe("Timeout in ms for MCP server requests. Defaults to 5000 (5 seconds) if not specified.")}).strict().meta({ref:"McpRemoteConfig"}),Ie.Mcp=W.discriminatedUnion("type",[Ie.McpLocal,Ie.McpRemote]),Ie.PermissionAction=W.enum(["ask","allow","deny"]).meta({ref:"PermissionActionConfig"}),Ie.PermissionObject=W.record(W.string(),Ie.PermissionAction).meta({ref:"PermissionObjectConfig"}),Ie.PermissionRule=W.union([Ie.PermissionAction,Ie.PermissionObject]).meta({ref:"PermissionRuleConfig"});let M=n(be=>typeof be=="object"&&be!==null&&!Array.isArray(be)?{__originalKeys:Object.keys(be),...be}:be,"permissionPreprocess"),C=n(be=>{if(typeof be=="string")return{"*":be};let ye=be,{__originalKeys:ae,...me}=ye;if(!ae)return me;let P={};for(let Z of ae)Z in me&&(P[Z]=me[Z]);return P},"permissionTransform");Ie.Permission=W.preprocess(M,W.object({__originalKeys:W.string().array().optional(),read:Ie.PermissionRule.optional(),edit:Ie.PermissionRule.optional(),glob:Ie.PermissionRule.optional(),grep:Ie.PermissionRule.optional(),list:Ie.PermissionRule.optional(),bash:Ie.PermissionRule.optional(),task:Ie.PermissionRule.optional(),external_directory:Ie.PermissionRule.optional(),todowrite:Ie.PermissionAction.optional(),question:Ie.PermissionAction.optional(),webfetch:Ie.PermissionAction.optional(),websearch:Ie.PermissionAction.optional(),codesearch:Ie.PermissionAction.optional(),lsp:Ie.PermissionRule.optional(),doom_loop:Ie.PermissionAction.optional(),skill:Ie.PermissionRule.optional()}).catchall(Ie.PermissionRule).or(Ie.PermissionAction)).transform(C).meta({ref:"PermissionConfig"}),Ie.Command=W.object({template:W.string(),description:W.string().optional(),agent:W.string().optional(),model:e.optional(),subtask:W.boolean().optional()}),Ie.Skills=W.object({paths:W.array(W.string()).optional().describe("Additional paths to skill folders"),urls:W.array(W.string()).optional().describe("URLs to fetch skills from (e.g., https://example.com/.well-known/skills/)")}),Ie.Agent=W.object({model:e.optional(),variant:W.string().optional().describe("Default model variant for this agent (applies only when using the agent's configured model)."),temperature:W.number().optional(),top_p:W.number().optional(),prompt:W.string().optional(),tools:W.record(W.string(),W.boolean()).optional().describe("@deprecated Use 'permission' field instead"),disable:W.boolean().optional(),description:W.string().optional().describe("Description of when to use the agent"),mode:W.enum(["subagent","primary","all"]).optional(),hidden:W.boolean().optional().describe("Hide this subagent from the @ autocomplete menu (default: false, only applies to mode: subagent)"),options:W.record(W.string(),W.any()).optional(),color:W.union([W.string().regex(/^#[0-9a-fA-F]{6}$/,"Invalid hex color format"),W.enum(["primary","secondary","accent","success","warning","error","info"])]).optional().describe("Hex color code (e.g., #FF5733) or theme color (e.g., primary)"),steps:W.number().int().positive().optional().describe("Maximum number of agentic iterations before forcing text-only response"),maxSteps:W.number().int().positive().optional().describe("@deprecated Use 'steps' field instead."),permission:Ie.Permission.optional()}).catchall(W.any()).transform((be,ye)=>{let ae=new Set(["name","model","variant","prompt","description","temperature","top_p","mode","hidden","color","steps","maxSteps","options","permission","disable","tools"]),me={...be.options};for(let[J,fe]of Object.entries(be))ae.has(J)||(me[J]=fe);let P={};for(let[J,fe]of Object.entries(be.tools??{})){let _e=fe?"allow":"deny";J==="write"||J==="edit"||J==="patch"||J==="multiedit"?P.edit=_e:P[J]=_e}Object.assign(P,be.permission);let Z=be.steps??be.maxSteps;return{...be,options:me,permission:P,steps:Z}}).meta({ref:"AgentConfig"}),Ie.Keybinds=W.object({leader:W.string().optional().default("ctrl+x").describe("Leader key for keybind combinations"),app_exit:W.string().optional().default("ctrl+c,ctrl+d,<leader>q").describe("Exit the application"),editor_open:W.string().optional().default("<leader>e").describe("Open external editor"),theme_list:W.string().optional().default("<leader>t").describe("List available themes"),sidebar_toggle:W.string().optional().default("<leader>b").describe("Toggle sidebar"),scrollbar_toggle:W.string().optional().default("none").describe("Toggle session scrollbar"),username_toggle:W.string().optional().default("none").describe("Toggle username visibility"),status_view:W.string().optional().default("<leader>s").describe("View status"),session_export:W.string().optional().default("<leader>x").describe("Export session to editor"),session_new:W.string().optional().default("<leader>n").describe("Create a new session"),session_list:W.string().optional().default("<leader>l").describe("List all sessions"),session_timeline:W.string().optional().default("<leader>g").describe("Show session timeline"),session_fork:W.string().optional().default("none").describe("Fork session from message"),session_rename:W.string().optional().default("ctrl+r").describe("Rename session"),session_delete:W.string().optional().default("ctrl+d").describe("Delete session"),stash_delete:W.string().optional().default("ctrl+d").describe("Delete stash entry"),model_provider_list:W.string().optional().default("ctrl+a").describe("Open provider list from model dialog"),model_favorite_toggle:W.string().optional().default("ctrl+f").describe("Toggle model favorite status"),session_share:W.string().optional().default("none").describe("Share current session"),session_unshare:W.string().optional().default("none").describe("Unshare current session"),session_interrupt:W.string().optional().default("escape").describe("Interrupt current session"),session_compact:W.string().optional().default("<leader>c").describe("Compact the session"),messages_page_up:W.string().optional().default("pageup,ctrl+alt+b").describe("Scroll messages up by one page"),messages_page_down:W.string().optional().default("pagedown,ctrl+alt+f").describe("Scroll messages down by one page"),messages_line_up:W.string().optional().default("ctrl+alt+y").describe("Scroll messages up by one line"),messages_line_down:W.string().optional().default("ctrl+alt+e").describe("Scroll messages down by one line"),messages_half_page_up:W.string().optional().default("ctrl+alt+u").describe("Scroll messages up by half page"),messages_half_page_down:W.string().optional().default("ctrl+alt+d").describe("Scroll messages down by half page"),messages_first:W.string().optional().default("ctrl+g,home").describe("Navigate to first message"),messages_last:W.string().optional().default("ctrl+alt+g,end").describe("Navigate to last message"),messages_next:W.string().optional().default("none").describe("Navigate to next message"),messages_previous:W.string().optional().default("none").describe("Navigate to previous message"),messages_last_user:W.string().optional().default("none").describe("Navigate to last user message"),messages_copy:W.string().optional().default("<leader>y").describe("Copy message"),messages_undo:W.string().optional().default("<leader>u").describe("Undo message"),messages_redo:W.string().optional().default("<leader>r").describe("Redo message"),messages_toggle_conceal:W.string().optional().default("<leader>h").describe("Toggle code block concealment in messages"),tool_details:W.string().optional().default("none").describe("Toggle tool details visibility"),model_list:W.string().optional().default("<leader>m").describe("List available models"),model_cycle_recent:W.string().optional().default("f2").describe("Next recently used model"),model_cycle_recent_reverse:W.string().optional().default("shift+f2").describe("Previous recently used model"),model_cycle_favorite:W.string().optional().default("none").describe("Next favorite model"),model_cycle_favorite_reverse:W.string().optional().default("none").describe("Previous favorite model"),command_list:W.string().optional().default("ctrl+p").describe("List available commands"),agent_list:W.string().optional().default("<leader>a").describe("List agents"),agent_cycle:W.string().optional().default("tab").describe("Next agent"),agent_cycle_reverse:W.string().optional().default("shift+tab").describe("Previous agent"),variant_cycle:W.string().optional().default("ctrl+t").describe("Cycle model variants"),input_clear:W.string().optional().default("ctrl+c").describe("Clear input field"),input_paste:W.string().optional().default("ctrl+v").describe("Paste from clipboard"),input_submit:W.string().optional().default("return").describe("Submit input"),input_newline:W.string().optional().default("shift+return,ctrl+return,alt+return,ctrl+j").describe("Insert newline in input"),input_move_left:W.string().optional().default("left,ctrl+b").describe("Move cursor left in input"),input_move_right:W.string().optional().default("right,ctrl+f").describe("Move cursor right in input"),input_move_up:W.string().optional().default("up").describe("Move cursor up in input"),input_move_down:W.string().optional().default("down").describe("Move cursor down in input"),input_select_left:W.string().optional().default("shift+left").describe("Select left in input"),input_select_right:W.string().optional().default("shift+right").describe("Select right in input"),input_select_up:W.string().optional().default("shift+up").describe("Select up in input"),input_select_down:W.string().optional().default("shift+down").describe("Select down in input"),input_line_home:W.string().optional().default("ctrl+a").describe("Move to start of line in input"),input_line_end:W.string().optional().default("ctrl+e").describe("Move to end of line in input"),input_select_line_home:W.string().optional().default("ctrl+shift+a").describe("Select to start of line in input"),input_select_line_end:W.string().optional().default("ctrl+shift+e").describe("Select to end of line in input"),input_visual_line_home:W.string().optional().default("alt+a").describe("Move to start of visual line in input"),input_visual_line_end:W.string().optional().default("alt+e").describe("Move to end of visual line in input"),input_select_visual_line_home:W.string().optional().default("alt+shift+a").describe("Select to start of visual line in input"),input_select_visual_line_end:W.string().optional().default("alt+shift+e").describe("Select to end of visual line in input"),input_buffer_home:W.string().optional().default("home").describe("Move to start of buffer in input"),input_buffer_end:W.string().optional().default("end").describe("Move to end of buffer in input"),input_select_buffer_home:W.string().optional().default("shift+home").describe("Select to start of buffer in input"),input_select_buffer_end:W.string().optional().default("shift+end").describe("Select to end of buffer in input"),input_delete_line:W.string().optional().default("ctrl+shift+d").describe("Delete line in input"),input_delete_to_line_end:W.string().optional().default("ctrl+k").describe("Delete to end of line in input"),input_delete_to_line_start:W.string().optional().default("ctrl+u").describe("Delete to start of line in input"),input_backspace:W.string().optional().default("backspace,shift+backspace").describe("Backspace in input"),input_delete:W.string().optional().default("ctrl+d,delete,shift+delete").describe("Delete character in input"),input_undo:W.string().optional().default("ctrl+-,super+z").describe("Undo in input"),input_redo:W.string().optional().default("ctrl+.,super+shift+z").describe("Redo in input"),input_word_forward:W.string().optional().default("alt+f,alt+right,ctrl+right").describe("Move word forward in input"),input_word_backward:W.string().optional().default("alt+b,alt+left,ctrl+left").describe("Move word backward in input"),input_select_word_forward:W.string().optional().default("alt+shift+f,alt+shift+right").describe("Select word forward in input"),input_select_word_backward:W.string().optional().default("alt+shift+b,alt+shift+left").describe("Select word backward in input"),input_delete_word_forward:W.string().optional().default("alt+d,alt+delete,ctrl+delete").describe("Delete word forward in input"),input_delete_word_backward:W.string().optional().default("ctrl+w,ctrl+backspace,alt+backspace").describe("Delete word backward in input"),history_previous:W.string().optional().default("up").describe("Previous history item"),history_next:W.string().optional().default("down").describe("Next history item"),session_child_first:W.string().optional().default("<leader>down").describe("Go to first child session"),session_child_cycle:W.string().optional().default("right").describe("Go to next child session"),session_child_cycle_reverse:W.string().optional().default("left").describe("Go to previous child session"),session_parent:W.string().optional().default("up").describe("Go to parent session"),terminal_suspend:W.string().optional().default("ctrl+z").describe("Suspend terminal"),terminal_title_toggle:W.string().optional().default("none").describe("Toggle terminal title"),tips_toggle:W.string().optional().default("<leader>h").describe("Toggle tips on home screen"),plugin_manager:W.string().optional().default("none").describe("Open plugin manager dialog"),display_thinking:W.string().optional().default("none").describe("Toggle thinking blocks visibility")}).strict().meta({ref:"KeybindsConfig"}),Ie.Server=W.object({port:W.number().int().positive().optional().describe("Port to listen on"),hostname:W.string().optional().describe("Hostname to listen on"),mdns:W.boolean().optional().describe("Enable mDNS service discovery"),mdnsDomain:W.string().optional().describe("Custom domain name for mDNS service (default: opencode.local)"),cors:W.array(W.string()).optional().describe("Additional domains to allow for CORS")}).strict().meta({ref:"ServerConfig"}),Ie.Layout=W.enum(["auto","stretch"]).meta({ref:"LayoutConfig"}),Ie.Provider=ir.Provider.partial().extend({whitelist:W.array(W.string()).optional(),blacklist:W.array(W.string()).optional(),models:W.record(W.string(),ir.Model.partial().extend({variants:W.record(W.string(),W.object({disabled:W.boolean().optional().describe("Disable this variant for the model")}).catchall(W.any())).optional().describe("Variant-specific configuration")})).optional(),options:W.object({apiKey:W.string().optional(),baseURL:W.string().optional(),enterpriseUrl:W.string().optional().describe("GitHub Enterprise URL for copilot authentication"),setCacheKey:W.boolean().optional().describe("Enable promptCacheKey for this provider (default false)"),timeout:W.union([W.number().int().positive().describe("Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout."),W.literal(!1).describe("Disable timeout for this provider entirely.")]).optional().describe("Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout."),chunkTimeout:W.number().int().positive().optional().describe("Timeout in milliseconds between streamed SSE chunks for this provider. If no chunk arrives within this window, the request is aborted.")}).catchall(W.any()).optional()}).strict().meta({ref:"ProviderConfig"}),Ie.Info=W.object({$schema:W.string().optional().describe("JSON schema reference for configuration validation"),logLevel:qe.Level.optional().describe("Log level"),server:Ie.Server.optional().describe("Server configuration for opencode serve and web commands"),command:W.record(W.string(),Ie.Command).optional().describe("Command configuration, see https://opencode.ai/docs/commands"),skills:Ie.Skills.optional().describe("Additional skill folder paths"),watcher:W.object({ignore:W.array(W.string()).optional()}).optional(),snapshot:W.boolean().optional().describe("Enable or disable snapshot tracking. When false, filesystem snapshots are not recorded and undoing or reverting will not undo/redo file changes. Defaults to true."),plugin:Ie.PluginSpec.array().optional(),share:W.enum(["manual","auto","disabled"]).optional().describe("Control sharing behavior:'manual' allows manual sharing via commands, 'auto' enables automatic sharing, 'disabled' disables all sharing"),autoshare:W.boolean().optional().describe("@deprecated Use 'share' field instead. Share newly created sessions automatically"),autoupdate:W.union([W.boolean(),W.literal("notify")]).optional().describe("Automatically update to the latest version. Set to true to auto-update, false to disable, or 'notify' to show update notifications"),disabled_providers:W.array(W.string()).optional().describe("Disable providers that are loaded automatically"),enabled_providers:W.array(W.string()).optional().describe("When set, ONLY these providers will be enabled. All other providers will be ignored"),model:e.describe("Model to use in the format of provider/model, eg anthropic/claude-2").optional(),small_model:e.describe("Small model to use for tasks like title generation in the format of provider/model").optional(),default_agent:W.string().optional().describe("Default agent to use when none is specified. Must be a primary agent. Falls back to 'build' if not set or if the specified agent is invalid."),username:W.string().optional().describe("Custom username to display in conversations instead of system username"),mode:W.object({build:Ie.Agent.optional(),plan:Ie.Agent.optional()}).catchall(Ie.Agent).optional().describe("@deprecated Use `agent` field instead."),agent:W.object({plan:Ie.Agent.optional(),build:Ie.Agent.optional(),general:Ie.Agent.optional(),explore:Ie.Agent.optional(),title:Ie.Agent.optional(),summary:Ie.Agent.optional(),compaction:Ie.Agent.optional()}).catchall(Ie.Agent).optional().describe("Agent configuration, see https://opencode.ai/docs/agents"),provider:W.record(W.string(),Ie.Provider).optional().describe("Custom provider configurations and model overrides"),mcp:W.record(W.string(),W.union([Ie.Mcp,W.object({enabled:W.boolean()}).strict()])).optional().describe("MCP (Model Context Protocol) server configurations"),formatter:W.union([W.literal(!1),W.record(W.string(),W.object({disabled:W.boolean().optional(),command:W.array(W.string()).optional(),environment:W.record(W.string(),W.string()).optional(),extensions:W.array(W.string()).optional()}))]).optional(),lsp:W.union([W.literal(!1),W.record(W.string(),W.union([W.object({disabled:W.literal(!0)}),W.object({command:W.array(W.string()),extensions:W.array(W.string()).optional(),disabled:W.boolean().optional(),env:W.record(W.string(),W.string()).optional(),initialization:W.record(W.string(),W.any()).optional()})]))]).optional().refine(be=>{if(!be||typeof be=="boolean")return!0;let ye=new Set(Object.values($s).map(ae=>ae.id));return Object.entries(be).every(([ae,me])=>me.disabled||ye.has(ae)?!0:!!me.extensions)},{error:"For custom LSP servers, 'extensions' array is required."}),instructions:W.array(W.string()).optional().describe("Additional instruction files or patterns to include"),layout:Ie.Layout.optional().describe("@deprecated Always uses stretch layout."),permission:Ie.Permission.optional(),tools:W.record(W.string(),W.boolean()).optional(),enterprise:W.object({url:W.string().optional().describe("Enterprise URL")}).optional(),compaction:W.object({auto:W.boolean().optional().describe("Enable automatic compaction when context is full (default: true)"),prune:W.boolean().optional().describe("Enable pruning of old tool outputs (default: true)"),reserved:W.number().int().min(0).optional().describe("Token buffer for compaction. Leaves enough window to avoid overflow during compaction.")}).optional(),experimental:W.object({disable_paste_summary:W.boolean().optional(),batch_tool:W.boolean().optional().describe("Enable the batch tool"),openTelemetry:W.boolean().optional().describe("Enable OpenTelemetry spans for AI SDK calls (using the 'experimental_telemetry' flag)"),primary_tools:W.array(W.string()).optional().describe("Tools that should only be available to primary agents."),continue_loop_on_deny:W.boolean().optional().describe("Continue the agent loop when a tool call is denied"),mcp_timeout:W.number().int().positive().optional().describe("Timeout in milliseconds for model context protocol (MCP) requests")}).optional()}).strict().meta({ref:"Config"});class H extends Fg.Service()("@opencode/Config"){static{n(this,"Service")}}Ie.Service=H;function R(){let be=["opencode.jsonc","opencode.json","config.json"].map(ye=>en.join(je.Path.config,ye));for(let ye of be)if(Zi(ye))return ye;return be[0]}n(R,"globalConfigFile");function L(be,ye,ae=[]){if(!Ro(ye)){let me=jg(be,ae,ye,{formattingOptions:{insertSpaces:!0,tabSize:2}});return Rg(be,me)}return Object.entries(ye).reduce((me,[P,Z])=>Z===void 0?me:L(me,Z,[...ae,P]),be)}n(L,"patchJsonc");function q(be){let{plugin_origins:ye,...ae}=be;return ae}n(q,"writable");function X(be,ye){let ae=[],me=Mg(be,ae,{allowTrailingComma:!0});if(ae.length){let Z=be.split(`
|
|
40
|
+
`),J=ae.map(fe=>{let _e=be.substring(0,fe.offset).split(`
|
|
41
|
+
`),te=_e.length,we=_e[_e.length-1].length+1,$e=Z[te-1],ee=`${Lg(fe.error)} at line ${te}, column ${we}`;return $e?`${ee}
|
|
42
|
+
Line ${te}: ${$e}
|
|
43
|
+
${"".padStart(we+9)}^`:ee}).join(`
|
|
44
|
+
`);throw new Ie.JsonError({path:ye,message:`
|
|
45
|
+
--- JSONC Input ---
|
|
46
|
+
${be}
|
|
47
|
+
--- Errors ---
|
|
48
|
+
${J}
|
|
49
|
+
--- End ---`})}let P=Ie.Info.safeParse(me);if(P.success)return P.data;throw new Ie.InvalidError({path:ye,issues:P.error.issues})}n(X,"parseConfig"),{JsonError:Ie.JsonError,InvalidError:Ie.InvalidError}=ls,Ie.ConfigDirectoryTypoError=tt.create("ConfigDirectoryTypoError",W.object({path:W.string(),dir:W.string(),suggestion:W.string()})),Ie.layer=Qi.effect(H,ct.gen(function*(){let be=yield*ut.Service,ye=yield*Fn.Service,ae=yield*Gi.Service,me=ct.fnUntraced(function*(Ae){return yield*be.readFileString(Ae).pipe(ct.catchIf(Fe=>Fe.reason._tag==="NotFound",()=>ct.succeed(void 0)),ct.orDie)}),P=ct.fnUntraced(function*(Ae,Fe){let Re=Ae,nt="path"in Fe?Fe.path:Fe.source,et="path"in Fe,Ue=yield*ct.promise(()=>ls.parseText(Ae,"path"in Fe?Fe.path:{source:Fe.source,dir:Fe.dir})),ot=(()=>{if(!Ue||typeof Ue!="object"||Array.isArray(Ue))return Ue;let wt={...Ue};return("theme"in wt||"keybinds"in wt||"tui"in wt)&&(delete wt.theme,delete wt.keybinds,delete wt.tui,i.warn("tui keys in opencode config are deprecated; move them to tui.json",{path:nt})),wt})(),Xe=Ie.Info.safeParse(ot);if(Xe.success){if(!Xe.data.$schema&&et){Xe.data.$schema="https://opencode.ai/config.json";let xt=Re.replace(/^\s*\{/,`{
|
|
50
|
+
"$schema": "https://opencode.ai/config.json",`);yield*be.writeFileString(Fe.path,xt).pipe(ct.catch(()=>ct.void))}let wt=Xe.data;if(wt.plugin&&et){let xt=wt.plugin;for(let _t=0;_t<xt.length;_t++)xt[_t]=yield*ct.promise(()=>j(xt[_t],Fe.path))}return wt}throw new Ie.InvalidError({path:nt,issues:Xe.error.issues})}),Z=ct.fnUntraced(function*(Ae){i.info("loading",{path:Ae});let Fe=yield*me(Ae);return Fe?yield*P(Fe,{path:Ae}):{}}),J=ct.fnUntraced(function*(){let Ae=Ag({},Yn(yield*Z(en.join(je.Path.config,"config.json"))),Yn(yield*Z(en.join(je.Path.config,"opencode.json"))),Yn(yield*Z(en.join(je.Path.config,"opencode.jsonc")))),Fe=en.join(je.Path.config,"config");return Zi(Fe)&&(yield*ct.promise(()=>import(Xi(Fe).href,{with:{type:"toml"}}).then(async Re=>{let{provider:nt,model:et,...Ue}=Re.default;nt&&et&&(Ae.model=`${nt}/${et}`),Ae.$schema="https://opencode.ai/config.json",Ae=Yn(Ae,Ue),await pc.writeFile(en.join(je.Path.config,"config.json"),JSON.stringify(Ae,null,2)),await pc.unlink(Fe)}).catch(()=>{}))),Ae}),[fe,_e]=yield*ct.cachedInvalidateWithTTL(J().pipe(ct.tapError(Ae=>ct.sync(()=>i.error("failed to load global config, using defaults",{error:String(Ae)}))),ct.orElseSucceed(()=>({}))),zg.infinity),te=ct.fn("Config.getGlobal")(function*(){return yield*fe}),we=ct.fnUntraced(function*(Ae){let Fe=yield*ye.all().pipe(ct.orDie),Re={},nt=new Set,et,Ue=n(dt=>dt.startsWith("http://")||dt.startsWith("https://")?"global":dt==="OPENCODE_CONFIG_CONTENT"||he.containsPath(dt)?"local":"global","scope"),ot=n((dt,Ot,sn)=>{if(!Ot?.length)return;let dn=sn??Ue(dt),Pn=O([...Re.plugin_origins??[],...Ot.map(ao=>({spec:ao,source:dt,scope:dn}))]);Re.plugin=Pn.map(ao=>ao.spec),Re.plugin_origins=Pn},"track"),Xe=n((dt,Ot,sn)=>{Re=c(Re,Ot),ot(dt,Ot.plugin,sn)},"merge");for(let[dt,Ot]of Object.entries(Fe))if(Ot.type==="wellknown"){let sn=dt.replace(/\/+$/,"");process.env[Ot.key]=Ot.token,i.debug("fetching remote config",{url:`${sn}/.well-known/opencode`});let dn=yield*ct.promise(()=>fetch(`${sn}/.well-known/opencode`));if(!dn.ok)throw new Error(`failed to fetch remote config from ${sn}: ${dn.status}`);let ao=(yield*ct.promise(()=>dn.json())).config??{};ao.$schema||(ao.$schema="https://opencode.ai/config.json");let Io=`${sn}/.well-known/opencode`,ko=yield*P(JSON.stringify(ao),{dir:en.dirname(Io),source:Io});Xe(Io,ko,"global"),i.debug("loaded remote config from well-known",{url:sn})}let wt=yield*te();if(Xe(je.Path.config,wt,"global"),Ce.OPENCODE_CONFIG&&(Xe(Ce.OPENCODE_CONFIG,yield*Z(Ce.OPENCODE_CONFIG)),i.debug("loaded custom config",{path:Ce.OPENCODE_CONFIG})),!Ce.OPENCODE_DISABLE_PROJECT_CONFIG)for(let dt of yield*ct.promise(()=>ls.projectFiles("opencode",Ae.directory,Ae.worktree)))Xe(dt,yield*Z(dt),"local");Re.agent=Re.agent||{},Re.mode=Re.mode||{},Re.plugin=Re.plugin||[];let xt=yield*ct.promise(()=>ls.directories(Ae.directory,Ae.worktree));Ce.OPENCODE_CONFIG_DIR&&i.debug("loading config from OPENCODE_CONFIG_DIR",{path:Ce.OPENCODE_CONFIG_DIR});let _t=[];for(let dt of Cg(xt)){if(dt.endsWith(".opencode")||dt===Ce.OPENCODE_CONFIG_DIR)for(let dn of["opencode.json","opencode.jsonc"]){let Pn=en.join(dt,dn);i.debug(`loading config from ${Pn}`),Xe(Pn,yield*Z(Pn)),Re.agent??={},Re.mode??={},Re.plugin??=[]}let Ot=qt(async()=>{await l(dt)});Ot.catch(dn=>{i.warn("background dependency install failed",{dir:dt,error:dn})}),_t.push(Ot),Re.command=Yn(Re.command??{},yield*ct.promise(()=>w(dt))),Re.agent=Yn(Re.agent,yield*ct.promise(()=>I(dt))),Re.agent=Yn(Re.agent,yield*ct.promise(()=>x(dt)));let sn=yield*ct.promise(()=>h(dt));ot(dt,sn)}if(Re.agent=Yn(Re.agent,yield*ct.promise(()=>r(Ae.directory))),process.env.OPENCODE_CONFIG_CONTENT){let dt="OPENCODE_CONFIG_CONTENT",Ot=yield*P(process.env.OPENCODE_CONFIG_CONTENT,{dir:Ae.directory,source:dt});Xe(dt,Ot,"local"),i.debug("loaded custom config from OPENCODE_CONFIG_CONTENT")}let Ao=ea.getOrUndefined(yield*ae.activeOrg().pipe(ct.catch(()=>ct.succeed(ea.none()))));if(Ao&&(yield*ct.gen(function*(){let[dt,Ot]=yield*ct.all([ae.config(Ao.account.id,Ao.org.id),ae.token(Ao.account.id)],{concurrency:2});if(ea.isSome(Ot)&&(process.env.OPENCODE_CONSOLE_TOKEN=Ot.value,Tt.set("OPENCODE_CONSOLE_TOKEN",Ot.value)),et=Ao.org.name,ea.isSome(dt)){let sn=`${Ao.account.url}/api/config`,dn=yield*P(JSON.stringify(dt.value),{dir:en.dirname(sn),source:sn});for(let Pn of Object.keys(dn.provider??{}))nt.add(Pn);Xe(sn,dn,"global")}}).pipe(ct.catch(dt=>(i.debug("failed to fetch remote account config",{error:dt instanceof Error?dt.message:String(dt)}),ct.void)))),Zi(p))for(let dt of["opencode.json","opencode.jsonc"]){let Ot=en.join(p,dt);Xe(Ot,yield*Z(Ot),"global")}Re=c(Re,yield*ct.promise(()=>s()));for(let[dt,Ot]of Object.entries(Re.mode??{}))Re.agent=Yn(Re.agent??{},{[dt]:{...Ot,mode:"primary"}});if(Ce.OPENCODE_PERMISSION&&(Re.permission=Yn(Re.permission??{},JSON.parse(Ce.OPENCODE_PERMISSION))),Re.tools){let dt={};for(let[Ot,sn]of Object.entries(Re.tools)){let dn=sn?"allow":"deny";if(Ot==="write"||Ot==="edit"||Ot==="patch"||Ot==="multiedit"){dt.edit=dn;continue}dt[Ot]=dn}Re.permission=Yn(dt,Re.permission??{})}return Re.username||(Re.username=Sd.userInfo().username),Re.autoshare===!0&&!Re.share&&(Re.share="auto"),Ce.OPENCODE_DISABLE_AUTOCOMPACT&&(Re.compaction={...Re.compaction,auto:!1}),Ce.OPENCODE_DISABLE_PRUNE&&(Re.compaction={...Re.compaction,prune:!1}),{config:Re,directories:xt,deps:_t,consoleState:{consoleManagedProviders:Array.from(nt),activeOrgName:et,switchableOrgCount:0}}}),$e=yield*ge.make(ct.fn("Config.state")(function*(Ae){return yield*we(Ae)})),ee=ct.fn("Config.get")(function*(){return yield*ge.use($e,Ae=>Ae.config)}),de=ct.fn("Config.directories")(function*(){return yield*ge.use($e,Ae=>Ae.directories)}),ke=ct.fn("Config.getConsoleState")(function*(){return yield*ge.use($e,Ae=>Ae.consoleState)}),se=ct.fn("Config.waitForDependencies")(function*(){yield*ge.useEffect($e,Ae=>ct.promise(()=>Promise.all(Ae.deps).then(()=>{})))}),Pe=ct.fn("Config.update")(function*(Ae){let Fe=yield*ge.directory,Re=en.join(Fe,"config.json");Ir.assert(Re,"config update");let nt=yield*Z(Re);yield*be.writeFileString(Re,JSON.stringify(Yn(q(nt),q(Ae)),null,2)).pipe(ct.orDie),yield*ct.promise(()=>he.dispose())}),Ne=ct.fn("Config.invalidate")(function*(Ae){yield*_e;let Fe=he.disposeAll().catch(()=>{}).finally(()=>Ei.emit("event",{directory:"global",payload:{type:ud.Disposed.type,properties:{}}}));Ae&&(yield*ct.promise(()=>Fe))}),Me=ct.fn("Config.updateGlobal")(function*(Ae){let Fe=R(),Re=(yield*me(Fe))??"{}",nt=q(Ae),et;if(Fe.endsWith(".jsonc")){let Ue=L(Re,nt);et=X(Ue,Fe),yield*be.writeFileString(Fe,Ue).pipe(ct.orDie)}else{let Ue=X(Re,Fe),ot=Yn(q(Ue),nt);yield*be.writeFileString(Fe,JSON.stringify(ot,null,2)).pipe(ct.orDie),et=ot}return yield*Ne(),et});return H.of({get:ee,getGlobal:te,getConsoleState:ke,update:Pe,updateGlobal:Me,invalidate:Ne,directories:de,waitForDependencies:se})})),Ie.defaultLayer=Ie.layer.pipe(Qi.provide(ut.defaultLayer),Qi.provide(Fn.defaultLayer),Qi.provide(Gi.defaultLayer));let{runPromise:De}=Ke(H,Ie.defaultLayer);async function Oe(){return De(be=>be.get())}Ie.get=Oe,n(Oe,"get");async function xe(){return De(be=>be.getGlobal())}Ie.getGlobal=xe,n(xe,"getGlobal");async function ie(){return De(be=>be.getConsoleState())}Ie.getConsoleState=ie,n(ie,"getConsoleState");async function le(be){return De(ye=>ye.update(be))}Ie.update=le,n(le,"update");async function Le(be){return De(ye=>ye.updateGlobal(be))}Ie.updateGlobal=Le,n(Le,"updateGlobal");async function ve(be=!1){return De(ye=>ye.invalidate(be))}Ie.invalidate=ve,n(ve,"invalidate");async function Te(){return De(be=>be.directories())}Ie.directories=Te,n(Te,"directories");async function it(){return De(be=>be.waitForDependencies())}Ie.waitForDependencies=it,n(it,"waitForDependencies")})(rt||={});import na from"zod";import{EventEmitter as $g}from"events";import{sqliteTable as Dd,text as Ys,integer as Td}from"drizzle-orm/sqlite-core";var fo=Dd("event_sequence",{aggregate_id:Ys().notNull().primaryKey(),seq:Td().notNull()}),ta=Dd("event",{id:Ys().primaryKey(),aggregate_id:Ys().notNull().references(()=>fo.aggregate_id,{onDelete:"cascade"}),seq:Td().notNull(),type:Ys().notNull(),data:Ys({mode:"json"}).$type().notNull()});import{Schema as Pd}from"effect";import Ug from"zod";var _d=Pd.String.pipe(Pd.brand("EventID"),An(e=>({make:n(t=>e.makeUnsafe(t),"make"),ascending:n(t=>e.makeUnsafe(Nt.ascending("event",t)),"ascending"),zod:Nt.schema("event").pipe(Ug.custom())})));var on;(I=>{I.registry=new Map;let t,o=new Map,i=!1,m,y=new $g;function p(){i=!1,t=void 0,m=n((r,x)=>x,"convertEvent")}I.reset=p,n(p,"reset");function f(r){t=new Map(r.projectors);for(let[x,h]of o.entries()){let v=I.registry.get(b(x,h));mt.define(v.type,v.properties||v.schema)}i=!0,m=r.convertEvent||((x,h)=>h)}I.init=f,n(f,"init");function b(r,x){return x?`${r}.${x}`:r}I.versionedType=b,n(b,"versionedType");function d(r){if(i)throw new Error("Error defining sync event: sync system has been frozen");let x={type:r.type,version:r.version,aggregate:r.aggregate,schema:r.schema,properties:r.busSchema?r.busSchema:r.schema};return o.set(x.type,Math.max(x.version,o.get(x.type)||0)),I.registry.set(b(x.type,x.version),x),x}I.define=d,n(d,"define");function s(r,x){return[r,x]}I.project=s,n(s,"project");function c(r,x,h){if(t==null)throw new Error("No projectors available. Call `SyncEvent.init` to install projectors");let v=t.get(r);if(!v)throw new Error(`Projector not found for event: ${r.type}`);Xt.transaction(S=>{v(S,x.data),Ce.OPENCODE_EXPERIMENTAL_WORKSPACES&&(S.insert(fo).values({aggregate_id:x.aggregateID,seq:x.seq}).onConflictDoUpdate({target:fo.aggregate_id,set:{seq:x.seq}}).run(),S.insert(ta).values({id:x.id,seq:x.seq,aggregate_id:x.aggregateID,type:b(r.type,r.version),data:x.data}).run()),Xt.effect(()=>{if(y.emit("event",{def:r,event:x}),h?.publish){let j=m(r.type,x.data);j instanceof Promise?j.then(O=>{Ve.publish({type:r.type,properties:r.schema},O)}):Ve.publish({type:r.type,properties:r.schema},j)}})})}n(c,"process");function l(r,x){let h=I.registry.get(r.type);if(!h)throw new Error(`Unknown event type: ${r.type}`);let S=Xt.use(O=>O.select({seq:fo.seq}).from(fo).where((0,We.eq)(fo.aggregate_id,r.aggregateID)).get())?.seq??-1;if(r.seq<=S)return;let j=S+1;if(r.seq!==j)throw new Error(`Sequence mismatch for aggregate "${r.aggregateID}": expected ${j}, got ${r.seq}`);c(h,r,{publish:!!x?.republish})}I.replay=l,n(l,"replay");function g(r,x){let h=x[r.aggregate];if(h==null)throw new Error(`SyncEvent.run: "${r.aggregate}" required but not found: ${JSON.stringify(x)}`);if(r.version!==o.get(r.type))throw new Error(`SyncEvent.run: running old versions of events is not allowed: ${r.type}`);Xt.transaction(v=>{let S=_d.ascending(),j=v.select({seq:fo.seq}).from(fo).where((0,We.eq)(fo.aggregate_id,h)).get(),O=j?.seq!=null?j.seq+1:0;c(r,{id:S,seq:O,aggregateID:h,data:x},{publish:!0})},{behavior:"immediate"})}I.run=g,n(g,"run");function u(r){Xt.transaction(x=>{x.delete(fo).where((0,We.eq)(fo.aggregate_id,r)).run(),x.delete(ta).where((0,We.eq)(ta.aggregate_id,r)).run()})}I.remove=u,n(u,"remove");function a(r){return y.on("event",r),()=>y.off("event",r)}I.subscribeAll=a,n(a,"subscribeAll");function w(){return na.union(I.registry.entries().map(([r,x])=>na.object({type:na.literal(r),aggregate:na.literal(x.aggregate),data:x.schema}).meta({ref:"SyncEvent."+x.type})).toArray()).meta({ref:"SyncEvent"})}I.payloads=w,n(w,"payloads")})(on||={});import jn from"path";import Ad from"zod";import{Effect as Vt,Exit as Hg,Layer as Cd,Option as ra,RcMap as Rd,Schema as pn,ServiceMap as Gg,TxReentrantLock as Ks}from"effect";import{Effect as gn,Layer as Od,ServiceMap as qg,Stream as oa}from"effect";import{ChildProcess as Bg,ChildProcessSpawner as Wg}from"effect/unstable/process";var mo;(x=>{let e=["--no-optional-locks","-c","core.autocrlf=false","-c","core.fsmonitor=false","-c","core.longpaths=true","-c","core.symlinks=true","-c","core.quotepath=false"],t=n(h=>h.text().trim(),"out"),o=n(h=>h.split("\0").filter(Boolean),"nuls"),i=n(h=>({exitCode:1,text:n(()=>"","text"),stdout:Buffer.alloc(0),stderr:Buffer.from(h instanceof Error?h.message:String(h))}),"fail"),m=n(h=>h==="??"?"added":h.includes("U")?"modified":h.includes("A")&&!h.includes("D")?"added":h.includes("D")&&!h.includes("A")?"deleted":"modified","kind");class y extends qg.Service()("@opencode/Git"){static{n(this,"Service")}}x.Service=y,x.layer=Od.effect(y,gn.gen(function*(){let h=yield*Wg.ChildProcessSpawner,v=gn.fn("Git.run")(function*(N,A){let F=Bg.make("git",[...e,...N],{cwd:A.cwd,env:A.env,extendEnv:!0,stdin:"ignore",stdout:"pipe",stderr:"pipe"}),V=yield*h.spawn(F),[Y,re]=yield*gn.all([oa.mkString(oa.decodeText(V.stdout)),oa.mkString(oa.decodeText(V.stderr))],{concurrency:2});return{exitCode:yield*V.exitCode,text:n(()=>Y,"text"),stdout:Buffer.from(Y),stderr:Buffer.from(re)}},gn.scoped,gn.catch(N=>gn.succeed(i(N)))),S=gn.fn("Git.text")(function*(N,A){return(yield*v(N,A)).text()}),j=gn.fn("Git.lines")(function*(N,A){return(yield*S(N,A)).split(/\r?\n/).map(F=>F.trim()).filter(Boolean)}),O=gn.fnUntraced(function*(N){return yield*j(["for-each-ref","--format=%(refname:short)","refs/heads"],{cwd:N})}),k=gn.fnUntraced(function*(N,A){let F=yield*v(["config","init.defaultBranch"],{cwd:N}),V=t(F);if(!(!V||!A.includes(V)))return{name:V,ref:V}}),E=gn.fnUntraced(function*(N){let A=yield*j(["remote"],{cwd:N});return A.includes("origin")?"origin":A.length===1?A[0]:A.includes("upstream")?"upstream":A[0]}),D=gn.fn("Git.branch")(function*(N){let A=yield*v(["symbolic-ref","--quiet","--short","HEAD"],{cwd:N});return A.exitCode!==0?void 0:t(A)||void 0}),z=gn.fn("Git.prefix")(function*(N){let A=yield*v(["rev-parse","--show-prefix"],{cwd:N});return A.exitCode!==0?"":t(A)}),_=gn.fn("Git.defaultBranch")(function*(N){let A=yield*E(N);if(A){let Y=yield*v(["symbolic-ref",`refs/remotes/${A}/HEAD`],{cwd:N});if(Y.exitCode===0){let re=t(Y).replace(/^refs\/remotes\//,""),ue=re.startsWith(`${A}/`)?re.slice(`${A}/`.length):"";if(ue)return{name:ue,ref:re}}}let F=yield*O(N),V=yield*k(N,F);if(V)return V;if(F.includes("main"))return{name:"main",ref:"main"};if(F.includes("master"))return{name:"master",ref:"master"}}),B=gn.fn("Git.hasHead")(function*(N){return(yield*v(["rev-parse","--verify","HEAD"],{cwd:N})).exitCode===0}),$=gn.fn("Git.mergeBase")(function*(N,A,F="HEAD"){let V=yield*v(["merge-base",A,F],{cwd:N});return V.exitCode!==0?void 0:t(V)||void 0}),M=gn.fn("Git.show")(function*(N,A,F,V=""){let Y=V?`${V}${F}`:F,re=yield*v(["show",`${A}:${Y}`],{cwd:N});return re.exitCode!==0||re.stdout.includes(0)?"":re.text()}),C=gn.fn("Git.status")(function*(N){return o(yield*S(["status","--porcelain=v1","--untracked-files=all","--no-renames","-z","--","."],{cwd:N})).flatMap(A=>{let F=A.slice(3);if(!F)return[];let V=A.slice(0,2);return[{file:F,code:V,status:m(V)}]})}),T=gn.fn("Git.diff")(function*(N,A){let F=o(yield*S(["diff","--no-ext-diff","--no-renames","--name-status","-z",A,"--","."],{cwd:N}));return F.flatMap((V,Y)=>{if(Y%2!==0)return[];let re=F[Y+1];return!V||!re?[]:[{file:re,code:V,status:m(V)}]})}),G=gn.fn("Git.stats")(function*(N,A){return o(yield*S(["diff","--no-ext-diff","--no-renames","--numstat","-z",A,"--","."],{cwd:N})).flatMap(F=>{let V=F.indexOf(" "),Y=F.indexOf(" ",V+1);if(V===-1||Y===-1)return[];let re=F.slice(Y+1);if(!re)return[];let ue=F.slice(0,V),H=F.slice(V+1,Y),R=ue==="-"?0:Number.parseInt(ue||"0",10),L=H==="-"?0:Number.parseInt(H||"0",10);return[{file:re,additions:Number.isFinite(R)?R:0,deletions:Number.isFinite(L)?L:0}]})});return y.of({run:v,branch:D,prefix:z,defaultBranch:_,hasHead:B,mergeBase:$,show:M,status:C,diff:T,stats:G})})),x.defaultLayer=x.layer.pipe(Od.provide(uo));let{runPromise:b}=Ke(y,x.defaultLayer);async function d(h,v){return b(S=>S.run(h,v))}x.run=d,n(d,"run");async function s(h){return b(v=>v.branch(h))}x.branch=s,n(s,"branch");async function c(h){return b(v=>v.prefix(h))}x.prefix=c,n(c,"prefix");async function l(h){return b(v=>v.defaultBranch(h))}x.defaultBranch=l,n(l,"defaultBranch");async function g(h){return b(v=>v.hasHead(h))}x.hasHead=g,n(g,"hasHead");async function u(h,v,S){return b(j=>j.mergeBase(h,v,S))}x.mergeBase=u,n(u,"mergeBase");async function a(h,v,S,j){return b(O=>O.show(h,v,S,j))}x.show=a,n(a,"show");async function w(h){return b(v=>v.status(h))}x.status=w,n(w,"status");async function I(h,v){return b(S=>S.diff(h,v))}x.diff=I,n(I,"diff");async function r(h,v){return b(S=>S.stats(h,v))}x.stats=r,n(r,"stats")})(mo||={});var Ho;(O=>{let e=qe.create({service:"storage"});O.NotFoundError=tt.create("NotFoundError",Ad.object({message:Ad.string()}));let o=pn.Struct({path:pn.optional(pn.Struct({root:pn.optional(pn.String)}))}),i=pn.Struct({id:pn.String}),m=pn.Struct({id:pn.String}),y=pn.Struct({additions:pn.Number,deletions:pn.Number}),p=pn.Struct({id:pn.String,projectID:pn.String,summary:pn.Struct({diffs:pn.Array(y)})}),f=pn.decodeUnknownOption(o),b=pn.decodeUnknownOption(i),d=pn.decodeUnknownOption(m),s=pn.decodeUnknownOption(p);class c extends Gg.Service()("@opencode/Storage"){static{n(this,"Service")}}O.Service=c;function l(k,E){return jn.join(k,...E)+".json"}n(l,"file");function g(k){return!k||typeof k!="object"?!1:"code"in k&&k.code==="ENOENT"?!0:"reason"in k&&k.reason&&typeof k.reason=="object"&&"_tag"in k.reason?k.reason._tag==="NotFound":!1}n(g,"missing");function u(k){let E=Number.parseInt(k,10);return Number.isNaN(E)?0:E}n(u,"parseMigration");let a=[Vt.fn("Storage.migration.1")(function*(k,E){let D=jn.resolve(k,"../project");if(!(yield*E.isDir(D)))return;let z=yield*E.glob("*",{cwd:D,include:"all"});for(let _ of z){let B=jn.join(D,_);if(!(yield*E.isDir(B)))continue;e.info(`migrating project ${_}`);let $=_,M="/";if($!=="global"){for(let G of yield*E.glob("storage/session/message/*/*.json",{cwd:B,absolute:!0})){let N=f(yield*E.readJson(G),{onExcessProperty:"preserve"}),A=ra.isSome(N)?N.value.path?.root:void 0;if(A){M=A;break}}if(!M||!(yield*E.isDir(M)))continue;let C=yield*Vt.promise(()=>mo.run(["rev-list","--max-parents=0","--all"],{cwd:M})),[T]=C.text().split(`
|
|
51
|
+
`).filter(Boolean).map(G=>G.trim()).toSorted();if(!T)continue;$=T,yield*E.writeWithDirs(jn.join(k,"project",$+".json"),JSON.stringify({id:T,vcs:"git",worktree:M,time:{created:Date.now(),initialized:Date.now()}},null,2)),e.info(`migrating sessions for project ${$}`);for(let G of yield*E.glob("storage/session/info/*.json",{cwd:B,absolute:!0})){let N=jn.join(k,"session",$,jn.basename(G));e.info("copying",{sessionFile:G,dest:N});let A=yield*E.readJson(G),F=b(A,{onExcessProperty:"preserve"});if(yield*E.writeWithDirs(N,JSON.stringify(A,null,2)),!ra.isNone(F)){e.info(`migrating messages for session ${F.value.id}`);for(let V of yield*E.glob(`storage/session/message/${F.value.id}/*.json`,{cwd:B,absolute:!0})){let Y=jn.join(k,"message",F.value.id,jn.basename(V));e.info("copying",{msgFile:V,dest:Y});let re=yield*E.readJson(V),ue=d(re,{onExcessProperty:"preserve"});if(yield*E.writeWithDirs(Y,JSON.stringify(re,null,2)),!ra.isNone(ue)){e.info(`migrating parts for message ${ue.value.id}`);for(let H of yield*E.glob(`storage/session/part/${F.value.id}/${ue.value.id}/*.json`,{cwd:B,absolute:!0})){let R=jn.join(k,"part",ue.value.id,jn.basename(H)),L=yield*E.readJson(H);e.info("copying",{partFile:H,dest:R}),yield*E.writeWithDirs(R,JSON.stringify(L,null,2))}}}}}}}}),Vt.fn("Storage.migration.2")(function*(k,E){for(let D of yield*E.glob("session/*/*.json",{cwd:k,absolute:!0})){let z=yield*E.readJson(D),_=s(z,{onExcessProperty:"preserve"});if(ra.isNone(_))continue;let B=_.value.summary.diffs;yield*E.writeWithDirs(jn.join(k,"session_diff",_.value.id+".json"),JSON.stringify(B,null,2)),yield*E.writeWithDirs(jn.join(k,"session",_.value.projectID,_.value.id+".json"),JSON.stringify({...z,summary:{additions:B.reduce(($,M)=>$+M.additions,0),deletions:B.reduce(($,M)=>$+M.deletions,0)}},null,2))}})];O.layer=Cd.effect(c,Vt.gen(function*(){let k=yield*ut.Service,E=yield*Rd.make({lookup:n(()=>Ks.make(),"lookup"),idleTimeToLive:0}),D=yield*Vt.cached(Vt.gen(function*(){let A=jn.join(je.Path.data,"storage"),F=jn.join(A,"migration"),V=yield*k.readFileString(F).pipe(Vt.map(u),Vt.catchIf(g,()=>Vt.succeed(0)),Vt.orElseSucceed(()=>0));for(let Y=V;Y<a.length;Y++){e.info("running migration",{index:Y});let re=a[Y],ue=yield*Vt.exit(re(A,k));if(Hg.isFailure(ue)){e.error("failed to run migration",{index:Y,cause:ue.cause});break}yield*k.writeWithDirs(F,String(Y+1))}return{dir:A}})),z=n(A=>Vt.fail(new O.NotFoundError({message:`Resource not found: ${A}`})),"fail"),_=n((A,F)=>F.pipe(Vt.catchIf(g,()=>z(A))),"wrap"),B=Vt.fnUntraced(function*(A,F){yield*k.writeWithDirs(A,JSON.stringify(F,null,2))}),$=n((A,F)=>Vt.scoped(Vt.gen(function*(){let V=l((yield*D).dir,A);return yield*F(V,yield*Rd.get(E,V))})),"withResolved"),M=Vt.fn("Storage.remove")(function*(A){yield*$(A,(F,V)=>Ks.withWriteLock(V,k.remove(F).pipe(Vt.catchIf(g,()=>Vt.void))))}),C=n(A=>Vt.gen(function*(){return yield*$(A,(V,Y)=>Ks.withReadLock(Y,_(V,k.readJson(V))))}),"read"),T=n((A,F)=>Vt.gen(function*(){return yield*$(A,(Y,re)=>Ks.withWriteLock(re,Vt.gen(function*(){let ue=yield*_(Y,k.readJson(Y));return F(ue),yield*B(Y,ue),ue})))}),"update"),G=n((A,F)=>Vt.gen(function*(){yield*$(A,(V,Y)=>Ks.withWriteLock(Y,B(V,F)))}),"write"),N=Vt.fn("Storage.list")(function*(A){let F=(yield*D).dir,V=jn.join(F,...A);return(yield*k.glob("**/*",{cwd:V,include:"file"}).pipe(Vt.catch(()=>Vt.succeed([])))).map(re=>[...A,...re.slice(0,-5).split(jn.sep)]).toSorted((re,ue)=>re.join("/").localeCompare(ue.join("/")))});return c.of({remove:M,read:C,update:T,write:G,list:N})})),O.defaultLayer=O.layer.pipe(Cd.provide(ut.defaultLayer));let{runPromise:r}=Ke(c,O.defaultLayer);async function x(k){return r(E=>E.remove(k))}O.remove=x,n(x,"remove");async function h(k){return r(E=>E.read(k))}O.read=h,n(h,"read");async function v(k,E){return r(D=>D.update(k,E))}O.update=v,n(v,"update");async function S(k,E){return r(D=>D.write(k,E))}O.write=S,n(S,"write");async function j(k){return r(E=>E.list(k))}O.list=j,n(j,"list")})(Ho||={});import Vg from"zod";function sa(e){let t={};for(let[o,i]of Object.entries(e.required().shape))t[o]=i.nullable();return Vg.object(t)}n(sa,"updateSchema");import K from"zod";import{APICallError as ah,convertToModelMessages as ch,LoadAPIKeyError as lh}from"ai";import Xs from"path";import{pathToFileURL as jr,fileURLToPath as Jg}from"url";import{createMessageConnection as Yg,StreamMessageReader as Kg,StreamMessageWriter as Xg}from"vscode-jsonrpc/node.js";var jd={".abap":"abap",".bat":"bat",".bib":"bibtex",".bibtex":"bibtex",".clj":"clojure",".cljs":"clojure",".cljc":"clojure",".edn":"clojure",".coffee":"coffeescript",".c":"c",".cpp":"cpp",".cxx":"cpp",".cc":"cpp",".c++":"cpp",".cs":"csharp",".css":"css",".d":"d",".pas":"pascal",".pascal":"pascal",".diff":"diff",".patch":"diff",".dart":"dart",".dockerfile":"dockerfile",".ex":"elixir",".exs":"elixir",".erl":"erlang",".ets":"typescript",".hrl":"erlang",".fs":"fsharp",".fsi":"fsharp",".fsx":"fsharp",".fsscript":"fsharp",".gitcommit":"git-commit",".gitrebase":"git-rebase",".go":"go",".groovy":"groovy",".gleam":"gleam",".hbs":"handlebars",".handlebars":"handlebars",".hs":"haskell",".lhs":"haskell",".html":"html",".htm":"html",".ini":"ini",".java":"java",".jl":"julia",".js":"javascript",".kt":"kotlin",".kts":"kotlin",".jsx":"javascriptreact",".json":"json",".tex":"latex",".latex":"latex",".less":"less",".lua":"lua",".makefile":"makefile",makefile:"makefile",".md":"markdown",".markdown":"markdown",".m":"objective-c",".mm":"objective-cpp",".pl":"perl",".pm":"perl",".pm6":"perl6",".php":"php",".ps1":"powershell",".psm1":"powershell",".pug":"jade",".jade":"jade",".py":"python",".r":"r",".cshtml":"razor",".razor":"razor",".rb":"ruby",".rake":"ruby",".gemspec":"ruby",".ru":"ruby",".erb":"erb",".html.erb":"erb",".js.erb":"erb",".css.erb":"erb",".json.erb":"erb",".rs":"rust",".scss":"scss",".sass":"sass",".scala":"scala",".shader":"shaderlab",".sh":"shellscript",".bash":"shellscript",".zsh":"shellscript",".ksh":"shellscript",".sql":"sql",".svelte":"svelte",".swift":"swift",".ts":"typescript",".tsx":"typescriptreact",".mts":"typescript",".cts":"typescript",".mtsx":"typescriptreact",".ctsx":"typescriptreact",".xml":"xml",".xsl":"xsl",".yaml":"yaml",".yml":"yaml",".mjs":"javascript",".cjs":"javascript",".vue":"vue",".zig":"zig",".zon":"zig",".astro":"astro",".ml":"ocaml",".mli":"ocaml",".tf":"terraform",".tfvars":"terraform-vars",".hcl":"hcl",".nix":"nix",".typ":"typst",".typc":"typst"};import Zs from"zod";function ps(e,t){let o;return Promise.race([e.then(i=>(clearTimeout(o),i)),new Promise((i,m)=>{o=setTimeout(()=>{m(new Error(`Operation timed out after ${t}ms`))},t)})])}n(ps,"withTimeout");var Zg=150,fc;(m=>{let e=qe.create({service:"lsp.client"});m.InitializeError=tt.create("LSPInitializeError",Zs.object({serverID:Zs.string()})),m.Event={Diagnostics:mt.define("lsp.client.diagnostics",Zs.object({serverID:Zs.string(),path:Zs.string()}))};async function i(y){let p=e.clone().tag("serverID",y.serverID);p.info("starting client");let f=Yg(new Kg(y.server.process.stdout),new Xg(y.server.process.stdin)),b=new Map;f.onNotification("textDocument/publishDiagnostics",c=>{let l=Ee.normalizePath(Jg(c.uri));p.info("textDocument/publishDiagnostics",{path:l,count:c.diagnostics.length});let g=b.has(l);b.set(l,c.diagnostics),!(!g&&y.serverID==="typescript")&&Ve.publish(m.Event.Diagnostics,{path:l,serverID:y.serverID})}),f.onRequest("window/workDoneProgress/create",c=>(p.info("window/workDoneProgress/create",c),null)),f.onRequest("workspace/configuration",async()=>[y.server.initialization??{}]),f.onRequest("client/registerCapability",async()=>{}),f.onRequest("client/unregisterCapability",async()=>{}),f.onRequest("workspace/workspaceFolders",async()=>[{name:"workspace",uri:jr(y.root).href}]),f.listen(),p.info("sending initialize"),await ps(f.sendRequest("initialize",{rootUri:jr(y.root).href,processId:y.server.process.pid,workspaceFolders:[{name:"workspace",uri:jr(y.root).href}],initializationOptions:{...y.server.initialization},capabilities:{window:{workDoneProgress:!0},workspace:{configuration:!0,didChangeWatchedFiles:{dynamicRegistration:!0}},textDocument:{synchronization:{didOpen:!0,didChange:!0},publishDiagnostics:{versionSupport:!0}}}}),45e3).catch(c=>{throw p.error("initialize error",{error:c}),new m.InitializeError({serverID:y.serverID},{cause:c})}),await f.sendNotification("initialized",{}),y.server.initialization&&await f.sendNotification("workspace/didChangeConfiguration",{settings:y.server.initialization});let d={},s={root:y.root,get serverID(){return y.serverID},get connection(){return f},notify:{async open(c){c.path=Xs.isAbsolute(c.path)?c.path:Xs.resolve(he.directory,c.path);let l=await Ee.readText(c.path),g=Xs.extname(c.path),u=jd[g]??"plaintext",a=d[c.path];if(a!==void 0){e.info("workspace/didChangeWatchedFiles",c),await f.sendNotification("workspace/didChangeWatchedFiles",{changes:[{uri:jr(c.path).href,type:2}]});let w=a+1;d[c.path]=w,e.info("textDocument/didChange",{path:c.path,version:w}),await f.sendNotification("textDocument/didChange",{textDocument:{uri:jr(c.path).href,version:w},contentChanges:[{text:l}]});return}e.info("workspace/didChangeWatchedFiles",c),await f.sendNotification("workspace/didChangeWatchedFiles",{changes:[{uri:jr(c.path).href,type:1}]}),e.info("textDocument/didOpen",c),b.delete(c.path),await f.sendNotification("textDocument/didOpen",{textDocument:{uri:jr(c.path).href,languageId:u,version:0,text:l}}),d[c.path]=0}},get diagnostics(){return b},async waitForDiagnostics(c){let l=Ee.normalizePath(Xs.isAbsolute(c.path)?c.path:Xs.resolve(he.directory,c.path));e.info("waiting for diagnostics",{path:l});let g,u;return await ps(new Promise(a=>{g=Ve.subscribe(m.Event.Diagnostics,w=>{w.properties.path===l&&w.properties.serverID===s.serverID&&(u&&clearTimeout(u),u=setTimeout(()=>{e.info("got diagnostics",{path:l}),g?.(),a()},Zg))})}),3e3).catch(()=>{}).finally(()=>{u&&clearTimeout(u),g?.()})},async shutdown(){p.info("shutting down"),f.end(),f.dispose(),await St.stop(y.server.process),p.info("shutdown")}};return p.info("initialized"),s}m.create=i,n(i,"create")})(fc||={});import mc from"path";import{pathToFileURL as fs,fileURLToPath as Qg}from"url";import tn from"zod";import{Effect as Wt,Layer as Md,ServiceMap as eh}from"effect";var Pt;(z=>{let e=qe.create({service:"lsp"});z.Event={Updated:mt.define("lsp.updated",tn.object({}))},z.Range=tn.object({start:tn.object({line:tn.number(),character:tn.number()}),end:tn.object({line:tn.number(),character:tn.number()})}).meta({ref:"Range"}),z.Symbol=tn.object({name:tn.string(),kind:tn.number(),location:tn.object({uri:tn.string(),range:z.Range})}).meta({ref:"Symbol"}),z.DocumentSymbol=tn.object({name:tn.string(),detail:tn.string().optional(),kind:tn.number(),range:z.Range,selectionRange:z.Range}).meta({ref:"DocumentSymbol"}),z.Status=tn.object({id:tn.string(),name:tn.string(),root:tn.string(),status:tn.union([tn.literal("connected"),tn.literal("error")])}).meta({ref:"LSPStatus"});let p;(xe=>(xe[xe.File=1]="File",xe[xe.Module=2]="Module",xe[xe.Namespace=3]="Namespace",xe[xe.Package=4]="Package",xe[xe.Class=5]="Class",xe[xe.Method=6]="Method",xe[xe.Property=7]="Property",xe[xe.Field=8]="Field",xe[xe.Constructor=9]="Constructor",xe[xe.Enum=10]="Enum",xe[xe.Interface=11]="Interface",xe[xe.Function=12]="Function",xe[xe.Variable=13]="Variable",xe[xe.Constant=14]="Constant",xe[xe.String=15]="String",xe[xe.Number=16]="Number",xe[xe.Boolean=17]="Boolean",xe[xe.Array=18]="Array",xe[xe.Object=19]="Object",xe[xe.Key=20]="Key",xe[xe.Null=21]="Null",xe[xe.EnumMember=22]="EnumMember",xe[xe.Struct=23]="Struct",xe[xe.Event=24]="Event",xe[xe.Operator=25]="Operator",xe[xe.TypeParameter=26]="TypeParameter"))(p||={});let f=[5,12,6,11,13,14,23,10],b=n(_=>{Ce.OPENCODE_EXPERIMENTAL_LSP_TY?_.pyright&&(e.info("LSP server pyright is disabled because OPENCODE_EXPERIMENTAL_LSP_TY is enabled"),delete _.pyright):_.ty&&delete _.ty},"filterExperimentalServers");class d extends eh.Service()("@opencode/LSP"){static{n(this,"Service")}}z.Service=d,z.layer=Md.effect(d,Wt.gen(function*(){let _=yield*rt.Service,B=yield*ge.make(Wt.fn("LSP.state")(function*(){let Q=yield*_.get(),oe={};if(Q.lsp===!1)e.info("all LSPs are disabled");else{for(let pe of Object.values($s))oe[pe.id]=pe;b(oe);for(let[pe,De]of Object.entries(Q.lsp??{})){let Oe=oe[pe];if(De.disabled){e.info(`LSP server ${pe} is disabled`),delete oe[pe];continue}oe[pe]={...Oe,id:pe,root:Oe?.root??(async()=>he.directory),extensions:De.extensions??Oe?.extensions??[],spawn:n(async xe=>({process:ht(De.command[0],De.command.slice(1),{cwd:xe,env:{...process.env,...De.env}}),initialization:De.initialization}),"spawn")}}e.info("enabled LSP servers",{serverIds:Object.values(oe).map(pe=>pe.id).join(", ")})}let ce={clients:[],servers:oe,broken:new Set,spawning:new Map};return yield*Wt.addFinalizer(()=>Wt.promise(async()=>{await Promise.all(ce.clients.map(pe=>pe.shutdown()))})),ce})),$=Wt.fnUntraced(function*(Q){if(!he.containsPath(Q))return[];let oe=yield*ge.get(B);return yield*Wt.promise(async()=>{let ce=mc.parse(Q).ext||Q,pe=[];async function De(Oe,xe,ie){let le=await Oe.spawn(xe).then(Te=>(Te||oe.broken.add(ie),Te)).catch(Te=>{oe.broken.add(ie),e.error(`Failed to spawn LSP server ${Oe.id}`,{error:Te})});if(!le)return;e.info("spawned lsp server",{serverID:Oe.id});let Le=await fc.create({serverID:Oe.id,server:le,root:xe}).catch(async Te=>{oe.broken.add(ie),await St.stop(le.process),e.error(`Failed to initialize LSP client ${Oe.id}`,{error:Te})});if(!Le)return;let ve=oe.clients.find(Te=>Te.root===xe&&Te.serverID===Oe.id);return ve?(await St.stop(le.process),ve):(oe.clients.push(Le),Le)}n(De,"schedule");for(let Oe of Object.values(oe.servers)){if(Oe.extensions.length&&!Oe.extensions.includes(ce))continue;let xe=await Oe.root(Q);if(!xe||oe.broken.has(xe+Oe.id))continue;let ie=oe.clients.find(Te=>Te.root===xe&&Te.serverID===Oe.id);if(ie){pe.push(ie);continue}let le=oe.spawning.get(xe+Oe.id);if(le){let Te=await le;if(!Te)continue;pe.push(Te);continue}let Le=De(Oe,xe,xe+Oe.id);oe.spawning.set(xe+Oe.id,Le),Le.finally(()=>{oe.spawning.get(xe+Oe.id)===Le&&oe.spawning.delete(xe+Oe.id)});let ve=await Le;ve&&(pe.push(ve),Ve.publish(z.Event.Updated,{}))}return pe})}),M=Wt.fnUntraced(function*(Q,oe){let ce=yield*$(Q);return yield*Wt.promise(()=>Promise.all(ce.map(pe=>oe(pe))))}),C=Wt.fnUntraced(function*(Q){let oe=yield*ge.get(B);return yield*Wt.promise(()=>Promise.all(oe.clients.map(ce=>Q(ce))))}),T=Wt.fn("LSP.init")(function*(){yield*ge.get(B)}),G=Wt.fn("LSP.status")(function*(){let Q=yield*ge.get(B),oe=[];for(let ce of Q.clients)oe.push({id:ce.serverID,name:Q.servers[ce.serverID].id,root:mc.relative(he.directory,ce.root),status:"connected"});return oe}),N=Wt.fn("LSP.hasClients")(function*(Q){let oe=yield*ge.get(B);return yield*Wt.promise(async()=>{let ce=mc.parse(Q).ext||Q;for(let pe of Object.values(oe.servers)){if(pe.extensions.length&&!pe.extensions.includes(ce))continue;let De=await pe.root(Q);if(De&&!oe.broken.has(De+pe.id))return!0}return!1})}),A=Wt.fn("LSP.touchFile")(function*(Q,oe){e.info("touching file",{file:Q});let ce=yield*$(Q);yield*Wt.promise(()=>Promise.all(ce.map(async pe=>{let De=oe?pe.waitForDiagnostics({path:Q}):Promise.resolve();return await pe.notify.open({path:Q}),De})).catch(pe=>{e.error("failed to touch file",{err:pe,file:Q})}))}),F=Wt.fn("LSP.diagnostics")(function*(){let Q={},oe=yield*C(async ce=>ce.diagnostics);for(let ce of oe)for(let[pe,De]of ce.entries()){let Oe=Q[pe]||[];Oe.push(...De),Q[pe]=Oe}return Q}),V=Wt.fn("LSP.hover")(function*(Q){return yield*M(Q.file,oe=>oe.connection.sendRequest("textDocument/hover",{textDocument:{uri:fs(Q.file).href},position:{line:Q.line,character:Q.character}}).catch(()=>null))}),Y=Wt.fn("LSP.definition")(function*(Q){return(yield*M(Q.file,ce=>ce.connection.sendRequest("textDocument/definition",{textDocument:{uri:fs(Q.file).href},position:{line:Q.line,character:Q.character}}).catch(()=>null))).flat().filter(Boolean)}),re=Wt.fn("LSP.references")(function*(Q){return(yield*M(Q.file,ce=>ce.connection.sendRequest("textDocument/references",{textDocument:{uri:fs(Q.file).href},position:{line:Q.line,character:Q.character},context:{includeDeclaration:!0}}).catch(()=>[]))).flat().filter(Boolean)}),ue=Wt.fn("LSP.implementation")(function*(Q){return(yield*M(Q.file,ce=>ce.connection.sendRequest("textDocument/implementation",{textDocument:{uri:fs(Q.file).href},position:{line:Q.line,character:Q.character}}).catch(()=>null))).flat().filter(Boolean)}),H=Wt.fn("LSP.documentSymbol")(function*(Q){let oe=Qg(Q);return(yield*M(oe,pe=>pe.connection.sendRequest("textDocument/documentSymbol",{textDocument:{uri:Q}}).catch(()=>[]))).flat().filter(Boolean)}),R=Wt.fn("LSP.workspaceSymbol")(function*(Q){return(yield*C(ce=>ce.connection.sendRequest("workspace/symbol",{query:Q}).then(pe=>pe.filter(De=>f.includes(De.kind))).then(pe=>pe.slice(0,10)).catch(()=>[]))).flat()}),L=Wt.fn("LSP.prepareCallHierarchy")(function*(Q){return(yield*M(Q.file,ce=>ce.connection.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:fs(Q.file).href},position:{line:Q.line,character:Q.character}}).catch(()=>[]))).flat().filter(Boolean)}),q=Wt.fnUntraced(function*(Q,oe){return(yield*M(Q.file,async pe=>{let De=await pe.connection.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:fs(Q.file).href},position:{line:Q.line,character:Q.character}}).catch(()=>[]);return De?.length?pe.connection.sendRequest(oe,{item:De[0]}).catch(()=>[]):[]})).flat().filter(Boolean)}),X=Wt.fn("LSP.incomingCalls")(function*(Q){return yield*q(Q,"callHierarchy/incomingCalls")}),ne=Wt.fn("LSP.outgoingCalls")(function*(Q){return yield*q(Q,"callHierarchy/outgoingCalls")});return d.of({init:T,status:G,hasClients:N,touchFile:A,diagnostics:F,hover:V,definition:Y,references:re,implementation:ue,documentSymbol:H,workspaceSymbol:R,prepareCallHierarchy:L,incomingCalls:X,outgoingCalls:ne})})),z.defaultLayer=z.layer.pipe(Md.provide(rt.defaultLayer));let{runPromise:l}=Ke(d,z.defaultLayer);z.init=n(async()=>l(_=>_.init()),"init"),z.status=n(async()=>l(_=>_.status()),"status"),z.hasClients=n(async _=>l(B=>B.hasClients(_)),"hasClients"),z.touchFile=n(async(_,B)=>l($=>$.touchFile(_,B)),"touchFile"),z.diagnostics=n(async()=>l(_=>_.diagnostics()),"diagnostics"),z.hover=n(async _=>l(B=>B.hover(_)),"hover"),z.definition=n(async _=>l(B=>B.definition(_)),"definition"),z.references=n(async _=>l(B=>B.references(_)),"references"),z.implementation=n(async _=>l(B=>B.implementation(_)),"implementation"),z.documentSymbol=n(async _=>l(B=>B.documentSymbol(_)),"documentSymbol"),z.workspaceSymbol=n(async _=>l(B=>B.workspaceSymbol(_)),"workspaceSymbol"),z.prepareCallHierarchy=n(async _=>l(B=>B.prepareCallHierarchy(_)),"prepareCallHierarchy"),z.incomingCalls=n(async _=>l(B=>B.incomingCalls(_)),"incomingCalls"),z.outgoingCalls=n(async _=>l(B=>B.outgoingCalls(_)),"outgoingCalls");let D;(B=>{function _($){let C={1:"ERROR",2:"WARN",3:"INFO",4:"HINT"}[$.severity||1],T=$.range.start.line+1,G=$.range.start.character+1;return`${C} [${T}:${G}] ${$.message}`}B.pretty=_,n(_,"pretty")})(D=z.Diagnostic||={})})(Pt||={});import{Cause as th,Duration as Ld,Effect as Ye,Layer as ia,Schedule as nh,Semaphore as oh,ServiceMap as rh,Stream as lr}from"effect";import{ChildProcess as Nd,ChildProcessSpawner as zd}from"effect/unstable/process";import ms from"path";import Lo from"zod";var $n;(x=>{x.Patch=Lo.object({hash:Lo.string(),files:Lo.string().array()}),x.FileDiff=Lo.object({file:Lo.string(),before:Lo.string(),after:Lo.string(),additions:Lo.number(),deletions:Lo.number(),status:Lo.enum(["added","deleted","modified"]).optional()}).meta({ref:"FileDiff"});let o=qe.create({service:"snapshot"}),i="7.days",m=2*1024*1024,y=["-c","core.longpaths=true","-c","core.symlinks=true"],p=["-c","core.autocrlf=false",...y],f=[...p,"-c","core.quotepath=false"];class b extends rh.Service()("@opencode/Snapshot"){static{n(this,"Service")}}x.Service=b,x.layer=ia.effect(b,Ye.gen(function*(){let h=yield*ut.Service,v=yield*zd.ChildProcessSpawner,S=yield*rt.Service,j=new Map,O=n(E=>{let D=j.get(E);if(D)return D;let z=oh.makeUnsafe(1);return j.set(E,z),z},"lock"),k=yield*ge.make(Ye.fn("Snapshot.state")(function*(E){let D={directory:E.directory,worktree:E.worktree,gitdir:ms.join(je.Path.data,"snapshot",E.project.id,qo.fast(E.worktree)),vcs:E.project.vcs},z=n(q=>["--git-dir",D.gitdir,"--work-tree",D.worktree,...q],"args"),_=Ye.fnUntraced(function*(q,X){let ne=Nd.make("git",q,{cwd:X?.cwd,env:X?.env,extendEnv:!0}),Q=yield*v.spawn(ne),[oe,ce]=yield*Ye.all([lr.mkString(lr.decodeText(Q.stdout)),lr.mkString(lr.decodeText(Q.stderr))],{concurrency:2});return{code:yield*Q.exitCode,text:oe,stderr:ce}},Ye.scoped,Ye.catch(q=>Ye.succeed({code:zd.ExitCode(1),text:"",stderr:String(q)}))),B=n(q=>h.exists(q).pipe(Ye.orDie),"exists"),$=n(q=>h.readFileString(q).pipe(Ye.catch(()=>Ye.succeed(""))),"read"),M=n(q=>h.remove(q).pipe(Ye.catch(()=>Ye.void)),"remove"),C=n(q=>O(D.gitdir).withPermits(1)(q),"locked"),T=Ye.fnUntraced(function*(){return D.vcs!=="git"?!1:(yield*S.get()).snapshot!==!1}),G=Ye.fnUntraced(function*(){let X=(yield*_(["rev-parse","--path-format=absolute","--git-path","info/exclude"],{cwd:D.worktree})).text.trim();if(X&&(yield*B(X)))return X}),N=Ye.fnUntraced(function*(q=[]){let X=yield*G(),ne=ms.join(D.gitdir,"info","exclude"),Q=[X?(yield*$(X)).trimEnd():"",...q.map(oe=>`/${oe.replaceAll("\\","/")}`)].filter(Boolean).join(`
|
|
52
|
+
`);yield*h.ensureDir(ms.join(D.gitdir,"info")).pipe(Ye.orDie),yield*h.writeFileString(ne,Q?`${Q}
|
|
53
|
+
`:"").pipe(Ye.orDie)}),A=Ye.fnUntraced(function*(){yield*N();let[q,X]=yield*Ye.all([_([...f,...z(["diff-files","--name-only","-z","--","."])],{cwd:D.directory}),_([...f,...z(["ls-files","--others","--exclude-standard","-z","--","."])],{cwd:D.directory})],{concurrency:2});if(q.code!==0||X.code!==0){o.warn("failed to list snapshot files",{diffCode:q.code,diffStderr:q.stderr,otherCode:X.code,otherStderr:X.stderr});return}let ne=q.text.split("\0").filter(Boolean),Q=X.text.split("\0").filter(Boolean),oe=Array.from(new Set([...ne,...Q]));if(!oe.length)return;let ce=(yield*Ye.all(oe.map(De=>h.stat(ms.join(D.directory,De)).pipe(Ye.catch(()=>Ye.void)).pipe(Ye.map(Oe=>!Oe||Oe.type!=="File"?void 0:(typeof Oe.size=="bigint"?Number(Oe.size):Oe.size)>m?De:void 0))),{concurrency:8})).filter(De=>!!De);yield*N(ce);let pe=yield*_([...p,...z(["add","--sparse","."])],{cwd:D.directory});pe.code!==0&&o.warn("failed to add snapshot files",{exitCode:pe.code,stderr:pe.stderr})}),F=Ye.fnUntraced(function*(){return yield*C(Ye.gen(function*(){if(!(yield*T())||!(yield*B(D.gitdir)))return;let q=yield*_(z(["gc",`--prune=${i}`]),{cwd:D.directory});if(q.code!==0){o.warn("cleanup failed",{exitCode:q.code,stderr:q.stderr});return}o.info("cleanup",{prune:i})}))}),V=Ye.fnUntraced(function*(){return yield*C(Ye.gen(function*(){if(!(yield*T()))return;let q=yield*B(D.gitdir);yield*h.ensureDir(D.gitdir).pipe(Ye.orDie),q||(yield*_(["init"],{env:{GIT_DIR:D.gitdir,GIT_WORK_TREE:D.worktree}}),yield*_(["--git-dir",D.gitdir,"config","core.autocrlf","false"]),yield*_(["--git-dir",D.gitdir,"config","core.longpaths","true"]),yield*_(["--git-dir",D.gitdir,"config","core.symlinks","true"]),yield*_(["--git-dir",D.gitdir,"config","core.fsmonitor","false"]),o.info("initialized")),yield*A();let ne=(yield*_(z(["write-tree"]),{cwd:D.directory})).text.trim();return o.info("tracking",{hash:ne,cwd:D.directory,git:D.gitdir}),ne}))}),Y=Ye.fnUntraced(function*(q){return yield*C(Ye.gen(function*(){yield*A();let X=yield*_([...f,...z(["diff","--cached","--no-ext-diff","--name-only",q,"--","."])],{cwd:D.directory});return X.code!==0?(o.warn("failed to get diff",{hash:q,exitCode:X.code}),{hash:q,files:[]}):{hash:q,files:X.text.trim().split(`
|
|
54
|
+
`).map(ne=>ne.trim()).filter(Boolean).map(ne=>ms.join(D.worktree,ne).replaceAll("\\","/"))}}))}),re=n(()=>{if(!Ir.allows(D.worktree))return o.error("refused to restore a snapshot in the user's project folder",{worktree:D.worktree}),new Error(`snapshot restore refused: ${D.worktree} is the user's project folder. Nothing was written.`)},"assertRestorable"),ue=Ye.fnUntraced(function*(q){let X=re();return X?yield*Ye.die(X):yield*C(Ye.gen(function*(){o.info("restore",{commit:q});let ne=yield*_([...y,...z(["read-tree",q])],{cwd:D.worktree});if(ne.code===0){let Q=yield*_([...y,...z(["checkout-index","-a","-f"])],{cwd:D.worktree});if(Q.code===0)return;o.error("failed to restore snapshot",{snapshot:q,exitCode:Q.code,stderr:Q.stderr});return}o.error("failed to restore snapshot",{snapshot:q,exitCode:ne.code,stderr:ne.stderr})}))}),H=Ye.fnUntraced(function*(q){let X=re();return X?yield*Ye.die(X):yield*C(Ye.gen(function*(){let ne=[],Q=new Set;for(let pe of q)for(let De of pe.files)Q.has(De)||(Q.add(De),ne.push({hash:pe.hash,file:De,rel:ms.relative(D.worktree,De).replaceAll("\\","/")}));let oe=Ye.fnUntraced(function*(pe){if(o.info("reverting",{file:pe.file,hash:pe.hash}),(yield*_([...y,...z(["checkout",pe.hash,"--",pe.file])],{cwd:D.worktree})).code===0)return;let Oe=yield*_([...y,...z(["ls-tree",pe.hash,"--",pe.rel])],{cwd:D.worktree});if(Oe.code===0&&Oe.text.trim()){o.info("file existed in snapshot but checkout failed, keeping",{file:pe.file,hash:pe.hash});return}o.info("file did not exist in snapshot, deleting",{file:pe.file,hash:pe.hash}),yield*M(pe.file)}),ce=n((pe,De)=>pe===De||pe.startsWith(`${De}/`)||De.startsWith(`${pe}/`),"clash");for(let pe=0;pe<ne.length;){let De=ne[pe],Oe=[De],xe=pe+1;for(;xe<ne.length&&Oe.length<100;){let ve=ne[xe];if(ve.hash!==De.hash||Oe.some(Te=>ce(Te.rel,ve.rel)))break;Oe.push(ve),xe+=1}if(Oe.length===1){yield*oe(De),pe=xe;continue}let ie=yield*_([...y,...z(["ls-tree","--name-only",De.hash,"--",...Oe.map(ve=>ve.rel)])],{cwd:D.worktree});if(ie.code!==0){o.info("batched ls-tree failed, falling back to single-file revert",{hash:De.hash,files:Oe.length});for(let ve of Oe)yield*oe(ve);pe=xe;continue}let le=new Set(ie.text.trim().split(`
|
|
55
|
+
`).map(ve=>ve.trim()).filter(Boolean)),Le=Oe.filter(ve=>le.has(ve.rel));if(Le.length&&(o.info("reverting",{hash:De.hash,files:Le.length}),(yield*_([...y,...z(["checkout",De.hash,"--",...Le.map(Te=>Te.file)])],{cwd:D.worktree})).code!==0)){o.info("batched checkout failed, falling back to single-file revert",{hash:De.hash,files:Le.length});for(let Te of Oe)yield*oe(Te);pe=xe;continue}for(let ve of Oe)le.has(ve.rel)||(o.info("file did not exist in snapshot, deleting",{file:ve.file,hash:ve.hash}),yield*M(ve.file));pe=xe}}))}),R=Ye.fnUntraced(function*(q){return yield*C(Ye.gen(function*(){yield*A();let X=yield*_([...f,...z(["diff","--cached","--no-ext-diff",q,"--","."])],{cwd:D.worktree});return X.code!==0?(o.warn("failed to get diff",{hash:q,exitCode:X.code,stderr:X.stderr}),""):X.text.trim()}))}),L=Ye.fnUntraced(function*(q,X){return yield*C(Ye.gen(function*(){let ne=Ye.fnUntraced(function*(ie){return ie.binary?["",""]:ie.status==="added"?["",yield*_([...p,...z(["show",`${X}:${ie.file}`])]).pipe(Ye.map(le=>le.text))]:ie.status==="deleted"?[yield*_([...p,...z(["show",`${q}:${ie.file}`])]).pipe(Ye.map(le=>le.text)),""]:yield*Ye.all([_([...p,...z(["show",`${q}:${ie.file}`])]).pipe(Ye.map(le=>le.text)),_([...p,...z(["show",`${X}:${ie.file}`])]).pipe(Ye.map(le=>le.text))],{concurrency:2})}),Q=Ye.fnUntraced(function*(ie){let le=ie.flatMap(P=>P.binary?[]:P.status==="added"?[{file:P.file,side:"after",ref:`${X}:${P.file}`}]:P.status==="deleted"?[{file:P.file,side:"before",ref:`${q}:${P.file}`}]:[{file:P.file,side:"before",ref:`${q}:${P.file}`},{file:P.file,side:"after",ref:`${X}:${P.file}`}]);if(!le.length)return new Map;let Le=Nd.make("git",[...p,...z(["cat-file","--batch"])],{cwd:D.directory,extendEnv:!0,stdin:lr.make(new TextEncoder().encode(le.map(P=>P.ref).join(`
|
|
56
|
+
`)+`
|
|
57
|
+
`))}),ve=yield*v.spawn(Le),[Te,it]=yield*Ye.all([lr.mkUint8Array(ve.stdout),lr.mkString(lr.decodeText(ve.stderr))],{concurrency:2});if((yield*ve.exitCode)!==0){o.info("git cat-file --batch failed during snapshot diff, falling back to per-file git show",{stderr:it,refs:le.length});return}let be=n((P,Z)=>{o.info(P,{...Z,refs:le.length})},"fail"),ye=new Map,ae=new TextDecoder,me=0;for(let P of le){let Z=me;for(;Z<Te.length&&Te[Z]!==10;)Z+=1;if(Z>=Te.length)return be("git cat-file --batch returned a truncated header during snapshot diff, falling back to per-file git show");let J=ae.decode(Te.slice(me,Z));me=Z+1;let fe=ye.get(P.file)??{before:"",after:""};if(J.endsWith(" missing")){ye.set(P.file,fe);continue}let _e=J.match(/^[0-9a-f]+ blob (\d+)$/);if(!_e)return be("git cat-file --batch returned an unexpected header during snapshot diff, falling back to per-file git show",{head:J});let te=Number(_e[1]);if(!Number.isInteger(te)||te<0||me+te>=Te.length||Te[me+te]!==10)return be("git cat-file --batch returned truncated content during snapshot diff, falling back to per-file git show",{head:J});let we=ae.decode(Te.slice(me,me+te));P.side==="before"&&(fe.before=we),P.side==="after"&&(fe.after=we),ye.set(P.file,fe),me+=te+1}return me!==Te.length?be("git cat-file --batch returned trailing data during snapshot diff, falling back to per-file git show"):ye},Ye.scoped,Ye.catch(()=>Ye.succeed(void 0))),oe=[],ce=new Map,pe=yield*_([...f,...z(["diff","--no-ext-diff","--name-status","--no-renames",q,X,"--","."])],{cwd:D.directory});for(let ie of pe.text.trim().split(`
|
|
58
|
+
`)){if(!ie)continue;let[le,Le]=ie.split(" ");!le||!Le||ce.set(Le,le.startsWith("A")?"added":le.startsWith("D")?"deleted":"modified")}let Oe=(yield*_([...f,...z(["diff","--no-ext-diff","--no-renames","--numstat",q,X,"--","."])],{cwd:D.directory})).text.trim().split(`
|
|
59
|
+
`).filter(Boolean).flatMap(ie=>{let[le,Le,ve]=ie.split(" ");if(!ve)return[];let Te=le==="-"&&Le==="-",it=Te?0:parseInt(le),Ie=Te?0:parseInt(Le);return[{file:ve,status:ce.get(ve)??"modified",binary:Te,additions:Number.isFinite(it)?it:0,deletions:Number.isFinite(Ie)?Ie:0}]}),xe=100;for(let ie=0;ie<Oe.length;ie+=xe){let le=Oe.slice(ie,ie+xe),Le=yield*Q(le);for(let ve of le){let Te=Le?.get(ve.file)??{before:"",after:""},[it,Ie]=ve.binary?["",""]:Le?[Te.before,Te.after]:yield*ne(ve);oe.push({file:ve.file,before:it,after:Ie,additions:ve.additions,deletions:ve.deletions,status:ve.status})}}return oe}))});return yield*F().pipe(Ye.catchCause(q=>(o.error("cleanup loop failed",{cause:th.pretty(q)}),Ye.void)),Ye.repeat(nh.spaced(Ld.hours(1))),Ye.delay(Ld.minutes(1)),Ye.forkScoped),{cleanup:F,track:V,patch:Y,restore:ue,revert:H,diff:R,diffFull:L}}));return b.of({init:Ye.fn("Snapshot.init")(function*(){yield*ge.get(k)}),cleanup:Ye.fn("Snapshot.cleanup")(function*(){return yield*ge.useEffect(k,E=>E.cleanup())}),track:Ye.fn("Snapshot.track")(function*(){return yield*ge.useEffect(k,E=>E.track())}),patch:Ye.fn("Snapshot.patch")(function*(E){return yield*ge.useEffect(k,D=>D.patch(E))}),restore:Ye.fn("Snapshot.restore")(function*(E){return yield*ge.useEffect(k,D=>D.restore(E))}),revert:Ye.fn("Snapshot.revert")(function*(E){return yield*ge.useEffect(k,D=>D.revert(E))}),diff:Ye.fn("Snapshot.diff")(function*(E){return yield*ge.useEffect(k,D=>D.diff(E))}),diffFull:Ye.fn("Snapshot.diffFull")(function*(E,D){return yield*ge.useEffect(k,z=>z.diffFull(E,D))})})})),x.defaultLayer=x.layer.pipe(ia.provide(uo),ia.provide(ut.defaultLayer),ia.provide(rt.defaultLayer));let{runPromise:c}=Ke(b,x.defaultLayer);async function l(){return c(h=>h.init())}x.init=l,n(l,"init");async function g(){return c(h=>h.track())}x.track=g,n(g,"track");async function u(h){return c(v=>v.patch(h))}x.patch=u,n(u,"patch");async function a(h){return c(v=>v.restore(h))}x.restore=a,n(a,"restore");async function w(h){return c(v=>v.revert(h))}x.revert=w,n(w,"revert");async function I(h){return c(v=>v.diff(h))}x.diff=I,n(I,"diff");async function r(h,v){return c(S=>S.diffFull(h,v))}x.diffFull=r,n(r,"diffFull")})($n||={});import{STATUS_CODES as Fd}from"http";var Oo;(g=>{class e extends Error{static{n(this,"ResponseStreamError")}name="ProviderResponseStreamError"}g.ResponseStreamError=e,g.RESPONSE_INCOMPLETE_CODE="response_incomplete",g.RESPONSE_FAILED_CODE="response_failed";let i=[/prompt is too long/i,/input is too long for requested model/i,/exceeds the context window/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/context[_ ]length[_ ]exceeded/i,/request entity too large/i,/context length is only \d+ tokens/i,/input length.*exceeds.*context length/i,/prompt too long; exceeded (?:max )?context length/i,/too large for model with \d+ maximum context length/i,/model_context_window_exceeded/i];function m(u){let a=u.statusCode;return a&&a===404||u.isRetryable}n(m,"isOpenAiErrorRetryable");function y(u){return i.some(a=>a.test(u))?!0:/^4(00|13)\s*(status code)?\s*\(no body\)/i.test(u)}n(y,"isOverflow");function p(u,a){return qt(()=>{let w=a.message;if(w===""){if(a.responseBody)return a.responseBody;if(a.statusCode){let I=Fd[a.statusCode];if(I)return I}return"Unknown error"}if(!a.responseBody||a.statusCode&&w!==Fd[a.statusCode])return w;try{let I=JSON.parse(a.responseBody),r=I.message||I.error||I.error?.message;if(r&&typeof r=="string")return`${w}: ${r}`}catch{}return/^\s*<!doctype|^\s*<html/i.test(a.responseBody)?a.statusCode===401?"Unauthorized: request was blocked by a gateway or proxy. Your authentication token may be missing or expired \u2014 try running `opencode auth login <your provider URL>` to re-authenticate.":a.statusCode===403?"Forbidden: request was blocked by a gateway or proxy. You may not have permission to access this resource \u2014 check your account and provider settings.":w:`${w}: ${a.responseBody}`}).trim()}n(p,"message");function f(u){if(typeof u=="string")try{let a=JSON.parse(u);return a&&typeof a=="object"?a:void 0}catch{return}if(typeof u=="object"&&u!==null)return u}n(f,"json");let b=new Set(["usage_limit_reached","insufficient_quota","billing_hard_limit_reached","quota_exceeded"]);function d(u){let a=f(u),w=a&&typeof a.error=="object"?a.error:void 0,I=Array.isArray(w?.details)?w.details:[];for(let r of I){if(!r||typeof r!="object")continue;let x=r;if(typeof x["@type"]!="string"||!x["@type"].endsWith("google.rpc.RetryInfo"))continue;let h=typeof x.retryDelay=="string"?/^(\d+(?:\.\d+)?)s$/.exec(x.retryDelay):null;if(h)return Math.ceil(Number.parseFloat(h[1])*1e3)}}g.statedRetryDelayMs=d,n(d,"statedRetryDelayMs");function s(u){let a=d(u.body);if(a!==void 0&&a<=6e5)return;let w=f(u.body),I=qt(()=>{if(!w)return;let z=w.error;return z&&typeof z=="object"?z:w}),r=typeof I?.type=="string"?I.type:"",x=typeof I?.code=="string"?I.code:"",h=typeof I?.message=="string"?I.message:u.message??"",v=typeof I?.resets_at=="number"?I.resets_at:void 0,S=typeof I?.resets_in_seconds=="number"?I.resets_in_seconds:void 0,j=typeof I?.plan_type=="string"?I.plan_type:void 0,O=b.has(r)||b.has(x),k=u.statusCode===429||u.statusCode===402,E=/usage limit|quota/i.test(h),D=(S??0)>600||v!==void 0&&v*1e3-Date.now()>6e5;if(O||k&&(E||D))return{message:h||"Provider usage limit reached",planType:j,resetsAt:v??(S!==void 0?Math.round(Date.now()/1e3)+S:void 0)??(a!==void 0?Math.round((Date.now()+a)/1e3):void 0)}}g.quotaExhaustion=s,n(s,"quotaExhaustion");function c(u){let a=f(u),w=typeof a?.message=="string"?f(a.message)??a:a;if(!w)return;let I=JSON.stringify(w);if(w.type!=="error")return;switch(w?.error?.code){case"context_length_exceeded":return{type:"context_overflow",message:"Input exceeds context window of this model",responseBody:I};case"insufficient_quota":return{type:"quota",message:"Quota exceeded. Check your plan and billing details.",responseBody:I};case"usage_not_included":return{type:"api_error",message:"To use Codex with your ChatGPT plan, upgrade to Plus: https://chatgpt.com/explore/plus.",isRetryable:!1,responseBody:I};case"invalid_prompt":return{type:"api_error",message:typeof w?.error?.message=="string"?w?.error?.message:"Invalid prompt.",isRetryable:!1,responseBody:I};case"server_error":return{type:"api_error",message:typeof w?.error?.message=="string"?w?.error?.message:"Server error.",isRetryable:!0,responseBody:I};case g.RESPONSE_INCOMPLETE_CODE:return{type:"unknown",message:typeof w?.error?.message=="string"?w?.error?.message:"The response failed.",responseBody:I}}let r=s({body:w});if(r)return{type:"quota",message:r.message,planType:r.planType,resetsAt:r.resetsAt,responseBody:I};if(w?.error?.type===g.RESPONSE_FAILED_CODE){let x=typeof w.error.code=="string"?w.error.code:"";return{type:"api_error",message:typeof w.error.message=="string"&&w.error.message?w.error.message:"The response failed.",isRetryable:!/invalid|policy/i.test(x),responseBody:I}}}g.parseStreamError=c,n(c,"parseStreamError");function l(u){let a=p(u.providerID,u.error),w=f(u.error.responseBody);if(y(a)||u.error.statusCode===413||w?.error?.code==="context_length_exceeded")return{type:"context_overflow",message:a,responseBody:u.error.responseBody};let I=s({statusCode:u.error.statusCode,body:w,message:a});if(I)return{type:"quota",message:I.message,statusCode:u.error.statusCode,planType:I.planType,resetsAt:I.resetsAt,responseBody:u.error.responseBody};let r=u.error.url?{url:u.error.url}:void 0;return{type:"api_error",message:a,statusCode:u.error.statusCode,isRetryable:u.providerID.startsWith("openai")?m(u.error):u.error.isRetryable,responseHeaders:qt(()=>{let x=d(u.error.responseBody),h=u.error.responseHeaders;return x===void 0||h?.["retry-after"]||h?.["retry-after-ms"]?h:{...h??{},"retry-after-ms":String(x)}}),responseBody:u.error.responseBody,metadata:r}}g.parseAPICallError=l,n(l,"parseAPICallError")})(Oo||={});import{Schema as aa}from"effect";import ca from"zod";var sh=aa.String.pipe(aa.brand("ProviderID")),Et=sh.pipe(An(e=>({make:n(t=>e.makeUnsafe(t),"make"),zod:ca.string().pipe(ca.custom()),opencode:e.makeUnsafe("opencode"),anthropic:e.makeUnsafe("anthropic"),openai:e.makeUnsafe("openai"),google:e.makeUnsafe("google"),googleVertex:e.makeUnsafe("google-vertex"),githubCopilot:e.makeUnsafe("github-copilot"),amazonBedrock:e.makeUnsafe("amazon-bedrock"),azure:e.makeUnsafe("azure"),openrouter:e.makeUnsafe("openrouter"),mistral:e.makeUnsafe("mistral"),gitlab:e.makeUnsafe("gitlab")}))),ih=aa.String.pipe(aa.brand("ModelID")),Ut=ih.pipe(An(e=>({make:n(t=>e.makeUnsafe(t),"make"),zod:ca.string().pipe(ca.custom())})));import{Effect as la}from"effect";var Qe;(ie=>{function e(le){return le.startsWith("image/")||le==="application/pdf"}ie.isMedia=e,n(e,"isMedia"),ie.OutputLengthError=tt.create("MessageOutputLengthError",K.object({})),ie.AbortedError=tt.create("MessageAbortedError",K.object({message:K.string()})),ie.StructuredOutputError=tt.create("StructuredOutputError",K.object({message:K.string(),retries:K.number()})),ie.AuthError=tt.create("ProviderAuthError",K.object({providerID:K.string(),message:K.string()})),ie.ProviderQuotaError=tt.create("ProviderQuotaError",K.object({providerID:K.string(),message:K.string(),planType:K.string().optional(),resetsAt:K.number().optional(),statusCode:K.number().optional(),responseBody:K.string().optional()})),ie.APIError=tt.create("APIError",K.object({message:K.string(),statusCode:K.number().optional(),isRetryable:K.boolean(),responseHeaders:K.record(K.string(),K.string()).optional(),responseBody:K.string().optional(),metadata:K.record(K.string(),K.string()).optional()})),ie.ContextOverflowError=tt.create("ContextOverflowError",K.object({message:K.string(),responseBody:K.string().optional()})),ie.OutputFormatText=K.object({type:K.literal("text")}).meta({ref:"OutputFormatText"}),ie.OutputFormatJsonSchema=K.object({type:K.literal("json_schema"),schema:K.record(K.string(),K.any()).meta({ref:"JSONSchema"}),retryCount:K.number().int().min(0).default(2)}).meta({ref:"OutputFormatJsonSchema"}),ie.Format=K.discriminatedUnion("type",[ie.OutputFormatText,ie.OutputFormatJsonSchema]).meta({ref:"OutputFormat"});let c=K.object({id:It.zod,sessionID:He.zod,messageID:pt.zod});ie.SnapshotPart=c.extend({type:K.literal("snapshot"),snapshot:K.string()}).meta({ref:"SnapshotPart"}),ie.PatchPart=c.extend({type:K.literal("patch"),hash:K.string(),files:K.string().array()}).meta({ref:"PatchPart"}),ie.TextPart=c.extend({type:K.literal("text"),text:K.string(),synthetic:K.boolean().optional(),ignored:K.boolean().optional(),time:K.object({start:K.number(),end:K.number().optional()}).optional(),metadata:K.record(K.string(),K.any()).optional()}).meta({ref:"TextPart"}),ie.ReasoningPart=c.extend({type:K.literal("reasoning"),text:K.string(),metadata:K.record(K.string(),K.any()).optional(),time:K.object({start:K.number(),end:K.number().optional()})}).meta({ref:"ReasoningPart"});let w=K.object({text:K.object({value:K.string(),start:K.number().int(),end:K.number().int()}).meta({ref:"FilePartSourceText"})});ie.FileSource=w.extend({type:K.literal("file"),path:K.string()}).meta({ref:"FileSource"}),ie.SymbolSource=w.extend({type:K.literal("symbol"),path:K.string(),range:Pt.Range,name:K.string(),kind:K.number().int()}).meta({ref:"SymbolSource"}),ie.ResourceSource=w.extend({type:K.literal("resource"),clientName:K.string(),uri:K.string()}).meta({ref:"ResourceSource"}),ie.FilePartSource=K.discriminatedUnion("type",[ie.FileSource,ie.SymbolSource,ie.ResourceSource]).meta({ref:"FilePartSource"}),ie.FilePart=c.extend({type:K.literal("file"),mime:K.string(),filename:K.string().optional(),url:K.string(),source:ie.FilePartSource.optional()}).meta({ref:"FilePart"}),ie.AgentPart=c.extend({type:K.literal("agent"),name:K.string(),source:K.object({value:K.string(),start:K.number().int(),end:K.number().int()}).optional()}).meta({ref:"AgentPart"}),ie.CompactionPart=c.extend({type:K.literal("compaction"),auto:K.boolean(),overflow:K.boolean().optional()}).meta({ref:"CompactionPart"}),ie.SubtaskPart=c.extend({type:K.literal("subtask"),prompt:K.string(),description:K.string(),agent:K.string(),model:K.object({providerID:Et.zod,modelID:Ut.zod}).optional(),command:K.string().optional()}).meta({ref:"SubtaskPart"}),ie.RetryPart=c.extend({type:K.literal("retry"),attempt:K.number(),error:ie.APIError.Schema,time:K.object({created:K.number()})}).meta({ref:"RetryPart"}),ie.StepStartPart=c.extend({type:K.literal("step-start"),snapshot:K.string().optional()}).meta({ref:"StepStartPart"}),ie.StepFinishPart=c.extend({type:K.literal("step-finish"),reason:K.string(),snapshot:K.string().optional(),cost:K.number(),tokens:K.object({total:K.number().optional(),input:K.number(),output:K.number(),reasoning:K.number(),cache:K.object({read:K.number(),write:K.number()})})}).meta({ref:"StepFinishPart"}),ie.ToolStatePending=K.object({status:K.literal("pending"),input:K.record(K.string(),K.any()),raw:K.string()}).meta({ref:"ToolStatePending"}),ie.ToolStateRunning=K.object({status:K.literal("running"),input:K.record(K.string(),K.any()),title:K.string().optional(),metadata:K.record(K.string(),K.any()).optional(),time:K.object({start:K.number()})}).meta({ref:"ToolStateRunning"}),ie.ToolStateCompleted=K.object({status:K.literal("completed"),input:K.record(K.string(),K.any()),output:K.string(),title:K.string(),metadata:K.record(K.string(),K.any()),time:K.object({start:K.number(),end:K.number(),compacted:K.number().optional()}),attachments:ie.FilePart.array().optional()}).meta({ref:"ToolStateCompleted"}),ie.ToolStateError=K.object({status:K.literal("error"),input:K.record(K.string(),K.any()),error:K.string(),metadata:K.record(K.string(),K.any()).optional(),time:K.object({start:K.number(),end:K.number()})}).meta({ref:"ToolStateError"}),ie.ToolState=K.discriminatedUnion("status",[ie.ToolStatePending,ie.ToolStateRunning,ie.ToolStateCompleted,ie.ToolStateError]).meta({ref:"ToolState"}),ie.ToolPart=c.extend({type:K.literal("tool"),callID:K.string(),tool:K.string(),state:ie.ToolState,metadata:K.record(K.string(),K.any()).optional()}).meta({ref:"ToolPart"});let T=K.object({id:pt.zod,sessionID:He.zod});ie.User=T.extend({role:K.literal("user"),time:K.object({created:K.number()}),format:ie.Format.optional(),summary:K.object({title:K.string().optional(),body:K.string().optional(),diffs:$n.FileDiff.array()}).optional(),agent:K.string(),model:K.object({providerID:Et.zod,modelID:Ut.zod}),system:K.string().optional(),tools:K.record(K.string(),K.boolean()).optional(),variant:K.string().optional(),quiet:K.boolean().optional()}).meta({ref:"UserMessage"}),ie.Part=K.discriminatedUnion("type",[ie.TextPart,ie.SubtaskPart,ie.ReasoningPart,ie.FilePart,ie.ToolPart,ie.StepStartPart,ie.StepFinishPart,ie.SnapshotPart,ie.PatchPart,ie.AgentPart,ie.RetryPart,ie.CompactionPart]).meta({ref:"Part"}),ie.Assistant=T.extend({role:K.literal("assistant"),time:K.object({created:K.number(),completed:K.number().optional()}),error:K.discriminatedUnion("name",[ie.AuthError.Schema,ie.ProviderQuotaError.Schema,tt.Unknown.Schema,ie.OutputLengthError.Schema,ie.AbortedError.Schema,ie.StructuredOutputError.Schema,ie.ContextOverflowError.Schema,ie.APIError.Schema]).optional(),parentID:pt.zod,modelID:Ut.zod,providerID:Et.zod,servedModelID:K.string().optional(),mode:K.string(),agent:K.string(),path:K.object({cwd:K.string(),root:K.string()}),summary:K.boolean().optional(),aside:K.boolean().optional(),cost:K.number(),tokens:K.object({total:K.number().optional(),input:K.number(),output:K.number(),reasoning:K.number(),cache:K.object({read:K.number(),write:K.number()})}),structured:K.any().optional(),variant:K.string().optional(),finish:K.string().optional()}).meta({ref:"AssistantMessage"}),ie.Info=K.discriminatedUnion("role",[ie.User,ie.Assistant]).meta({ref:"Message"}),ie.Event={Updated:on.define({type:"message.updated",version:1,aggregate:"sessionID",schema:K.object({sessionID:He.zod,info:ie.Info})}),Removed:on.define({type:"message.removed",version:1,aggregate:"sessionID",schema:K.object({sessionID:He.zod,messageID:pt.zod})}),PartUpdated:on.define({type:"message.part.updated",version:1,aggregate:"sessionID",schema:K.object({sessionID:He.zod,part:ie.Part,time:K.number()})}),PartDelta:mt.define("message.part.delta",K.object({sessionID:He.zod,messageID:pt.zod,partID:It.zod,field:K.string(),delta:K.string()})),PartRemoved:on.define({type:"message.part.removed",version:1,aggregate:"sessionID",schema:K.object({sessionID:He.zod,messageID:pt.zod,partID:It.zod})})},ie.WithParts=K.object({info:ie.Info,parts:K.array(ie.Part)});let re=K.object({id:pt.zod,time:K.number()});ie.cursor={encode(le){return Buffer.from(JSON.stringify(le)).toString("base64url")},decode(le){return re.parse(JSON.parse(Buffer.from(le,"base64url").toString("utf8")))}};let H=n(le=>({...le.data,id:le.id,sessionID:le.session_id}),"info"),R=n(le=>({...le.data,id:le.id,sessionID:le.session_id,messageID:le.message_id}),"part"),L=n(le=>(0,We.or)((0,We.lt)(lo.time_created,le.time),(0,We.and)((0,We.eq)(lo.time_created,le.time),(0,We.lt)(lo.id,le.id))),"older");function q(le){let Le=le.map(Te=>Te.id),ve=new Map;if(Le.length>0){let Te=Xt.use(it=>it.select().from(nr).where((0,We.inArray)(nr.message_id,Le)).orderBy(nr.message_id,nr.id).all());for(let it of Te){let Ie=R(it),be=ve.get(it.message_id);be?be.push(Ie):ve.set(it.message_id,[Ie])}}return le.map(Te=>({info:H(Te),parts:ve.get(Te.id)??[]}))}n(q,"hydrate"),ie.toModelMessagesEffect=la.fnUntraced(function*(le,Le,ve){let Te=[],it=new Set,Ie=(()=>{if(Le.api.npm==="@ai-sdk/anthropic"||Le.api.npm==="@ai-sdk/openai"||Le.api.npm==="@ai-sdk/amazon-bedrock"||Le.api.npm==="@ai-sdk/google-vertex/anthropic")return!0;if(Le.api.npm==="@ai-sdk/google"){let ae=Le.api.id.toLowerCase();return ae.includes("gemini-3")&&!ae.includes("gemini-2")}return!1})(),be=n(ae=>{let me=ae.output;if(typeof me=="string")return{type:"text",value:me};if(typeof me=="object"){let P=me,Z=(P.attachments??[]).filter(J=>J.url.startsWith("data:")&&J.url.includes(","));return{type:"content",value:[...P.text?[{type:"text",text:P.text}]:[],...Z.map(J=>({type:"media",mediaType:J.mime,data:qt(()=>{let fe=J.url.indexOf(",");return fe===-1?J.url:J.url.slice(fe+1)})}))]}}return{type:"json",value:me}},"toModelOutput");for(let ae of le)if(ae.parts.length!==0){if(ae.info.role==="user"){let me={id:ae.info.id,role:"user",parts:[]};Te.push(me);for(let P of ae.parts)P.type==="text"&&!P.ignored&&me.parts.push({type:"text",text:P.text}),P.type==="file"&&P.mime!=="text/plain"&&P.mime!=="application/x-directory"&&(ve?.stripMedia&&e(P.mime)?me.parts.push({type:"text",text:`[Attached ${P.mime}: ${P.filename??"file"}]`}):me.parts.push({type:"file",url:P.url,mediaType:P.mime,filename:P.filename})),P.type==="compaction"&&me.parts.push({type:"text",text:"What did we do so far?"}),P.type==="subtask"&&me.parts.push({type:"text",text:"The following tool was executed by the user"})}if(ae.info.role==="assistant"){let me=`${Le.providerID}/${Le.id}`!=`${ae.info.providerID}/${ae.info.modelID}`,P=[];if(ae.info.error&&!(ie.AbortedError.isInstance(ae.info.error)&&ae.parts.some(J=>J.type!=="step-start"&&J.type!=="reasoning")))continue;if(ae.info.aside){let J=ae.parts.filter(fe=>fe.type==="text"&&!fe.ignored).map(fe=>fe.text.trim()).filter(Boolean).join(`
|
|
60
|
+
`);J&&Te.push({id:ae.info.id,role:"user",parts:[{type:"text",text:`[While a tool was running you already answered the user's message above: "${J}". Do not answer it again; carry on with your work.]`}]});continue}let Z={id:ae.info.id,role:"assistant",parts:[]};for(let J of ae.parts){if(J.type==="text"&&Z.parts.push({type:"text",text:J.text,...me?{}:{providerMetadata:J.metadata}}),J.type==="step-start"&&Z.parts.push({type:"step-start"}),J.type==="tool"){if(it.add(J.tool),J.state.status==="completed"){let fe=J.state.time.compacted?"[Old tool result content cleared]":J.state.output,_e=J.state.time.compacted||ve?.stripMedia?[]:J.state.attachments??[],te=_e.filter(de=>e(de.mime)),we=_e.filter(de=>!e(de.mime));!Ie&&te.length>0&&P.push(...te);let $e=Ie?_e:we,ee=$e.length>0?{text:fe,attachments:$e}:fe;Z.parts.push({type:"tool-"+J.tool,state:"output-available",toolCallId:J.callID,input:J.state.input,output:ee,...me?{}:{callProviderMetadata:J.metadata}})}J.state.status==="error"&&Z.parts.push({type:"tool-"+J.tool,state:"output-error",toolCallId:J.callID,input:J.state.input,errorText:J.state.error,...me?{}:{callProviderMetadata:J.metadata}}),(J.state.status==="pending"||J.state.status==="running")&&Z.parts.push({type:"tool-"+J.tool,state:"output-error",toolCallId:J.callID,input:J.state.input,errorText:ve?.runningToolNote??"[Tool execution was interrupted]",...me?{}:{callProviderMetadata:J.metadata}})}J.type==="reasoning"&&Z.parts.push({type:"reasoning",text:J.text,...me?{}:{providerMetadata:J.metadata}})}Z.parts.length>0&&(Te.push(Z),P.length>0&&Te.push({id:pt.ascending(),role:"user",parts:[{type:"text",text:"Attached image(s) from tool result:"},...P.map(J=>({type:"file",url:J.url,mediaType:J.mime}))]}))}}let ye=Object.fromEntries(Array.from(it).map(ae=>[ae,{toModelOutput:be}]));return yield*la.promise(()=>ch(Te.filter(ae=>ae.parts.some(me=>me.type!=="step-start")),{tools:ye}))});function ne(le,Le,ve){return la.runPromise((0,ie.toModelMessagesEffect)(le,Le,ve))}ie.toModelMessages=ne,n(ne,"toModelMessages");function Q(le){let Le=le.before?ie.cursor.decode(le.before):void 0,ve=Le?(0,We.and)((0,We.eq)(lo.session_id,le.sessionID),L(Le)):(0,We.eq)(lo.session_id,le.sessionID),Te=Xt.use(ae=>ae.select().from(lo).where(ve).orderBy((0,We.desc)(lo.time_created),(0,We.desc)(lo.id)).limit(le.limit+1).all());if(Te.length===0){if(!Xt.use(me=>me.select({id:zt.id}).from(zt).where((0,We.eq)(zt.id,le.sessionID)).get()))throw new kr({message:`Session not found: ${le.sessionID}`});return{items:[],more:!1}}let it=Te.length>le.limit,Ie=it?Te.slice(0,le.limit):Te,be=q(Ie);be.reverse();let ye=Ie.at(-1);return{items:be,more:it,cursor:it&&ye?ie.cursor.encode({id:ye.id,time:ye.time_created}):void 0}}ie.page=Q,n(Q,"page");function*oe(le){let ve;for(;;){let Te=Q({sessionID:le,limit:50,before:ve});if(Te.items.length===0)break;for(let it=Te.items.length-1;it>=0;it--)yield Te.items[it];if(!Te.more||!Te.cursor)break;ve=Te.cursor}}ie.stream=oe,n(oe,"stream");function ce(le){return Xt.use(ve=>ve.select().from(nr).where((0,We.eq)(nr.message_id,le)).orderBy(nr.id).all()).map(ve=>({...ve.data,id:ve.id,sessionID:ve.session_id,messageID:ve.message_id}))}ie.parts=ce,n(ce,"parts");function pe(le){let Le=Xt.use(ve=>ve.select().from(lo).where((0,We.and)((0,We.eq)(lo.id,le.messageID),(0,We.eq)(lo.session_id,le.sessionID))).get());if(!Le)throw new kr({message:`Message not found: ${le.messageID}`});return{info:H(Le),parts:ce(le.messageID)}}ie.get=pe,n(pe,"get");function De(le){let Le=[],ve=new Set;for(let Te of le){if(Le.push(Te),Te.info.role==="user"&&ve.has(Te.info.id)&&Te.parts.some(it=>it.type==="compaction"))break;Te.info.role==="assistant"&&Te.info.summary&&Te.info.finish&&!Te.info.error&&ve.add(Te.info.parentID)}return Le.reverse(),Le}ie.filterCompacted=De,n(De,"filterCompacted"),ie.filterCompactedEffect=la.fnUntraced(function*(le){return De(oe(le))});function xe(le,Le){switch(!0){case(le instanceof DOMException&&le.name==="AbortError"):return new ie.AbortedError({message:le.message},{cause:le}).toObject();case ie.OutputLengthError.isInstance(le):return le;case le instanceof ie.APIError:return le.toObject();case lh.isInstance(le):return new ie.AuthError({providerID:Le.providerID,message:le.message},{cause:le}).toObject();case Ud(le)!==void 0:{let Te=Ud(le);return new ie.APIError({message:"Connection reset by server",isRetryable:!0,metadata:{code:Te.code??"",syscall:Te.syscall??"",message:Te.message??""}},{cause:le}).toObject()}case(le instanceof TypeError&&le.message==="terminated"):{if(Le.aborted)return new ie.AbortedError({message:le.message},{cause:le}).toObject();let Te=le.cause;return new ie.APIError({message:"Connection closed by server",isRetryable:!0,metadata:{code:typeof Te?.code=="string"?Te.code:"",message:typeof Te?.message=="string"?Te.message:""}},{cause:le}).toObject()}case(le instanceof Error&&le.code==="ZlibError"):return Le.aborted?new ie.AbortedError({message:le.message},{cause:le}).toObject():new ie.APIError({message:"Response decompression failed",isRetryable:!0,metadata:{code:le.code,message:le.message}},{cause:le}).toObject();case le instanceof Oo.ResponseStreamError:return new ie.APIError({message:le.message,isRetryable:!0,metadata:{code:le.name}},{cause:le}).toObject();case ah.isInstance(le):let ve=Oo.parseAPICallError({providerID:Le.providerID,error:le});return ve.type==="context_overflow"?new ie.ContextOverflowError({message:ve.message,responseBody:ve.responseBody},{cause:le}).toObject():ve.type==="quota"?new ie.ProviderQuotaError({providerID:Le.providerID,message:ve.message,planType:ve.planType,resetsAt:ve.resetsAt,statusCode:ve.statusCode,responseBody:ve.responseBody},{cause:le}).toObject():new ie.APIError({message:ve.message,statusCode:ve.statusCode,isRetryable:ve.isRetryable,responseHeaders:ve.responseHeaders,responseBody:ve.responseBody,metadata:ve.metadata},{cause:le}).toObject();case le instanceof Error:return new tt.Unknown({message:jo(le)},{cause:le}).toObject();default:try{let Te=Oo.parseStreamError(le);if(Te)return Te.type==="context_overflow"?new ie.ContextOverflowError({message:Te.message,responseBody:Te.responseBody},{cause:le}).toObject():Te.type==="quota"?new ie.ProviderQuotaError({providerID:Le.providerID,message:Te.message,planType:Te.planType,resetsAt:Te.resetsAt,responseBody:Te.responseBody},{cause:le}).toObject():Te.type==="unknown"?new tt.Unknown({message:Te.message},{cause:le}).toObject():new ie.APIError({message:Te.message,isRetryable:Te.isRetryable,responseBody:Te.responseBody},{cause:le}).toObject()}catch{}return new tt.Unknown({message:JSON.stringify(le)},{cause:le}).toObject()}}ie.fromError=xe,n(xe,"fromError")})(Qe||={});function Ud(e){let t=e;for(let o=0;o<4&&t;o++){if(t?.code==="ECONNRESET")return t;t=t?.cause}}n(Ud,"connectionResetError");import hi from"path";import ex from"os";import Kt from"zod";import ph from"zod";import{Effect as ur,Layer as Mr,ServiceMap as fh}from"effect";import dh from"zod";import{Effect as Go,Layer as gs,ServiceMap as uh}from"effect";var dr;(b=>{function e(d){if(!d.startsWith('"')||!d.endsWith('"'))return d;let s=d.slice(1,-1),c=[];for(let l=0;l<s.length;l++){let g=s[l];if(g!=="\\"){c.push(g.charCodeAt(0));continue}let u=s[l+1];if(!u){c.push(92);continue}if(u>="0"&&u<="7"){let I=s.slice(l+1,l+4).match(/^[0-7]{1,3}/);if(!I){c.push(u.charCodeAt(0)),l++;continue}c.push(parseInt(I[0],8)),l+=I[0].length;continue}let a=u==="n"?`
|
|
61
|
+
`:u==="r"?"\r":u==="t"?" ":u==="b"?"\b":u==="f"?"\f":u==="v"?"\v":u==="\\"||u==='"'?u:void 0;c.push((a??u).charCodeAt(0)),l++}return Buffer.from(c).toString()}n(e,"unquoteGitPath");class t extends uh.Service()("@opencode/SessionSummary"){static{n(this,"Service")}}b.Service=t,b.layer=gs.effect(t,Go.gen(function*(){let d=yield*yt.Service,s=yield*$n.Service,c=yield*Ho.Service,l=yield*Ve.Service,g=Go.fn("SessionSummary.computeDiff")(function*(w){let I,r;for(let x of w.messages){if(!I){for(let h of x.parts)if(h.type==="step-start"&&h.snapshot){I=h.snapshot;break}}for(let h of x.parts)h.type==="step-finish"&&h.snapshot&&(r=h.snapshot)}return I&&r?yield*s.diffFull(I,r):[]}),u=Go.fn("SessionSummary.summarize")(function*(w){let I=yield*d.messages({sessionID:w.sessionID});if(!I.length)return;let r=yield*g({messages:I});yield*d.setSummary({sessionID:w.sessionID,summary:{additions:r.reduce((S,j)=>S+j.additions,0),deletions:r.reduce((S,j)=>S+j.deletions,0),files:r.length}}),yield*c.write(["session_diff",w.sessionID],r).pipe(Go.ignore),yield*l.publish(yt.Event.Diff,{sessionID:w.sessionID,diff:r});let x=I.filter(S=>S.info.id===w.messageID||S.info.role==="assistant"&&S.info.parentID===w.messageID),h=x.find(S=>S.info.id===w.messageID);if(!h||h.info.role!=="user")return;let v=yield*g({messages:x});h.info.summary={...h.info.summary,diffs:v},yield*d.updateMessage(h.info)}),a=Go.fn("SessionSummary.diff")(function*(w){let I=yield*c.read(["session_diff",w.sessionID]).pipe(Go.catch(()=>Go.succeed([]))),r=I.map(h=>{let v=e(h.file);return v===h.file?h:{...h,file:v}});return r.some((h,v)=>h.file!==I[v]?.file)&&(yield*c.write(["session_diff",w.sessionID],r).pipe(Go.ignore)),r});return t.of({summarize:u,diff:a,computeDiff:g})})),b.defaultLayer=gs.unwrap(Go.sync(()=>b.layer.pipe(gs.provide(yt.defaultLayer),gs.provide($n.defaultLayer),gs.provide(Ho.defaultLayer),gs.provide(Ve.layer))));let{runPromise:m}=Ke(t,b.defaultLayer);b.summarize=n(d=>{m(s=>s.summarize(d)).catch(()=>{})},"summarize"),b.DiffInput=dh.object({sessionID:He.zod,messageID:pt.zod.optional()});async function f(d){return m(s=>s.diff(d))}b.diff=f,n(f,"diff")})(dr||={});var da;(d=>{let e=qe.create({service:"session.revert"});d.RevertInput=ph.object({sessionID:He.zod,messageID:pt.zod,partID:It.zod.optional()});class o extends fh.Service()("@opencode/SessionRevert"){static{n(this,"Service")}}d.Service=o,d.layer=Mr.effect(o,ur.gen(function*(){let s=yield*yt.Service,c=yield*$n.Service,l=yield*Ho.Service,g=yield*Ve.Service,u=yield*dr.Service,a=ur.fn("SessionRevert.revert")(function*(r){yield*ur.promise(()=>No.assertNotBusy(r.sessionID));let x=yield*s.messages({sessionID:r.sessionID}),h,v=yield*s.get(r.sessionID),S,j=[];for(let E of x){E.info.role==="user"&&(h=E.info);let D=[];for(let z of E.parts){if(S){z.type==="patch"&&j.push(z);continue}if(!S){if(E.info.id===r.messageID&&!r.partID||z.id===r.partID){let _=D.some(B=>["text","tool"].includes(B.type))?r.partID:void 0;S={messageID:!_&&h?h.id:E.info.id,partID:_}}D.push(z)}}}if(!S)return v;S.snapshot=v.revert?.snapshot??(yield*c.track()),v.revert?.snapshot&&(yield*c.restore(v.revert.snapshot)),yield*c.revert(j),S.snapshot&&(S.diff=yield*c.diff(S.snapshot));let O=x.filter(E=>Nt.compareAscending(E.info.id,S.messageID)>=0),k=yield*u.computeDiff({messages:O});return yield*l.write(["session_diff",r.sessionID],k).pipe(ur.ignore),yield*g.publish(yt.Event.Diff,{sessionID:r.sessionID,diff:k}),yield*s.setRevert({sessionID:r.sessionID,revert:S,summary:{additions:k.reduce((E,D)=>E+D.additions,0),deletions:k.reduce((E,D)=>E+D.deletions,0),files:k.length}}),yield*s.get(r.sessionID)}),w=ur.fn("SessionRevert.unrevert")(function*(r){e.info("unreverting",r),yield*ur.promise(()=>No.assertNotBusy(r.sessionID));let x=yield*s.get(r.sessionID);return x.revert?(x.revert.snapshot&&(yield*c.restore(x.revert.snapshot)),yield*s.clearRevert(r.sessionID),yield*s.get(r.sessionID)):x}),I=ur.fn("SessionRevert.cleanup")(function*(r){if(!r.revert)return;let x=r.id,h=yield*s.messages({sessionID:x}),v=r.revert.messageID,S=[],j;for(let O of h)if(!(Nt.compareAscending(O.info.id,v)<0)){if(Nt.compareAscending(O.info.id,v)>0){S.push(O);continue}if(r.revert.partID){j=O;continue}S.push(O)}for(let O of S)on.run(Qe.Event.Removed,{sessionID:x,messageID:O.info.id});if(r.revert.partID&&j){let O=r.revert.partID,k=j.parts.findIndex(E=>E.id===O);if(k>=0){let E=j.parts.slice(k);j.parts=j.parts.slice(0,k);for(let D of E)on.run(Qe.Event.PartRemoved,{sessionID:x,messageID:j.info.id,partID:D.id})}}yield*s.clearRevert(x)});return o.of({revert:a,unrevert:w,cleanup:I})})),d.defaultLayer=Mr.unwrap(ur.sync(()=>d.layer.pipe(Mr.provide(yt.defaultLayer),Mr.provide($n.defaultLayer),Mr.provide(Ho.defaultLayer),Mr.provide(Ve.layer),Mr.provide(dr.defaultLayer))));let{runPromise:y}=Ke(o,d.defaultLayer);async function p(s){return y(c=>c.revert(s))}d.revert=p,n(p,"revert");async function f(s){return y(c=>c.unrevert(s))}d.unrevert=f,n(f,"unrevert");async function b(s){return y(c=>c.cleanup(s))}d.cleanup=b,n(b,"cleanup")})(da||={});import wn from"zod";import Ge from"zod";import{createHash as mh}from"node:crypto";import{appendFileSync as gh,existsSync as hh}from"node:fs";import $d from"node:path";var Qs;(b=>{let e=n(()=>$d.join(je.Path.data,"request-trace.on"),"flag"),t=n(()=>$d.join(je.Path.data,"request-trace.jsonl"),"file"),o=n(d=>mh("sha1").update(typeof d=="string"?d:JSON.stringify(d??null)).digest("hex").slice(0,8),"h"),i=n(d=>JSON.stringify(d??null).includes('"cache_control"')?"*":"","marked");function m(){try{return hh(e())}catch{return!1}}b.on=m,n(m,"on");function y(d,s){let c={model:d?.model};return Array.isArray(d?.input)?(c.key=d.prompt_cache_key??s?.["session-id"],c.tools=o(d.tools),c.toolNames=o((d.tools??[]).map(l=>l.name)),c.instructions=o(d.instructions),c.items=d.input.map(l=>`${l.type??l.role}:${o(l)}`),c.reasoning=d.reasoning,c.store=d.store,c.include=d.include,c.continues=Array.isArray(d.input)&&/_call_output$/.test(d.input[d.input.length-1]?.type??"")):Array.isArray(d?.messages)&&(c.tools=o(d.tools)+i(d.tools?.[d.tools.length-1]),c.system=Array.isArray(d.system)?d.system.map(l=>o(l.text)+i(l)):o(d.system),c.items=d.messages.map(l=>`${l.role}:`+(Array.isArray(l.content)?l.content.map(g=>o({...g,cache_control:void 0})+i(g)).join("+"):o(l.content))),c.thinking=d.thinking,c.effort=d.output_config??d.effort),c}b.shape=y,n(y,"shape");function p(d,s,c){if(s.sentAt=c,s.headersMs=Date.now()-c,s.status=d.status,!d.body)return f(s),d;let l,g,u=new TextDecoder,a=d.body.pipeThrough(new TransformStream({transform(w,I){let r=Date.now()-c;if(l===void 0&&(l=r),g===void 0){let x=u.decode(w,{stream:!0});/output_text\.delta|function_call_arguments\.delta|reasoning_summary_text\.delta|"content_block_delta"|"input_json_delta"|"text_delta"|"thinking_delta"/.test(x)&&(g=r)}I.enqueue(w)},flush(){f({...s,firstChunkMs:l,firstOutputMs:g,endMs:Date.now()-c})}}));return new Response(a,{status:d.status,statusText:d.statusText,headers:d.headers})}b.wrap=p,n(p,"wrap");function f(d){try{gh(t(),JSON.stringify(d)+`
|
|
62
|
+
`)}catch{}}n(f,"write")})(Qs||={});import Jo from"os";import Hu from"fuzzysort";import{mapValues as ys,mergeDeep as Nr,omit as Gu,pickBy as Vu,sortBy as lb}from"remeda";import{NoSuchModelError as db}from"ai";var qd=n(({onSseError:e,onSseEvent:t,responseTransformer:o,responseValidator:i,sseDefaultRetryDelay:m,sseMaxRetryAttempts:y,sseMaxRetryDelay:p,sseSleepFn:f,url:b,...d})=>{let s,c=f??(u=>new Promise(a=>setTimeout(a,u)));return{stream:n(async function*(){let u=m??3e3,a=0,w=d.signal??new AbortController().signal;for(;!w.aborted;){a++;let I=d.headers instanceof Headers?d.headers:new Headers(d.headers);s!==void 0&&I.set("Last-Event-ID",s);try{let r=await fetch(b,{...d,headers:I,signal:w});if(!r.ok)throw new Error(`SSE failed: ${r.status} ${r.statusText}`);if(!r.body)throw new Error("No body in SSE response");let x=r.body.pipeThrough(new TextDecoderStream).getReader(),h="",v=n(()=>{try{x.cancel()}catch{}},"abortHandler");w.addEventListener("abort",v);try{for(;;){let{done:S,value:j}=await x.read();if(S)break;h+=j;let O=h.split(`
|
|
63
|
+
|
|
64
|
+
`);h=O.pop()??"";for(let k of O){let E=k.split(`
|
|
65
|
+
`),D=[],z;for(let $ of E)if($.startsWith("data:"))D.push($.replace(/^data:\s*/,""));else if($.startsWith("event:"))z=$.replace(/^event:\s*/,"");else if($.startsWith("id:"))s=$.replace(/^id:\s*/,"");else if($.startsWith("retry:")){let M=Number.parseInt($.replace(/^retry:\s*/,""),10);Number.isNaN(M)||(u=M)}let _,B=!1;if(D.length){let $=D.join(`
|
|
66
|
+
`);try{_=JSON.parse($),B=!0}catch{_=$}}B&&(i&&await i(_),o&&(_=await o(_))),t?.({data:_,event:z,id:s,retry:u}),D.length&&(yield _)}}}finally{w.removeEventListener("abort",v),x.releaseLock()}break}catch(r){if(e?.(r),y!==void 0&&a>=y)break;let x=Math.min(u*2**(a-1),p??3e4);await c(x)}}},"createStream")()}},"createSseClient");var Bd=n(async(e,t)=>{let o=typeof t=="function"?await t(e):t;if(o)return e.scheme==="bearer"?`Bearer ${o}`:e.scheme==="basic"?`Basic ${btoa(o)}`:o},"getAuthToken");var gc={bodySerializer:n(e=>JSON.stringify(e,(t,o)=>typeof o=="bigint"?o.toString():o),"bodySerializer")};var yh=n(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorArrayExplode"),bh=n(e=>{switch(e){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},"separatorArrayNoExplode"),wh=n(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorObjectExplode"),ua=n(({allowReserved:e,explode:t,name:o,style:i,value:m})=>{if(!t){let f=(e?m:m.map(b=>encodeURIComponent(b))).join(bh(i));switch(i){case"label":return`.${f}`;case"matrix":return`;${o}=${f}`;case"simple":return f;default:return`${o}=${f}`}}let y=yh(i),p=m.map(f=>i==="label"||i==="simple"?e?f:encodeURIComponent(f):hs({allowReserved:e,name:o,value:f})).join(y);return i==="label"||i==="matrix"?y+p:p},"serializeArrayParam"),hs=n(({allowReserved:e,name:t,value:o})=>{if(o==null)return"";if(typeof o=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?o:encodeURIComponent(o)}`},"serializePrimitiveParam"),pa=n(({allowReserved:e,explode:t,name:o,style:i,value:m,valueOnly:y})=>{if(m instanceof Date)return y?m.toISOString():`${o}=${m.toISOString()}`;if(i!=="deepObject"&&!t){let b=[];Object.entries(m).forEach(([s,c])=>{b=[...b,s,e?c:encodeURIComponent(c)]});let d=b.join(",");switch(i){case"form":return`${o}=${d}`;case"label":return`.${d}`;case"matrix":return`;${o}=${d}`;default:return d}}let p=wh(i),f=Object.entries(m).map(([b,d])=>hs({allowReserved:e,name:i==="deepObject"?`${o}[${b}]`:b,value:d})).join(p);return i==="label"||i==="matrix"?p+f:f},"serializeObjectParam");var xh=/\{[^{}]+\}/g,vh=n(({path:e,url:t})=>{let o=t,i=t.match(xh);if(i)for(let m of i){let y=!1,p=m.substring(1,m.length-1),f="simple";p.endsWith("*")&&(y=!0,p=p.substring(0,p.length-1)),p.startsWith(".")?(p=p.substring(1),f="label"):p.startsWith(";")&&(p=p.substring(1),f="matrix");let b=e[p];if(b==null)continue;if(Array.isArray(b)){o=o.replace(m,ua({explode:y,name:p,style:f,value:b}));continue}if(typeof b=="object"){o=o.replace(m,pa({explode:y,name:p,style:f,value:b,valueOnly:!0}));continue}if(f==="matrix"){o=o.replace(m,`;${hs({name:p,value:b})}`);continue}let d=encodeURIComponent(f==="label"?`.${b}`:b);o=o.replace(m,d)}return o},"defaultPathSerializer"),Wd=n(({baseUrl:e,path:t,query:o,querySerializer:i,url:m})=>{let y=m.startsWith("/")?m:`/${m}`,p=(e??"")+y;t&&(p=vh({path:t,url:p}));let f=o?i(o):"";return f.startsWith("?")&&(f=f.substring(1)),f&&(p+=`?${f}`),p},"getUrl");var Hd=n(({allowReserved:e,array:t,object:o}={})=>n(m=>{let y=[];if(m&&typeof m=="object")for(let p in m){let f=m[p];if(f!=null)if(Array.isArray(f)){let b=ua({allowReserved:e,explode:!0,name:p,style:"form",value:f,...t});b&&y.push(b)}else if(typeof f=="object"){let b=pa({allowReserved:e,explode:!0,name:p,style:"deepObject",value:f,...o});b&&y.push(b)}else{let b=hs({allowReserved:e,name:p,value:f});b&&y.push(b)}}return y.join("&")},"querySerializer"),"createQuerySerializer"),Gd=n(e=>{if(!e)return"stream";let t=e.split(";")[0]?.trim();if(t){if(t.startsWith("application/json")||t.endsWith("+json"))return"json";if(t==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some(o=>t.startsWith(o)))return"blob";if(t.startsWith("text/"))return"text"}},"getParseAs"),Ih=n((e,t)=>t?!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)):!1,"checkForExistence"),Vd=n(async({security:e,...t})=>{for(let o of e){if(Ih(t,o.name))continue;let i=await Bd(o,t.auth);if(!i)continue;let m=o.name??"Authorization";switch(o.in){case"query":t.query||(t.query={}),t.query[m]=i;break;case"cookie":t.headers.append("Cookie",`${m}=${i}`);break;default:t.headers.set(m,i);break}}},"setAuthParams"),hc=n(e=>Wd({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:typeof e.querySerializer=="function"?e.querySerializer:Hd(e.querySerializer),url:e.url}),"buildUrl"),yc=n((e,t)=>{let o={...e,...t};return o.baseUrl?.endsWith("/")&&(o.baseUrl=o.baseUrl.substring(0,o.baseUrl.length-1)),o.headers=fa(e.headers,t.headers),o},"mergeConfigs"),fa=n((...e)=>{let t=new Headers;for(let o of e){if(!o||typeof o!="object")continue;let i=o instanceof Headers?o.entries():Object.entries(o);for(let[m,y]of i)if(y===null)t.delete(m);else if(Array.isArray(y))for(let p of y)t.append(m,p);else y!==void 0&&t.set(m,typeof y=="object"?JSON.stringify(y):y)}return t},"mergeHeaders"),ei=class{static{n(this,"Interceptors")}_fns;constructor(){this._fns=[]}clear(){this._fns=[]}getInterceptorIndex(t){return typeof t=="number"?this._fns[t]?t:-1:this._fns.indexOf(t)}exists(t){let o=this.getInterceptorIndex(t);return!!this._fns[o]}eject(t){let o=this.getInterceptorIndex(t);this._fns[o]&&(this._fns[o]=null)}update(t,o){let i=this.getInterceptorIndex(t);return this._fns[i]?(this._fns[i]=o,t):!1}use(t){return this._fns=[...this._fns,t],this._fns.length-1}},Jd=n(()=>({error:new ei,request:new ei,response:new ei}),"createInterceptors"),kh=Hd({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Eh={"Content-Type":"application/json"},ti=n((e={})=>({...gc,headers:Eh,parseAs:"auto",querySerializer:kh,...e}),"createConfig");var ni=n((e={})=>{let t=yc(ti(),e),o=n(()=>({...t}),"getConfig"),i=n(b=>(t=yc(t,b),o()),"setConfig"),m=Jd(),y=n(async b=>{let d={...t,...b,fetch:b.fetch??t.fetch??globalThis.fetch,headers:fa(t.headers,b.headers),serializedBody:void 0};d.security&&await Vd({...d,security:d.security}),d.requestValidator&&await d.requestValidator(d),d.body&&d.bodySerializer&&(d.serializedBody=d.bodySerializer(d.body)),(d.serializedBody===void 0||d.serializedBody==="")&&d.headers.delete("Content-Type");let s=hc(d);return{opts:d,url:s}},"beforeRequest"),p=n(async b=>{let{opts:d,url:s}=await y(b),c={redirect:"follow",...d,body:d.serializedBody},l=new Request(s,c);for(let h of m.request._fns)h&&(l=await h(l,d));let g=d.fetch,u=await g(l);for(let h of m.response._fns)h&&(u=await h(u,l,d));let a={request:l,response:u};if(u.ok){if(u.status===204||u.headers.get("Content-Length")==="0")return d.responseStyle==="data"?{}:{data:{},...a};let h=(d.parseAs==="auto"?Gd(u.headers.get("Content-Type")):d.parseAs)??"json",v;switch(h){case"arrayBuffer":case"blob":case"formData":case"json":case"text":v=await u[h]();break;case"stream":return d.responseStyle==="data"?u.body:{data:u.body,...a}}return h==="json"&&(d.responseValidator&&await d.responseValidator(v),d.responseTransformer&&(v=await d.responseTransformer(v))),d.responseStyle==="data"?v:{data:v,...a}}let w=await u.text(),I;try{I=JSON.parse(w)}catch{}let r=I??w,x=r;for(let h of m.error._fns)h&&(x=await h(r,u,l,d));if(x=x||{},d.throwOnError)throw x;return d.responseStyle==="data"?void 0:{error:x,...a}},"request"),f=n(b=>{let d=n(s=>p({...s,method:b}),"fn");return d.sse=async s=>{let{opts:c,url:l}=await y(s);return qd({...c,body:c.body,headers:c.headers,method:b,url:l})},d},"makeMethod");return{buildUrl:hc,connect:f("CONNECT"),delete:f("DELETE"),get:f("GET"),getConfig:o,head:f("HEAD"),interceptors:m,options:f("OPTIONS"),patch:f("PATCH"),post:f("POST"),put:f("PUT"),request:p,setConfig:i,trace:f("TRACE")}},"createClient");var Sh={$body_:"body",$headers_:"headers",$path_:"path",$query_:"query"},dO=Object.entries(Sh);var Yd=ni(ti({baseUrl:"http://localhost:4096"}));var Zt=class{static{n(this,"_HeyApiClient")}_client=Yd;constructor(t){t?.client&&(this._client=t.client)}},bc=class extends Zt{static{n(this,"Global")}event(t){return(t?.client??this._client).get.sse({url:"/global/event",...t})}},wc=class extends Zt{static{n(this,"Project")}list(t){return(t?.client??this._client).get({url:"/project",...t})}current(t){return(t?.client??this._client).get({url:"/project/current",...t})}},xc=class extends Zt{static{n(this,"Pty")}list(t){return(t?.client??this._client).get({url:"/pty",...t})}create(t){return(t?.client??this._client).post({url:"/pty",...t,headers:{"Content-Type":"application/json",...t?.headers}})}remove(t){return(t.client??this._client).delete({url:"/pty/{id}",...t})}get(t){return(t.client??this._client).get({url:"/pty/{id}",...t})}update(t){return(t.client??this._client).put({url:"/pty/{id}",...t,headers:{"Content-Type":"application/json",...t.headers}})}connect(t){return(t.client??this._client).get({url:"/pty/{id}/connect",...t})}},vc=class extends Zt{static{n(this,"Config")}get(t){return(t?.client??this._client).get({url:"/config",...t})}update(t){return(t?.client??this._client).patch({url:"/config",...t,headers:{"Content-Type":"application/json",...t?.headers}})}providers(t){return(t?.client??this._client).get({url:"/config/providers",...t})}},Ic=class extends Zt{static{n(this,"Tool")}ids(t){return(t?.client??this._client).get({url:"/experimental/tool/ids",...t})}list(t){return(t.client??this._client).get({url:"/experimental/tool",...t})}},kc=class extends Zt{static{n(this,"Instance")}dispose(t){return(t?.client??this._client).post({url:"/instance/dispose",...t})}},Ec=class extends Zt{static{n(this,"Path")}get(t){return(t?.client??this._client).get({url:"/path",...t})}},Sc=class extends Zt{static{n(this,"Vcs")}get(t){return(t?.client??this._client).get({url:"/vcs",...t})}},Dc=class extends Zt{static{n(this,"Session")}list(t){return(t?.client??this._client).get({url:"/session",...t})}create(t){return(t?.client??this._client).post({url:"/session",...t,headers:{"Content-Type":"application/json",...t?.headers}})}status(t){return(t?.client??this._client).get({url:"/session/status",...t})}delete(t){return(t.client??this._client).delete({url:"/session/{id}",...t})}get(t){return(t.client??this._client).get({url:"/session/{id}",...t})}update(t){return(t.client??this._client).patch({url:"/session/{id}",...t,headers:{"Content-Type":"application/json",...t.headers}})}children(t){return(t.client??this._client).get({url:"/session/{id}/children",...t})}todo(t){return(t.client??this._client).get({url:"/session/{id}/todo",...t})}init(t){return(t.client??this._client).post({url:"/session/{id}/init",...t,headers:{"Content-Type":"application/json",...t.headers}})}fork(t){return(t.client??this._client).post({url:"/session/{id}/fork",...t,headers:{"Content-Type":"application/json",...t.headers}})}abort(t){return(t.client??this._client).post({url:"/session/{id}/abort",...t})}unshare(t){return(t.client??this._client).delete({url:"/session/{id}/share",...t})}share(t){return(t.client??this._client).post({url:"/session/{id}/share",...t})}diff(t){return(t.client??this._client).get({url:"/session/{id}/diff",...t})}summarize(t){return(t.client??this._client).post({url:"/session/{id}/summarize",...t,headers:{"Content-Type":"application/json",...t.headers}})}messages(t){return(t.client??this._client).get({url:"/session/{id}/message",...t})}prompt(t){return(t.client??this._client).post({url:"/session/{id}/message",...t,headers:{"Content-Type":"application/json",...t.headers}})}message(t){return(t.client??this._client).get({url:"/session/{id}/message/{messageID}",...t})}promptAsync(t){return(t.client??this._client).post({url:"/session/{id}/prompt_async",...t,headers:{"Content-Type":"application/json",...t.headers}})}command(t){return(t.client??this._client).post({url:"/session/{id}/command",...t,headers:{"Content-Type":"application/json",...t.headers}})}shell(t){return(t.client??this._client).post({url:"/session/{id}/shell",...t,headers:{"Content-Type":"application/json",...t.headers}})}revert(t){return(t.client??this._client).post({url:"/session/{id}/revert",...t,headers:{"Content-Type":"application/json",...t.headers}})}unrevert(t){return(t.client??this._client).post({url:"/session/{id}/unrevert",...t})}},Tc=class extends Zt{static{n(this,"Command")}list(t){return(t?.client??this._client).get({url:"/command",...t})}},Pc=class extends Zt{static{n(this,"Oauth")}authorize(t){return(t.client??this._client).post({url:"/provider/{id}/oauth/authorize",...t,headers:{"Content-Type":"application/json",...t.headers}})}callback(t){return(t.client??this._client).post({url:"/provider/{id}/oauth/callback",...t,headers:{"Content-Type":"application/json",...t.headers}})}},_c=class extends Zt{static{n(this,"Provider")}list(t){return(t?.client??this._client).get({url:"/provider",...t})}auth(t){return(t?.client??this._client).get({url:"/provider/auth",...t})}oauth=new Pc({client:this._client})},Oc=class extends Zt{static{n(this,"Find")}text(t){return(t.client??this._client).get({url:"/find",...t})}files(t){return(t.client??this._client).get({url:"/find/file",...t})}symbols(t){return(t.client??this._client).get({url:"/find/symbol",...t})}},Ac=class extends Zt{static{n(this,"File")}list(t){return(t.client??this._client).get({url:"/file",...t})}read(t){return(t.client??this._client).get({url:"/file/content",...t})}status(t){return(t?.client??this._client).get({url:"/file/status",...t})}},Cc=class extends Zt{static{n(this,"App")}log(t){return(t?.client??this._client).post({url:"/log",...t,headers:{"Content-Type":"application/json",...t?.headers}})}agents(t){return(t?.client??this._client).get({url:"/agent",...t})}},ma=class extends Zt{static{n(this,"Auth")}remove(t){return(t.client??this._client).delete({url:"/mcp/{name}/auth",...t})}start(t){return(t.client??this._client).post({url:"/mcp/{name}/auth",...t})}callback(t){return(t.client??this._client).post({url:"/mcp/{name}/auth/callback",...t,headers:{"Content-Type":"application/json",...t.headers}})}authenticate(t){return(t.client??this._client).post({url:"/mcp/{name}/auth/authenticate",...t})}set(t){return(t.client??this._client).put({url:"/auth/{id}",...t,headers:{"Content-Type":"application/json",...t.headers}})}},Rc=class extends Zt{static{n(this,"Mcp")}status(t){return(t?.client??this._client).get({url:"/mcp",...t})}add(t){return(t?.client??this._client).post({url:"/mcp",...t,headers:{"Content-Type":"application/json",...t?.headers}})}connect(t){return(t.client??this._client).post({url:"/mcp/{name}/connect",...t})}disconnect(t){return(t.client??this._client).post({url:"/mcp/{name}/disconnect",...t})}auth=new ma({client:this._client})},jc=class extends Zt{static{n(this,"Lsp")}status(t){return(t?.client??this._client).get({url:"/lsp",...t})}},Mc=class extends Zt{static{n(this,"Formatter")}status(t){return(t?.client??this._client).get({url:"/formatter",...t})}},Lc=class extends Zt{static{n(this,"Control")}next(t){return(t?.client??this._client).get({url:"/tui/control/next",...t})}response(t){return(t?.client??this._client).post({url:"/tui/control/response",...t,headers:{"Content-Type":"application/json",...t?.headers}})}},Nc=class extends Zt{static{n(this,"Tui")}appendPrompt(t){return(t?.client??this._client).post({url:"/tui/append-prompt",...t,headers:{"Content-Type":"application/json",...t?.headers}})}openHelp(t){return(t?.client??this._client).post({url:"/tui/open-help",...t})}openSessions(t){return(t?.client??this._client).post({url:"/tui/open-sessions",...t})}openThemes(t){return(t?.client??this._client).post({url:"/tui/open-themes",...t})}openModels(t){return(t?.client??this._client).post({url:"/tui/open-models",...t})}submitPrompt(t){return(t?.client??this._client).post({url:"/tui/submit-prompt",...t})}clearPrompt(t){return(t?.client??this._client).post({url:"/tui/clear-prompt",...t})}executeCommand(t){return(t?.client??this._client).post({url:"/tui/execute-command",...t,headers:{"Content-Type":"application/json",...t?.headers}})}showToast(t){return(t?.client??this._client).post({url:"/tui/show-toast",...t,headers:{"Content-Type":"application/json",...t?.headers}})}publish(t){return(t?.client??this._client).post({url:"/tui/publish",...t,headers:{"Content-Type":"application/json",...t?.headers}})}control=new Lc({client:this._client})},zc=class extends Zt{static{n(this,"Event")}subscribe(t){return(t?.client??this._client).get.sse({url:"/event",...t})}},ga=class extends Zt{static{n(this,"OpencodeClient")}postSessionIdPermissionsPermissionId(t){return(t.client??this._client).post({url:"/session/{id}/permissions/{permissionID}",...t,headers:{"Content-Type":"application/json",...t.headers}})}global=new bc({client:this._client});project=new wc({client:this._client});pty=new xc({client:this._client});config=new vc({client:this._client});tool=new Ic({client:this._client});instance=new kc({client:this._client});path=new Ec({client:this._client});vcs=new Sc({client:this._client});session=new Dc({client:this._client});command=new Tc({client:this._client});provider=new _c({client:this._client});find=new Oc({client:this._client});file=new Ac({client:this._client});app=new Cc({client:this._client});mcp=new Rc({client:this._client});lsp=new jc({client:this._client});formatter=new Mc({client:this._client});tui=new Nc({client:this._client});auth=new ma({client:this._client});event=new zc({client:this._client})};function Dh(e,t){if(e)return t&&(e===t||e===encodeURIComponent(t))?t:e}n(Dh,"pick");function Th(e,t){if(e.method!=="GET"&&e.method!=="HEAD")return e;let o=Dh(e.headers.get("x-opencode-directory"),t);if(!o)return e;let i=new URL(e.url);i.searchParams.has("directory")||i.searchParams.set("directory",o);let m=new Request(i,e);return m.headers.delete("x-opencode-directory"),m}n(Th,"rewrite");function Fc(e){e?.fetch||(e={...e,fetch:n(i=>(i.timeout=!1,fetch(i)),"customFetch")}),e?.directory&&(e.headers={...e.headers,"x-opencode-directory":encodeURIComponent(e.directory)});let t=ni(e);return t.interceptors.request.use(o=>Th(o,e?.directory)),new ga({client:t})}n(Fc,"createOpencodeClient");import LO from"cross-spawn";import $c from"os";import{setTimeout as Ah}from"node:timers/promises";import{createServer as Ch}from"http";import Rh from"path";import Uc from"fs/promises";import Ph from"path";var _h=272e3,Oh=1440*60*1e3;function Kd(e,t=new Date){let o=Array.isArray(e?.models)?e.models:Array.isArray(e)?e:[],i={};for(let m of o){let y=typeof m?.slug=="string"?m.slug:void 0,p=Number(m?.context_window);if(!y||!Number.isFinite(p)||p<=0)continue;let f=Number(m?.max_context_window);i[y]={contextWindow:p,...Number.isFinite(f)&&f>0?{maxContextWindow:f}:{}}}return{fetchedAt:t.toISOString(),models:i}}n(Kd,"parsePlanCatalog");function Xd(e,t,o){let i=o?.models[e];if(!i&&!/^gpt-\d/.test(e))return;let m=i?.contextWindow??_h,y=t.input??Math.max(0,t.context-t.output),p=y>0?Math.min(m,y):m;return{input:p,output:t.output,context:p+t.output}}n(Xd,"planLimitFor");async function Zd(e){try{let t=JSON.parse(await Uc.readFile(e,"utf8"));if(t&&typeof t.fetchedAt=="string"&&t.models&&typeof t.models=="object")return t}catch{}}n(Zd,"readPlanCatalog");async function Qd(e,t){await Uc.mkdir(Ph.dirname(e),{recursive:!0}),await Uc.writeFile(e,JSON.stringify(t,null,2))}n(Qd,"writePlanCatalog");function eu(e,t=Date.now()){if(!e||Object.keys(e.models).length===0)return!0;let o=Date.parse(e.fetchedAt);return!Number.isFinite(o)||t-o>Oh}n(eu,"planCatalogStale");var oi=qe.create({service:"plugin.codex"}),ri="app_EMoamEEZ73f0CkXaXp7hrann",Vo="https://auth.openai.com",jh="https://chatgpt.com/backend-api/codex/responses",Mh="https://chatgpt.com/backend-api/codex/models",Lh="0.155.0",pr=1455,Nh=3e3;async function zh(){let e=Fh(43),o=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",o),m=ou(i);return{verifier:e,challenge:m}}n(zh,"generatePKCE");function Fh(e){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",o=crypto.getRandomValues(new Uint8Array(e));return Array.from(o).map(i=>t[i%t.length]).join("")}n(Fh,"generateRandomString");function ou(e){let t=new Uint8Array(e),o=String.fromCharCode(...t);return btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}n(ou,"base64UrlEncode");function Uh(){return ou(crypto.getRandomValues(new Uint8Array(32)).buffer)}n(Uh,"generateState");function tu(e){let t=e.split(".");if(t.length===3)try{return JSON.parse(Buffer.from(t[1],"base64url").toString())}catch{return}}n(tu,"parseJwtClaims");function nu(e){return e.chatgpt_account_id||e["https://api.openai.com/auth"]?.chatgpt_account_id||e.organizations?.[0]?.id}n(nu,"extractAccountIdFromClaims");function qc(e){if(e.id_token){let t=tu(e.id_token),o=t&&nu(t);if(o)return o}if(e.access_token){let t=tu(e.access_token);return t?nu(t):void 0}}n(qc,"extractAccountId");function $h(e,t,o){let i=new URLSearchParams({response_type:"code",client_id:ri,redirect_uri:e,scope:"openid profile email offline_access",code_challenge:t.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:o,originator:"opencode"});return`${Vo}/oauth/authorize?${i.toString()}`}n($h,"buildAuthorizeUrl");async function qh(e,t,o){let i=await fetch(`${Vo}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,redirect_uri:t,client_id:ri,code_verifier:o.verifier}).toString()});if(!i.ok)throw new Error(`Token exchange failed: ${i.status}`);return i.json()}n(qh,"exchangeCodeForTokens");async function Bh(e,t=Vo){let o=await fetch(`${t}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:ri}).toString()});if(!o.ok)throw new Error(`Token refresh failed: ${o.status}`);return o.json()}n(Bh,"refreshAccessToken");var Wh=`<!doctype html>
|
|
67
|
+
<html>
|
|
68
|
+
<head>
|
|
69
|
+
<title>OpenCode - Codex Authorization Successful</title>
|
|
70
|
+
<style>
|
|
71
|
+
body {
|
|
72
|
+
font-family:
|
|
73
|
+
system-ui,
|
|
74
|
+
-apple-system,
|
|
75
|
+
sans-serif;
|
|
76
|
+
display: flex;
|
|
77
|
+
justify-content: center;
|
|
78
|
+
align-items: center;
|
|
79
|
+
height: 100vh;
|
|
80
|
+
margin: 0;
|
|
81
|
+
background: #131010;
|
|
82
|
+
color: #f1ecec;
|
|
83
|
+
}
|
|
84
|
+
.container {
|
|
85
|
+
text-align: center;
|
|
86
|
+
padding: 2rem;
|
|
87
|
+
}
|
|
88
|
+
h1 {
|
|
89
|
+
color: #f1ecec;
|
|
90
|
+
margin-bottom: 1rem;
|
|
91
|
+
}
|
|
92
|
+
p {
|
|
93
|
+
color: #b7b1b1;
|
|
94
|
+
}
|
|
95
|
+
</style>
|
|
96
|
+
</head>
|
|
97
|
+
<body>
|
|
98
|
+
<div class="container">
|
|
99
|
+
<h1>Authorization Successful</h1>
|
|
100
|
+
<p>You can close this window and return to OpenCode.</p>
|
|
101
|
+
</div>
|
|
102
|
+
<script>
|
|
103
|
+
setTimeout(() => window.close(), 2000)
|
|
104
|
+
</script>
|
|
105
|
+
</body>
|
|
106
|
+
</html>`,Bc=n(e=>`<!doctype html>
|
|
107
|
+
<html>
|
|
108
|
+
<head>
|
|
109
|
+
<title>OpenCode - Codex Authorization Failed</title>
|
|
110
|
+
<style>
|
|
111
|
+
body {
|
|
112
|
+
font-family:
|
|
113
|
+
system-ui,
|
|
114
|
+
-apple-system,
|
|
115
|
+
sans-serif;
|
|
116
|
+
display: flex;
|
|
117
|
+
justify-content: center;
|
|
118
|
+
align-items: center;
|
|
119
|
+
height: 100vh;
|
|
120
|
+
margin: 0;
|
|
121
|
+
background: #131010;
|
|
122
|
+
color: #f1ecec;
|
|
123
|
+
}
|
|
124
|
+
.container {
|
|
125
|
+
text-align: center;
|
|
126
|
+
padding: 2rem;
|
|
127
|
+
}
|
|
128
|
+
h1 {
|
|
129
|
+
color: #fc533a;
|
|
130
|
+
margin-bottom: 1rem;
|
|
131
|
+
}
|
|
132
|
+
p {
|
|
133
|
+
color: #b7b1b1;
|
|
134
|
+
}
|
|
135
|
+
.error {
|
|
136
|
+
color: #ff917b;
|
|
137
|
+
font-family: monospace;
|
|
138
|
+
margin-top: 1rem;
|
|
139
|
+
padding: 1rem;
|
|
140
|
+
background: #3c140d;
|
|
141
|
+
border-radius: 0.5rem;
|
|
142
|
+
}
|
|
143
|
+
</style>
|
|
144
|
+
</head>
|
|
145
|
+
<body>
|
|
146
|
+
<div class="container">
|
|
147
|
+
<h1>Authorization Failed</h1>
|
|
148
|
+
<p>An error occurred during authorization.</p>
|
|
149
|
+
<div class="error">${e}</div>
|
|
150
|
+
</div>
|
|
151
|
+
</body>
|
|
152
|
+
</html>`,"HTML_ERROR"),Lr,qn;async function Hh(){return Lr?{port:pr,redirectUri:`http://localhost:${pr}/auth/callback`}:(Lr=Ch((e,t)=>{let o=new URL(e.url||"/",`http://localhost:${pr}`);if(o.pathname==="/auth/callback"){let i=o.searchParams.get("code"),m=o.searchParams.get("state"),y=o.searchParams.get("error"),p=o.searchParams.get("error_description");if(y){let b=p||y;qn?.reject(new Error(b)),qn=void 0,t.writeHead(200,{"Content-Type":"text/html"}),t.end(Bc(b));return}if(!i){let b="Missing authorization code";qn?.reject(new Error(b)),qn=void 0,t.writeHead(400,{"Content-Type":"text/html"}),t.end(Bc(b));return}if(!qn||m!==qn.state){let b="Invalid state - potential CSRF attack";qn?.reject(new Error(b)),qn=void 0,t.writeHead(400,{"Content-Type":"text/html"}),t.end(Bc(b));return}let f=qn;qn=void 0,qh(i,`http://localhost:${pr}/auth/callback`,f.pkce).then(b=>f.resolve(b)).catch(b=>f.reject(b)),t.writeHead(200,{"Content-Type":"text/html"}),t.end(Wh);return}if(o.pathname==="/cancel"){qn?.reject(new Error("Login cancelled")),qn=void 0,t.writeHead(200),t.end("Login cancelled");return}t.writeHead(404),t.end("Not found")}),await new Promise((e,t)=>{Lr.listen(pr,()=>{oi.info("codex oauth server started",{port:pr}),e()}),Lr.on("error",t)}),{port:pr,redirectUri:`http://localhost:${pr}/auth/callback`})}n(Hh,"startOAuthServer");function Gh(){Lr&&(Lr.close(()=>{oi.info("codex oauth server stopped")}),Lr=void 0)}n(Gh,"stopOAuthServer");function Vh(e,t){return new Promise((o,i)=>{let m=setTimeout(()=>{qn&&(qn=void 0,i(new Error("OAuth callback timeout - authorization took too long")))},3e5);qn={pkce:e,state:t,resolve:n(y=>{clearTimeout(m),o(y)},"resolve"),reject:n(y=>{clearTimeout(m),i(y)},"reject")}})}n(Vh,"waitForOAuthCallback");async function ru(e,t={}){let o=t.issuer??Vo,i=t.codexApiEndpoint??jh;return{auth:{provider:"openai",async loader(m,y){if((await m()).type!=="oauth")return{};let f=new Set(["gpt-5.5","gpt-5.2","gpt-5.3-codex","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]);for(let g of Object.keys(y.models)){if(g.includes("codex")||f.has(g))continue;let u=g.match(/^gpt-(\d+)(?:\.(\d+))?(?:-|$)/);if(u){let a=Number(u[1]),w=Number(u[2]??0);if(a>5||a===5&&w>4)continue}delete y.models[g]}for(let g of Object.values(y.models))g.cost={input:0,output:0,cache:{read:0,write:0}};let b=Rh.join(je.Path.state,"codex-plan-models.json"),d=n(g=>{for(let[u,a]of Object.entries(y.models)){if(!a.limit)continue;let w=Xd(a.api?.id??u,a.limit,g);w&&(a.limit=w)}},"applyPlanLimits"),s=await Zd(b);d(s);let c,l=n(async function(u,a){a?.headers&&(a.headers instanceof Headers?(a.headers.delete("authorization"),a.headers.delete("Authorization")):Array.isArray(a.headers)?a.headers=a.headers.filter(([v])=>v.toLowerCase()!=="authorization"):(delete a.headers.authorization,delete a.headers.Authorization));let w=await m();if(w.type!=="oauth")return fetch(u,a);let I=w;if(!w.access||w.expires<Date.now()){c||(oi.info("refreshing codex access token"),c=Bh(w.refresh,o).then(async S=>{let j=qc(S)||I.accountId;return await e.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:S.refresh_token,access:S.access_token,expires:Date.now()+(S.expires_in??3600)*1e3,...j&&{accountId:j}}}),{access:S.access_token,accountId:j}}).finally(()=>{c=void 0}));let v=await c;w.access=v.access,I.accountId=v.accountId}let r=new Headers;if(a?.headers)if(a.headers instanceof Headers)a.headers.forEach((v,S)=>r.set(S,v));else if(Array.isArray(a.headers))for(let[v,S]of a.headers)S!==void 0&&r.set(v,String(S));else for(let[v,S]of Object.entries(a.headers))S!==void 0&&r.set(v,String(S));r.set("authorization",`Bearer ${w.access}`),I.accountId&&r.set("ChatGPT-Account-Id",I.accountId);let x=u instanceof URL?u:new URL(typeof u=="string"?u:u.url),h=x.pathname.includes("/v1/responses")||x.pathname.includes("/chat/completions")?new URL(i):x;return fetch(h,{...a,headers:r})},"planFetch");return eu(s)&&t.refreshPlanCatalog!==!1&&!t.codexApiEndpoint&&l(`${Mh}?client_version=${Lh}`,{method:"GET"}).then(async g=>{if(!g.ok)throw new Error(`models list ${g.status}`);let u=Kd(await g.json());Object.keys(u.models).length!==0&&(await Qd(b,u),d(u),oi.info("plan model list refreshed",{models:Object.keys(u.models).length}))}).catch(g=>oi.warn("plan model list not refreshed; keeping the cached or default windows",{error:String(g)})),{apiKey:sd,fetch:l}},methods:[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:n(async()=>{let{redirectUri:m}=await Hh(),y=await zh(),p=Uh(),f=$h(m,y,p),b=Vh(y,p);return{url:f,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:n(async()=>{let d=await b;Gh();let s=qc(d);return{type:"success",refresh:d.refresh_token,access:d.access_token,expires:Date.now()+(d.expires_in??3600)*1e3,accountId:s}},"callback")}},"authorize")},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:n(async()=>{let m=await fetch(`${Vo}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":`opencode/${Ft.VERSION}`},body:JSON.stringify({client_id:ri})});if(!m.ok)throw new Error("Failed to initiate device authorization");let y=await m.json(),p=Math.max(parseInt(y.interval)||5,1)*1e3;return{url:`${Vo}/codex/device`,instructions:`Enter code: ${y.user_code}`,method:"auto",async callback(){for(;;){let f=await fetch(`${Vo}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":`opencode/${Ft.VERSION}`},body:JSON.stringify({device_auth_id:y.device_auth_id,user_code:y.user_code})});if(f.ok){let b=await f.json(),d=await fetch(`${Vo}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:b.authorization_code,redirect_uri:`${Vo}/deviceauth/callback`,client_id:ri,code_verifier:b.code_verifier}).toString()});if(!d.ok)throw new Error(`Token exchange failed: ${d.status}`);let s=await d.json();return{type:"success",refresh:s.refresh_token,access:s.access_token,expires:Date.now()+(s.expires_in??3600)*1e3,accountId:qc(s)}}if(f.status!==403&&f.status!==404)return{type:"failed"};await Ah(p+Nh)}}}},"authorize")},{label:"Manually enter API Key",type:"api"}]},"chat.headers":n(async(m,y)=>{m.model.providerID==="openai"&&(y.headers.originator="opencode",y.headers["User-Agent"]=`opencode/${Ft.VERSION} (${$c.platform()} ${$c.release()}; ${$c.arch()})`,y.headers["session-id"]=m.sessionID,y.headers["thread-id"]=m.sessionID)},"chat.headers"),"chat.params":n(async(m,y)=>{m.model.providerID==="openai"&&(y.maxOutputTokens=void 0)},"chat.params")}}n(ru,"CodexAuthPlugin");import{setTimeout as Hc}from"node:timers/promises";import{z as Mt}from"zod";var Wc;(i=>{i.schema=Mt.object({data:Mt.array(Mt.object({model_picker_enabled:Mt.boolean(),id:Mt.string(),name:Mt.string(),version:Mt.string(),supported_endpoints:Mt.array(Mt.string()).optional(),capabilities:Mt.object({family:Mt.string(),limits:Mt.object({max_context_window_tokens:Mt.number(),max_output_tokens:Mt.number(),max_prompt_tokens:Mt.number(),vision:Mt.object({max_prompt_image_size:Mt.number(),max_prompt_images:Mt.number(),supported_media_types:Mt.array(Mt.string())}).optional()}),supports:Mt.object({adaptive_thinking:Mt.boolean().optional(),max_thinking_budget:Mt.number().optional(),min_thinking_budget:Mt.number().optional(),reasoning_effort:Mt.array(Mt.string()).optional(),streaming:Mt.boolean(),structured_outputs:Mt.boolean().optional(),tool_calls:Mt.boolean(),vision:Mt.boolean().optional()})})}))});function t(m,y,p,f){let b=!!y.capabilities.supports.adaptive_thinking||!!y.capabilities.supports.reasoning_effort?.length||y.capabilities.supports.max_thinking_budget!==void 0||y.capabilities.supports.min_thinking_budget!==void 0,d=(y.capabilities.supports.vision??!1)||(y.capabilities.limits.vision?.supported_media_types??[]).some(s=>s.startsWith("image/"));return{id:m,providerID:"github-copilot",api:{id:y.id,url:p,npm:"@ai-sdk/github-copilot"},status:"active",limit:{context:y.capabilities.limits.max_context_window_tokens,input:y.capabilities.limits.max_prompt_tokens,output:y.capabilities.limits.max_output_tokens},capabilities:{temperature:f?.capabilities.temperature??!0,reasoning:f?.capabilities.reasoning??b,attachment:f?.capabilities.attachment??!0,toolcall:y.capabilities.supports.tool_calls,input:{text:!0,audio:!1,image:d,video:!1,pdf:!1},output:{text:!0,audio:!1,image:!1,video:!1,pdf:!1},interleaved:!1},family:f?.family??y.capabilities.family,name:f?.name??y.name,cost:{input:0,output:0,cache:{read:0,write:0}},options:f?.options??{},headers:f?.headers??{},release_date:f?.release_date??(y.version.startsWith(`${y.id}-`)?y.version.slice(y.id.length+1):y.version),variants:f?.variants??{}}}n(t,"build");async function o(m,y={},p={}){let f=await fetch(`${m}/models`,{headers:y,signal:AbortSignal.timeout(5e3)}).then(async s=>{if(!s.ok)throw new Error(`Failed to fetch models: ${s.status}`);return i.schema.parse(await s.json())}),b={...p},d=new Map(f.data.filter(s=>s.model_picker_enabled).map(s=>[s.id,s]));for(let[s,c]of Object.entries(b)){let l=d.get(c.api.id);if(!l){delete b[s];continue}b[s]=t(s,l,m,c)}for(let[s,c]of d)s in b||(b[s]=t(s,c,m));return b}i.get=o,n(o,"get")})(Wc||={});var Jh=qe.create({service:"plugin.copilot"}),su="Ov23li8tweQw6odWQebz",Gc=3e3;function cu(e){return e.replace(/^https?:\/\//,"").replace(/\/$/,"")}n(cu,"normalizeDomain");function Yh(e){return{DEVICE_CODE_URL:`https://${e}/login/device/code`,ACCESS_TOKEN_URL:`https://${e}/login/oauth/access_token`}}n(Yh,"getUrls");function iu(e){return e?`https://copilot-api.${cu(e)}`:"https://api.githubcopilot.com"}n(iu,"base");function au(e){return{...e,api:{...e.api,npm:"@ai-sdk/github-copilot"}}}n(au,"fix");async function lu(e){let t=e.client;return{provider:{id:"github-copilot",async models(o,i){return i.auth?.type!=="oauth"?Object.fromEntries(Object.entries(o.models).map(([m,y])=>[m,au(y)])):Wc.get(iu(i.auth.enterpriseUrl),{Authorization:`Bearer ${i.auth.refresh}`,"User-Agent":`opencode/${Ft.VERSION}`},o.models).catch(m=>(Jh.error("failed to fetch copilot models",{error:m}),Object.fromEntries(Object.entries(o.models).map(([y,p])=>[y,au(p)]))))}},auth:{provider:"github-copilot",async loader(o){let i=await o();return!i||i.type!=="oauth"?{}:{baseURL:iu(i.enterpriseUrl),apiKey:"",async fetch(y,p){let f=await o();if(f.type!=="oauth")return fetch(y,p);let b=y instanceof URL?y.href:y.toString(),{isVision:d,isAgent:s}=qt(()=>{try{let l=typeof p?.body=="string"?JSON.parse(p.body):p?.body;if(l?.messages&&b.includes("completions")){let g=l.messages[l.messages.length-1];return{isVision:l.messages.some(u=>Array.isArray(u.content)&&u.content.some(a=>a.type==="image_url")),isAgent:g?.role!=="user"}}if(l?.input){let g=l.input[l.input.length-1];return{isVision:l.input.some(u=>Array.isArray(u?.content)&&u.content.some(a=>a.type==="input_image")),isAgent:g?.role!=="user"}}if(l?.messages){let g=l.messages[l.messages.length-1],u=Array.isArray(g?.content)&&g.content.some(a=>a?.type!=="tool_result");return{isVision:l.messages.some(a=>Array.isArray(a?.content)&&a.content.some(w=>w?.type==="image"||w?.type==="tool_result"&&Array.isArray(w?.content)&&w.content.some(I=>I?.type==="image"))),isAgent:!(g?.role==="user"&&u)}}}catch{}return{isVision:!1,isAgent:!1}}),c={"x-initiator":s?"agent":"user",...p?.headers,"User-Agent":`opencode/${Ft.VERSION}`,Authorization:`Bearer ${f.refresh}`,"Openai-Intent":"conversation-edits"};return d&&(c["Copilot-Vision-Request"]="true"),delete c["x-api-key"],delete c.authorization,fetch(y,{...p,headers:c})}}},methods:[{type:"oauth",label:"Login with GitHub Copilot",prompts:[{type:"select",key:"deploymentType",message:"Select GitHub deployment type",options:[{label:"GitHub.com",value:"github.com",hint:"Public"},{label:"GitHub Enterprise",value:"enterprise",hint:"Data residency or self-hosted"}]},{type:"text",key:"enterpriseUrl",message:"Enter your GitHub Enterprise URL or domain",placeholder:"company.ghe.com or https://company.ghe.com",when:{key:"deploymentType",op:"eq",value:"enterprise"},validate:n(o=>{if(!o)return"URL or domain is required";try{return(o.includes("://")?new URL(o):new URL(`https://${o}`)).hostname?void 0:"Please enter a valid URL or domain"}catch{return"Please enter a valid URL (e.g., company.ghe.com or https://company.ghe.com)"}},"validate")}],async authorize(o={}){let i=o.deploymentType||"github.com",m="github.com";if(i==="enterprise"){let b=o.enterpriseUrl;m=cu(b)}let y=Yh(m),p=await fetch(y.DEVICE_CODE_URL,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":`opencode/${Ft.VERSION}`},body:JSON.stringify({client_id:su,scope:"read:user"})});if(!p.ok)throw new Error("Failed to initiate device authorization");let f=await p.json();return{url:f.verification_uri,instructions:`Enter code: ${f.user_code}`,method:"auto",async callback(){for(;;){let b=await fetch(y.ACCESS_TOKEN_URL,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":`opencode/${Ft.VERSION}`},body:JSON.stringify({client_id:su,device_code:f.device_code,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(!b.ok)return{type:"failed"};let d=await b.json();if(d.access_token){let s={type:"success",refresh:d.access_token,access:d.access_token,expires:0};return i==="enterprise"&&(s.enterpriseUrl=m),s}if(d.error==="authorization_pending"){await Hc(f.interval*1e3+Gc);continue}if(d.error==="slow_down"){let s=(f.interval+5)*1e3,c=d.interval;c&&typeof c=="number"&&c>0&&(s=c*1e3),await Hc(s+Gc);continue}if(d.error)return{type:"failed"};await Hc(f.interval*1e3+Gc)}}}}}]},"chat.params":n(async(o,i)=>{o.model.providerID.includes("github-copilot")&&o.model.api.id.includes("gpt")&&(i.maxOutputTokens=void 0)},"chat.params"),"chat.headers":n(async(o,i)=>{if(!o.model.providerID.includes("github-copilot"))return;if(o.model.api.npm==="@ai-sdk/anthropic"&&(i.headers["anthropic-beta"]="interleaved-thinking-2025-05-14"),(await t.session.message({path:{id:o.message.sessionID,messageID:o.message.id},query:{directory:e.directory},throwOnError:!0}).catch(()=>{}))?.data.parts?.some(p=>p.type==="compaction")){i.headers["x-initiator"]="agent";return}let y=await t.session.get({path:{id:o.sessionID},query:{directory:e.directory},throwOnError:!0}).catch(()=>{});!y||!y.data.parentID||(i.headers["x-initiator"]="agent")},"chat.headers")}}n(lu,"CopilotAuthPlugin");import{gitlabAuthPlugin as Kh}from"opencode-gitlab-auth";import{PoeAuthPlugin as Xh}from"opencode-poe-auth";async function du(e){return{auth:{provider:"cloudflare-workers-ai",methods:[{type:"api",label:"API key",prompts:[...process.env.CLOUDFLARE_ACCOUNT_ID?[]:[{type:"text",key:"accountId",message:"Enter your Cloudflare Account ID",placeholder:"e.g. 1234567890abcdef1234567890abcdef"}]]}]}}}n(du,"CloudflareWorkersAuthPlugin");async function uu(e){return{auth:{provider:"cloudflare-ai-gateway",methods:[{type:"api",label:"Gateway API token",prompts:[...process.env.CLOUDFLARE_ACCOUNT_ID?[]:[{type:"text",key:"accountId",message:"Enter your Cloudflare Account ID",placeholder:"e.g. 1234567890abcdef1234567890abcdef"}],...process.env.CLOUDFLARE_GATEWAY_ID?[]:[{type:"text",key:"gatewayId",message:"Enter your Cloudflare AI Gateway ID",placeholder:"e.g. my-gateway"}]]}]}}}n(uu,"CloudflareAIGatewayAuthPlugin");import{Effect as On,Layer as Jc,ServiceMap as Zh,Stream as Qh}from"effect";var Vc;(y=>{function e(p){let f=rt.pluginSpecifier(p);return{spec:f,options:rt.pluginOptions(p),deprecated:yd(f)}}n(e,"plan");async function t(p,f){let b="";try{b=await xd(p.spec)}catch(s){return{ok:!1,stage:"install",error:s}}if(!b)return{ok:!1,stage:"install",error:new Error(`Plugin ${p.spec} target is empty`)};let d;try{d=await vd(p.spec,b,f)}catch(s){return{ok:!1,stage:"entry",error:s}}if(!d.entry)return{ok:!1,stage:"missing",value:{...p,source:d.source,target:d.target,pkg:d.pkg,message:`Plugin ${p.spec} does not expose a ${f} entrypoint`}};if(d.source==="npm")try{await wd(d.target,Ft.VERSION,d.pkg)}catch(s){return{ok:!1,stage:"compatibility",error:s}}return{ok:!0,value:{...p,source:d.source,target:d.target,entry:d.entry,pkg:d.pkg}}}y.resolve=t,n(t,"resolve");async function o(p){let f;try{f=await import(p.entry)}catch(b){return{ok:!1,error:b}}return f?{ok:!0,value:{...p,mod:f}}:{ok:!1,error:new Error(`Plugin ${p.spec} module is empty`)}}y.load=o,n(o,"load");async function i(p,f,b,d,s,c){let l=p.plan;if(l.deprecated)return;c?.start?.(p,b);let g=await t(l,f);if(!g.ok){if(g.stage==="missing"){if(s){let a=await s(g.value,p.origin,b);if(a!==void 0)return a}c?.missing?.(p,b,g.value.message,g.value);return}c?.error?.(p,b,g.stage,g.error);return}let u=await o(g.value);if(!u.ok){c?.error?.(p,b,"load",u.error,g.value);return}return d?d(u.value,p.origin,b):u.value}n(i,"attempt");async function m(p){let f=p.items.map(c=>({origin:c,plan:e(c.spec)})),b=[];for(let c of f)b.push(i(c,p.kind,!1,p.finish,p.missing,p.report));let d=await Promise.all(b);if(p.wait){let c;for(let l=0;l<f.length;l++){if(d[l]!==void 0)continue;let g=f[l];!g||Yi(g.plan.spec)!=="file"||(c??=p.wait(),await c,d[l]=await i(g,p.kind,!0,p.finish,p.missing,p.report))}}let s=[];for(let c of d)c!==void 0&&s.push(c);return s}y.loadExternal=m,n(m,"loadExternal")})(Vc||={});var ln;(u=>{let e=qe.create({service:"plugin"});class t extends Zh.Service()("@opencode/Plugin"){static{n(this,"Service")}}u.Service=t;let o=[ru,lu,Kh,Xh,du,uu];function i(a){return typeof a=="function"}n(i,"isServerPlugin");function m(a){if(i(a))return a;if(!(!a||typeof a!="object"||!("server"in a))&&i(a.server))return a.server}n(m,"getServerPlugin");function y(a){let w=new Set,I=[];for(let[r,x]of Object.entries(a)){if(r==="__esModule"||r==="__name"||r==="__export"||r==="module.exports"||w.has(x))continue;w.add(x);let h=x;h&&typeof h=="object"&&"default"in h&&typeof h.default=="function"&&(h=h.default);let v=m(h);v&&I.push(v)}if(I.length===0)throw new TypeError("Plugin export is not a function");return I}n(y,"getLegacyPlugins");function p(a,w){On.runFork(a.publish(yt.Event.Error,{error:new tt.Unknown({message:w}).toObject()}))}n(p,"publishPluginError");async function f(a,w,I){let r=kd(a.mod,a.spec,"server","detect");if(r){await Ed(a.source,a.spec,a.target,Id(r.id,a.spec),a.pkg),I.push(await r.server(w,a.options));return}for(let x of y(a.mod))I.push(await x(w,a.options))}n(f,"applyPlugin"),u.layer=Jc.effect(t,On.gen(function*(){let a=yield*Ve.Service,w=yield*rt.Service,I=yield*ge.make(On.fn("Plugin.state")(function*(v){let S=[],{Server:j}=yield*On.promise(()=>import("./server-PIYRZLBG.js")),O=Fc({baseUrl:"http://localhost:4096",directory:v.directory,headers:Ce.OPENCODE_SERVER_PASSWORD?{Authorization:`Basic ${Buffer.from(`${Ce.OPENCODE_SERVER_USERNAME??"opencode"}:${Ce.OPENCODE_SERVER_PASSWORD}`).toString("base64")}`}:void 0,fetch:n(async(..._)=>j.Default().fetch(..._),"fetch")}),k=yield*w.get(),E={client:O,project:v.project,worktree:v.worktree,directory:v.directory,get serverUrl(){return j.url??new URL("http://localhost:4096")},$:typeof Bun>"u"?void 0:Bun.$};for(let _ of o){e.info("loading internal plugin",{name:_.name});let B=yield*On.tryPromise({try:n(()=>_(E),"try"),catch:n($=>{e.error("failed to load internal plugin",{name:_.name,error:$})},"catch")}).pipe(On.option);B._tag==="Some"&&S.push(B.value)}let D=Ce.OPENCODE_PURE?[]:k.plugin_origins??[];Ce.OPENCODE_PURE&&k.plugin_origins?.length&&e.info("skipping external plugins in pure mode",{count:k.plugin_origins.length}),D.length&&(yield*w.waitForDependencies());let z=yield*On.promise(()=>Vc.loadExternal({items:D,kind:"server",report:{start(_){e.info("loading plugin",{path:_.plan.spec})},missing(_,B,$){e.warn("plugin has no server entrypoint",{path:_.plan.spec,message:$})},error(_,B,$,M,C){let T=_.plan.spec,G=M instanceof Error?M.cause??M:M,N=$==="load"?jo(M):jo(G);if($==="install"){let A=Ji(T);e.error("failed to install plugin",{pkg:A.pkg,version:A.version,error:N}),p(a,`Failed to install plugin ${A.pkg}@${A.version}: ${N}`);return}if($==="compatibility"){e.warn("plugin incompatible",{path:T,error:N}),p(a,`Plugin ${T} skipped: ${N}`);return}if($==="entry"){e.error("failed to resolve plugin server entry",{path:T,error:N}),p(a,`Failed to load plugin ${T}: ${N}`);return}e.error("failed to load plugin",{path:T,target:C?.entry,error:N}),p(a,`Failed to load plugin ${T}: ${N}`)}}}));for(let _ of z)_&&(yield*On.tryPromise({try:n(()=>f(_,E,S),"try"),catch:n(B=>{let $=jo(B);return e.error("failed to load plugin",{path:_.spec,error:$}),$},"catch")}).pipe(On.catch(B=>a.publish(yt.Event.Error,{error:new tt.Unknown({message:`Failed to load plugin ${_.spec}: ${B}`}).toObject()}))));for(let _ of S)yield*On.tryPromise({try:n(()=>Promise.resolve(_.config?.(k)),"try"),catch:n(B=>{e.error("plugin config hook failed",{error:B})},"catch")}).pipe(On.ignore);return yield*a.subscribeAll().pipe(Qh.runForEach(_=>On.sync(()=>{for(let B of S)B.event?.({event:_})})),On.forkScoped),{hooks:S}})),r=On.fn("Plugin.trigger")(function*(v,S,j){if(!v)return j;let O=yield*ge.get(I);for(let k of O.hooks){let E=k[v];if(E)try{yield*On.promise(async()=>E(S,j))}catch(D){e.error("plugin hook error",{name:v,error:D instanceof Error?D.message:String(D)})}}return j}),x=On.fn("Plugin.list")(function*(){return(yield*ge.get(I)).hooks}),h=On.fn("Plugin.init")(function*(){yield*ge.get(I)});return t.of({trigger:r,list:x,init:h})})),u.defaultLayer=u.layer.pipe(Jc.provide(Ve.layer),Jc.provide(rt.defaultLayer));let{runPromise:s}=Ke(t,u.defaultLayer);async function c(a,w,I){return s(r=>r.trigger(a,w,I))}u.trigger=c,n(c,"trigger");async function l(){return s(a=>a.list())}u.list=l,n(l,"list");async function g(){return s(a=>a.init())}u.init=g,n(g,"init")})(ln||={});import ub from"path";import{Effect as gt,Layer as ai,ServiceMap as pb}from"effect";import{createAmazonBedrock as fb}from"@ai-sdk/amazon-bedrock";import{createAnthropic as mb}from"@ai-sdk/anthropic";import{createAzure as gb}from"@ai-sdk/azure";import{createGoogleGenerativeAI as hb}from"@ai-sdk/google";import{createVertex as yb}from"@ai-sdk/google-vertex";import{createVertexAnthropic as bb}from"@ai-sdk/google-vertex/anthropic";import{createOpenAI as wb}from"@ai-sdk/openai";import{createOpenAICompatible as Ju}from"@ai-sdk/openai-compatible";import{createOpenRouter as xb}from"@openrouter/ai-sdk-provider";import{withoutTrailingSlash as rb,withUserAgentSuffix as sb}from"@ai-sdk/provider-utils";import{InvalidResponseDataError as Xc}from"@ai-sdk/provider";import{combineHeaders as gu,createEventSourceResponseHandler as ry,createJsonErrorResponseHandler as sy,createJsonResponseHandler as iy,generateId as ya,isParsableJson as hu,parseProviderOptions as yu,postJsonToApi as bu}from"@ai-sdk/provider-utils";import{z as ft}from"zod/v4";import{UnsupportedFunctionalityError as ey}from"@ai-sdk/provider";import{convertToBase64 as ty}from"@ai-sdk/provider-utils";function si(e){return e?.providerOptions?.copilot??{}}n(si,"getOpenAIMetadata");function pu(e){let t=[];for(let{role:o,content:i,...m}of e){let y=si({...m});switch(o){case"system":{t.push({role:"system",content:i,...y});break}case"user":{if(i.length===1&&i[0].type==="text"){t.push({role:"user",content:i[0].text,...si(i[0])});break}t.push({role:"user",content:i.map(p=>{let f=si(p);switch(p.type){case"text":return{type:"text",text:p.text,...f};case"file":if(p.mediaType.startsWith("image/")){let b=p.mediaType==="image/*"?"image/jpeg":p.mediaType;return{type:"image_url",image_url:{url:p.data instanceof URL?p.data.toString():`data:${b};base64,${ty(p.data)}`},...f}}else throw new ey({functionality:`file part media type ${p.mediaType}`})}}),...y});break}case"assistant":{let p="",f,b,d=[];for(let s of i){let c=si(s),l=s.providerOptions?.copilot?.reasoningOpaque;switch(l&&!b&&(b=l),s.type){case"text":{p+=s.text;break}case"reasoning":{s.text&&(f=s.text);break}case"tool-call":{d.push({id:s.toolCallId,type:"function",function:{name:s.toolName,arguments:JSON.stringify(s.input)},...c});break}}}t.push({role:"assistant",content:p||null,tool_calls:d.length>0?d:void 0,reasoning_text:b?f:void 0,reasoning_opaque:b,...y});break}case"tool":{for(let p of i){if(p.type==="tool-approval-response")continue;let f=p.output,b;switch(f.type){case"text":case"error-text":b=f.value;break;case"execution-denied":b=f.reason??"Tool execution denied.";break;case"content":case"json":case"error-json":b=JSON.stringify(f.value);break}let d=si(p);t.push({role:"tool",tool_call_id:p.toolCallId,content:b,...d})}break}default:{let p=o;throw new Error(`Unsupported role: ${p}`)}}}return t}n(pu,"convertToOpenAICompatibleChatMessages");function Yc({id:e,model:t,created:o}){return{id:e??void 0,modelId:t??void 0,timestamp:o!=null?new Date(o*1e3):void 0}}n(Yc,"getResponseMetadata");function Kc(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}n(Kc,"mapOpenAICompatibleFinishReason");import{z as ii}from"zod/v4";var ha=ii.object({user:ii.string().optional(),reasoningEffort:ii.string().optional(),textVerbosity:ii.string().optional(),thinking_budget:ii.number().optional()});import{z as fr}from"zod/v4";var ny=fr.object({error:fr.object({message:fr.string(),type:fr.string().nullish(),param:fr.any().nullish(),code:fr.union([fr.string(),fr.number()]).nullish()})}),fu={errorSchema:ny,errorToMessage:n(e=>e.error.message,"errorToMessage")};import{UnsupportedFunctionalityError as oy}from"@ai-sdk/provider";function mu({tools:e,toolChoice:t}){e=e?.length?e:void 0;let o=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:o};let i=[];for(let y of e)y.type==="provider"?o.push({type:"unsupported",feature:`tool type: ${y.type}`}):i.push({type:"function",function:{name:y.name,description:y.description,parameters:y.inputSchema}});if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:o};let m=t.type;switch(m){case"auto":case"none":case"required":return{tools:i,toolChoice:m,toolWarnings:o};case"tool":return{tools:i,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:o};default:{let y=m;throw new oy({functionality:`tool choice type: ${y}`})}}}n(mu,"prepareTools");var ba=class{static{n(this,"OpenAICompatibleChatLanguageModel")}specificationVersion="v3";supportsStructuredOutputs;modelId;config;failedResponseHandler;chunkSchema;constructor(t,o){this.modelId=t,this.config=o;let i=o.errorStructure??fu;this.chunkSchema=cy(i.errorSchema),this.failedResponseHandler=sy(i),this.supportsStructuredOutputs=o.supportsStructuredOutputs??!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){return this.config.supportedUrls?.()??{}}async getArgs({prompt:t,maxOutputTokens:o,temperature:i,topP:m,topK:y,frequencyPenalty:p,presencePenalty:f,providerOptions:b,stopSequences:d,responseFormat:s,seed:c,toolChoice:l,tools:g}){let u=[],a=Object.assign(await yu({provider:"copilot",providerOptions:b,schema:ha})??{},await yu({provider:this.providerOptionsName,providerOptions:b,schema:ha})??{});y!=null&&u.push({type:"unsupported",feature:"topK"}),s?.type==="json"&&s.schema!=null&&!this.supportsStructuredOutputs&&u.push({type:"unsupported",feature:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});let{tools:w,toolChoice:I,toolWarnings:r}=mu({tools:g,toolChoice:l});return{args:{model:this.modelId,user:a.user,max_tokens:o,temperature:i,top_p:m,frequency_penalty:p,presence_penalty:f,response_format:s?.type==="json"?this.supportsStructuredOutputs===!0&&s.schema!=null?{type:"json_schema",json_schema:{schema:s.schema,name:s.name??"response",description:s.description}}:{type:"json_object"}:void 0,stop:d,seed:c,...Object.fromEntries(Object.entries(b?.[this.providerOptionsName]??{}).filter(([x])=>!Object.keys(ha.shape).includes(x))),reasoning_effort:a.reasoningEffort,verbosity:a.textVerbosity,messages:pu(t),tools:w,tool_choice:I,thinking_budget:a.thinking_budget},warnings:[...u,...r]}}async doGenerate(t){let{args:o,warnings:i}=await this.getArgs({...t}),m=JSON.stringify(o),{responseHeaders:y,value:p,rawValue:f}=await bu({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:gu(this.config.headers(),t.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:iy(ay),abortSignal:t.abortSignal,fetch:this.config.fetch}),b=p.choices[0],d=[],s=b.message.content;s!=null&&s.length>0&&d.push({type:"text",text:s,providerMetadata:b.message.reasoning_opaque?{copilot:{reasoningOpaque:b.message.reasoning_opaque}}:void 0});let c=b.message.reasoning_text;if(c!=null&&c.length>0&&d.push({type:"reasoning",text:c,providerMetadata:b.message.reasoning_opaque?{copilot:{reasoningOpaque:b.message.reasoning_opaque}}:void 0}),b.message.tool_calls!=null)for(let u of b.message.tool_calls)d.push({type:"tool-call",toolCallId:u.id??ya(),toolName:u.function.name,input:u.function.arguments,providerMetadata:b.message.reasoning_opaque?{copilot:{reasoningOpaque:b.message.reasoning_opaque}}:void 0});let l={[this.providerOptionsName]:{},...await this.config.metadataExtractor?.extractMetadata?.({parsedBody:f})},g=p.usage?.completion_tokens_details;return g?.accepted_prediction_tokens!=null&&(l[this.providerOptionsName].acceptedPredictionTokens=g?.accepted_prediction_tokens),g?.rejected_prediction_tokens!=null&&(l[this.providerOptionsName].rejectedPredictionTokens=g?.rejected_prediction_tokens),{content:d,finishReason:{unified:Kc(b.finish_reason),raw:b.finish_reason??void 0},usage:{inputTokens:{total:p.usage?.prompt_tokens??void 0,noCache:void 0,cacheRead:p.usage?.prompt_tokens_details?.cached_tokens??void 0,cacheWrite:void 0},outputTokens:{total:p.usage?.completion_tokens??void 0,text:void 0,reasoning:p.usage?.completion_tokens_details?.reasoning_tokens??void 0},raw:p.usage??void 0},providerMetadata:l,request:{body:m},response:{...Yc(p),headers:y,body:f},warnings:i}}async doStream(t){let{args:o,warnings:i}=await this.getArgs({...t}),m={...o,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},y=this.config.metadataExtractor?.createStreamExtractor(),{responseHeaders:p,value:f}=await bu({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:gu(this.config.headers(),t.headers),body:m,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:ry(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),b=[],d={unified:"other",raw:void 0},s={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0},c=!0,l=this.providerOptionsName,g=!1,u=!1,a;return{stream:f.pipeThrough(new TransformStream({start(w){w.enqueue({type:"stream-start",warnings:i})},transform(w,I){if(t.includeRawChunks&&I.enqueue({type:"raw",rawValue:w.rawValue}),!w.success){d={unified:"error",raw:void 0},I.enqueue({type:"error",error:w.error});return}let r=w.value;if(y?.processChunk(w.rawValue),"error"in r){d={unified:"error",raw:void 0},I.enqueue({type:"error",error:r.error.message});return}if(c&&(c=!1,I.enqueue({type:"response-metadata",...Yc(r)})),r.usage!=null){let{prompt_tokens:S,completion_tokens:j,total_tokens:O,prompt_tokens_details:k,completion_tokens_details:E}=r.usage;s.promptTokens=S??void 0,s.completionTokens=j??void 0,s.totalTokens=O??void 0,E?.reasoning_tokens!=null&&(s.completionTokensDetails.reasoningTokens=E?.reasoning_tokens),E?.accepted_prediction_tokens!=null&&(s.completionTokensDetails.acceptedPredictionTokens=E?.accepted_prediction_tokens),E?.rejected_prediction_tokens!=null&&(s.completionTokensDetails.rejectedPredictionTokens=E?.rejected_prediction_tokens),k?.cached_tokens!=null&&(s.promptTokensDetails.cachedTokens=k?.cached_tokens)}let x=r.choices[0];if(x?.finish_reason!=null&&(d={unified:Kc(x.finish_reason),raw:x.finish_reason??void 0}),x?.delta==null)return;let h=x.delta;if(h.reasoning_opaque){if(a!=null)throw new Xc({data:h,message:"Multiple reasoning_opaque values received in a single response. Only one thinking part per response is supported."});a=h.reasoning_opaque}let v=h.reasoning_text;if(v&&(g||(I.enqueue({type:"reasoning-start",id:"reasoning-0"}),g=!0),I.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:v})),h.content&&(g&&!u&&(I.enqueue({type:"reasoning-end",id:"reasoning-0",providerMetadata:a?{copilot:{reasoningOpaque:a}}:void 0}),g=!1),u||(I.enqueue({type:"text-start",id:"txt-0",providerMetadata:a?{copilot:{reasoningOpaque:a}}:void 0}),u=!0),I.enqueue({type:"text-delta",id:"txt-0",delta:h.content})),h.tool_calls!=null){g&&(I.enqueue({type:"reasoning-end",id:"reasoning-0",providerMetadata:a?{copilot:{reasoningOpaque:a}}:void 0}),g=!1);for(let S of h.tool_calls){let j=S.index;if(b[j]==null){if(S.id==null)throw new Xc({data:S,message:"Expected 'id' to be a string."});if(S.function?.name==null)throw new Xc({data:S,message:"Expected 'function.name' to be a string."});I.enqueue({type:"tool-input-start",id:S.id,toolName:S.function.name}),b[j]={id:S.id,type:"function",function:{name:S.function.name,arguments:S.function.arguments??""},hasFinished:!1};let k=b[j];k.function?.name!=null&&k.function?.arguments!=null&&(k.function.arguments.length>0&&I.enqueue({type:"tool-input-delta",id:k.id,delta:k.function.arguments}),hu(k.function.arguments)&&(I.enqueue({type:"tool-input-end",id:k.id}),I.enqueue({type:"tool-call",toolCallId:k.id??ya(),toolName:k.function.name,input:k.function.arguments,providerMetadata:a?{copilot:{reasoningOpaque:a}}:void 0}),k.hasFinished=!0));continue}let O=b[j];O.hasFinished||(S.function?.arguments!=null&&(O.function.arguments+=S.function?.arguments??""),I.enqueue({type:"tool-input-delta",id:O.id,delta:S.function.arguments??""}),O.function?.name!=null&&O.function?.arguments!=null&&hu(O.function.arguments)&&(I.enqueue({type:"tool-input-end",id:O.id}),I.enqueue({type:"tool-call",toolCallId:O.id??ya(),toolName:O.function.name,input:O.function.arguments,providerMetadata:a?{copilot:{reasoningOpaque:a}}:void 0}),O.hasFinished=!0))}}},flush(w){g&&w.enqueue({type:"reasoning-end",id:"reasoning-0",providerMetadata:a?{copilot:{reasoningOpaque:a}}:void 0}),u&&w.enqueue({type:"text-end",id:"txt-0"});for(let r of b.filter(x=>!x.hasFinished))w.enqueue({type:"tool-input-end",id:r.id}),w.enqueue({type:"tool-call",toolCallId:r.id??ya(),toolName:r.function.name,input:r.function.arguments});let I={[l]:{},...a?{copilot:{reasoningOpaque:a}}:{},...y?.buildMetadata()};s.completionTokensDetails.acceptedPredictionTokens!=null&&(I[l].acceptedPredictionTokens=s.completionTokensDetails.acceptedPredictionTokens),s.completionTokensDetails.rejectedPredictionTokens!=null&&(I[l].rejectedPredictionTokens=s.completionTokensDetails.rejectedPredictionTokens),w.enqueue({type:"finish",finishReason:d,usage:{inputTokens:{total:s.promptTokens,noCache:s.promptTokens!=null&&s.promptTokensDetails.cachedTokens!=null?s.promptTokens-s.promptTokensDetails.cachedTokens:void 0,cacheRead:s.promptTokensDetails.cachedTokens,cacheWrite:void 0},outputTokens:{total:s.completionTokens,text:void 0,reasoning:s.completionTokensDetails.reasoningTokens},raw:{prompt_tokens:s.promptTokens??null,completion_tokens:s.completionTokens??null,total_tokens:s.totalTokens??null}},providerMetadata:I})}})),request:{body:m},response:{headers:p}}}},wu=ft.object({prompt_tokens:ft.number().nullish(),completion_tokens:ft.number().nullish(),total_tokens:ft.number().nullish(),prompt_tokens_details:ft.object({cached_tokens:ft.number().nullish()}).nullish(),completion_tokens_details:ft.object({reasoning_tokens:ft.number().nullish(),accepted_prediction_tokens:ft.number().nullish(),rejected_prediction_tokens:ft.number().nullish()}).nullish()}).nullish(),ay=ft.object({id:ft.string().nullish(),created:ft.number().nullish(),model:ft.string().nullish(),choices:ft.array(ft.object({message:ft.object({role:ft.literal("assistant").nullish(),content:ft.string().nullish(),reasoning_text:ft.string().nullish(),reasoning_opaque:ft.string().nullish(),tool_calls:ft.array(ft.object({id:ft.string().nullish(),function:ft.object({name:ft.string(),arguments:ft.string()})})).nullish()}),finish_reason:ft.string().nullish()})),usage:wu}),cy=n(e=>ft.union([ft.object({id:ft.string().nullish(),created:ft.number().nullish(),model:ft.string().nullish(),choices:ft.array(ft.object({delta:ft.object({role:ft.enum(["assistant"]).nullish(),content:ft.string().nullish(),reasoning_text:ft.string().nullish(),reasoning_opaque:ft.string().nullish(),tool_calls:ft.array(ft.object({index:ft.number(),id:ft.string().nullish(),function:ft.object({name:ft.string().nullish(),arguments:ft.string().nullish()})})).nullish()}).nullish(),finish_reason:ft.string().nullish()})),usage:wu}),e]),"createOpenAICompatibleChatChunkSchema");import{APICallError as Sy}from"@ai-sdk/provider";import{combineHeaders as Au,createEventSourceResponseHandler as Dy,createJsonResponseHandler as Ty,generateId as wa,parseProviderOptions as Py,postJsonToApi as Cu}from"@ai-sdk/provider-utils";import{z as U}from"zod/v4";import{z as mr}from"zod/v4";import{createJsonErrorResponseHandler as ly}from"@ai-sdk/provider-utils";var dy=mr.object({error:mr.object({message:mr.string(),type:mr.string().nullish(),param:mr.any().nullish(),code:mr.union([mr.string(),mr.number()]).nullish()})}),Zc=ly({errorSchema:dy,errorToMessage:n(e=>e.error.message,"errorToMessage")});import{UnsupportedFunctionalityError as py}from"@ai-sdk/provider";import{convertToBase64 as xu,parseProviderOptions as fy}from"@ai-sdk/provider-utils";import{z as tl}from"zod/v4";import{createProviderToolFactoryWithOutputSchema as uy}from"@ai-sdk/provider-utils";import{z as to}from"zod/v4";var Qc=to.object({action:to.object({type:to.literal("exec"),command:to.array(to.string()),timeoutMs:to.number().optional(),user:to.string().optional(),workingDirectory:to.string().optional(),env:to.record(to.string(),to.string()).optional()})}),el=to.object({output:to.string()}),DC=uy({id:"openai.local_shell",inputSchema:Qc,outputSchema:el});function vu(e,t){return t?t.some(o=>e.startsWith(o)):!1}n(vu,"isFileId");async function Iu({prompt:e,systemMessageMode:t,fileIdPrefixes:o,store:i,hasLocalShellTool:m=!1}){let y=[],p=[],f=new Set;for(let{role:b,content:d}of e)switch(b){case"system":{switch(t){case"system":{y.push({role:"system",content:d});break}case"developer":{y.push({role:"developer",content:d});break}case"remove":{p.push({type:"other",message:"system messages are removed for this model"});break}default:{let s=t;throw new Error(`Unsupported system message mode: ${s}`)}}break}case"user":{y.push({role:"user",content:d.map((s,c)=>{switch(s.type){case"text":return{type:"input_text",text:s.text};case"file":if(s.mediaType.startsWith("image/")){let l=s.mediaType==="image/*"?"image/jpeg":s.mediaType;return{type:"input_image",...s.data instanceof URL?{image_url:s.data.toString()}:typeof s.data=="string"&&vu(s.data,o)?{file_id:s.data}:{image_url:`data:${l};base64,${xu(s.data)}`},detail:s.providerOptions?.openai?.imageDetail}}else{if(s.mediaType==="application/pdf")return s.data instanceof URL?{type:"input_file",file_url:s.data.toString()}:{type:"input_file",...typeof s.data=="string"&&vu(s.data,o)?{file_id:s.data}:{filename:s.filename??`part-${c}.pdf`,file_data:`data:application/pdf;base64,${xu(s.data)}`}};throw new py({functionality:`file part media type ${s.mediaType}`})}}})});break}case"assistant":{let s={},c={};for(let l of d)switch(l.type){case"text":{y.push({role:"assistant",content:[{type:"output_text",text:l.text}],id:l.providerOptions?.openai?.itemId??void 0});break}case"tool-call":{if(c[l.toolCallId]=l,l.providerExecuted)break;if(m&&l.toolName==="local_shell"){let g=Qc.parse(l.input);y.push({type:"local_shell_call",call_id:l.toolCallId,id:l.providerOptions?.openai?.itemId??void 0,action:{type:"exec",command:g.action.command,timeout_ms:g.action.timeoutMs,user:g.action.user,working_directory:g.action.workingDirectory,env:g.action.env}});break}y.push({type:"function_call",call_id:l.toolCallId,name:l.toolName,arguments:JSON.stringify(l.input),id:l.providerOptions?.openai?.itemId??void 0});break}case"tool-result":{i?y.push({type:"item_reference",id:l.toolCallId}):p.push({type:"other",message:`Results for OpenAI tool ${l.toolName} are not sent to the API when store is false`});break}case"reasoning":{let g=await fy({provider:"copilot",providerOptions:l.providerOptions,schema:my}),u=g?.itemId;if(u!=null){let a=s[u];if(i)a===void 0&&(y.push({type:"item_reference",id:u}),s[u]={type:"reasoning",id:u,summary:[]});else{let w=[];l.text.length>0?w.push({type:"summary_text",text:l.text}):a!==void 0&&p.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(l)}.`}),a===void 0?(s[u]={type:"reasoning",id:u,encrypted_content:g?.reasoningEncryptedContent,summary:w},y.push(s[u])):a.summary.push(...w)}}else p.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(l)}.`});break}}break}case"tool":{for(let s of d){if(s.type==="tool-approval-response"){if(f.has(s.approvalId))continue;f.add(s.approvalId),i&&y.push({type:"item_reference",id:s.approvalId}),y.push({type:"mcp_approval_response",approval_request_id:s.approvalId,approve:s.approved});continue}let c=s.output;if(c.type==="execution-denied"&&c.providerOptions?.openai?.approvalId)continue;if(m&&s.toolName==="local_shell"&&c.type==="json"){y.push({type:"local_shell_call_output",call_id:s.toolCallId,output:el.parse(c.value).output});break}let l;switch(c.type){case"text":case"error-text":l=c.value;break;case"execution-denied":l=c.reason??"Tool execution denied.";break;case"content":case"json":case"error-json":l=JSON.stringify(c.value);break}y.push({type:"function_call_output",call_id:s.toolCallId,output:l})}break}default:{let s=b;throw new Error(`Unsupported role: ${s}`)}}return{input:y,warnings:p}}n(Iu,"convertToOpenAIResponsesInput");var my=tl.object({itemId:tl.string().nullish(),reasoningEncryptedContent:tl.string().nullish()});function nl({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"other"}}n(nl,"mapOpenAIResponseFinishReason");import{UnsupportedFunctionalityError as Ey}from"@ai-sdk/provider";import{createProviderToolFactoryWithOutputSchema as gy}from"@ai-sdk/provider-utils";import{z as Sn}from"zod/v4";var hy=Sn.object({code:Sn.string().nullish(),containerId:Sn.string()}),yy=Sn.object({outputs:Sn.array(Sn.discriminatedUnion("type",[Sn.object({type:Sn.literal("logs"),logs:Sn.string()}),Sn.object({type:Sn.literal("image"),url:Sn.string()})])).nullish()}),ku=Sn.object({container:Sn.union([Sn.string(),Sn.object({fileIds:Sn.array(Sn.string()).optional()})]).optional()}),zC=gy({id:"openai.code_interpreter",inputSchema:hy,outputSchema:yy});import{createProviderToolFactoryWithOutputSchema as by}from"@ai-sdk/provider-utils";import{z as At}from"zod/v4";var Eu=At.object({key:At.string(),type:At.enum(["eq","ne","gt","gte","lt","lte"]),value:At.union([At.string(),At.number(),At.boolean()])}),Su=At.object({type:At.enum(["and","or"]),filters:At.array(At.union([Eu,At.lazy(()=>Su)]))}),Du=At.object({vectorStoreIds:At.array(At.string()),maxNumResults:At.number().optional(),ranking:At.object({ranker:At.string().optional(),scoreThreshold:At.number().optional()}).optional(),filters:At.union([Eu,Su]).optional()}),wy=At.object({queries:At.array(At.string()),results:At.array(At.object({attributes:At.record(At.string(),At.unknown()),fileId:At.string(),filename:At.string(),score:At.number(),text:At.string()})).nullable()}),BC=by({id:"openai.file_search",inputSchema:At.object({}),outputSchema:wy});import{createProviderToolFactory as xy}from"@ai-sdk/provider-utils";import{z as rn}from"zod/v4";var Tu=rn.object({filters:rn.object({allowedDomains:rn.array(rn.string()).optional()}).optional(),searchContextSize:rn.enum(["low","medium","high"]).optional(),userLocation:rn.object({type:rn.literal("approximate"),country:rn.string().optional(),city:rn.string().optional(),region:rn.string().optional(),timezone:rn.string().optional()}).optional()}),VC=xy({id:"openai.web_search",inputSchema:rn.object({action:rn.discriminatedUnion("type",[rn.object({type:rn.literal("search"),query:rn.string().nullish()}),rn.object({type:rn.literal("open_page"),url:rn.string()}),rn.object({type:rn.literal("find"),url:rn.string(),pattern:rn.string()})]).nullish()})});import{createProviderToolFactory as vy}from"@ai-sdk/provider-utils";import{z as hn}from"zod/v4";var Pu=hn.object({searchContextSize:hn.enum(["low","medium","high"]).optional(),userLocation:hn.object({type:hn.literal("approximate"),country:hn.string().optional(),city:hn.string().optional(),region:hn.string().optional(),timezone:hn.string().optional()}).optional()}),ZC=vy({id:"openai.web_search_preview",inputSchema:hn.object({action:hn.discriminatedUnion("type",[hn.object({type:hn.literal("search"),query:hn.string().nullish()}),hn.object({type:hn.literal("open_page"),url:hn.string()}),hn.object({type:hn.literal("find"),url:hn.string(),pattern:hn.string()})]).nullish()})});import{createProviderToolFactoryWithOutputSchema as Iy}from"@ai-sdk/provider-utils";import{z as Mn}from"zod/v4";var _u=Mn.object({background:Mn.enum(["auto","opaque","transparent"]).optional(),inputFidelity:Mn.enum(["low","high"]).optional(),inputImageMask:Mn.object({fileId:Mn.string().optional(),imageUrl:Mn.string().optional()}).optional(),model:Mn.string().optional(),moderation:Mn.enum(["auto"]).optional(),outputCompression:Mn.number().int().min(0).max(100).optional(),outputFormat:Mn.enum(["png","jpeg","webp"]).optional(),partialImages:Mn.number().int().min(0).max(3).optional(),quality:Mn.enum(["auto","low","medium","high"]).optional(),size:Mn.enum(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict(),ky=Mn.object({result:Mn.string()}),nR=Iy({id:"openai.image_generation",inputSchema:Mn.object({}),outputSchema:ky});function Ou({tools:e,toolChoice:t,strictJsonSchema:o}){e=e?.length?e:void 0;let i=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i};let m=[];for(let p of e)switch(p.type){case"function":m.push({type:"function",name:p.name,description:p.description,parameters:p.inputSchema,strict:o});break;case"provider":{switch(p.id){case"openai.file_search":{let f=Du.parse(p.args);m.push({type:"file_search",vector_store_ids:f.vectorStoreIds,max_num_results:f.maxNumResults,ranking_options:f.ranking?{ranker:f.ranking.ranker,score_threshold:f.ranking.scoreThreshold}:void 0,filters:f.filters});break}case"openai.local_shell":{m.push({type:"local_shell"});break}case"openai.web_search_preview":{let f=Pu.parse(p.args);m.push({type:"web_search_preview",search_context_size:f.searchContextSize,user_location:f.userLocation});break}case"openai.web_search":{let f=Tu.parse(p.args);m.push({type:"web_search",filters:f.filters!=null?{allowed_domains:f.filters.allowedDomains}:void 0,search_context_size:f.searchContextSize,user_location:f.userLocation});break}case"openai.code_interpreter":{let f=ku.parse(p.args);m.push({type:"code_interpreter",container:f.container==null?{type:"auto",file_ids:void 0}:typeof f.container=="string"?f.container:{type:"auto",file_ids:f.container.fileIds}});break}case"openai.image_generation":{let f=_u.parse(p.args);m.push({type:"image_generation",background:f.background,input_fidelity:f.inputFidelity,input_image_mask:f.inputImageMask?{file_id:f.inputImageMask.fileId,image_url:f.inputImageMask.imageUrl}:void 0,model:f.model,moderation:f.moderation,partial_images:f.partialImages,quality:f.quality,output_compression:f.outputCompression,output_format:f.outputFormat,size:f.size});break}}break}default:i.push({type:"unsupported",feature:"tool type"});break}if(t==null)return{tools:m,toolChoice:void 0,toolWarnings:i};let y=t.type;switch(y){case"auto":case"none":case"required":return{tools:m,toolChoice:y,toolWarnings:i};case"tool":return{tools:m,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="image_generation"||t.toolName==="web_search_preview"||t.toolName==="web_search"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:i};default:{let p=y;throw new Ey({functionality:`tool choice type: ${p}`})}}}n(Ou,"prepareResponsesTools");var Ru=U.object({type:U.literal("web_search_call"),id:U.string(),status:U.string(),action:U.discriminatedUnion("type",[U.object({type:U.literal("search"),query:U.string().nullish()}),U.object({type:U.literal("open_page"),url:U.string()}),U.object({type:U.literal("find"),url:U.string(),pattern:U.string()})]).nullish()}),ju=U.object({type:U.literal("file_search_call"),id:U.string(),queries:U.array(U.string()),results:U.array(U.object({attributes:U.record(U.string(),U.unknown()),file_id:U.string(),filename:U.string(),score:U.number(),text:U.string()})).nullish()}),Mu=U.object({type:U.literal("code_interpreter_call"),id:U.string(),code:U.string().nullable(),container_id:U.string(),outputs:U.array(U.discriminatedUnion("type",[U.object({type:U.literal("logs"),logs:U.string()}),U.object({type:U.literal("image"),url:U.string()})])).nullable()}),Lu=U.object({type:U.literal("local_shell_call"),id:U.string(),call_id:U.string(),action:U.object({type:U.literal("exec"),command:U.array(U.string()),timeout_ms:U.number().optional(),user:U.string().optional(),working_directory:U.string().optional(),env:U.record(U.string(),U.string()).optional()})}),Nu=U.object({type:U.literal("image_generation_call"),id:U.string(),result:U.string()}),zu=20,Fu=U.array(U.object({token:U.string(),logprob:U.number(),top_logprobs:U.array(U.object({token:U.string(),logprob:U.number()}))})),xa=class{static{n(this,"OpenAIResponsesLanguageModel")}specificationVersion="v3";modelId;config;constructor(t,o){this.modelId=t,this.config=o}supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]};get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:o,stopSequences:i,topP:m,topK:y,presencePenalty:p,frequencyPenalty:f,seed:b,prompt:d,providerOptions:s,tools:c,toolChoice:l,responseFormat:g}){let u=[],a=nb(this.modelId);y!=null&&u.push({type:"unsupported",feature:"topK"}),b!=null&&u.push({type:"unsupported",feature:"seed"}),p!=null&&u.push({type:"unsupported",feature:"presencePenalty"}),f!=null&&u.push({type:"unsupported",feature:"frequencyPenalty"}),i!=null&&u.push({type:"unsupported",feature:"stopSequences"});let w=await Py({provider:"copilot",providerOptions:s,schema:ob}),{input:I,warnings:r}=await Iu({prompt:d,systemMessageMode:a.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:w?.store??!0,hasLocalShellTool:S("openai.local_shell")});u.push(...r);let x=w?.strictJsonSchema??!1,h=w?.include;function v(_){h=h!=null?[...h,_]:[_]}n(v,"addInclude");function S(_){return c?.find(B=>B.type==="provider"&&B.id===_)!=null}n(S,"hasOpenAITool");let j=typeof w?.logprobs=="number"?w?.logprobs:w?.logprobs===!0?zu:void 0;j&&v("message.output_text.logprobs");let O=c?.find(_=>_.type==="provider"&&(_.id==="openai.web_search"||_.id==="openai.web_search_preview"))?.name;O&&v("web_search_call.action.sources"),S("openai.code_interpreter")&&v("code_interpreter_call.outputs");let k={model:this.modelId,input:I,temperature:o,top_p:m,max_output_tokens:t,...(g?.type==="json"||w?.textVerbosity)&&{text:{...g?.type==="json"&&{format:g.schema!=null?{type:"json_schema",strict:x,name:g.name??"response",description:g.description,schema:g.schema}:{type:"json_object"}},...w?.textVerbosity&&{verbosity:w.textVerbosity}}},max_tool_calls:w?.maxToolCalls,metadata:w?.metadata,parallel_tool_calls:w?.parallelToolCalls,previous_response_id:w?.previousResponseId,store:w?.store,user:w?.user,instructions:w?.instructions,service_tier:w?.serviceTier,include:h,prompt_cache_key:w?.promptCacheKey,safety_identifier:w?.safetyIdentifier,top_logprobs:j,...a.isReasoningModel&&(w?.reasoningEffort!=null||w?.reasoningSummary!=null)&&{reasoning:{...w?.reasoningEffort!=null&&{effort:w.reasoningEffort},...w?.reasoningSummary!=null&&{summary:w.reasoningSummary}}},...a.requiredAutoTruncation&&{truncation:"auto"}};a.isReasoningModel?(k.temperature!=null&&(k.temperature=void 0,u.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),k.top_p!=null&&(k.top_p=void 0,u.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(w?.reasoningEffort!=null&&u.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),w?.reasoningSummary!=null&&u.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),w?.serviceTier==="flex"&&!a.supportsFlexProcessing&&(u.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete k.service_tier),w?.serviceTier==="priority"&&!a.supportsPriorityProcessing&&(u.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete k.service_tier);let{tools:E,toolChoice:D,toolWarnings:z}=Ou({tools:c,toolChoice:l,strictJsonSchema:x});return{webSearchToolName:O,args:{...k,tools:E,tool_choice:D},warnings:[...u,...z]}}async doGenerate(t){let{args:o,warnings:i,webSearchToolName:m}=await this.getArgs(t),y=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:p,value:f,rawValue:b}=await Cu({url:y,headers:Au(this.config.headers(),t.headers),body:o,failedResponseHandler:Zc,successfulResponseHandler:Ty(U.object({id:U.string(),created_at:U.number(),error:U.object({code:U.string(),message:U.string()}).nullish(),model:U.string(),output:U.array(U.discriminatedUnion("type",[U.object({type:U.literal("message"),role:U.literal("assistant"),id:U.string(),content:U.array(U.object({type:U.literal("output_text"),text:U.string(),logprobs:Fu.nullish(),annotations:U.array(U.discriminatedUnion("type",[U.object({type:U.literal("url_citation"),start_index:U.number(),end_index:U.number(),url:U.string(),title:U.string()}),U.object({type:U.literal("file_citation"),file_id:U.string(),filename:U.string().nullish(),index:U.number().nullish(),start_index:U.number().nullish(),end_index:U.number().nullish(),quote:U.string().nullish()}),U.object({type:U.literal("container_file_citation")})]))}))}),Ru,ju,Mu,Nu,Lu,U.object({type:U.literal("function_call"),call_id:U.string(),name:U.string(),arguments:U.string(),id:U.string()}),U.object({type:U.literal("computer_call"),id:U.string(),status:U.string().optional()}),U.object({type:U.literal("reasoning"),id:U.string(),encrypted_content:U.string().nullish(),summary:U.array(U.object({type:U.literal("summary_text"),text:U.string()}))})])),service_tier:U.string().nullish(),incomplete_details:U.object({reason:U.string()}).nullish(),usage:Uu})),abortSignal:t.abortSignal,fetch:this.config.fetch});if(f.error)throw new Sy({message:f.error.message,url:y,requestBodyValues:o,statusCode:400,responseHeaders:p,responseBody:b,isRetryable:!1});let d=[],s=[],c=!1;for(let g of f.output)switch(g.type){case"reasoning":{g.summary.length===0&&g.summary.push({type:"summary_text",text:""});for(let u of g.summary)d.push({type:"reasoning",text:u.text,providerMetadata:{openai:{itemId:g.id,reasoningEncryptedContent:g.encrypted_content??null}}});break}case"image_generation_call":{d.push({type:"tool-call",toolCallId:g.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),d.push({type:"tool-result",toolCallId:g.id,toolName:"image_generation",result:{result:g.result}});break}case"local_shell_call":{d.push({type:"tool-call",toolCallId:g.call_id,toolName:"local_shell",input:JSON.stringify({action:g.action}),providerMetadata:{openai:{itemId:g.id}}});break}case"message":{for(let u of g.content){t.providerOptions?.openai?.logprobs&&u.logprobs&&s.push(u.logprobs),d.push({type:"text",text:u.text,providerMetadata:{openai:{itemId:g.id}}});for(let a of u.annotations)a.type==="url_citation"?d.push({type:"source",sourceType:"url",id:this.config.generateId?.()??wa(),url:a.url,title:a.title}):a.type==="file_citation"&&d.push({type:"source",sourceType:"document",id:this.config.generateId?.()??wa(),mediaType:"text/plain",title:a.quote??a.filename??"Document",filename:a.filename??a.file_id})}break}case"function_call":{c=!0,d.push({type:"tool-call",toolCallId:g.call_id,toolName:g.name,input:g.arguments,providerMetadata:{openai:{itemId:g.id}}});break}case"web_search_call":{d.push({type:"tool-call",toolCallId:g.id,toolName:m??"web_search",input:JSON.stringify({action:g.action}),providerExecuted:!0}),d.push({type:"tool-result",toolCallId:g.id,toolName:m??"web_search",result:{status:g.status}});break}case"computer_call":{d.push({type:"tool-call",toolCallId:g.id,toolName:"computer_use",input:"",providerExecuted:!0}),d.push({type:"tool-result",toolCallId:g.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:g.status||"completed"}});break}case"file_search_call":{d.push({type:"tool-call",toolCallId:g.id,toolName:"file_search",input:"{}",providerExecuted:!0}),d.push({type:"tool-result",toolCallId:g.id,toolName:"file_search",result:{queries:g.queries,results:g.results?.map(u=>({attributes:u.attributes,fileId:u.file_id,filename:u.filename,score:u.score,text:u.text}))??null}});break}case"code_interpreter_call":{d.push({type:"tool-call",toolCallId:g.id,toolName:"code_interpreter",input:JSON.stringify({code:g.code,containerId:g.container_id}),providerExecuted:!0}),d.push({type:"tool-result",toolCallId:g.id,toolName:"code_interpreter",result:{outputs:g.outputs}});break}}let l={openai:{responseId:f.id}};return s.length>0&&(l.openai.logprobs=s),typeof f.service_tier=="string"&&(l.openai.serviceTier=f.service_tier),{content:d,finishReason:{unified:nl({finishReason:f.incomplete_details?.reason,hasFunctionCall:c}),raw:f.incomplete_details?.reason},usage:{inputTokens:{total:f.usage.input_tokens,noCache:f.usage.input_tokens_details?.cached_tokens!=null?f.usage.input_tokens-f.usage.input_tokens_details.cached_tokens:void 0,cacheRead:f.usage.input_tokens_details?.cached_tokens??void 0,cacheWrite:void 0},outputTokens:{total:f.usage.output_tokens,text:void 0,reasoning:f.usage.output_tokens_details?.reasoning_tokens??void 0},raw:f.usage},request:{body:o},response:{id:f.id,timestamp:new Date(f.created_at*1e3),modelId:f.model,headers:p,body:b},providerMetadata:l,warnings:i}}async doStream(t){let{args:o,warnings:i,webSearchToolName:m}=await this.getArgs(t),{responseHeaders:y,value:p}=await Cu({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Au(this.config.headers(),t.headers),body:{...o,stream:!0},failedResponseHandler:Zc,successfulResponseHandler:Dy(qy),abortSignal:t.abortSignal,fetch:this.config.fetch}),f=this,b={unified:"other",raw:void 0},d={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0},s=[],c=null,l={},g=!1,u={},a=null,w=null,I;return{stream:p.pipeThrough(new TransformStream({start(r){r.enqueue({type:"stream-start",warnings:i})},transform(r,x){if(t.includeRawChunks&&x.enqueue({type:"raw",rawValue:r.rawValue}),!r.success){b={unified:"error",raw:void 0},x.enqueue({type:"error",error:r.error});return}let h=r.value;if(qu(h))h.item.type==="function_call"?(l[h.output_index]={toolName:h.item.name,toolCallId:h.item.call_id},x.enqueue({type:"tool-input-start",id:h.item.call_id,toolName:h.item.name})):h.item.type==="web_search_call"?(l[h.output_index]={toolName:m??"web_search",toolCallId:h.item.id},x.enqueue({type:"tool-input-start",id:h.item.id,toolName:m??"web_search"})):h.item.type==="computer_call"?(l[h.output_index]={toolName:"computer_use",toolCallId:h.item.id},x.enqueue({type:"tool-input-start",id:h.item.id,toolName:"computer_use"})):h.item.type==="code_interpreter_call"?(l[h.output_index]={toolName:"code_interpreter",toolCallId:h.item.id,codeInterpreter:{containerId:h.item.container_id}},x.enqueue({type:"tool-input-start",id:h.item.id,toolName:"code_interpreter"}),x.enqueue({type:"tool-input-delta",id:h.item.id,delta:`{"containerId":"${h.item.container_id}","code":"`})):h.item.type==="file_search_call"?x.enqueue({type:"tool-call",toolCallId:h.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):h.item.type==="image_generation_call"?x.enqueue({type:"tool-call",toolCallId:h.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):h.item.type==="message"?(w=h.item.id,x.enqueue({type:"text-start",id:h.item.id,providerMetadata:{openai:{itemId:h.item.id}}})):Xy(h)&&(u[h.output_index]={canonicalId:h.item.id,encryptedContent:h.item.encrypted_content,summaryParts:[0]},a=h.output_index,x.enqueue({type:"reasoning-start",id:`${h.item.id}:0`,providerMetadata:{openai:{itemId:h.item.id,reasoningEncryptedContent:h.item.encrypted_content??null}}}));else if($u(h)){if(h.item.type==="function_call")l[h.output_index]=void 0,g=!0,x.enqueue({type:"tool-input-end",id:h.item.call_id}),x.enqueue({type:"tool-call",toolCallId:h.item.call_id,toolName:h.item.name,input:h.item.arguments,providerMetadata:{openai:{itemId:h.item.id}}});else if(h.item.type==="web_search_call")l[h.output_index]=void 0,x.enqueue({type:"tool-input-end",id:h.item.id}),x.enqueue({type:"tool-call",toolCallId:h.item.id,toolName:"web_search",input:JSON.stringify({action:h.item.action}),providerExecuted:!0}),x.enqueue({type:"tool-result",toolCallId:h.item.id,toolName:"web_search",result:{status:h.item.status}});else if(h.item.type==="computer_call")l[h.output_index]=void 0,x.enqueue({type:"tool-input-end",id:h.item.id}),x.enqueue({type:"tool-call",toolCallId:h.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),x.enqueue({type:"tool-result",toolCallId:h.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:h.item.status||"completed"}});else if(h.item.type==="file_search_call")l[h.output_index]=void 0,x.enqueue({type:"tool-result",toolCallId:h.item.id,toolName:"file_search",result:{queries:h.item.queries,results:h.item.results?.map(v=>({attributes:v.attributes,fileId:v.file_id,filename:v.filename,score:v.score,text:v.text}))??null}});else if(h.item.type==="code_interpreter_call")l[h.output_index]=void 0,x.enqueue({type:"tool-result",toolCallId:h.item.id,toolName:"code_interpreter",result:{outputs:h.item.outputs}});else if(h.item.type==="image_generation_call")x.enqueue({type:"tool-result",toolCallId:h.item.id,toolName:"image_generation",result:{result:h.item.result}});else if(h.item.type==="local_shell_call")l[h.output_index]=void 0,x.enqueue({type:"tool-call",toolCallId:h.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:h.item.action.command,timeoutMs:h.item.action.timeout_ms,user:h.item.action.user,workingDirectory:h.item.action.working_directory,env:h.item.action.env}}),providerMetadata:{openai:{itemId:h.item.id}}});else if(h.item.type==="message")w&&(x.enqueue({type:"text-end",id:w}),w=null);else if(Wy(h)){let v=u[h.output_index];if(v){for(let S of v.summaryParts)x.enqueue({type:"reasoning-end",id:`${v.canonicalId}:${S}`,providerMetadata:{openai:{itemId:v.canonicalId,reasoningEncryptedContent:h.item.encrypted_content??null}}});delete u[h.output_index],a===h.output_index&&(a=null)}}}else if(Vy(h)){let v=l[h.output_index];v!=null&&x.enqueue({type:"tool-input-delta",id:v.toolCallId,delta:h.delta})}else if(Jy(h))x.enqueue({type:"tool-result",toolCallId:h.item_id,toolName:"image_generation",result:{result:h.partial_image_b64}});else if(Yy(h)){let v=l[h.output_index];v!=null&&x.enqueue({type:"tool-input-delta",id:v.toolCallId,delta:JSON.stringify(h.delta).slice(1,-1)})}else if(Ky(h)){let v=l[h.output_index];v!=null&&(x.enqueue({type:"tool-input-delta",id:v.toolCallId,delta:'"}'}),x.enqueue({type:"tool-input-end",id:v.toolCallId}),x.enqueue({type:"tool-call",toolCallId:v.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:h.code,containerId:v.codeInterpreter.containerId}),providerExecuted:!0}))}else if(Gy(h))c=h.response.id,x.enqueue({type:"response-metadata",id:h.response.id,timestamp:new Date(h.response.created_at*1e3),modelId:h.response.model});else if(By(h))w||(w=h.item_id,x.enqueue({type:"text-start",id:w,providerMetadata:{openai:{itemId:h.item_id}}})),x.enqueue({type:"text-delta",id:w,delta:h.delta}),t.providerOptions?.openai?.logprobs&&h.logprobs&&s.push(h.logprobs);else if(Qy(h)){let v=a!==null?u[a]:null;v&&h.summary_index>0&&(v.summaryParts.push(h.summary_index),x.enqueue({type:"reasoning-start",id:`${v.canonicalId}:${h.summary_index}`,providerMetadata:{openai:{itemId:v.canonicalId,reasoningEncryptedContent:v.encryptedContent??null}}}))}else if(eb(h)){let v=a!==null?u[a]:null;v&&x.enqueue({type:"reasoning-delta",id:`${v.canonicalId}:${h.summary_index}`,delta:h.delta,providerMetadata:{openai:{itemId:v.canonicalId}}})}else Hy(h)?(b={unified:nl({finishReason:h.response.incomplete_details?.reason,hasFunctionCall:g}),raw:h.response.incomplete_details?.reason??void 0},d.inputTokens=h.response.usage.input_tokens,d.outputTokens=h.response.usage.output_tokens,d.totalTokens=h.response.usage.input_tokens+h.response.usage.output_tokens,d.reasoningTokens=h.response.usage.output_tokens_details?.reasoning_tokens??void 0,d.cachedInputTokens=h.response.usage.input_tokens_details?.cached_tokens??void 0,typeof h.response.service_tier=="string"&&(I=h.response.service_tier)):Zy(h)?h.annotation.type==="url_citation"?x.enqueue({type:"source",sourceType:"url",id:f.config.generateId?.()??wa(),url:h.annotation.url,title:h.annotation.title}):h.annotation.type==="file_citation"&&x.enqueue({type:"source",sourceType:"document",id:f.config.generateId?.()??wa(),mediaType:"text/plain",title:h.annotation.quote??h.annotation.filename??"Document",filename:h.annotation.filename??h.annotation.file_id}):tb(h)&&x.enqueue({type:"error",error:h})},flush(r){w&&(r.enqueue({type:"text-end",id:w}),w=null);let x={openai:{responseId:c}};s.length>0&&(x.openai.logprobs=s),I!==void 0&&(x.openai.serviceTier=I),r.enqueue({type:"finish",finishReason:b,usage:{inputTokens:{total:d.inputTokens,noCache:d.inputTokens!=null&&d.cachedInputTokens!=null?d.inputTokens-d.cachedInputTokens:void 0,cacheRead:d.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:d.outputTokens,text:void 0,reasoning:d.reasoningTokens},raw:{input_tokens:d.inputTokens,output_tokens:d.outputTokens,total_tokens:d.totalTokens}},providerMetadata:x})}})),request:{body:o},response:{headers:y}}}},Uu=U.object({input_tokens:U.number(),input_tokens_details:U.object({cached_tokens:U.number().nullish()}).nullish(),output_tokens:U.number(),output_tokens_details:U.object({reasoning_tokens:U.number().nullish()}).nullish()}),_y=U.object({type:U.literal("response.output_text.delta"),item_id:U.string(),delta:U.string(),logprobs:Fu.nullish()}),Oy=U.object({type:U.literal("error"),code:U.string(),message:U.string(),param:U.string().nullish(),sequence_number:U.number()}),Ay=U.object({type:U.enum(["response.completed","response.incomplete"]),response:U.object({incomplete_details:U.object({reason:U.string()}).nullish(),usage:Uu,service_tier:U.string().nullish()})}),Cy=U.object({type:U.literal("response.created"),response:U.object({id:U.string(),created_at:U.number(),model:U.string(),service_tier:U.string().nullish()})}),Ry=U.object({type:U.literal("response.output_item.added"),output_index:U.number(),item:U.discriminatedUnion("type",[U.object({type:U.literal("message"),id:U.string()}),U.object({type:U.literal("reasoning"),id:U.string(),encrypted_content:U.string().nullish()}),U.object({type:U.literal("function_call"),id:U.string(),call_id:U.string(),name:U.string(),arguments:U.string()}),U.object({type:U.literal("web_search_call"),id:U.string(),status:U.string(),action:U.object({type:U.literal("search"),query:U.string().optional()}).nullish()}),U.object({type:U.literal("computer_call"),id:U.string(),status:U.string()}),U.object({type:U.literal("file_search_call"),id:U.string()}),U.object({type:U.literal("image_generation_call"),id:U.string()}),U.object({type:U.literal("code_interpreter_call"),id:U.string(),container_id:U.string(),code:U.string().nullable(),outputs:U.array(U.discriminatedUnion("type",[U.object({type:U.literal("logs"),logs:U.string()}),U.object({type:U.literal("image"),url:U.string()})])).nullable(),status:U.string()})])}),jy=U.object({type:U.literal("response.output_item.done"),output_index:U.number(),item:U.discriminatedUnion("type",[U.object({type:U.literal("message"),id:U.string()}),U.object({type:U.literal("reasoning"),id:U.string(),encrypted_content:U.string().nullish()}),U.object({type:U.literal("function_call"),id:U.string(),call_id:U.string(),name:U.string(),arguments:U.string(),status:U.literal("completed")}),Mu,Nu,Ru,ju,Lu,U.object({type:U.literal("computer_call"),id:U.string(),status:U.literal("completed")})])}),My=U.object({type:U.literal("response.function_call_arguments.delta"),item_id:U.string(),output_index:U.number(),delta:U.string()}),Ly=U.object({type:U.literal("response.image_generation_call.partial_image"),item_id:U.string(),output_index:U.number(),partial_image_b64:U.string()}),Ny=U.object({type:U.literal("response.code_interpreter_call_code.delta"),item_id:U.string(),output_index:U.number(),delta:U.string()}),zy=U.object({type:U.literal("response.code_interpreter_call_code.done"),item_id:U.string(),output_index:U.number(),code:U.string()}),Fy=U.object({type:U.literal("response.output_text.annotation.added"),annotation:U.discriminatedUnion("type",[U.object({type:U.literal("url_citation"),url:U.string(),title:U.string()}),U.object({type:U.literal("file_citation"),file_id:U.string(),filename:U.string().nullish(),index:U.number().nullish(),start_index:U.number().nullish(),end_index:U.number().nullish(),quote:U.string().nullish()})])}),Uy=U.object({type:U.literal("response.reasoning_summary_part.added"),item_id:U.string(),summary_index:U.number()}),$y=U.object({type:U.literal("response.reasoning_summary_text.delta"),item_id:U.string(),summary_index:U.number(),delta:U.string()}),qy=U.union([_y,Ay,Cy,Ry,jy,My,Ly,Ny,zy,Fy,Uy,$y,Oy,U.object({type:U.string()}).loose()]);function By(e){return e.type==="response.output_text.delta"}n(By,"isTextDeltaChunk");function $u(e){return e.type==="response.output_item.done"}n($u,"isResponseOutputItemDoneChunk");function Wy(e){return $u(e)&&e.item.type==="reasoning"}n(Wy,"isResponseOutputItemDoneReasoningChunk");function Hy(e){return e.type==="response.completed"||e.type==="response.incomplete"}n(Hy,"isResponseFinishedChunk");function Gy(e){return e.type==="response.created"}n(Gy,"isResponseCreatedChunk");function Vy(e){return e.type==="response.function_call_arguments.delta"}n(Vy,"isResponseFunctionCallArgumentsDeltaChunk");function Jy(e){return e.type==="response.image_generation_call.partial_image"}n(Jy,"isResponseImageGenerationCallPartialImageChunk");function Yy(e){return e.type==="response.code_interpreter_call_code.delta"}n(Yy,"isResponseCodeInterpreterCallCodeDeltaChunk");function Ky(e){return e.type==="response.code_interpreter_call_code.done"}n(Ky,"isResponseCodeInterpreterCallCodeDoneChunk");function qu(e){return e.type==="response.output_item.added"}n(qu,"isResponseOutputItemAddedChunk");function Xy(e){return qu(e)&&e.item.type==="reasoning"}n(Xy,"isResponseOutputItemAddedReasoningChunk");function Zy(e){return e.type==="response.output_text.annotation.added"}n(Zy,"isResponseAnnotationAddedChunk");function Qy(e){return e.type==="response.reasoning_summary_part.added"}n(Qy,"isResponseReasoningSummaryPartAddedChunk");function eb(e){return e.type==="response.reasoning_summary_text.delta"}n(eb,"isResponseReasoningSummaryTextDeltaChunk");function tb(e){return e.type==="error"}n(tb,"isErrorChunk");function nb(e){let t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),o=e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini"),i={requiredAutoTruncation:!1,systemMessageMode:"system",supportsFlexProcessing:t,supportsPriorityProcessing:o};return e.startsWith("gpt-5-chat")?{...i,isReasoningModel:!1}:e.startsWith("o")||e.startsWith("gpt-5")||e.startsWith("codex-")||e.startsWith("computer-use")?e.startsWith("o1-mini")||e.startsWith("o1-preview")?{...i,isReasoningModel:!0,systemMessageMode:"remove"}:{...i,isReasoningModel:!0,systemMessageMode:"developer"}:{...i,isReasoningModel:!1}}n(nb,"getResponsesModelConfig");var ob=U.object({include:U.array(U.enum(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:U.string().nullish(),logprobs:U.union([U.boolean(),U.number().min(1).max(zu)]).optional(),maxToolCalls:U.number().nullish(),metadata:U.any().nullish(),parallelToolCalls:U.boolean().nullish(),previousResponseId:U.string().nullish(),promptCacheKey:U.string().nullish(),reasoningEffort:U.string().nullish(),reasoningSummary:U.string().nullish(),safetyIdentifier:U.string().nullish(),serviceTier:U.enum(["auto","flex","priority"]).nullish(),store:U.boolean().nullish(),strictJsonSchema:U.boolean().nullish(),textVerbosity:U.enum(["low","medium","high"]).nullish(),user:U.string().nullish()});var ib="0.1.0";function va(e={}){let t=rb(e.baseURL??"https://api.openai.com/v1");if(!t)throw new Error("baseURL is required");let o={...e.apiKey&&{Authorization:`Bearer ${e.apiKey}`},...e.headers},i=n(()=>sb(o,`ai-sdk/openai-compatible/${ib}`),"getHeaders"),m=n(b=>new ba(b,{provider:`${e.name??"openai-compatible"}.chat`,headers:i,url:n(({path:d})=>`${t}${d}`,"url"),fetch:e.fetch}),"createChatModel"),y=n(b=>new xa(b,{provider:`${e.name??"openai-compatible"}.responses`,headers:i,url:n(({path:d})=>`${t}${d}`,"url"),fetch:e.fetch}),"createResponsesModel"),p=n(b=>m(b),"createLanguageModel"),f=n(function(b){return m(b)},"provider");return f.languageModel=p,f.chat=m,f.responses=y,f}n(va,"createOpenaiCompatible");var ab=va();import{createXai as vb}from"@ai-sdk/xai";import{createMistral as Ib}from"@ai-sdk/mistral";import{createGroq as kb}from"@ai-sdk/groq";import{createDeepInfra as Eb}from"@ai-sdk/deepinfra";import{createCerebras as Sb}from"@ai-sdk/cerebras";import{createCohere as Db}from"@ai-sdk/cohere";import{createGateway as Tb}from"@ai-sdk/gateway";import{createTogetherAI as Pb}from"@ai-sdk/togetherai";import{createPerplexity as _b}from"@ai-sdk/perplexity";import{createVercel as Ob}from"@ai-sdk/vercel";import{createVenice as Ab}from"venice-ai-sdk-provider";import{createGitLab as Cb,VERSION as Rb,isWorkflowModel as jb,discoverWorkflowModels as Mb}from"gitlab-ai-provider";import{fromNodeProviderChain as Lb}from"@aws-sdk/credential-providers";import{GoogleAuth as Nb}from"google-auth-library";import{mergeDeep as Bu,unique as cb}from"remeda";function Wu(e){if(e.startsWith("image/"))return"image";if(e.startsWith("audio/"))return"audio";if(e.startsWith("video/"))return"video";if(e==="application/pdf")return"pdf"}n(Wu,"mimeToModality");var Jt;($=>{$.OUTPUT_TOKEN_MAX=Ce.OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX||32e3;function t(M){switch(M){case"@ai-sdk/github-copilot":return"copilot";case"@ai-sdk/azure":return"azure";case"@ai-sdk/openai":return"openai";case"@ai-sdk/amazon-bedrock":return"bedrock";case"@ai-sdk/anthropic":case"@ai-sdk/google-vertex/anthropic":return"anthropic";case"@ai-sdk/google-vertex":return"vertex";case"@ai-sdk/google":return"google";case"@ai-sdk/gateway":return"gateway";case"@openrouter/ai-sdk-provider":return"openrouter"}}n(t,"sdkKey");function o(M){let C=M.providerOptions;return C?Object.values(C).some(T=>!!T&&(typeof T.signature=="string"||typeof T.redactedData=="string")):!1}n(o,"hasThinkingSignature");function i(M){return M.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"\uFFFD")}$.sanitizeSurrogates=i,n(i,"sanitizeSurrogates");function m(M){let C=M.output;return C.type==="text"||C.type==="error-text"?{...M,output:{...C,value:i(C.value)}}:C.type==="content"?{...M,output:{...C,value:C.value.map(T=>T.type==="text"?{...T,text:i(T.text)}:T)}}:M}n(m,"sanitizeToolResult");function y(M){return M.map(C=>{switch(C.role){case"system":return typeof C.content=="string"?{...C,content:i(C.content)}:C;case"user":return typeof C.content=="string"?{...C,content:i(C.content)}:{...C,content:C.content.map(T=>T.type==="text"?{...T,text:i(T.text)}:T)};case"assistant":return typeof C.content=="string"?{...C,content:i(C.content)}:{...C,content:C.content.map(T=>T.type==="text"||T.type==="reasoning"?{...T,text:i(T.text)}:T.type==="tool-result"?m(T):T)};case"tool":return{...C,content:C.content.map(T=>T.type==="tool-result"?m(T):T)}}return C})}n(y,"sanitizeMessages");function p(M,C,T){if(M=y(M),(C.api.npm==="@ai-sdk/anthropic"||C.api.npm==="@ai-sdk/amazon-bedrock")&&(M=M.map(G=>{if(typeof G.content=="string")return G.content===""?void 0:G;if(!Array.isArray(G.content))return G;let N=G.content.filter(A=>A.type==="text"?A.text!=="":A.type==="reasoning"?A.text!==""||o(A):!0);if(N.length!==0)return{...G,content:N}}).filter(G=>G!==void 0&&G.content!=="")),C.api.id.includes("claude")){let G=n(N=>N.replace(/[^a-zA-Z0-9_-]/g,"_"),"scrub");return M.map(N=>N.role==="assistant"&&Array.isArray(N.content)?{...N,content:N.content.map(A=>A.type==="tool-call"||A.type==="tool-result"?{...A,toolCallId:G(A.toolCallId)}:A)}:N.role==="tool"&&Array.isArray(N.content)?{...N,content:N.content.map(A=>A.type==="tool-result"?{...A,toolCallId:G(A.toolCallId)}:A)}:N)}if(C.providerID==="mistral"||C.api.id.toLowerCase().includes("mistral")||C.api.id.toLocaleLowerCase().includes("devstral")){let G=n(A=>A.replace(/[^a-zA-Z0-9]/g,"").substring(0,9).padEnd(9,"0"),"scrub"),N=[];for(let A=0;A<M.length;A++){let F=M[A],V=M[A+1];F.role==="assistant"&&Array.isArray(F.content)&&(F.content=F.content.map(Y=>Y.type==="tool-call"||Y.type==="tool-result"?{...Y,toolCallId:G(Y.toolCallId)}:Y)),F.role==="tool"&&Array.isArray(F.content)&&(F.content=F.content.map(Y=>Y.type==="tool-result"?{...Y,toolCallId:G(Y.toolCallId)}:Y)),N.push(F),F.role==="tool"&&V?.role==="user"&&N.push({role:"assistant",content:[{type:"text",text:"Done."}]})}return N}if(typeof C.capabilities.interleaved=="object"&&C.capabilities.interleaved.field){let G=C.capabilities.interleaved.field;return M.map(N=>{if(N.role==="assistant"&&Array.isArray(N.content)){let F=N.content.filter(Y=>Y.type==="reasoning").map(Y=>Y.text).join(""),V=N.content.filter(Y=>Y.type!=="reasoning");return F?{...N,content:V,providerOptions:{...N.providerOptions,openaiCompatible:{...N.providerOptions?.openaiCompatible,[G]:F}}}:{...N,content:V}}return N})}return M}n(p,"normalizeMessages");function f(M,C){return M==="message"&&C==="5m"?{type:"ephemeral"}:{type:"ephemeral",ttl:"1h"}}$.cacheControlFor=f,n(f,"cacheControlFor");function b(M,C,T){let G=M.filter(A=>A.role==="system").slice(0,2),N=M.filter(A=>A.role!=="system").slice(-2);for(let A of cb([...G,...N]))d(A,C,f(A.role==="system"?"system":"message",T));return M}n(b,"applyCaching");function d(M,C,T){let G={anthropic:{cacheControl:T},openrouter:{cacheControl:{type:"ephemeral"}},bedrock:{cachePoint:{type:"default"}},openaiCompatible:{cache_control:{type:"ephemeral"}},copilot:{copilot_cache_control:{type:"ephemeral"}}};if(!(C.providerID==="anthropic"||C.providerID.includes("bedrock")||C.api.npm==="@ai-sdk/amazon-bedrock")&&Array.isArray(M.content)&&M.content.length>0){let F=M.content[M.content.length-1];if(F&&typeof F=="object"&&F.type!=="tool-approval-request"&&F.type!=="tool-approval-response"){F.providerOptions=Bu(F.providerOptions??{},G);return}}M.providerOptions=Bu(M.providerOptions??{},G)}n(d,"applyCachePoint");function s(M,C){return M.map(T=>{if(T.role==="tool"&&Array.isArray(T.content))return c(T,C);if(T.role!=="user"||!Array.isArray(T.content))return T;let G=T.content.map(N=>{if(N.type!=="file"&&N.type!=="image")return N;if(N.type==="image"){let re=N.image.toString();if(re.startsWith("data:")){let ue=re.match(/^data:([^;]+);base64,(.*)$/);if(ue&&(!ue[2]||ue[2].length===0))return{type:"text",text:"ERROR: Image file is empty or corrupted. Please provide a valid image."}}}let A=N.type==="image"?N.image.toString().split(";")[0].replace("data:",""):N.mediaType,F=N.type==="file"?N.filename:void 0,V=Wu(A);return!V||C.capabilities.input[V]?N:{type:"text",text:`ERROR: Cannot read ${F?`"${F}"`:V} (this model does not support ${V} input). Inform the user.`}});return{...T,content:G}})}n(s,"unsupportedParts");function c(M,C){let T=!1,G=M.content.map(N=>{if(N?.type!=="tool-result"||N.output?.type!=="content"||!Array.isArray(N.output.value))return N;let A=N.output.value.map(F=>{if(!F||F.type!=="media"&&F.type!=="file-data"&&F.type!=="image-data")return F;let V=typeof F.mediaType=="string"?Wu(F.mediaType):void 0;if(!V||C.capabilities.input[V])return F;T=!0;let Y=V==="pdf"?" Use read_files on the same path for the PDF's text.":"";return{type:"text",text:`NOTE: ${N.toolName??"the tool"} returned a ${V==="pdf"?"PDF":V} that this model cannot take as input, so it was left out.${Y}`}});return{...N,output:{...N.output,value:A}}});return T?{...M,content:G}:M}n(c,"unsupportedToolMedia");function l(M,C,T,G={}){M=s(M,C),M=p(M,C,T),(C.providerID==="anthropic"||C.providerID==="google-vertex-anthropic"||C.api.id.includes("anthropic")||C.api.id.includes("claude")||C.id.includes("anthropic")||C.id.includes("claude")||C.api.npm==="@ai-sdk/anthropic")&&C.api.npm!=="@ai-sdk/gateway"&&(M=b(M,C,G.messageCacheTtl));let N=t(C.api.npm);if(N&&N!==C.providerID){let A=n(F=>{if(!F||!(C.providerID in F))return F;let V={...F};return V[N]=V[C.providerID],delete V[C.providerID],V},"remap");M=M.map(F=>Array.isArray(F.content)?{...F,providerOptions:A(F.providerOptions),content:F.content.map(V=>V.type==="tool-approval-request"||V.type==="tool-approval-response"?{...V}:{...V,providerOptions:A(V.providerOptions)})}:{...F,providerOptions:A(F.providerOptions)})}return M}$.message=l,n(l,"message");function g(M){let C=M.id.toLowerCase();if(C.includes("qwen"))return .55;if(!C.includes("claude")){if(C.includes("gemini")||C.includes("glm-4.6")||C.includes("glm-4.7")||C.includes("minimax-m2"))return 1;if(C.includes("kimi-k2"))return["thinking","k2.","k2p","k2-5"].some(T=>C.includes(T))?1:.6}}$.temperature=g,n(g,"temperature");function u(M){let C=M.id.toLowerCase();if(C.includes("qwen"))return 1;if(["minimax-m2","gemini","kimi-k2.5","kimi-k2p5","kimi-k2-5"].some(T=>C.includes(T)))return .95}$.topP=u,n(u,"topP");function a(M){let C=M.id.toLowerCase();if(C.includes("minimax-m2"))return["m2.","m25","m21"].some(T=>C.includes(T))?40:20;if(C.includes("gemini"))return 64}$.topK=a,n(a,"topK");let w=["low","medium","high"],I=["none","minimal",...w,"xhigh"];function r(M){let C=/claude-(opus|sonnet|haiku|fable)-(\d{1,2})(?:[-.](\d{1,2}))?(?!\d)/.exec(M.toLowerCase());if(C)return{family:C[1],major:Number(C[2]),minor:C[3]===void 0?0:Number(C[3])}}$.claudeVersion=r,n(r,"claudeVersion");let x=["none","minimal","low","medium","high","xhigh","max"];function h(M,C){if(!M||C.length===0)return;if(C.includes(M))return M;let T=x.indexOf(M);if(T<0)return;let G,N=1/0;for(let A of C){let F=x.indexOf(A);if(F<0)continue;let V=Math.abs(F-T);(V<N||V===N&&G!==void 0&&F<x.indexOf(G))&&(G=A,N=V)}return G}$.nearestVariant=h,n(h,"nearestVariant");function v(M){if(!M.capabilities.reasoning)return{};let C=M.id.toLowerCase(),T=r(M.api.id),G=!!T&&(T.major>4||T.major===4&&T.minor>=6),A=M.api.npm==="@ai-sdk/anthropic"&&!!T&&T.major>=5&&(T.family==="opus"||T.family==="sonnet")?["low","medium","high","xhigh","max"]:["low","medium","high","max"];if(C.includes("deepseek")||C.includes("minimax")||C.includes("glm")||C.includes("mistral")||C.includes("kimi")||C.includes("k2p5")||C.includes("qwen"))return{};if(C.includes("grok")&&C.includes("grok-3-mini"))return M.api.npm==="@openrouter/ai-sdk-provider"?{low:{reasoning:{effort:"low"}},high:{reasoning:{effort:"high"}}}:{low:{reasoningEffort:"low"},high:{reasoningEffort:"high"}};if(C.includes("grok"))return{};switch(M.api.npm){case"@openrouter/ai-sdk-provider":return!M.id.includes("gpt")&&!M.id.includes("gemini-3")&&!M.id.includes("claude")?{}:Object.fromEntries(I.map(H=>[H,{reasoning:{effort:H}}]));case"@ai-sdk/gateway":return M.id.includes("anthropic")?G?Object.fromEntries(A.map(H=>[H,{thinking:{type:"adaptive"},effort:H}])):{high:{thinking:{type:"enabled",budgetTokens:16e3}},max:{thinking:{type:"enabled",budgetTokens:31999}}}:M.id.includes("google")?C.includes("2.5")?{high:{thinkingConfig:{includeThoughts:!0,thinkingBudget:16e3}},max:{thinkingConfig:{includeThoughts:!0,thinkingBudget:24576}}}:Object.fromEntries(["low","high"].map(H=>[H,{includeThoughts:!0,thinkingLevel:H}])):Object.fromEntries(I.map(H=>[H,{reasoningEffort:H}]));case"@ai-sdk/github-copilot":if(M.id.includes("gemini"))return{};if(M.id.includes("claude"))return Object.fromEntries(w.map(H=>[H,{reasoningEffort:H}]));let F=qt(()=>{if(C.includes("5.1-codex-max")||C.includes("5.2")||C.includes("5.3"))return[...w,"xhigh"];let H=[...w];return C.includes("gpt-5")&&M.release_date>="2025-12-04"&&H.push("xhigh"),H});return Object.fromEntries(F.map(H=>[H,{reasoningEffort:H,reasoningSummary:"auto",include:["reasoning.encrypted_content"]}]));case"@ai-sdk/cerebras":case"@ai-sdk/togetherai":case"@ai-sdk/xai":case"@ai-sdk/deepinfra":case"venice-ai-sdk-provider":case"@ai-sdk/openai-compatible":return Object.fromEntries(w.map(H=>[H,{reasoningEffort:H}]));case"@ai-sdk/azure":if(C==="o1-mini")return{};let V=["low","medium","high"];return(C.includes("gpt-5-")||C==="gpt-5")&&V.unshift("minimal"),Object.fromEntries(V.map(H=>[H,{reasoningEffort:H,reasoningSummary:"auto",include:["reasoning.encrypted_content"]}]));case"@ai-sdk/openai":if(C==="gpt-5-pro")return{};let Y=qt(()=>{if(C.includes("codex"))return C.includes("5.2")||C.includes("5.3")?[...w,"xhigh"]:w;let H=[...w];return(C.includes("gpt-5-")||C==="gpt-5")&&H.unshift("minimal"),M.release_date>="2025-11-13"&&H.unshift("none"),M.release_date>="2025-12-04"&&H.push("xhigh"),H});return Object.fromEntries(Y.map(H=>[H,{reasoningEffort:H,reasoningSummary:"auto",include:["reasoning.encrypted_content"]}]));case"@ai-sdk/anthropic":case"@ai-sdk/google-vertex/anthropic":return G?Object.fromEntries(A.map(H=>[H,{thinking:{type:"adaptive"},effort:H}])):{high:{thinking:{type:"enabled",budgetTokens:Math.min(16e3,Math.floor(M.limit.output/2-1))}},max:{thinking:{type:"enabled",budgetTokens:Math.min(31999,M.limit.output-1)}}};case"@ai-sdk/amazon-bedrock":return G?Object.fromEntries(A.map(H=>[H,{reasoningConfig:{type:"adaptive",maxReasoningEffort:H}}])):M.api.id.includes("anthropic")?{high:{reasoningConfig:{type:"enabled",budgetTokens:16e3}},max:{reasoningConfig:{type:"enabled",budgetTokens:31999}}}:Object.fromEntries(w.map(H=>[H,{reasoningConfig:{type:"enabled",maxReasoningEffort:H}}]));case"@ai-sdk/google-vertex":case"@ai-sdk/google":if(C.includes("2.5"))return{high:{thinkingConfig:{includeThoughts:!0,thinkingBudget:16e3}},max:{thinkingConfig:{includeThoughts:!0,thinkingBudget:24576}}};let re=["low","high"];return C.includes("3.1")&&(re=["low","medium","high"]),Object.fromEntries(re.map(H=>[H,{thinkingConfig:{includeThoughts:!0,thinkingLevel:H}}]));case"@ai-sdk/mistral":return{};case"@ai-sdk/cohere":return{};case"@ai-sdk/groq":let ue=["none",...w];return Object.fromEntries(ue.map(H=>[H,{reasoningEffort:H}]));case"@ai-sdk/perplexity":return{};case"@jerome-benoit/sap-ai-provider-v2":return M.api.id.includes("anthropic")?G?Object.fromEntries(A.map(H=>[H,{thinking:{type:"adaptive"},effort:H}])):{high:{thinking:{type:"enabled",budgetTokens:16e3}},max:{thinking:{type:"enabled",budgetTokens:31999}}}:M.api.id.includes("gemini")&&C.includes("2.5")?{high:{thinkingConfig:{includeThoughts:!0,thinkingBudget:16e3}},max:{thinkingConfig:{includeThoughts:!0,thinkingBudget:24576}}}:M.api.id.includes("gpt")||/\bo[1-9]/.test(M.api.id)?Object.fromEntries(w.map(H=>[H,{reasoningEffort:H}])):{}}return{}}$.variants=v,n(v,"variants");function S(M){let C={};(M.model.providerID==="openai"||M.model.api.npm==="@ai-sdk/openai"||M.model.api.npm==="@ai-sdk/github-copilot")&&(C.store=!1),M.model.api.npm==="@openrouter/ai-sdk-provider"&&(C.usage={include:!0},M.model.api.id.includes("gemini-3")&&(C.reasoning={effort:"high"})),(M.model.providerID==="baseten"||M.model.providerID==="opencode"&&["kimi-k2-thinking","glm-4.6"].includes(M.model.api.id))&&(C.chat_template_args={enable_thinking:!0}),["zai","zhipuai"].includes(M.model.providerID)&&M.model.api.npm==="@ai-sdk/openai-compatible"&&(C.thinking={type:"enabled",clear_thinking:!1}),(M.model.providerID==="openai"||M.providerOptions?.setCacheKey)&&(C.promptCacheKey=M.sessionID),(M.model.api.npm==="@ai-sdk/google"||M.model.api.npm==="@ai-sdk/google-vertex")&&M.model.capabilities.reasoning&&(C.thinkingConfig={includeThoughts:!0},M.model.api.id.includes("gemini-3")&&(C.thinkingConfig.thinkingLevel="high"));let T=M.model.api.id.toLowerCase();return(M.model.api.npm==="@ai-sdk/anthropic"||M.model.api.npm==="@ai-sdk/google-vertex/anthropic")&&(T.includes("k2p5")||T.includes("kimi-k2.5")||T.includes("kimi-k2p5"))&&(C.thinking={type:"enabled",budgetTokens:Math.min(16e3,Math.floor(M.model.limit.output/2-1))}),M.model.providerID==="alibaba-cn"&&M.model.capabilities.reasoning&&M.model.api.npm==="@ai-sdk/openai-compatible"&&!T.includes("kimi-k2-thinking")&&(C.enable_thinking=!0),M.model.api.id.includes("gpt-5")&&!M.model.api.id.includes("gpt-5-chat")&&(M.model.api.id.includes("gpt-5-pro")||(C.reasoningEffort="medium",C.reasoningSummary="auto"),M.model.api.id.includes("gpt-5.")&&!M.model.api.id.includes("codex")&&!M.model.api.id.includes("-chat")&&M.model.providerID!=="azure"&&(C.textVerbosity="low"),M.model.providerID.startsWith("opencode")&&(C.promptCacheKey=M.sessionID,C.include=["reasoning.encrypted_content"],C.reasoningSummary="auto")),M.model.providerID==="venice"&&(C.promptCacheKey=M.sessionID),M.model.providerID==="openrouter"&&(C.prompt_cache_key=M.sessionID),M.model.api.npm==="@ai-sdk/gateway"&&(C.gateway={caching:"auto"}),C}$.options=S,n(S,"options");function j(M){return M.providerID==="openai"||M.api.npm==="@ai-sdk/openai"||M.api.npm==="@ai-sdk/github-copilot"?M.api.id.includes("gpt-5")?M.api.id.includes("5.")?{store:!1,reasoningEffort:"low"}:{store:!1,reasoningEffort:"minimal"}:{store:!1}:M.providerID==="google"?M.api.id.includes("gemini-3")?{thinkingConfig:{thinkingLevel:"minimal"}}:{thinkingConfig:{thinkingBudget:0}}:M.providerID==="openrouter"?M.api.id.includes("google")?{reasoning:{enabled:!1}}:{reasoningEffort:"minimal"}:M.providerID==="venice"?{veniceParameters:{disableThinking:!0}}:{}}$.smallOptions=j,n(j,"smallOptions");let O={amazon:"bedrock"};function k(M){let C=/claude-(?:([a-z]+)-)?(\d+)(?:[.-](\d{1,2}))?(?:-([a-z]+))?(?:[.@-]|$)/i.exec(M);if(!C)return!1;let T=Number(C[2]),G=Number(C[3]??0);return T===5&&G===1&&(C[1]??C[4])?.toLowerCase()==="mythos"?!1:T>5||T===5&&G>=1}n(k,"anthropicBindsThinking");function E(M,C){if(!k(M.api.id))return C;let T={prefixMismatchBehavior:"drop_block"},G=C.thinking;return G?(G.type===void 0&&(G={type:"adaptive",...G}),G.type!=="adaptive"&&G.type!=="enabled"?C:{...C,thinking:{...G,blockBinding:T}}):{...C,thinking:{blockBinding:T}}}n(E,"anthropicBlockBinding");function D(M,C){if(M.api.npm==="@ai-sdk/openai"&&(M.capabilities.reasoning||C.reasoningEffort!==void 0||C.reasoningSummary!==void 0)&&(C={...C,forceReasoning:!0}),M.api.npm==="@ai-sdk/gateway"){let G=M.api.id.indexOf("/"),N=G>0?M.api.id.slice(0,G):void 0,A=N?O[N]??N:void 0,F=C.gateway,V=Object.fromEntries(Object.entries(C).filter(([ue])=>ue!=="gateway")),Y=Object.keys(V).length>0,re={};return F!==void 0&&(re.gateway=F),Y&&(A?re[A]=V:F&&typeof F=="object"&&!Array.isArray(F)?re.gateway={...F,...V}:re.gateway=V),re}let T=t(M.api.npm)??M.providerID;return(M.api.npm==="@ai-sdk/anthropic"||M.api.npm==="@ai-sdk/google-vertex/anthropic")&&(C=E(M,C)),M.api.npm==="@ai-sdk/azure"?{openai:C,azure:C}:{[T]:C}}$.providerOptions=D,n(D,"providerOptions");function z(M){return Math.min(M.limit.output,$.OUTPUT_TOKEN_MAX)||$.OUTPUT_TOKEN_MAX}$.maxOutputTokens=z,n(z,"maxOutputTokens");function _(M){return M.providerID==="openai"||M.providerID==="azure"?!1:void 0}$.toolStrict=_,n(_,"toolStrict");function B(M,C){if(M.providerID==="google"||M.api.id.includes("gemini")){let T=n(F=>typeof F=="object"&&F!==null&&!Array.isArray(F),"isPlainObject"),G=n(F=>T(F)&&(Array.isArray(F.anyOf)||Array.isArray(F.oneOf)||Array.isArray(F.allOf)),"hasCombiner"),N=n(F=>T(F)?G(F)?!0:["type","properties","items","prefixItems","enum","const","$ref","additionalProperties","patternProperties","required","not","if","then","else"].some(V=>V in F):!1,"hasSchemaIntent"),A=n(F=>{if(F===null||typeof F!="object")return F;if(Array.isArray(F))return F.map(A);let V={};for(let[Y,re]of Object.entries(F))Y==="enum"&&Array.isArray(re)?(V[Y]=re.map(ue=>String(ue)),(V.type==="integer"||V.type==="number")&&(V.type="string")):typeof re=="object"&&re!==null?V[Y]=A(re):V[Y]=re;return V.type==="object"&&V.properties&&Array.isArray(V.required)&&(V.required=V.required.filter(Y=>Y in V.properties)),V.type==="array"&&!G(V)&&(V.items==null&&(V.items={}),T(V.items)&&!N(V.items)&&(V.items.type="string")),V.type&&V.type!=="object"&&!G(V)&&(delete V.properties,delete V.required),V},"sanitizeGemini");C=A(C)}return C}$.schema=B,n(B,"schema")})(Jt||={});var ol;(p=>{p.INCOMPLETE_CODE=Oo.RESPONSE_INCOMPLETE_CODE,p.FAILED_CODE=Oo.RESPONSE_FAILED_CODE;function o(f,b,d,s){return{type:"error",sequence_number:typeof f=="number"?f:0,error:{type:s??b,code:b,message:d,param:null}}}n(o,"errorEvent");function i(f){switch(f.type){case"response.failed":{let b=f.response?.error,d=typeof b?.code=="string"&&b.code?b.code:p.FAILED_CODE,s=typeof b?.message=="string"&&b.message?b.message:"The provider reported the response failed.";return o(f.sequence_number,d,s,p.FAILED_CODE)}case"response.incomplete":{let b=f.response?.incomplete_details?.reason;return b==="content_filter"?void 0:o(f.sequence_number,p.INCOMPLETE_CODE,`The response ended incomplete (${typeof b=="string"&&b?b:"no reason given"}).`)}case"error":{if(f.error&&typeof f.error=="object")return;let b=typeof f.code=="string"&&f.code?f.code:p.FAILED_CODE,d=typeof f.message=="string"&&f.message?f.message:"Stream error.";return o(f.sequence_number,b,d)}}}p.rewrite=i,n(i,"rewrite");let m=new Set(["response.completed","response.incomplete","response.failed","error"]);function y(f){if(!f.ok||!f.body)return f;let b=f.body.getReader(),d=new TextDecoder,s=new TextEncoder,c="",l=!1,g=!1,u=n(I=>{let r=I.split(/\r?\n/).filter(v=>v.startsWith("data:")).map(v=>v.slice(5).replace(/^ /,"")).join(`
|
|
153
|
+
`),x;try{x=r?JSON.parse(r):void 0}catch{x=void 0}if(!x||typeof x.type!="string")return I+`
|
|
154
|
+
|
|
155
|
+
`;x.type.startsWith("response.")&&(l=!0),m.has(x.type)&&(g=!0);let h=i(x);return h?`event: error
|
|
156
|
+
data: ${JSON.stringify(h)}
|
|
157
|
+
|
|
158
|
+
`:I+`
|
|
159
|
+
|
|
160
|
+
`},"block"),a=n(I=>{let r="";for(;;){let x=/\r?\n\r?\n/.exec(c);if(!x)break;r+=u(c.slice(0,x.index)),c=c.slice(x.index+x[0].length)}return I&&c.trim()&&(r+=u(c),c=""),r},"drain"),w=new ReadableStream({async pull(I){for(;;){let r=await b.read();if(r.done){c+=d.decode();let h=a(!0);if(h&&I.enqueue(s.encode(h)),l&&!g){I.error(new Oo.ResponseStreamError("Response stream ended before response.completed"));return}I.close();return}c+=d.decode(r.value,{stream:!0});let x=a(!1);if(x){I.enqueue(s.encode(x));return}}},async cancel(I){await b.cancel(I)}});return new Response(w,{headers:new Headers(f.headers),status:f.status,statusText:f.statusText})}p.wrap=y,n(y,"wrap")})(ol||={});var yn;(D=>{let e=qe.create({service:"provider"});function t(z){let _=/^gpt-(\d+)/.exec(z);return _?Number(_[1])>=5&&!z.startsWith("gpt-5-mini"):!1}n(t,"shouldUseCopilotResponsesApi");function o(z,_,B,$=!1){if(typeof _!="number"||_<=0||!z.body||!z.headers.get("content-type")?.includes("text/event-stream")&&!($&&z.ok))return z;let M=z.body.getReader(),C=new ReadableStream({async pull(T){let G=await new Promise((N,A)=>{let F=setTimeout(()=>{let V=new Oo.ResponseStreamError("SSE read timed out");B.abort(V),M.cancel(V).catch(()=>{}),A(V)},_);M.read().then(V=>{clearTimeout(F),N(V)},V=>{clearTimeout(F),A(V)})});if(G.done){T.close();return}T.enqueue(G.value)},async cancel(T){B.abort(T),await M.cancel(T)}});return new Response(C,{headers:new Headers(z.headers),status:z.status,statusText:z.statusText})}n(o,"wrapSSE");function i(){let z=Tt.get("OPENCODE_E2E_LLM_URL");if(!(typeof z!="string"||z===""))return z}n(i,"e2eURL");let m={"@ai-sdk/amazon-bedrock":fb,"@ai-sdk/anthropic":mb,"@ai-sdk/azure":gb,"@ai-sdk/google":hb,"@ai-sdk/google-vertex":yb,"@ai-sdk/google-vertex/anthropic":bb,"@ai-sdk/openai":wb,"@ai-sdk/openai-compatible":Ju,"@openrouter/ai-sdk-provider":xb,"@ai-sdk/xai":vb,"@ai-sdk/mistral":Ib,"@ai-sdk/groq":kb,"@ai-sdk/deepinfra":Eb,"@ai-sdk/cerebras":Sb,"@ai-sdk/cohere":Db,"@ai-sdk/gateway":Tb,"@ai-sdk/togetherai":Pb,"@ai-sdk/perplexity":_b,"@ai-sdk/vercel":Ob,"gitlab-ai-provider":Cb,"@ai-sdk/github-copilot":va,"venice-ai-sdk-provider":Ab};function y(z){return z.responses===void 0&&z.chat===void 0}n(y,"useLanguageModel");function p(z){return{anthropic:n(()=>gt.succeed({autoload:!1,options:{headers:{"anthropic-beta":"interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14"}}}),"anthropic"),opencode:gt.fnUntraced(function*(_){let B=Tt.all();return qt(()=>!!_.env.some(C=>B[C]))||!!(yield*z.auth(_.id))||!!(yield*z.config()).provider?.opencode?.options?.apiKey?{autoload:Object.keys(_.models).length>0,options:{}}:{autoload:!1}}),openai:n(()=>gt.succeed({autoload:!1,async getModel(_,B,$){return _.responses(B)},options:{}}),"openai"),xai:n(()=>gt.succeed({autoload:!1,async getModel(_,B,$){return _.responses(B)},options:{}}),"xai"),"github-copilot":n(()=>gt.succeed({autoload:!1,async getModel(_,B,$){return y(_)?_.languageModel(B):t(B)?_.responses(B):_.chat(B)},options:{}}),"github-copilot"),azure:n(_=>{let B=qt(()=>{let $=_.options?.resourceName;return typeof $=="string"&&$.trim()!==""?$:Tt.get("AZURE_RESOURCE_NAME")});return gt.succeed({autoload:!1,async getModel($,M,C){return y($)?$.languageModel(M):C?.useCompletionUrls?$.chat(M):$.responses(M)},options:{},vars($){return{...B&&{AZURE_RESOURCE_NAME:B}}}})},"azure"),"azure-cognitive-services":n(()=>{let _=Tt.get("AZURE_COGNITIVE_SERVICES_RESOURCE_NAME");return gt.succeed({autoload:!1,async getModel(B,$,M){return y(B)?B.languageModel($):M?.useCompletionUrls?B.chat($):B.responses($)},options:{baseURL:_?`https://${_}.cognitiveservices.azure.com/openai`:void 0}})},"azure-cognitive-services"),"amazon-bedrock":gt.fnUntraced(function*(){let _=(yield*z.config()).provider?.["amazon-bedrock"],B=yield*z.auth("amazon-bedrock"),$=_?.options?.region,M=Tt.get("AWS_REGION"),C=$??M??"us-east-1",T=_?.options?.profile,G=Tt.get("AWS_PROFILE"),N=T??G,A=Tt.get("AWS_ACCESS_KEY_ID"),F=qt(()=>{let H=process.env.AWS_BEARER_TOKEN_BEDROCK;if(H)return H;if(B?.type==="api")return process.env.AWS_BEARER_TOKEN_BEDROCK=B.key,B.key}),V=Tt.get("AWS_WEB_IDENTITY_TOKEN_FILE"),Y=!!(process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI||process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI);if(!N&&!A&&!F&&!V&&!Y)return{autoload:!1};let re={region:C};if(!F){let H=N?{profile:N}:{};re.credentialProvider=Lb(H)}let ue=_?.options?.endpoint??_?.options?.baseURL;return ue&&(re.baseURL=ue),{autoload:!0,options:re,async getModel(H,R,L){if(["global.","us.","eu.","jp.","apac.","au."].some(Q=>R.startsWith(Q)))return H.languageModel(R);let X=L?.region??C,ne=X.split("-")[0];switch(ne){case"us":{let Q=["nova-micro","nova-lite","nova-pro","nova-premier","nova-2","claude","deepseek"].some(ce=>R.includes(ce)),oe=X.startsWith("us-gov");Q&&!oe&&(R=`${ne}.${R}`);break}case"eu":{let Q=["eu-west-1","eu-west-2","eu-west-3","eu-north-1","eu-central-1","eu-south-1","eu-south-2"].some(ce=>X.includes(ce)),oe=["claude","nova-lite","nova-micro","llama3","pixtral"].some(ce=>R.includes(ce));Q&&oe&&(R=`${ne}.${R}`);break}case"ap":{let Q=["ap-southeast-2","ap-southeast-4"].includes(X),oe=X==="ap-northeast-1";Q&&["anthropic.claude-sonnet-4-5","anthropic.claude-haiku"].some(ce=>R.includes(ce))?(ne="au",R=`${ne}.${R}`):oe?["claude","nova-lite","nova-micro","nova-pro"].some(pe=>R.includes(pe))&&(ne="jp",R=`${ne}.${R}`):["claude","nova-lite","nova-micro","nova-pro"].some(pe=>R.includes(pe))&&(ne="apac",R=`${ne}.${R}`);break}}return H.languageModel(R)}}}),openrouter:n(()=>gt.succeed({autoload:!1,options:{headers:{"HTTP-Referer":"https://opencode.ai/","X-Title":"opencode"}}}),"openrouter"),vercel:n(()=>gt.succeed({autoload:!1,options:{headers:{"http-referer":"https://opencode.ai/","x-title":"opencode"}}}),"vercel"),"google-vertex":n(_=>{let B=_.options?.project??Tt.get("GOOGLE_CLOUD_PROJECT")??Tt.get("GCP_PROJECT")??Tt.get("GCLOUD_PROJECT"),$=String(_.options?.location??Tt.get("GOOGLE_VERTEX_LOCATION")??Tt.get("GOOGLE_CLOUD_LOCATION")??Tt.get("VERTEX_LOCATION")??"us-central1");return!B?gt.succeed({autoload:!1}):gt.succeed({autoload:!0,vars(C){let T=$==="global"?"aiplatform.googleapis.com":`${$}-aiplatform.googleapis.com`;return{...B&&{GOOGLE_VERTEX_PROJECT:B},GOOGLE_VERTEX_LOCATION:$,GOOGLE_VERTEX_ENDPOINT:T}},options:{project:B,location:$,fetch:n(async(C,T)=>{let A=await(await new Nb().getApplicationDefault()).credential.getAccessToken(),F=new Headers(T?.headers);return F.set("Authorization",`Bearer ${A.token}`),fetch(C,{...T,headers:F})},"fetch")},async getModel(C,T){let G=String(T).trim();return C.languageModel(G)}})},"google-vertex"),"google-vertex-anthropic":n(()=>{let _=Tt.get("GOOGLE_CLOUD_PROJECT")??Tt.get("GCP_PROJECT")??Tt.get("GCLOUD_PROJECT"),B=Tt.get("GOOGLE_CLOUD_LOCATION")??Tt.get("VERTEX_LOCATION")??"global";return!_?gt.succeed({autoload:!1}):gt.succeed({autoload:!0,options:{project:_,location:B},async getModel(M,C){let T=String(C).trim();return M.languageModel(T)}})},"google-vertex-anthropic"),"sap-ai-core":gt.fnUntraced(function*(){let _=yield*z.auth("sap-ai-core"),B=qt(()=>{let C=process.env.AICORE_SERVICE_KEY;if(C)return C;if(_?.type==="api")return process.env.AICORE_SERVICE_KEY=_.key,_.key}),$=process.env.AICORE_DEPLOYMENT_ID,M=process.env.AICORE_RESOURCE_GROUP;return{autoload:!!B,options:B?{deploymentId:$,resourceGroup:M}:{},async getModel(C,T){return C(T)}}}),zenmux:n(()=>gt.succeed({autoload:!1,options:{headers:{"HTTP-Referer":"https://opencode.ai/","X-Title":"opencode"}}}),"zenmux"),gitlab:gt.fnUntraced(function*(_){let B=Tt.get("GITLAB_INSTANCE_URL")||"https://gitlab.com",$=yield*z.auth(_.id),M=yield*gt.sync(()=>$?.type==="oauth"?$.access:$?.type==="api"?$.key:Tt.get("GITLAB_TOKEN")),C=(yield*z.config()).provider?.gitlab,T={"User-Agent":`opencode/${Ft.VERSION} gitlab-ai-provider/${Rb} (${Jo.platform()} ${Jo.release()}; ${Jo.arch()})`,"anthropic-beta":"context-1m-2025-08-07",...C?.options?.aiGatewayHeaders||{}},G={duo_agent_platform_agentic_chat:!0,duo_agent_platform:!0,...C?.options?.featureFlags||{}};return{autoload:!!M,options:{instanceUrl:B,apiKey:M,aiGatewayHeaders:T,featureFlags:G},async getModel(N,A,F){if(A.startsWith("duo-workflow-")){let V=F?.workflowRef,Y=jb(A)?A:"duo-workflow",re=N.workflowChat(Y,{featureFlags:G});return V&&(re.selectedModelRef=V),re}return N.agenticChat(A,{aiGatewayHeaders:T,featureFlags:G})},async discoverModels(){if(!M)return e.info("gitlab model discovery skipped: no apiKey"),{};try{let N=M,A=n(()=>$?.type==="api"?{"PRIVATE-TOKEN":N}:{Authorization:`Bearer ${N}`},"getHeaders");e.info("gitlab model discovery starting",{instanceUrl:B});let F=await Mb({instanceUrl:B,getHeaders:A},{workingDirectory:he.directory});if(!F.models.length)return e.info("gitlab model discovery skipped: no models found",{project:F.project?{id:F.project.id,path:F.project.pathWithNamespace}:null}),{};let V={};for(let Y of F.models)_.models[Y.id]||(V[Y.id]={id:Ut.make(Y.id),providerID:Et.make("gitlab"),name:`Agent Platform (${Y.name})`,family:"",api:{id:Y.id,url:B,npm:"gitlab-ai-provider"},status:"active",headers:{},options:{workflowRef:Y.ref},cost:{input:0,output:0,cache:{read:0,write:0}},limit:{context:Y.context,output:Y.output},capabilities:{temperature:!1,reasoning:!0,attachment:!0,toolcall:!0,input:{text:!0,audio:!1,image:!0,video:!1,pdf:!0},output:{text:!0,audio:!1,image:!1,video:!1,pdf:!1},interleaved:!1},release_date:"",variants:{}});return e.info("gitlab model discovery complete",{count:Object.keys(V).length,models:Object.keys(V)}),V}catch(N){return e.warn("gitlab model discovery failed",{error:N}),{}}}}}),"cloudflare-workers-ai":gt.fnUntraced(function*(_){if(_.options?.baseURL)return{autoload:!1};let B=yield*z.auth(_.id),$=Tt.get("CLOUDFLARE_ACCOUNT_ID")||(B?.type==="api"?B.metadata?.accountId:void 0);if(!$)return{autoload:!1,async getModel(){throw new Error("CLOUDFLARE_ACCOUNT_ID is missing. Set it with: export CLOUDFLARE_ACCOUNT_ID=<your-account-id>")}};let M=yield*gt.gen(function*(){let C=Tt.get("CLOUDFLARE_API_KEY");if(C)return C;if(B?.type==="api")return B.key});return{autoload:!!M,options:{apiKey:M,headers:{"User-Agent":`opencode/${Ft.VERSION} cloudflare-workers-ai (${Jo.platform()} ${Jo.release()}; ${Jo.arch()})`}},async getModel(C,T){return C.languageModel(T)},vars(C){return{CLOUDFLARE_ACCOUNT_ID:$}}}}),"cloudflare-ai-gateway":gt.fnUntraced(function*(_){if(_.options?.baseURL)return{autoload:!1};let B=yield*z.auth(_.id),$=Tt.get("CLOUDFLARE_ACCOUNT_ID")||(B?.type==="api"?B.metadata?.accountId:void 0),M=Tt.get("CLOUDFLARE_GATEWAY_ID")||(B?.type==="api"?B.metadata?.gatewayId:void 0);if(!$||!M){let Y=[$?void 0:"CLOUDFLARE_ACCOUNT_ID",M?void 0:"CLOUDFLARE_GATEWAY_ID"].filter(re=>!!re);return{autoload:!1,async getModel(){throw new Error(`${Y.join(" and ")} missing. Set with: ${Y.map(re=>`export ${re}=<value>`).join(" && ")}`)}}}let C=yield*gt.gen(function*(){let Y=Tt.get("CLOUDFLARE_API_TOKEN")||Tt.get("CF_AIG_TOKEN");if(Y)return Y;if(B?.type==="api")return B.key});if(!C)throw new Error("CLOUDFLARE_API_TOKEN (or CF_AIG_TOKEN) is required for Cloudflare AI Gateway. Set it via environment variable or run `opencode auth cloudflare-ai-gateway`.");let{createAiGateway:T}=yield*gt.promise(()=>import("ai-gateway-provider")),{createUnified:G}=yield*gt.promise(()=>import("ai-gateway-provider/providers/unified")),A={metadata:qt(()=>{if(_.options?.metadata)return _.options.metadata;try{return JSON.parse(_.options?.headers?.["cf-aig-metadata"])}catch{return}}),cacheTtl:_.options?.cacheTtl,cacheKey:_.options?.cacheKey,skipCache:_.options?.skipCache,collectLog:_.options?.collectLog,headers:{"User-Agent":`opencode/${Ft.VERSION} cloudflare-ai-gateway (${Jo.platform()} ${Jo.release()}; ${Jo.arch()})`}},F=T({accountId:$,gateway:M,apiKey:C,...Object.values(A).some(Y=>Y!==void 0)?{options:A}:{}}),V=G();return{autoload:!0,async getModel(Y,re,ue){return F(V(re))},options:{}}}),cerebras:n(()=>gt.succeed({autoload:!1,options:{headers:{"X-Cerebras-3rd-Party-Integration":"opencode"}}}),"cerebras"),kilo:n(()=>gt.succeed({autoload:!1,options:{headers:{"HTTP-Referer":"https://opencode.ai/","X-Title":"opencode"}}}),"kilo")}}n(p,"custom"),D.Model=Ge.object({id:Ut.zod,providerID:Et.zod,api:Ge.object({id:Ge.string(),url:Ge.string(),npm:Ge.string()}),name:Ge.string(),family:Ge.string().optional(),capabilities:Ge.object({temperature:Ge.boolean(),reasoning:Ge.boolean(),attachment:Ge.boolean(),toolcall:Ge.boolean(),input:Ge.object({text:Ge.boolean(),audio:Ge.boolean(),image:Ge.boolean(),video:Ge.boolean(),pdf:Ge.boolean()}),output:Ge.object({text:Ge.boolean(),audio:Ge.boolean(),image:Ge.boolean(),video:Ge.boolean(),pdf:Ge.boolean()}),interleaved:Ge.union([Ge.boolean(),Ge.object({field:Ge.enum(["reasoning_content","reasoning_details"])})])}),cost:Ge.object({input:Ge.number(),output:Ge.number(),cache:Ge.object({read:Ge.number(),write:Ge.number()}),experimentalOver200K:Ge.object({input:Ge.number(),output:Ge.number(),cache:Ge.object({read:Ge.number(),write:Ge.number()})}).optional()}),limit:Ge.object({context:Ge.number(),input:Ge.number().optional(),output:Ge.number()}),status:Ge.enum(["alpha","beta","deprecated","active"]),options:Ge.record(Ge.string(),Ge.any()),headers:Ge.record(Ge.string(),Ge.string()),release_date:Ge.string(),variants:Ge.record(Ge.string(),Ge.record(Ge.string(),Ge.any())).optional()}).meta({ref:"Model"}),D.Info=Ge.object({id:Et.zod,name:Ge.string(),source:Ge.enum(["env","config","custom","api"]),env:Ge.string().array(),key:Ge.string().optional(),options:Ge.record(Ge.string(),Ge.any()),models:Ge.record(Ge.string(),D.Model)}).meta({ref:"Provider"});class d extends pb.Service()("@opencode/Provider"){static{n(this,"Service")}}D.Service=d;function s(z,_){let B={id:Ut.make(_.id),providerID:Et.make(z.id),name:_.name,family:_.family,api:{id:_.id,url:_.provider?.api??z.api,npm:_.provider?.npm??z.npm??"@ai-sdk/openai-compatible"},status:_.status??"active",headers:_.headers??{},options:_.options??{},cost:{input:_.cost?.input??0,output:_.cost?.output??0,cache:{read:_.cost?.cache_read??0,write:_.cost?.cache_write??0},experimentalOver200K:_.cost?.context_over_200k?{cache:{read:_.cost.context_over_200k.cache_read??0,write:_.cost.context_over_200k.cache_write??0},input:_.cost.context_over_200k.input,output:_.cost.context_over_200k.output}:void 0},limit:{context:_.limit.context,input:_.limit.input,output:_.limit.output},capabilities:{temperature:_.temperature,reasoning:_.reasoning,attachment:_.attachment,toolcall:_.tool_call,input:{text:_.modalities?.input?.includes("text")??!1,audio:_.modalities?.input?.includes("audio")??!1,image:_.modalities?.input?.includes("image")??!1,video:_.modalities?.input?.includes("video")??!1,pdf:_.modalities?.input?.includes("pdf")??!1},output:{text:_.modalities?.output?.includes("text")??!1,audio:_.modalities?.output?.includes("audio")??!1,image:_.modalities?.output?.includes("image")??!1,video:_.modalities?.output?.includes("video")??!1,pdf:_.modalities?.output?.includes("pdf")??!1},interleaved:_.interleaved??!1},release_date:_.release_date,variants:{}};return B.variants=ys(Jt.variants(B),$=>$),B}n(s,"fromModelsDevModel");function c(z){return{id:Et.make(z.id),source:"custom",name:z.name,env:z.env??[],options:{},models:ys(z.models,_=>s(z,_))}}D.fromModelsDevProvider=c,n(c,"fromModelsDevProvider");let l=ai.effect(d,gt.gen(function*(){let z=yield*rt.Service,_=yield*Fn.Service,B=yield*ln.Service,$=yield*ge.make(()=>gt.gen(function*(){var Te=[];try{let Y=kn(Te,e.time("state"));let re=yield*z.get();let ue=yield*gt.promise(()=>ir.get());let H=ys(ue,c);let R={};let L=new Map;let q={};let X={};let ne=new Map;let Q={};let oe={auth:n(ye=>_.get(ye).pipe(gt.orDie),"auth"),config:n(()=>z.get(),"config")};e.info("init");function ce(ye,ae){let me=R[ye];if(me){R[ye]=Nr(me,ae);return}let P=H[ye];P&&(R[ye]=Nr(P,ae))}n(ce,"mergeProvider");let pe=yield*B.list();let De=Object.entries(re.provider??{});let Oe=new Set(re.disabled_providers??[]);let xe=re.enabled_providers?new Set(re.enabled_providers):null;function ie(ye){return!(xe&&!xe.has(ye)||Oe.has(ye))}n(ie,"isProviderAllowed");for(let[ye,ae]of De){let me=H[ye],P={id:Et.make(ye),name:ae.name??me?.name??ye,env:ae.env??me?.env??[],options:Nr(me?.options??{},ae.options??{}),source:"config",models:me?.models??{}};for(let[Z,J]of Object.entries(ae.models??{})){let fe=P.models[J.id??Z],_e=qt(()=>J.name?J.name:J.id&&J.id!==Z?Z:fe?.name??Z),te={id:Ut.make(Z),api:{id:J.id??fe?.api.id??Z,npm:J.provider?.npm??ae.npm??fe?.api.npm??ue[ye]?.npm??"@ai-sdk/openai-compatible",url:J.provider?.api??ae?.api??fe?.api.url??ue[ye]?.api},status:J.status??fe?.status??"active",name:_e,providerID:Et.make(ye),capabilities:{temperature:J.temperature??fe?.capabilities.temperature??!1,reasoning:J.reasoning??fe?.capabilities.reasoning??!1,attachment:J.attachment??fe?.capabilities.attachment??!1,toolcall:J.tool_call??fe?.capabilities.toolcall??!0,input:{text:J.modalities?.input?.includes("text")??fe?.capabilities.input.text??!0,audio:J.modalities?.input?.includes("audio")??fe?.capabilities.input.audio??!1,image:J.modalities?.input?.includes("image")??fe?.capabilities.input.image??!1,video:J.modalities?.input?.includes("video")??fe?.capabilities.input.video??!1,pdf:J.modalities?.input?.includes("pdf")??fe?.capabilities.input.pdf??!1},output:{text:J.modalities?.output?.includes("text")??fe?.capabilities.output.text??!0,audio:J.modalities?.output?.includes("audio")??fe?.capabilities.output.audio??!1,image:J.modalities?.output?.includes("image")??fe?.capabilities.output.image??!1,video:J.modalities?.output?.includes("video")??fe?.capabilities.output.video??!1,pdf:J.modalities?.output?.includes("pdf")??fe?.capabilities.output.pdf??!1},interleaved:J.interleaved??!1},cost:{input:J?.cost?.input??fe?.cost?.input??0,output:J?.cost?.output??fe?.cost?.output??0,cache:{read:J?.cost?.cache_read??fe?.cost?.cache.read??0,write:J?.cost?.cache_write??fe?.cost?.cache.write??0}},options:Nr(fe?.options??{},J.options??{}),limit:{context:J.limit?.context??fe?.limit?.context??0,input:J.limit?.input??fe?.limit?.input,output:J.limit?.output??fe?.limit?.output??0},headers:Nr(fe?.headers??{},J.headers??{}),family:J.family??fe?.family??"",release_date:J.release_date??fe?.release_date??"",variants:{}},we=Nr(Jt.variants(te),J.variants??{});te.variants=ys(Vu(we,$e=>!$e.disabled),$e=>Gu($e,["disabled"])),P.models[Z]=te}H[ye]=P}let le=Tt.all();for(let[ye,ae]of Object.entries(H)){let me=Et.make(ye);if(Oe.has(me))continue;let P=ae.env.map(Z=>le[Z]).find(Boolean);P&&ce(me,{source:"env",key:ae.env.length===1?P:void 0})}let Le=yield*_.all().pipe(gt.orDie);for(let[ye,ae]of Object.entries(Le)){let me=Et.make(ye);Oe.has(me)||ae.type==="api"&&ce(me,{source:"api",key:ae.key})}for(let ye of pe){if(!ye.auth)continue;let ae=Et.make(ye.auth.provider);if(Oe.has(ae)||!(yield*_.get(ae).pipe(gt.orDie))||!ye.auth.loader)continue;let Z=(yield*gt.promise(()=>ye.auth.loader(()=>gt.runPromise(_.get(ae).pipe(gt.orDie)),H[ye.auth.provider])))??{},J=R[ae]?{options:Z}:{source:"custom",options:Z};ce(ae,J)}for(let[ye,ae]of Object.entries(p(oe))){let me=Et.make(ye);if(Oe.has(me))continue;let P=H[me];if(!P){e.error("Provider does not exist in model list "+me);continue}let Z=yield*ae(P);if(Z&&(Z.autoload||R[me])){Z.getModel&&(q[me]=Z.getModel),Z.vars&&(X[me]=Z.vars),Z.discoverModels&&(Q[me]=Z.discoverModels);let J=Z.options??{},fe=R[me]?{options:J}:{source:"custom",options:J};ce(me,fe)}}for(let[ye,ae]of De){let me=Et.make(ye),P={source:"config"};ae.env&&(P.env=ae.env),ae.name&&(P.name=ae.name),ae.options&&(P.options=ae.options),ce(me,P)}let ve=Et.make("gitlab");Q[ve]&&R[ve]&&ie(ve)&&(yield*gt.promise(async()=>{try{let ye=await Q[ve]();for(let[ae,me]of Object.entries(ye))R[ve].models[ae]||(R[ve].models[ae]=me)}catch(ye){e.warn("state discovery error",{id:"gitlab",error:ye})}}));for(let ye of pe){let ae=ye.provider,me=ae?.models;if(!ae||!me)continue;let P=Et.make(ae.id);if(Oe.has(P))continue;let Z=R[P];if(!Z)continue;let J=yield*_.get(P).pipe(gt.orDie);Z.models=yield*gt.promise(async()=>{let fe=await me(Z,{auth:J});return Object.fromEntries(Object.entries(fe).map(([_e,te])=>[_e,{...te,id:Ut.make(_e),providerID:P}]))})}for(let[ye,ae]of Object.entries(R)){let me=Et.make(ye);if(!ie(me)){delete R[me];continue}let P=re.provider?.[me];for(let[Z,J]of Object.entries(ae.models)){J.api.id=J.api.id??J.id??Z,(Z==="gpt-5-chat-latest"||me===Et.openrouter&&Z==="openai/gpt-5-chat")&&delete ae.models[Z],J.status==="alpha"&&!Ce.OPENCODE_ENABLE_EXPERIMENTAL_MODELS&&delete ae.models[Z],J.status==="deprecated"&&delete ae.models[Z],(P?.blacklist&&P.blacklist.includes(Z)||P?.whitelist&&!P.whitelist.includes(Z))&&delete ae.models[Z],J.variants=ys(Jt.variants(J),_e=>_e);let fe=P?.models?.[Z]?.variants;if(fe&&J.variants){let _e=Nr(J.variants,fe);J.variants=ys(Vu(_e,te=>!te.disabled),te=>Gu(te,["disabled"]))}}if(Object.keys(ae.models).length===0){delete R[me];continue}e.info("found",{providerID:me})}return{models:L,providers:R,sdk:ne,modelLoaders:q,varsLoaders:X}}catch(it){var Ie=it,be=!0}finally{En(Te,Ie,be)}})),M=gt.fn("Provider.list")(()=>ge.use($,Y=>Y.providers));async function C(Y,re){try{var ue=[];try{let q=kn(ue,e.time("getSDK",{providerID:Y.providerID}));let X=re.providers[Y.providerID];let ne={...X.options};Y.providerID==="google-vertex"&&!Y.api.npm.includes("@ai-sdk/openai-compatible")&&delete ne.fetch;Y.api.npm.includes("@ai-sdk/openai-compatible")&&ne.includeUsage!==!1&&(ne.includeUsage=!0);let Q=qt(()=>{let ve=typeof ne.baseURL=="string"&&ne.baseURL!==""?ne.baseURL:Y.api.url;if(!ve)return;let Te=re.varsLoaders[Y.providerID];if(Te){let it=Te(ne);for(let[Ie,be]of Object.entries(it)){let ye="${"+Ie+"}";ve=ve.replaceAll(ye,be)}}return ve=ve.replace(/\$\{([^}]+)\}/g,(it,Ie)=>Tt.get(String(Ie))??it),ve});Q!==void 0&&(ne.baseURL=Q);ne.apiKey===void 0&&X.key&&(ne.apiKey=X.key);Y.headers&&(ne.headers={...ne.headers,...Y.headers});let oe=qo.fast(JSON.stringify({providerID:Y.providerID,npm:Y.api.npm,options:ne}));let ce=re.sdk.get(oe);if(ce)return ce;let pe=ne.fetch;let De=ne.chunkTimeout??(Y.providerID==="openai"?3e5:void 0);delete ne.chunkTimeout;ne.fetch=async(ve,Te)=>{let it=pe??fetch,Ie=Te??{},be=typeof De=="number"&&De>0?new AbortController:void 0,ye=[];Ie.signal&&ye.push(Ie.signal),be&&ye.push(be.signal),ne.timeout!==void 0&&ne.timeout!==null&&ne.timeout!==!1&&ye.push(AbortSignal.timeout(ne.timeout));let ae=ye.length===0?null:ye.length===1?ye[0]:AbortSignal.any(ye);ae&&(Ie.signal=ae);let me=!1;if(Y.api.npm==="@ai-sdk/openai"&&Ie.body&&Ie.method==="POST"){let te=JSON.parse(Ie.body);if(me=te.stream===!0,!(Y.providerID.includes("azure")&&te.store===!0)&&Array.isArray(te.input)){for(let ee of te.input)"id"in ee&&delete ee.id;Ie.body=JSON.stringify(te)}}let P=Ie.method==="POST"&&typeof Ie.body=="string"&&Qs.on()?(()=>{try{return Qs.shape(JSON.parse(Ie.body),Ie.headers)}catch{return}})():void 0,Z=Date.now(),J=await it(ve,{...Ie,timeout:!1}),fe=P?Qs.wrap(J,{provider:Y.providerID,...P},Z):J,_e=be?o(fe,De,be,me):fe;return me?ol.wrap(_e):_e};let Oe=m[Y.api.npm];if(Oe){e.info("using bundled provider",{providerID:Y.providerID,pkg:Y.api.npm});let ve=Oe({name:Y.providerID,...ne});return re.sdk.set(oe,ve),ve}let xe;if(Y.api.npm.startsWith("file://"))e.info("loading local provider",{pkg:Y.api.npm}),xe=Y.api.npm;else{let ve=await an.add(Y.api.npm);if(!ve.entrypoint)throw new Error(`Package ${Y.api.npm} has no import entrypoint`);xe=ve.entrypoint}let ie=await import(xe);let le=ie[Object.keys(ie).find(ve=>ve.startsWith("create"))];let Le=le({name:Y.providerID,...ne});re.sdk.set(oe,Le);return Le}catch(H){var R=H,L=!0}finally{En(ue,R,L)}}catch(q){throw new D.InitError({providerID:Y.providerID},{cause:q})}}n(C,"resolveSDK");let T=gt.fn("Provider.getProvider")(Y=>ge.use($,re=>re.providers[Y])),G=gt.fn("Provider.getModel")(function*(Y,re){let ue=yield*ge.get($),H=ue.providers[Y];if(!H){let L=Object.keys(ue.providers),q=Hu.go(Y,L,{limit:3,threshold:-1e4});throw new D.ModelNotFoundError({providerID:Y,modelID:re,suggestions:q.map(X=>X.target)})}let R=H.models[re];if(!R){let L=Object.keys(H.models),q=Hu.go(re,L,{limit:3,threshold:-1e4});throw new D.ModelNotFoundError({providerID:Y,modelID:re,suggestions:q.map(X=>X.target)})}return R}),N=gt.fn("Provider.getLanguage")(function*(Y){let re=yield*ge.get($),ue=`${Y.providerID}/${Y.id}`;return re.models.has(ue)?re.models.get(ue):yield*gt.promise(async()=>{let H=i();if(H){let q=Ju({name:Y.providerID,apiKey:"test-key",baseURL:H}).chatModel(Y.api.id);return re.models.set(ue,q),q}let R=re.providers[Y.providerID],L=await C(Y,re);try{let q=re.modelLoaders[Y.providerID]?await re.modelLoaders[Y.providerID](L,Y.api.id,{...R.options,...Y.options}):L.languageModel(Y.api.id);return re.models.set(ue,q),q}catch(q){throw q instanceof db?new D.ModelNotFoundError({modelID:Y.id,providerID:Y.providerID},{cause:q}):q}})}),A=gt.fn("Provider.closest")(function*(Y,re){let H=(yield*ge.get($)).providers[Y];if(H){for(let R of re)for(let L of Object.keys(H.models))if(L.includes(R))return{providerID:Y,modelID:L}}}),F=gt.fn("Provider.getSmallModel")(function*(Y){let re=yield*z.get();if(re.small_model){let L=O(re.small_model);return yield*G(L.providerID,L.modelID)}let H=(yield*ge.get($)).providers[Y];if(!H)return;let R=["claude-haiku-5-5","claude-haiku-5.5","claude-haiku-4-5","claude-haiku-4.5","3-5-haiku","3.5-haiku","gemini-3-flash","gemini-2.5-flash","gpt-5-nano"];Y.startsWith("opencode")&&(R=["gpt-5-nano"]),Y.startsWith("github-copilot")&&(R=["gpt-5-mini","claude-haiku-4.5",...R]);for(let L of R)if(Y===Et.amazonBedrock){let q=["global.","us.","eu."],X=Object.keys(H.models).filter(ce=>ce.includes(L)),ne=X.find(ce=>ce.startsWith("global."));if(ne)return yield*G(Y,Ut.make(ne));let Q=H.options?.region;if(Q){let ce=Q.split("-")[0];if(ce==="us"||ce==="eu"){let pe=X.find(De=>De.startsWith(`${ce}.`));if(pe)return yield*G(Y,Ut.make(pe))}}let oe=X.find(ce=>!q.some(pe=>ce.startsWith(pe)));if(oe)return yield*G(Y,Ut.make(oe))}else for(let q of Object.keys(H.models))if(q.includes(L))return yield*G(Y,Ut.make(q))}),V=gt.fn("Provider.defaultModel")(function*(){let Y=yield*z.get();if(Y.model)return O(Y.model);let re=yield*ge.get($),ue=yield*gt.promise(()=>Ee.readJson(ub.join(je.Path.state,"model.json")).then(L=>Array.isArray(L.recent)?L.recent:[]).catch(()=>[]));for(let L of ue){let q=re.providers[L.providerID];if(q&&q.models[L.modelID])return{providerID:L.providerID,modelID:L.modelID}}let H=Object.values(re.providers).find(L=>!Y.provider||Object.keys(Y.provider).includes(L.id));if(!H)throw new Error("no providers found");let[R]=j(Object.values(H.models));if(!R)throw new Error("no models found");return{providerID:H.id,modelID:R.id}});return d.of({list:M,getProvider:T,getModel:G,getLanguage:N,closest:A,getSmallModel:F,defaultModel:V})}));D.defaultLayer=ai.suspend(()=>l.pipe(ai.provide(rt.defaultLayer),ai.provide(Fn.defaultLayer),ai.provide(ln.defaultLayer)));let{runPromise:u}=Ke(d,D.defaultLayer);async function a(){return u(z=>z.list())}D.list=a,n(a,"list");async function w(z){return u(_=>_.getProvider(z))}D.getProvider=w,n(w,"getProvider");async function I(z,_){return u(B=>B.getModel(z,_))}D.getModel=I,n(I,"getModel");async function r(z){return u(_=>_.getLanguage(z))}D.getLanguage=r,n(r,"getLanguage");async function x(z,_){return u(B=>B.closest(z,_))}D.closest=x,n(x,"closest");async function h(z){return u(_=>_.getSmallModel(z))}D.getSmallModel=h,n(h,"getSmallModel");async function v(){return u(z=>z.defaultModel())}D.defaultModel=v,n(v,"defaultModel");let S=["gpt-5","claude-sonnet-4","big-pickle","gemini-3-pro"];function j(z){return lb(z,[_=>S.findIndex(B=>_.id.includes(B)),"desc"],[_=>_.id.includes("latest")?0:1,"asc"],[_=>_.id,"desc"])}D.sort=j,n(j,"sort");function O(z){let[_,...B]=z.split("/");return{providerID:Et.make(_),modelID:Ut.make(B.join("/"))}}D.parseModel=O,n(O,"parseModel"),D.ModelNotFoundError=tt.create("ProviderModelNotFoundError",Ge.object({providerID:Et.zod,modelID:Ut.zod,suggestions:Ge.array(Ge.string()).optional()})),D.InitError=tt.create("ProviderInitError",Ge.object({providerID:Et.zod}))})(yn||={});import{generateObject as Jb,streamObject as Yb}from"ai";var Yu=`You are an elite AI agent architect specializing in crafting high-performance agent configurations. Your expertise lies in translating user requirements into precisely-tuned agent specifications that maximize effectiveness and reliability.
|
|
161
|
+
|
|
162
|
+
**Important Context**: You may have access to project-specific instructions from CLAUDE.md files and other context that may include coding standards, project structure, and custom requirements. Consider this context when creating agents to ensure they align with the project's established patterns and practices.
|
|
163
|
+
|
|
164
|
+
When a user describes what they want an agent to do, you will:
|
|
165
|
+
|
|
166
|
+
1. **Extract Core Intent**: Identify the fundamental purpose, key responsibilities, and success criteria for the agent. Look for both explicit requirements and implicit needs. Consider any project-specific context from CLAUDE.md files. For agents that are meant to review code, you should assume that the user is asking to review recently written code and not the whole codebase, unless the user has explicitly instructed you otherwise.
|
|
167
|
+
|
|
168
|
+
2. **Design Expert Persona**: Create a compelling expert identity that embodies deep domain knowledge relevant to the task. The persona should inspire confidence and guide the agent's decision-making approach.
|
|
169
|
+
|
|
170
|
+
3. **Architect Comprehensive Instructions**: Develop a system prompt that:
|
|
171
|
+
|
|
172
|
+
- Establishes clear behavioral boundaries and operational parameters
|
|
173
|
+
- Provides specific methodologies and best practices for task execution
|
|
174
|
+
- Anticipates edge cases and provides guidance for handling them
|
|
175
|
+
- Incorporates any specific requirements or preferences mentioned by the user
|
|
176
|
+
- Defines output format expectations when relevant
|
|
177
|
+
- Aligns with project-specific coding standards and patterns from CLAUDE.md
|
|
178
|
+
|
|
179
|
+
4. **Optimize for Performance**: Include:
|
|
180
|
+
|
|
181
|
+
- Decision-making frameworks appropriate to the domain
|
|
182
|
+
- Quality control mechanisms and self-verification steps
|
|
183
|
+
- Efficient workflow patterns
|
|
184
|
+
- Clear escalation or fallback strategies
|
|
185
|
+
|
|
186
|
+
5. **Create Identifier**: Design a concise, descriptive identifier that:
|
|
187
|
+
- Uses lowercase letters, numbers, and hyphens only
|
|
188
|
+
- Is typically 2-4 words joined by hyphens
|
|
189
|
+
- Clearly indicates the agent's primary function
|
|
190
|
+
- Is memorable and easy to type
|
|
191
|
+
- Avoids generic terms like "helper" or "assistant"
|
|
192
|
+
|
|
193
|
+
6 **Example agent descriptions**:
|
|
194
|
+
|
|
195
|
+
- in the 'whenToUse' field of the JSON object, you should include examples of when this agent should be used.
|
|
196
|
+
- examples should be of the form:
|
|
197
|
+
- <example>
|
|
198
|
+
Context: The user is creating a code-review agent that should be called after a logical chunk of code is written.
|
|
199
|
+
user: "Please write a function that checks if a number is prime"
|
|
200
|
+
assistant: "Here is the relevant function: "
|
|
201
|
+
<function call omitted for brevity only for this example>
|
|
202
|
+
<commentary>
|
|
203
|
+
Since the user is greeting, use the Task tool to launch the greeting-responder agent to respond with a friendly joke.
|
|
204
|
+
</commentary>
|
|
205
|
+
assistant: "Now let me use the code-reviewer agent to review the code"
|
|
206
|
+
</example>
|
|
207
|
+
- <example>
|
|
208
|
+
Context: User is creating an agent to respond to the word "hello" with a friendly jok.
|
|
209
|
+
user: "Hello"
|
|
210
|
+
assistant: "I'm going to use the Task tool to launch the greeting-responder agent to respond with a friendly joke"
|
|
211
|
+
<commentary>
|
|
212
|
+
Since the user is greeting, use the greeting-responder agent to respond with a friendly joke.
|
|
213
|
+
</commentary>
|
|
214
|
+
</example>
|
|
215
|
+
- If the user mentioned or implied that the agent should be used proactively, you should include examples of this.
|
|
216
|
+
- NOTE: Ensure that in the examples, you are making the assistant use the Agent tool and not simply respond directly to the task.
|
|
217
|
+
|
|
218
|
+
Your output must be a valid JSON object with exactly these fields:
|
|
219
|
+
{
|
|
220
|
+
"identifier": "A unique, descriptive identifier using lowercase letters, numbers, and hyphens (e.g., 'code-reviewer', 'api-docs-writer', 'test-generator')",
|
|
221
|
+
"whenToUse": "A precise, actionable description starting with 'Use this agent when...' that clearly defines the triggering conditions and use cases. Ensure you include examples as described above.",
|
|
222
|
+
"systemPrompt": "The complete system prompt that will govern the agent's behavior, written in second person ('You are...', 'You will...') and structured for maximum clarity and effectiveness"
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
Key principles for your system prompts:
|
|
226
|
+
|
|
227
|
+
- Be specific rather than generic - avoid vague instructions
|
|
228
|
+
- Include concrete examples when they would clarify behavior
|
|
229
|
+
- Balance comprehensiveness with clarity - every instruction should add value
|
|
230
|
+
- Ensure the agent has enough context to handle variations of the core task
|
|
231
|
+
- Make the agent proactive in seeking clarification when needed
|
|
232
|
+
- Build in quality assurance and self-correction mechanisms
|
|
233
|
+
|
|
234
|
+
Remember: The agents you create should be autonomous experts capable of handling their designated tasks with minimal additional guidance. Your system prompts are their complete operational manual.
|
|
235
|
+
`;var Ku=`You are a helpful AI assistant tasked with summarizing conversations.
|
|
236
|
+
|
|
237
|
+
When asked to summarize, provide a detailed but concise summary of the conversation.
|
|
238
|
+
Focus on information that would be helpful for continuing the conversation, including:
|
|
239
|
+
- What was done
|
|
240
|
+
- What is currently being worked on
|
|
241
|
+
- Which files are being modified
|
|
242
|
+
- What needs to be done next
|
|
243
|
+
- Key user requests, constraints, or preferences that should persist
|
|
244
|
+
- Important technical decisions and why they were made
|
|
245
|
+
|
|
246
|
+
Your summary should be comprehensive enough to provide context but concise enough to be quickly understood.
|
|
247
|
+
|
|
248
|
+
Do not respond to any questions in the conversation, only output the summary.
|
|
249
|
+
Respond in the same language the user used in the conversation.
|
|
250
|
+
`;var Xu=`You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
|
|
251
|
+
|
|
252
|
+
Your strengths:
|
|
253
|
+
- Rapidly finding files using glob patterns
|
|
254
|
+
- Searching code and text with powerful regex patterns
|
|
255
|
+
- Reading and analyzing file contents
|
|
256
|
+
|
|
257
|
+
Guidelines:
|
|
258
|
+
- Use Glob for broad file pattern matching
|
|
259
|
+
- Use Grep for searching file contents with regex
|
|
260
|
+
- Use Read when you know the specific file path you need to read
|
|
261
|
+
- Use Bash for file operations like copying, moving, or listing directory contents
|
|
262
|
+
- Adapt your search approach based on the thoroughness level specified by the caller
|
|
263
|
+
- Return file paths as absolute paths in your final response
|
|
264
|
+
- For clear communication, avoid using emojis
|
|
265
|
+
- Do not create any files, or run bash commands that modify the user's system state in any way
|
|
266
|
+
|
|
267
|
+
Complete the user's search request efficiently and report your findings clearly.
|
|
268
|
+
`;var Zu=`Summarize what was done in this conversation. Write like a pull request description.
|
|
269
|
+
|
|
270
|
+
Rules:
|
|
271
|
+
- 2-3 sentences max
|
|
272
|
+
- Describe the changes made, not the process
|
|
273
|
+
- Do not mention running tests, builds, or other validation steps
|
|
274
|
+
- Do not explain what the user asked for
|
|
275
|
+
- Write in first person (I added..., I fixed...)
|
|
276
|
+
- Never ask questions or add new questions
|
|
277
|
+
- If the conversation ends with an unanswered question to the user, preserve that exact question
|
|
278
|
+
- If the conversation ends with an imperative statement or request to the user (e.g. "Now please run the command and paste the console output"), always include that exact request in the summary
|
|
279
|
+
`;var Qu=`You are a title generator. You output ONLY a thread title. Nothing else.
|
|
280
|
+
|
|
281
|
+
<task>
|
|
282
|
+
Generate a brief title that would help the user find this conversation later.
|
|
283
|
+
|
|
284
|
+
Follow all rules in <rules>
|
|
285
|
+
Use the <examples> so you know what a good title looks like.
|
|
286
|
+
Your output must be:
|
|
287
|
+
- A single line
|
|
288
|
+
- \u226450 characters
|
|
289
|
+
- No explanations
|
|
290
|
+
</task>
|
|
291
|
+
|
|
292
|
+
<rules>
|
|
293
|
+
- you MUST use the same language as the user message you are summarizing
|
|
294
|
+
- Title must be grammatically correct and read naturally - no word salad
|
|
295
|
+
- Never include tool names in the title (e.g. "read tool", "bash tool", "edit tool")
|
|
296
|
+
- Focus on the main topic or question the user needs to retrieve
|
|
297
|
+
- Vary your phrasing - avoid repetitive patterns like always starting with "Analyzing"
|
|
298
|
+
- When a file is mentioned, focus on WHAT the user wants to do WITH the file, not just that they shared it
|
|
299
|
+
- Keep exact: technical terms, numbers, filenames, HTTP codes
|
|
300
|
+
- Remove: the, this, my, a, an
|
|
301
|
+
- Never assume tech stack
|
|
302
|
+
- Never use tools
|
|
303
|
+
- NEVER respond to questions, just generate a title for the conversation
|
|
304
|
+
- The title should NEVER include "summarizing" or "generating" when generating a title
|
|
305
|
+
- DO NOT SAY YOU CANNOT GENERATE A TITLE OR COMPLAIN ABOUT THE INPUT
|
|
306
|
+
- Always output something meaningful, even if the input is minimal.
|
|
307
|
+
- If the user message is short or conversational (e.g. "hello", "lol", "what's up", "hey"):
|
|
308
|
+
\u2192 create a title that reflects the user's tone or intent (such as Greeting, Quick check-in, Light chat, Intro message, etc.)
|
|
309
|
+
</rules>
|
|
310
|
+
|
|
311
|
+
<examples>
|
|
312
|
+
"debug 500 errors in production" \u2192 Debugging production 500 errors
|
|
313
|
+
"refactor user service" \u2192 Refactoring user service
|
|
314
|
+
"why is app.js failing" \u2192 app.js failure investigation
|
|
315
|
+
"implement rate limiting" \u2192 Rate limiting implementation
|
|
316
|
+
"how do I connect postgres to my API" \u2192 Postgres API connection
|
|
317
|
+
"best practices for React hooks" \u2192 React hooks best practices
|
|
318
|
+
"@src/auth.ts can you add refresh token support" \u2192 Auth refresh token support
|
|
319
|
+
"@utils/parser.ts this is broken" \u2192 Parser bug fix
|
|
320
|
+
"look at @config.json" \u2192 Config review
|
|
321
|
+
"@App.tsx add dark mode toggle" \u2192 Dark mode toggle in App
|
|
322
|
+
</examples>
|
|
323
|
+
`;import{Deferred as Fr,Effect as Yo,Layer as ep,Schema as ci,ServiceMap as Fb}from"effect";import Ia from"os";import In from"zod";import{Schema as zb}from"effect";var zr=class extends Si()("PermissionID",zb.String){static{n(this,"PermissionID")}static make(t){return this.makeUnsafe(t)}static ascending(t){return this.makeUnsafe(Nt.ascending("permission",t))}static zod=Nt.schema("permission")};var lt;(E=>{let e=qe.create({service:"permission"});E.Action=In.enum(["allow","deny","ask"]).meta({ref:"PermissionAction"}),E.Rule=In.object({permission:In.string(),pattern:In.string(),action:E.Action}).meta({ref:"PermissionRule"}),E.Ruleset=E.Rule.array().meta({ref:"PermissionRuleset"}),E.Request=In.object({id:zr.zod,sessionID:He.zod,permission:In.string(),patterns:In.string().array(),metadata:In.record(In.string(),In.any()),always:In.string().array(),tool:In.object({messageID:pt.zod,callID:In.string()}).optional()}).meta({ref:"PermissionRequest"}),E.Reply=In.enum(["once","always","reject"]),E.Approval=In.object({projectID:Ns.zod,patterns:In.string().array()}),E.Event={Asked:mt.define("permission.asked",E.Request),Replied:mt.define("permission.replied",In.object({sessionID:He.zod,requestID:zr.zod,reply:E.Reply}))};class b extends ci.TaggedErrorClass()("PermissionRejectedError",{}){static{n(this,"RejectedError")}get message(){return"The user rejected permission to use this specific tool call."}}E.RejectedError=b;class d extends ci.TaggedErrorClass()("PermissionCorrectedError",{feedback:ci.String}){static{n(this,"CorrectedError")}get message(){return`The user rejected permission to use this specific tool call with the following feedback: ${this.feedback}`}}E.CorrectedError=d;class s extends ci.TaggedErrorClass()("PermissionDeniedError",{ruleset:ci.Any}){static{n(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)}`}}E.DeniedError=s,E.AskInput=E.Request.partial({id:!0}).extend({ruleset:E.Ruleset}),E.ReplyInput=In.object({requestID:zr.zod,reply:E.Reply,message:In.string().optional()});function g(D,z,..._){return e.info("evaluate",{permission:D,pattern:z,ruleset:_.flat()}),Di(D,z,..._)}E.evaluate=g,n(g,"evaluate");class u extends Fb.Service()("@opencode/Permission"){static{n(this,"Service")}}E.Service=u,E.layer=ep.effect(u,Yo.gen(function*(){let D=yield*Ve.Service,z=yield*ge.make(Yo.fn("Permission.state")(function*(M){let C=Xt.use(G=>G.select().from(Ga).where((0,We.eq)(Ga.project_id,M.project.id)).get()),T={pending:new Map,approved:C?.data??[]};return yield*Yo.addFinalizer(()=>Yo.gen(function*(){for(let G of T.pending.values())yield*Fr.fail(G.deferred,new b);T.pending.clear()})),T})),_=Yo.fn("Permission.ask")(function*(M){let{approved:C,pending:T}=yield*ge.get(z),{ruleset:G,...N}=M,A=!1;for(let re of N.patterns){let ue=g(N.permission,re,G,C);if(e.info("evaluated",{permission:N.permission,pattern:re,action:ue}),ue.action==="deny")return yield*new s({ruleset:G.filter(H=>Sr.match(N.permission,H.permission))});ue.action!=="allow"&&(A=!0)}if(!A)return;let F=N.id??zr.ascending(),V={id:F,...N};e.info("asking",{id:F,permission:V.permission,patterns:V.patterns});let Y=yield*Fr.make();return T.set(F,{info:V,deferred:Y}),yield*D.publish(E.Event.Asked,V),yield*Yo.ensuring(Fr.await(Y),Yo.sync(()=>{T.delete(F)}))}),B=Yo.fn("Permission.reply")(function*(M){let{approved:C,pending:T}=yield*ge.get(z),G=T.get(M.requestID);if(G){if(T.delete(M.requestID),yield*D.publish(E.Event.Replied,{sessionID:G.info.sessionID,requestID:G.info.id,reply:M.reply}),M.reply==="reject"){yield*Fr.fail(G.deferred,M.message?new d({feedback:M.message}):new b);for(let[N,A]of T.entries())A.info.sessionID===G.info.sessionID&&(T.delete(N),yield*D.publish(E.Event.Replied,{sessionID:A.info.sessionID,requestID:A.info.id,reply:"reject"}),yield*Fr.fail(A.deferred,new b));return}if(yield*Fr.succeed(G.deferred,void 0),M.reply!=="once"){for(let N of G.info.always)C.push({permission:G.info.permission,pattern:N,action:"allow"});for(let[N,A]of T.entries())A.info.sessionID!==G.info.sessionID||!A.info.patterns.every(V=>g(A.info.permission,V,C).action==="allow")||(T.delete(N),yield*D.publish(E.Event.Replied,{sessionID:A.info.sessionID,requestID:A.info.id,reply:"always"}),yield*Fr.succeed(A.deferred,void 0))}}}),$=Yo.fn("Permission.list")(function*(){let M=(yield*ge.get(z)).pending;return Array.from(M.values(),C=>C.info)});return u.of({ask:_,reply:B,list:$})}));function w(D){return D.startsWith("~/")?Ia.homedir()+D.slice(1):D==="~"?Ia.homedir():D.startsWith("$HOME/")?Ia.homedir()+D.slice(5):D.startsWith("$HOME")?Ia.homedir()+D.slice(5):D}n(w,"expand");function I(D){let z=[];for(let[_,B]of Object.entries(D)){if(typeof B=="string"){z.push({permission:_,action:B,pattern:"*"});continue}z.push(...Object.entries(B).map(([$,M])=>({permission:_,pattern:w($),action:M})))}return z}E.fromConfig=I,n(I,"fromConfig");function r(...D){return D.flat()}E.merge=r,n(r,"merge");let x=["edit","write","apply_patch","multiedit"];function h(D,z){let _=new Set;for(let B of D){let $=x.includes(B)?"edit":B,M=z.findLast(C=>Sr.match($,C.permission));M&&M.pattern==="*"&&M.action==="deny"&&_.add(B)}return _}E.disabled=h,n(h,"disabled"),E.defaultLayer=E.layer.pipe(ep.provide(Ve.layer)),{runPromise:E.runPromise}=Ke(u,E.defaultLayer);async function j(D){return(0,E.runPromise)(z=>z.ask(D))}E.ask=j,n(j,"ask");async function O(D){return(0,E.runPromise)(z=>z.reply(D))}E.reply=O,n(O,"reply");async function k(){return(0,E.runPromise)(D=>D.list())}E.list=k,n(k,"list")})(lt||={});import{mergeDeep as Kb,pipe as Xb,sortBy as Zb,values as Qb}from"remeda";import ws from"path";import Hb from"os";import li from"path";import{pathToFileURL as Gb}from"url";import no from"zod";import{Effect as bn,Layer as di,ServiceMap as Vb}from"effect";import{NodePath as Ub}from"@effect/platform-node";import{Effect as Ln,Layer as ka,Path as $b,Schema as bs,ServiceMap as qb}from"effect";import{FetchHttpClient as Bb,HttpClient as tp,HttpClientRequest as rl,HttpClientResponse as Wb}from"effect/unstable/http";var Ea;(f=>{class o extends bs.Class("IndexSkill")({name:bs.String,files:bs.Array(bs.String)}){static{n(this,"IndexSkill")}}class i extends bs.Class("Index")({skills:bs.Array(o)}){static{n(this,"Index")}}class m extends qb.Service()("@opencode/SkillDiscovery"){static{n(this,"Service")}}f.Service=m,f.layer=ka.effect(m,Ln.gen(function*(){let b=qe.create({service:"skill-discovery"}),d=yield*ut.Service,s=yield*$b.Path,c=tp.filterStatusOk(sr(yield*tp.HttpClient)),l=s.join(je.Path.cache,"skills"),g=Ln.fn("Discovery.download")(function*(a,w){return(yield*d.exists(w).pipe(Ln.orDie))?!0:yield*rl.get(a).pipe(c.execute,Ln.flatMap(I=>I.arrayBuffer),Ln.flatMap(I=>d.writeWithDirs(w,new Uint8Array(I))),Ln.as(!0),Ln.catch(I=>Ln.sync(()=>(b.error("failed to download",{url:a,err:I}),!1))))}),u=Ln.fn("Discovery.pull")(function*(a){let w=a.endsWith("/")?a:`${a}/`,I=new URL("index.json",w).href,r=w.slice(0,-1);b.info("fetching index",{url:I});let x=yield*rl.get(I).pipe(rl.acceptJson,c.execute,Ln.flatMap(Wb.schemaBodyJson(i)),Ln.catch(S=>Ln.sync(()=>(b.error("failed to fetch index",{url:I,err:S}),null))));if(!x)return[];let h=x.skills.filter(S=>S.files.includes("SKILL.md")?!0:(b.warn("skill entry missing SKILL.md",{url:I,skill:S.name}),!1));return(yield*Ln.forEach(h,S=>Ln.gen(function*(){let j=s.join(l,S.name);yield*Ln.forEach(S.files,k=>g(new URL(k,`${r}/${S.name}/`).href,s.join(j,k)),{concurrency:8});let O=s.join(j,"SKILL.md");return(yield*d.exists(O).pipe(Ln.orDie))?j:null}),{concurrency:4})).filter(S=>S!==null)});return m.of({pull:u})})),f.defaultLayer=f.layer.pipe(ka.provide(Bb.layer),ka.provide(ut.defaultLayer),ka.provide(Ub.layer))})(Ea||={});var Bn;(h=>{let e=qe.create({service:"skill"}),t=[".claude",".agents"],o="skills/**/SKILL.md",i="{skill,skills}/**/SKILL.md",m="**/SKILL.md";h.Info=no.object({name:no.string(),description:no.string(),location:no.string(),content:no.string()}),h.InvalidError=tt.create("SkillInvalidError",no.object({path:no.string(),message:no.string().optional(),issues:no.custom().optional()})),h.NameMismatchError=tt.create("SkillNameMismatchError",no.object({path:no.string(),expected:no.string(),actual:no.string()}));let b=bn.fnUntraced(function*(v,S,j){let O=yield*bn.tryPromise({try:n(()=>Un.parse(S),"try"),catch:n(E=>E,"catch")}).pipe(bn.catch(bn.fnUntraced(function*(E){let D=Un.FrontmatterError.isInstance(E)?E.data.message:`Failed to parse skill ${S}`,{Session:z}=yield*bn.promise(()=>import("./session-ACBIJ2VE.js"));yield*j.publish(z.Event.Error,{error:new tt.Unknown({message:D}).toObject()}),e.error("failed to load skill",{skill:S,err:E})})));if(!O)return;let k=h.Info.pick({name:!0,description:!0}).safeParse(O.data);k.success&&(v.skills[k.data.name]&&e.warn("duplicate skill name",{name:k.data.name,existing:v.skills[k.data.name].location,duplicate:S}),v.dirs.add(li.dirname(S)),v.skills[k.data.name]={name:k.data.name,description:k.data.description,location:S,content:O.content})}),d=bn.fnUntraced(function*(v,S,j,O,k){let E=yield*bn.tryPromise({try:n(()=>co.scan(O,{cwd:j,absolute:!0,include:"file",symlink:!0,dot:k?.dot}),"try"),catch:n(D=>D,"catch")}).pipe(bn.catch(D=>k?.scope?(e.error(`failed to scan ${k.scope} skills`,{dir:j,error:D}),bn.succeed([])):bn.die(D)));yield*bn.forEach(E,D=>b(v,D,S),{concurrency:"unbounded",discard:!0})}),s=bn.fnUntraced(function*(v,S,j,O,k,E,D){if(!Ce.OPENCODE_DISABLE_EXTERNAL_SKILLS){for(let $ of t){let M=li.join(je.Path.home,$);(yield*k.isDir(M))&&(yield*d(v,O,M,o,{dot:!0,scope:"global"}))}let B=yield*k.up({targets:t,start:E,stop:D}).pipe(bn.catch(()=>bn.succeed([])));for(let $ of B)yield*d(v,O,$,o,{dot:!0,scope:"project"})}let z=yield*S.directories();for(let B of z)yield*d(v,O,B,i);let _=yield*S.get();for(let B of _.skills?.paths??[]){let $=B.startsWith("~/")?li.join(Hb.homedir(),B.slice(2)):B,M=li.isAbsolute($)?$:li.join(E,$);if(!(yield*k.isDir(M))){e.warn("skill path not found",{path:M});continue}yield*d(v,O,M,m)}for(let B of _.skills?.urls??[]){let $=yield*j.pull(B);for(let M of $)v.dirs.add(M),yield*d(v,O,M,m)}e.info("init",{count:Object.keys(v.skills).length})});class c extends Vb.Service()("@opencode/Skill"){static{n(this,"Service")}}h.Service=c,h.layer=di.effect(c,bn.gen(function*(){let v=yield*Ea.Service,S=yield*rt.Service,j=yield*Ve.Service,O=yield*ut.Service,k=yield*ge.make(bn.fn("Skill.state")(function*(B){let $={skills:{},dirs:new Set};return yield*s($,S,v,j,O,B.directory,B.worktree),$})),E=bn.fn("Skill.get")(function*(B){return(yield*ge.get(k)).skills[B]}),D=bn.fn("Skill.all")(function*(){let B=yield*ge.get(k);return Object.values(B.skills)}),z=bn.fn("Skill.dirs")(function*(){let B=yield*ge.get(k);return Array.from(B.dirs)}),_=bn.fn("Skill.available")(function*(B){let $=yield*ge.get(k),M=Object.values($.skills).toSorted((C,T)=>C.name.localeCompare(T.name));return B?M.filter(C=>lt.evaluate("skill",C.name,B.permission).action!=="deny"):M});return c.of({get:E,all:D,dirs:z,available:_})})),h.defaultLayer=h.layer.pipe(di.provide(Ea.defaultLayer),di.provide(rt.defaultLayer),di.provide(Ve.layer),di.provide(ut.defaultLayer));function u(v,S){return v.length===0?"No skills are currently available.":S.verbose?["<available_skills>",...v.flatMap(j=>[" <skill>",` <name>${j.name}</name>`,` <description>${j.description}</description>`,` <location>${Gb(j.location).href}</location>`," </skill>"]),"</available_skills>"].join(`
|
|
324
|
+
`):["## Available Skills",...v.map(j=>`- **${j.name}**: ${j.description}`)].join(`
|
|
325
|
+
`)}h.fmt=u,n(u,"fmt");let{runPromise:a}=Ke(c,h.defaultLayer);async function w(v){return a(S=>S.get(v))}h.get=w,n(w,"get");async function I(){return a(v=>v.all())}h.all=I,n(I,"all");async function r(){return a(v=>v.dirs())}h.dirs=r,n(r,"dirs");async function x(v){return a(S=>S.available(v))}h.available=x,n(x,"available")})(Bn||={});import{Effect as oo,ServiceMap as ew,Layer as ui}from"effect";var ro;(d=>{d.Info=wn.object({name:wn.string(),description:wn.string().optional(),mode:wn.enum(["subagent","primary","all"]),native:wn.boolean().optional(),hidden:wn.boolean().optional(),topP:wn.number().optional(),temperature:wn.number().optional(),color:wn.string().optional(),permission:lt.Ruleset,model:wn.object({modelID:Ut.zod,providerID:Et.zod}).optional(),variant:wn.string().optional(),prompt:wn.string().optional(),options:wn.record(wn.string(),wn.any()),steps:wn.number().int().positive().optional()}).meta({ref:"Agent"});class t extends ew.Service()("@opencode/Agent"){static{n(this,"Service")}}d.Service=t,d.layer=ui.effect(t,oo.gen(function*(){let s=yield*rt.Service,c=yield*Fn.Service,l=yield*Bn.Service,g=yield*yn.Service,u=yield*ge.make(oo.fn("Agent.state")(function*(a){let w=yield*s.get(),I=yield*l.dirs(),r=[po.GLOB,...I.map(k=>ws.join(k,"*"))],x=lt.fromConfig({"*":"allow",doom_loop:"ask",external_directory:{"*":"ask",...Object.fromEntries(r.map(k=>[k,"allow"]))},question:"deny",plan_enter:"deny",plan_exit:"deny",read:{"*":"allow","*.env":"ask","*.env.*":"ask","*.env.example":"allow"}}),h=lt.fromConfig(w.permission??{}),v={build:{name:"build",description:"The default agent. Executes tools based on configured permissions.",options:{},permission:lt.merge(x,lt.fromConfig({question:"allow",plan_enter:"allow"}),h),mode:"primary",native:!0},plan:{name:"plan",description:"Plan mode. Disallows all edit tools.",options:{},permission:lt.merge(x,lt.fromConfig({question:"allow",plan_exit:"allow",external_directory:{[ws.join(je.Path.data,"plans","*")]:"allow"},edit:{"*":"deny",[ws.join(".opencode","plans","*.md")]:"allow",[ws.relative(he.worktree,ws.join(je.Path.data,ws.join("plans","*.md")))]:"allow"}}),h),mode:"primary",native:!0},general:{name:"general",description:"General-purpose agent for researching complex questions and executing multi-step tasks. Use this agent to execute multiple units of work in parallel.",permission:lt.merge(x,lt.fromConfig({todowrite:"deny"}),h),options:{},mode:"subagent",native:!0},explore:{name:"explore",permission:lt.merge(x,lt.fromConfig({"*":"deny",grep:"allow",glob:"allow",list:"allow",bash:"allow",webfetch:"allow",websearch:"allow",codesearch:"allow",read:"allow",external_directory:{"*":"ask",...Object.fromEntries(r.map(k=>[k,"allow"]))}}),h),description:'Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (eg. "src/components/**/*.tsx"), search code for keywords (eg. "API endpoints"), or answer questions about the codebase (eg. "how do API endpoints work?"). When calling this agent, specify the desired thoroughness level: "quick" for basic searches, "medium" for moderate exploration, or "very thorough" for comprehensive analysis across multiple locations and naming conventions.',prompt:Xu,options:{},mode:"subagent",native:!0},compaction:{name:"compaction",mode:"primary",native:!0,hidden:!0,prompt:Ku,permission:lt.merge(x,lt.fromConfig({"*":"deny"}),h),options:{}},title:{name:"title",mode:"primary",options:{},native:!0,hidden:!0,temperature:.5,permission:lt.merge(x,lt.fromConfig({"*":"deny"}),h),prompt:Qu},summary:{name:"summary",mode:"primary",options:{},native:!0,hidden:!0,permission:lt.merge(x,lt.fromConfig({"*":"deny"}),h),prompt:Zu}};for(let[k,E]of Object.entries(w.agent??{})){if(E.disable){delete v[k];continue}let D=v[k];D||(D=v[k]={name:k,mode:"all",permission:lt.merge(x,h),options:{},native:!1}),E.model&&(D.model=yn.parseModel(E.model)),D.variant=E.variant??D.variant,D.prompt=E.prompt??D.prompt,D.description=E.description??D.description,D.temperature=E.temperature??D.temperature,D.topP=E.top_p??D.topP,D.mode=E.mode??D.mode,D.color=E.color??D.color,D.hidden=E.hidden??D.hidden,D.name=E.name??D.name,D.steps=E.steps??D.steps,D.options=Kb(D.options,E.options??{}),D.permission=lt.merge(D.permission,lt.fromConfig(E.permission??{}))}for(let k in v)v[k].permission.some(z=>z.permission!=="external_directory"||z.action!=="deny"?!1:z.pattern===po.GLOB)||(v[k].permission=lt.merge(v[k].permission,lt.fromConfig({external_directory:{[po.GLOB]:"allow"}})));let S=oo.fnUntraced(function*(k){return v[k]}),j=oo.fnUntraced(function*(){let k=yield*s.get();return Xb(v,Qb(),Zb([E=>k.default_agent?E.name===k.default_agent:E.name==="build","desc"],[E=>E.name,"asc"]))}),O=oo.fnUntraced(function*(){let k=yield*s.get();if(k.default_agent){let D=v[k.default_agent];if(!D)throw new Error(`default agent "${k.default_agent}" not found`);if(D.mode==="subagent")throw new Error(`default agent "${k.default_agent}" is a subagent`);if(D.hidden===!0)throw new Error(`default agent "${k.default_agent}" is hidden`);return D.name}let E=Object.values(v).find(D=>D.mode!=="subagent"&&D.hidden!==!0);if(!E)throw new Error("no primary visible agent found");return E.name});return{get:S,list:j,defaultAgent:O}}));return t.of({get:oo.fn("Agent.get")(function*(a){return yield*ge.useEffect(u,w=>w.get(a))}),list:oo.fn("Agent.list")(function*(){return yield*ge.useEffect(u,a=>a.list())}),defaultAgent:oo.fn("Agent.defaultAgent")(function*(){return yield*ge.useEffect(u,a=>a.defaultAgent())}),generate:oo.fn("Agent.generate")(function*(a){let w=yield*s.get(),I=a.model??(yield*g.defaultModel()),r=yield*g.getModel(I.providerID,I.modelID),x=yield*g.getLanguage(r),h=[Yu];yield*oo.promise(()=>ln.trigger("experimental.chat.system.transform",{model:r},{system:h}));let v=yield*ge.useEffect(u,O=>O.list()),S={experimental_telemetry:{isEnabled:w.experimental?.openTelemetry,metadata:{userId:w.username??"unknown"}},temperature:.3,messages:[...h.map(O=>({role:"system",content:O})),{role:"user",content:`Create an agent configuration based on this request: "${a.description}".
|
|
326
|
+
|
|
327
|
+
IMPORTANT: The following identifiers already exist and must NOT be used: ${v.map(O=>O.name).join(", ")}
|
|
328
|
+
Return ONLY the JSON object, no other text, do not wrap in backticks`}],model:x,schema:wn.object({identifier:wn.string(),whenToUse:wn.string(),systemPrompt:wn.string()})},j=yield*c.get(I.providerID).pipe(oo.orDie);return I.providerID==="openai"&&j?.type==="oauth"?yield*oo.promise(async()=>{let O=Yb({...S,providerOptions:Jt.providerOptions(r,{store:!1}),onError:n(()=>{},"onError")});for await(let k of O.fullStream)if(k.type==="error")throw k.error;return O.object}):yield*oo.promise(()=>Jb(S).then(O=>O.object))})})})),d.defaultLayer=d.layer.pipe(ui.provide(yn.defaultLayer),ui.provide(Fn.defaultLayer),ui.provide(rt.defaultLayer),ui.provide(Bn.defaultLayer));let{runPromise:m}=Ke(t,d.defaultLayer);async function y(s){return m(c=>c.get(s))}d.get=y,n(y,"get");async function p(){return m(s=>s.list())}d.list=p,n(p,"list");async function f(){return m(s=>s.defaultAgent())}d.defaultAgent=f,n(f,"defaultAgent");async function b(s){return m(c=>c.generate(s))}d.generate=b,n(b,"generate")})(ro||={});import{tool as Wp,jsonSchema as bl,asSchema as tx}from"ai";import zo from"zod";var sl;(o=>{function t(i){return Math.max(0,Math.round((i||"").length/4))}o.estimate=t,n(t,"estimate")})(sl||={});import{Cause as wp,Effect as $t,Layer as ho,ServiceMap as hw}from"effect";import*as gr from"effect/Stream";import{Effect as xs,Layer as sw,Record as al,ServiceMap as iw}from"effect";import*as vs from"effect/Stream";import{streamText as aw,wrapLanguageModel as cw,tool as lw,jsonSchema as pp}from"ai";import{mergeDeep as cl,pipe as dw}from"remeda";import{GitLabWorkflowLanguageModel as fp}from"gitlab-ai-provider";import il from"path";import Sa from"fs/promises";import st from"zod";import{text as tw}from"node:stream/consumers";import{ZipReader as nw,BlobReader as ow,BlobWriter as rw}from"@zip.js/zip.js";var Ko;(w=>{let e=qe.create({service:"ripgrep"}),t=st.object({elapsed:st.object({secs:st.number(),nanos:st.number(),human:st.string()}),searches:st.number(),searches_with_match:st.number(),bytes_searched:st.number(),bytes_printed:st.number(),matched_lines:st.number(),matches:st.number()}),o=st.object({type:st.literal("begin"),data:st.object({path:st.object({text:st.string()})})});w.Match=st.object({type:st.literal("match"),data:st.object({path:st.object({text:st.string()}),lines:st.object({text:st.string()}),line_number:st.number(),absolute_offset:st.number(),submatches:st.array(st.object({match:st.object({text:st.string()}),start:st.number(),end:st.number()}))})});let m=st.object({type:st.literal("end"),data:st.object({path:st.object({text:st.string()}),binary_offset:st.number().nullable(),stats:t})}),y=st.object({type:st.literal("summary"),data:st.object({elapsed_total:st.object({human:st.string(),nanos:st.number(),secs:st.number()}),stats:t})}),p=st.union([o,w.Match,m,y]),f={"arm64-darwin":{platform:"aarch64-apple-darwin",extension:"tar.gz"},"arm64-linux":{platform:"aarch64-unknown-linux-gnu",extension:"tar.gz"},"x64-darwin":{platform:"x86_64-apple-darwin",extension:"tar.gz"},"x64-linux":{platform:"x86_64-unknown-linux-musl",extension:"tar.gz"},"arm64-win32":{platform:"aarch64-pc-windows-msvc",extension:"zip"},"x64-win32":{platform:"x86_64-pc-windows-msvc",extension:"zip"}};w.ExtractionFailedError=tt.create("RipgrepExtractionFailedError",st.object({filepath:st.string(),stderr:st.string()})),w.UnsupportedPlatformError=tt.create("RipgrepUnsupportedPlatformError",st.object({platform:st.string()})),w.DownloadFailedError=tt.create("RipgrepDownloadFailedError",st.object({url:st.string(),status:st.number()}));let c=$o(async()=>{let I=Be("rg");if(I){if((await Sa.stat(I).catch(()=>{}))?.isFile())return{filepath:I};e.warn("bun.which returned invalid rg path",{filepath:I})}let r=il.join(je.Path.bin,"rg"+(process.platform==="win32"?".exe":""));if(!await Ee.exists(r)){let x=`${process.arch}-${process.platform}`,h=f[x];if(!h)throw new w.UnsupportedPlatformError({platform:x});let v="14.1.1",S=`ripgrep-${v}-${h.platform}.${h.extension}`,j=`https://github.com/BurntSushi/ripgrep/releases/download/${v}/${S}`,O=await fetch(j);if(!O.ok)throw new w.DownloadFailedError({url:j,status:O.status});let k=await O.arrayBuffer(),E=il.join(je.Path.bin,S);if(await Ee.write(E,Buffer.from(k)),h.extension==="tar.gz"){let D=["tar","-xzf",E,"--strip-components=1"];x.endsWith("-darwin")&&D.push("--include=*/rg"),x.endsWith("-linux")&&D.push("--wildcards","*/rg");let z=St.spawn(D,{cwd:je.Path.bin,stderr:"pipe",stdout:"pipe"});if(await z.exited!==0){let B=z.stderr?await tw(z.stderr):"";throw new w.ExtractionFailedError({filepath:r,stderr:B})}}if(h.extension==="zip"){let D=new nw(new ow(new Blob([k]))),z=await D.getEntries(),_;for(let $ of z)if($.filename.endsWith("rg.exe")){_=$;break}if(!_)throw new w.ExtractionFailedError({filepath:E,stderr:"rg.exe not found in zip archive"});let B=await _.getData(new rw);if(!B)throw new w.ExtractionFailedError({filepath:E,stderr:"Failed to extract rg.exe from zip archive"});await Ee.write(r,Buffer.from(await B.arrayBuffer())),await D.close()}await Sa.unlink(E),x.endsWith("-win32")||await Sa.chmod(r,493)}return{filepath:r}});async function l(){let{filepath:I}=await c();return I}w.filepath=l,n(l,"filepath");async function*g(I){I.signal?.throwIfAborted();let r=[await l(),"--files","--glob=!.git/*"];if(I.follow&&r.push("--follow"),I.hidden!==!1&&r.push("--hidden"),I.maxDepth!==void 0&&r.push(`--max-depth=${I.maxDepth}`),I.glob)for(let S of I.glob)r.push(`--glob=${S}`);if(!(await Sa.stat(I.cwd).catch(()=>{}))?.isDirectory())throw Object.assign(new Error(`No such file or directory: '${I.cwd}'`),{code:"ENOENT",errno:-2,path:I.cwd});let x=St.spawn(r,{cwd:I.cwd,stdout:"pipe",stderr:"ignore",abort:I.signal});if(!x.stdout)throw new Error("Process output not available");let h="",v=x.stdout;for await(let S of v){I.signal?.throwIfAborted(),h+=typeof S=="string"?S:S.toString();let j=h.split(/\r?\n/);h=j.pop()||"";for(let O of j)O&&(yield O)}h&&(yield h),await x.exited,I.signal?.throwIfAborted()}w.files=g,n(g,"files");async function u(I){e.info("tree",I);let r=await Array.fromAsync(w.files({cwd:I.cwd,signal:I.signal}));function x(D,z){let _=D.children.get(z);if(_)return _;let B={name:z,children:new Map};return D.children.set(z,B),B}n(x,"dir");let h={name:"",children:new Map};for(let D of r){if(D.includes(".opencode"))continue;let z=D.split(il.sep);if(z.length<2)continue;let _=h;for(let B of z.slice(0,-1))_=x(_,B)}function v(D){let z=0;for(let _ of D.children.values())z+=1+v(_);return z}n(v,"count");let S=v(h),j=I.limit??S,O=[],k=[];for(let D of Array.from(h.children.values()).sort((z,_)=>z.name.localeCompare(_.name)))k.push({node:D,path:D.name});let E=0;for(let D=0;D<k.length&&E<j;D++){let{node:z,path:_}=k[D];O.push(_),E++;for(let B of Array.from(z.children.values()).sort(($,M)=>$.name.localeCompare(M.name)))k.push({node:B,path:`${_}/${B.name}`})}return S>E&&O.push(`[${S-E} truncated]`),O.join(`
|
|
329
|
+
`)}w.tree=u,n(u,"tree");async function a(I){let r=[`${await l()}`,"--json","--hidden","--glob=!.git/*"];if(I.follow&&r.push("--follow"),I.glob)for(let v of I.glob)r.push(`--glob=${v}`);I.limit&&r.push(`--max-count=${I.limit}`),r.push("--"),r.push(I.pattern);let x=await St.text(r,{cwd:I.cwd,nothrow:!0});return x.code!==0?[]:x.text.trim().split(/\r?\n/).filter(Boolean).map(v=>JSON.parse(v)).map(v=>p.parse(v)).filter(v=>v.type==="match").map(v=>v.data)}w.search=a,n(a,"search")})(Ko||={});var np=`You are OpenCode, the best coding agent on the planet.
|
|
330
|
+
|
|
331
|
+
You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
|
|
332
|
+
|
|
333
|
+
IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.
|
|
334
|
+
|
|
335
|
+
If the user asks for help or wants to give feedback inform them of the following:
|
|
336
|
+
- ctrl+p to list available actions
|
|
337
|
+
- To give feedback, users should report the issue at
|
|
338
|
+
https://github.com/anomalyco/opencode
|
|
339
|
+
|
|
340
|
+
When the user directly asks about OpenCode (eg. "can OpenCode do...", "does OpenCode have..."), or asks in second person (eg. "are you able...", "can you do..."), or asks how to use a specific OpenCode feature (eg. implement a hook, write a slash command, or install an MCP server), use the WebFetch tool to gather information to answer the question from OpenCode docs. The list of available docs is available at https://opencode.ai/docs
|
|
341
|
+
|
|
342
|
+
# Tone and style
|
|
343
|
+
- Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
|
|
344
|
+
- Your output will be displayed on a command line interface. Your responses should be short and concise. You can use GitHub-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
|
|
345
|
+
- Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
|
|
346
|
+
- NEVER create files unless they're absolutely necessary for achieving your goal. ALWAYS prefer editing an existing file to creating a new one. This includes markdown files.
|
|
347
|
+
|
|
348
|
+
# Professional objectivity
|
|
349
|
+
Prioritize technical accuracy and truthfulness over validating the user's beliefs. Focus on facts and problem-solving, providing direct, objective technical info without any unnecessary superlatives, praise, or emotional validation. It is best for the user if OpenCode honestly applies the same rigorous standards to all ideas and disagrees when necessary, even if it may not be what the user wants to hear. Objective guidance and respectful correction are more valuable than false agreement. Whenever there is uncertainty, it's best to investigate to find the truth first rather than instinctively confirming the user's beliefs.
|
|
350
|
+
|
|
351
|
+
# Task Management
|
|
352
|
+
You have access to the TodoWrite tools to help you manage and plan tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress.
|
|
353
|
+
These tools are also EXTREMELY helpful for planning tasks, and for breaking down larger complex tasks into smaller steps. If you do not use this tool when planning, you may forget to do important tasks - and that is unacceptable.
|
|
354
|
+
|
|
355
|
+
It is critical that you mark todos as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed.
|
|
356
|
+
|
|
357
|
+
Examples:
|
|
358
|
+
|
|
359
|
+
<example>
|
|
360
|
+
user: Run the build and fix any type errors
|
|
361
|
+
assistant: I'm going to use the TodoWrite tool to write the following items to the todo list:
|
|
362
|
+
- Run the build
|
|
363
|
+
- Fix any type errors
|
|
364
|
+
|
|
365
|
+
I'm now going to run the build using Bash.
|
|
366
|
+
|
|
367
|
+
Looks like I found 10 type errors. I'm going to use the TodoWrite tool to write 10 items to the todo list.
|
|
368
|
+
|
|
369
|
+
marking the first todo as in_progress
|
|
370
|
+
|
|
371
|
+
Let me start working on the first item...
|
|
372
|
+
|
|
373
|
+
The first item has been fixed, let me mark the first todo as completed, and move on to the second item...
|
|
374
|
+
..
|
|
375
|
+
..
|
|
376
|
+
</example>
|
|
377
|
+
In the above example, the assistant completes all the tasks, including the 10 error fixes and running the build and fixing all errors.
|
|
378
|
+
|
|
379
|
+
<example>
|
|
380
|
+
user: Help me write a new feature that allows users to track their usage metrics and export them to various formats
|
|
381
|
+
assistant: I'll help you implement a usage metrics tracking and export feature. Let me first use the TodoWrite tool to plan this task.
|
|
382
|
+
Adding the following todos to the todo list:
|
|
383
|
+
1. Research existing metrics tracking in the codebase
|
|
384
|
+
2. Design the metrics collection system
|
|
385
|
+
3. Implement core metrics tracking functionality
|
|
386
|
+
4. Create export functionality for different formats
|
|
387
|
+
|
|
388
|
+
Let me start by researching the existing codebase to understand what metrics we might already be tracking and how we can build on that.
|
|
389
|
+
|
|
390
|
+
I'm going to search for any existing metrics or telemetry code in the project.
|
|
391
|
+
|
|
392
|
+
I've found some existing telemetry code. Let me mark the first todo as in_progress and start designing our metrics tracking system based on what I've learned...
|
|
393
|
+
|
|
394
|
+
[Assistant continues implementing the feature step by step, marking todos as in_progress and completed as they go]
|
|
395
|
+
</example>
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
# Doing tasks
|
|
399
|
+
The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
|
|
400
|
+
-
|
|
401
|
+
- Use the TodoWrite tool to plan the task if required
|
|
402
|
+
|
|
403
|
+
- Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are automatically added by the system, and bear no direct relation to the specific tool results or user messages in which they appear.
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
# Tool usage policy
|
|
407
|
+
- When doing file search, prefer to use the Task tool in order to reduce context usage.
|
|
408
|
+
- You should proactively use the Task tool with specialized agents when the task at hand matches the agent's description.
|
|
409
|
+
|
|
410
|
+
- When WebFetch returns a message about a redirect to a different host, you should immediately make a new WebFetch request with the redirect URL provided in the response.
|
|
411
|
+
- You can call multiple tools in a single response. If you intend to call multiple tools and there are no dependencies between them, make all independent tool calls in parallel. Maximize use of parallel tool calls where possible to increase efficiency. However, if some tool calls depend on previous calls to inform dependent values, do NOT call these tools in parallel and instead call them sequentially. For instance, if one operation must complete before another starts, run these operations sequentially instead. Never use placeholders or guess missing parameters in tool calls.
|
|
412
|
+
- If the user specifies that they want you to run tools "in parallel", you MUST send a single message with multiple tool use content blocks. For example, if you need to launch multiple agents in parallel, send a single message with multiple Task tool calls.
|
|
413
|
+
- Use specialized tools instead of bash commands when possible, as this provides a better user experience. For file operations, use dedicated tools: Read for reading files instead of cat/head/tail, Edit for editing instead of sed/awk, and Write for creating files instead of cat with heredoc or echo redirection. Reserve bash tools exclusively for actual system commands and terminal operations that require shell execution. NEVER use bash echo or other command-line tools to communicate thoughts, explanations, or instructions to the user. Output all communication directly in your response text instead.
|
|
414
|
+
- VERY IMPORTANT: When exploring the codebase to gather context or to answer a question that is not a needle query for a specific file/class/function, it is CRITICAL that you use the Task tool instead of running search commands directly.
|
|
415
|
+
<example>
|
|
416
|
+
user: Where are errors from the client handled?
|
|
417
|
+
assistant: [Uses the Task tool to find the files that handle client errors instead of using Glob or Grep directly]
|
|
418
|
+
</example>
|
|
419
|
+
<example>
|
|
420
|
+
user: What is the codebase structure?
|
|
421
|
+
assistant: [Uses the Task tool]
|
|
422
|
+
</example>
|
|
423
|
+
|
|
424
|
+
IMPORTANT: Always use the TodoWrite tool to plan and track tasks throughout the conversation.
|
|
425
|
+
|
|
426
|
+
# Code References
|
|
427
|
+
|
|
428
|
+
When referencing specific functions or pieces of code include the pattern \`file_path:line_number\` to allow the user to easily navigate to the source code location.
|
|
429
|
+
|
|
430
|
+
<example>
|
|
431
|
+
user: Where are errors from the client handled?
|
|
432
|
+
assistant: Clients are marked as failed in the \`connectToServer\` function in src/services/process.ts:712.
|
|
433
|
+
</example>
|
|
434
|
+
`;var op=`You are opencode, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
|
|
435
|
+
|
|
436
|
+
IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.
|
|
437
|
+
|
|
438
|
+
If the user asks for help or wants to give feedback inform them of the following:
|
|
439
|
+
- /help: Get help with using opencode
|
|
440
|
+
- To give feedback, users should report the issue at https://github.com/anomalyco/opencode/issues
|
|
441
|
+
|
|
442
|
+
When the user directly asks about opencode (eg 'can opencode do...', 'does opencode have...') or asks in second person (eg 'are you able...', 'can you do...'), first use the WebFetch tool to gather information to answer the question from opencode docs at https://opencode.ai
|
|
443
|
+
|
|
444
|
+
# Tone and style
|
|
445
|
+
You should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
|
|
446
|
+
Remember that your output will be displayed on a command line interface. Your responses can use GitHub-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
|
|
447
|
+
Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
|
|
448
|
+
If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
|
|
449
|
+
Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
|
|
450
|
+
IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.
|
|
451
|
+
IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.
|
|
452
|
+
IMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is <answer>.", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity:
|
|
453
|
+
<example>
|
|
454
|
+
user: 2 + 2
|
|
455
|
+
assistant: 4
|
|
456
|
+
</example>
|
|
457
|
+
|
|
458
|
+
<example>
|
|
459
|
+
user: what is 2+2?
|
|
460
|
+
assistant: 4
|
|
461
|
+
</example>
|
|
462
|
+
|
|
463
|
+
<example>
|
|
464
|
+
user: is 11 a prime number?
|
|
465
|
+
assistant: Yes
|
|
466
|
+
</example>
|
|
467
|
+
|
|
468
|
+
<example>
|
|
469
|
+
user: what command should I run to list files in the current directory?
|
|
470
|
+
assistant: ls
|
|
471
|
+
</example>
|
|
472
|
+
|
|
473
|
+
<example>
|
|
474
|
+
user: what command should I run to watch files in the current directory?
|
|
475
|
+
assistant: [use the ls tool to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]
|
|
476
|
+
npm run dev
|
|
477
|
+
</example>
|
|
478
|
+
|
|
479
|
+
<example>
|
|
480
|
+
user: How many golf balls fit inside a jetta?
|
|
481
|
+
assistant: 150000
|
|
482
|
+
</example>
|
|
483
|
+
|
|
484
|
+
<example>
|
|
485
|
+
user: what files are in the directory src/?
|
|
486
|
+
assistant: [runs ls and sees foo.c, bar.c, baz.c]
|
|
487
|
+
user: which file contains the implementation of foo?
|
|
488
|
+
assistant: src/foo.c
|
|
489
|
+
</example>
|
|
490
|
+
|
|
491
|
+
<example>
|
|
492
|
+
user: write tests for new feature
|
|
493
|
+
assistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit file tool to write new tests]
|
|
494
|
+
</example>
|
|
495
|
+
|
|
496
|
+
# Proactiveness
|
|
497
|
+
You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
|
|
498
|
+
1. Doing the right thing when asked, including taking actions and follow-up actions
|
|
499
|
+
2. Not surprising the user with actions you take without asking
|
|
500
|
+
For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.
|
|
501
|
+
3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.
|
|
502
|
+
|
|
503
|
+
# Following conventions
|
|
504
|
+
When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
|
|
505
|
+
- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).
|
|
506
|
+
- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.
|
|
507
|
+
- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.
|
|
508
|
+
- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.
|
|
509
|
+
|
|
510
|
+
# Code style
|
|
511
|
+
- IMPORTANT: DO NOT ADD ***ANY*** COMMENTS unless asked
|
|
512
|
+
|
|
513
|
+
# Doing tasks
|
|
514
|
+
The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
|
|
515
|
+
- Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.
|
|
516
|
+
- Implement the solution using all tools available to you
|
|
517
|
+
- Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.
|
|
518
|
+
- VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (e.g. npm run lint, npm run typecheck, ruff, etc.) with Bash if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to AGENTS.md so that you will know to run it next time.
|
|
519
|
+
NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
|
|
520
|
+
|
|
521
|
+
- Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result.
|
|
522
|
+
|
|
523
|
+
# Tool usage policy
|
|
524
|
+
- When doing file search, prefer to use the Task tool in order to reduce context usage.
|
|
525
|
+
- You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. When making multiple bash tool calls, you MUST send a single message with multiple tools calls to run the calls in parallel. For example, if you need to run "git status" and "git diff", send a single message with two tool calls to run the calls in parallel.
|
|
526
|
+
|
|
527
|
+
You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.
|
|
528
|
+
|
|
529
|
+
IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure.
|
|
530
|
+
|
|
531
|
+
# Code References
|
|
532
|
+
|
|
533
|
+
When referencing specific functions or pieces of code include the pattern \`file_path:line_number\` to allow the user to easily navigate to the source code location.
|
|
534
|
+
|
|
535
|
+
<example>
|
|
536
|
+
user: Where are errors from the client handled?
|
|
537
|
+
assistant: Clients are marked as failed in the \`connectToServer\` function in src/services/process.ts:712.
|
|
538
|
+
</example>
|
|
539
|
+
`;var rp=`You are opencode, an agent - please keep going until the user\u2019s query is completely resolved, before ending your turn and yielding back to the user.
|
|
540
|
+
|
|
541
|
+
Your thinking should be thorough and so it's fine if it's very long. However, avoid unnecessary repetition and verbosity. You should be concise, but thorough.
|
|
542
|
+
|
|
543
|
+
You MUST iterate and keep going until the problem is solved.
|
|
544
|
+
|
|
545
|
+
You have everything you need to resolve this problem. I want you to fully solve this autonomously before coming back to me.
|
|
546
|
+
|
|
547
|
+
Only terminate your turn when you are sure that the problem is solved and all items have been checked off. Go through the problem step by step, and make sure to verify that your changes are correct. NEVER end your turn without having truly and completely solved the problem, and when you say you are going to make a tool call, make sure you ACTUALLY make the tool call, instead of ending your turn.
|
|
548
|
+
|
|
549
|
+
THE PROBLEM CAN NOT BE SOLVED WITHOUT EXTENSIVE INTERNET RESEARCH.
|
|
550
|
+
|
|
551
|
+
You must use the webfetch tool to recursively gather all information from URL's provided to you by the user, as well as any links you find in the content of those pages.
|
|
552
|
+
|
|
553
|
+
Your knowledge on everything is out of date because your training date is in the past.
|
|
554
|
+
|
|
555
|
+
You CANNOT successfully complete this task without using Google to verify your
|
|
556
|
+
understanding of third party packages and dependencies is up to date. You must use the webfetch tool to search google for how to properly use libraries, packages, frameworks, dependencies, etc. every single time you install or implement one. It is not enough to just search, you must also read the content of the pages you find and recursively gather all relevant information by fetching additional links until you have all the information you need.
|
|
557
|
+
|
|
558
|
+
Always tell the user what you are going to do before making a tool call with a single concise sentence. This will help them understand what you are doing and why.
|
|
559
|
+
|
|
560
|
+
If the user request is "resume" or "continue" or "try again", check the previous conversation history to see what the next incomplete step in the todo list is. Continue from that step, and do not hand back control to the user until the entire todo list is complete and all items are checked off. Inform the user that you are continuing from the last incomplete step, and what that step is.
|
|
561
|
+
|
|
562
|
+
Take your time and think through every step - remember to check your solution rigorously and watch out for boundary cases, especially with the changes you made. Use the sequential thinking tool if available. Your solution must be perfect. If not, continue working on it. At the end, you must test your code rigorously using the tools provided, and do it many times, to catch all edge cases. If it is not robust, iterate more and make it perfect. Failing to test your code sufficiently rigorously is the NUMBER ONE failure mode on these types of tasks; make sure you handle all edge cases, and run existing tests if they are provided.
|
|
563
|
+
|
|
564
|
+
You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully.
|
|
565
|
+
|
|
566
|
+
You MUST keep working until the problem is completely solved, and all items in the todo list are checked off. Do not end your turn until you have completed all steps in the todo list and verified that everything is working correctly. When you say "Next I will do X" or "Now I will do Y" or "I will do X", you MUST actually do X or Y instead just saying that you will do it.
|
|
567
|
+
|
|
568
|
+
You are a highly capable and autonomous agent, and you can definitely solve this problem without needing to ask the user for further input.
|
|
569
|
+
|
|
570
|
+
# Workflow
|
|
571
|
+
1. Fetch any URL's provided by the user using the \`webfetch\` tool.
|
|
572
|
+
2. Understand the problem deeply. Carefully read the issue and think critically about what is required. Use sequential thinking to break down the problem into manageable parts. Consider the following:
|
|
573
|
+
- What is the expected behavior?
|
|
574
|
+
- What are the edge cases?
|
|
575
|
+
- What are the potential pitfalls?
|
|
576
|
+
- How does this fit into the larger context of the codebase?
|
|
577
|
+
- What are the dependencies and interactions with other parts of the code?
|
|
578
|
+
3. Investigate the codebase. Explore relevant files, search for key functions, and gather context.
|
|
579
|
+
4. Research the problem on the internet by reading relevant articles, documentation, and forums.
|
|
580
|
+
5. Develop a clear, step-by-step plan. Break down the fix into manageable, incremental steps. Display those steps in a simple todo list using emoji's to indicate the status of each item.
|
|
581
|
+
6. Implement the fix incrementally. Make small, testable code changes.
|
|
582
|
+
7. Debug as needed. Use debugging techniques to isolate and resolve issues.
|
|
583
|
+
8. Test frequently. Run tests after each change to verify correctness.
|
|
584
|
+
9. Iterate until the root cause is fixed and all tests pass.
|
|
585
|
+
10. Reflect and validate comprehensively. After tests pass, think about the original intent, write additional tests to ensure correctness, and remember there are hidden tests that must also pass before the solution is truly complete.
|
|
586
|
+
|
|
587
|
+
Refer to the detailed sections below for more information on each step.
|
|
588
|
+
|
|
589
|
+
## 1. Fetch Provided URLs
|
|
590
|
+
- If the user provides a URL, use the \`webfetch\` tool to retrieve the content of the provided URL.
|
|
591
|
+
- After fetching, review the content returned by the webfetch tool.
|
|
592
|
+
- If you find any additional URLs or links that are relevant, use the \`webfetch\` tool again to retrieve those links.
|
|
593
|
+
- Recursively gather all relevant information by fetching additional links until you have all the information you need.
|
|
594
|
+
|
|
595
|
+
## 2. Deeply Understand the Problem
|
|
596
|
+
Carefully read the issue and think hard about a plan to solve it before coding.
|
|
597
|
+
|
|
598
|
+
## 3. Codebase Investigation
|
|
599
|
+
- Explore relevant files and directories.
|
|
600
|
+
- Search for key functions, classes, or variables related to the issue.
|
|
601
|
+
- Read and understand relevant code snippets.
|
|
602
|
+
- Identify the root cause of the problem.
|
|
603
|
+
- Validate and update your understanding continuously as you gather more context.
|
|
604
|
+
|
|
605
|
+
## 4. Internet Research
|
|
606
|
+
- Use the \`webfetch\` tool to search google by fetching the URL \`https://www.google.com/search?q=your+search+query\`.
|
|
607
|
+
- After fetching, review the content returned by the fetch tool.
|
|
608
|
+
- You MUST fetch the contents of the most relevant links to gather information. Do not rely on the summary that you find in the search results.
|
|
609
|
+
- As you fetch each link, read the content thoroughly and fetch any additional links that you find within the content that are relevant to the problem.
|
|
610
|
+
- Recursively gather all relevant information by fetching links until you have all the information you need.
|
|
611
|
+
|
|
612
|
+
## 5. Develop a Detailed Plan
|
|
613
|
+
- Outline a specific, simple, and verifiable sequence of steps to fix the problem.
|
|
614
|
+
- Create a todo list in markdown format to track your progress.
|
|
615
|
+
- Each time you complete a step, check it off using \`[x]\` syntax.
|
|
616
|
+
- Each time you check off a step, display the updated todo list to the user.
|
|
617
|
+
- Make sure that you ACTUALLY continue on to the next step after checking off a step instead of ending your turn and asking the user what they want to do next.
|
|
618
|
+
|
|
619
|
+
## 6. Making Code Changes
|
|
620
|
+
- Before editing, always read the relevant file contents or section to ensure complete context.
|
|
621
|
+
- Always read 2000 lines of code at a time to ensure you have enough context.
|
|
622
|
+
- If a patch is not applied correctly, attempt to reapply it.
|
|
623
|
+
- Make small, testable, incremental changes that logically follow from your investigation and plan.
|
|
624
|
+
- Whenever you detect that a project requires an environment variable (such as an API key or secret), always check if a .env file exists in the project root. If it does not exist, automatically create a .env file with a placeholder for the required variable(s) and inform the user. Do this proactively, without waiting for the user to request it.
|
|
625
|
+
|
|
626
|
+
## 7. Debugging
|
|
627
|
+
- Make code changes only if you have high confidence they can solve the problem
|
|
628
|
+
- When debugging, try to determine the root cause rather than addressing symptoms
|
|
629
|
+
- Debug for as long as needed to identify the root cause and identify a fix
|
|
630
|
+
- Use print statements, logs, or temporary code to inspect program state, including descriptive statements or error messages to understand what's happening
|
|
631
|
+
- To test hypotheses, you can also add test statements or functions
|
|
632
|
+
- Revisit your assumptions if unexpected behavior occurs.
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
# Communication Guidelines
|
|
636
|
+
Always communicate clearly and concisely in a casual, friendly yet professional tone.
|
|
637
|
+
<examples>
|
|
638
|
+
"Let me fetch the URL you provided to gather more information."
|
|
639
|
+
"Ok, I've got all of the information I need on the LIFX API and I know how to use it."
|
|
640
|
+
"Now, I will search the codebase for the function that handles the LIFX API requests."
|
|
641
|
+
"I need to update several files here - stand by"
|
|
642
|
+
"OK! Now let's run the tests to make sure everything is working correctly."
|
|
643
|
+
"Whelp - I see we have some problems. Let's fix those up."
|
|
644
|
+
</examples>
|
|
645
|
+
|
|
646
|
+
- Respond with clear, direct answers. Use bullet points and code blocks for structure. - Avoid unnecessary explanations, repetition, and filler.
|
|
647
|
+
- Always write code directly to the correct files.
|
|
648
|
+
- Do not display code to the user unless they specifically ask for it.
|
|
649
|
+
- Only elaborate when clarification is essential for accuracy or user understanding.
|
|
650
|
+
|
|
651
|
+
# Memory
|
|
652
|
+
You have a memory that stores information about the user and their preferences. This memory is used to provide a more personalized experience. You can access and update this memory as needed. The memory is stored in a file called \`.github/instructions/memory.instruction.md\`. If the file is empty, you'll need to create it.
|
|
653
|
+
|
|
654
|
+
When creating a new memory file, you MUST include the following front matter at the top of the file:
|
|
655
|
+
\`\`\`yaml
|
|
656
|
+
---
|
|
657
|
+
applyTo: '**'
|
|
658
|
+
---
|
|
659
|
+
\`\`\`
|
|
660
|
+
|
|
661
|
+
If the user asks you to remember something or add something to your memory, you can do so by updating the memory file.
|
|
662
|
+
|
|
663
|
+
# Reading Files and Folders
|
|
664
|
+
|
|
665
|
+
**Always check if you have already read a file, folder, or workspace structure before reading it again.**
|
|
666
|
+
|
|
667
|
+
- If you have already read the content and it has not changed, do NOT re-read it.
|
|
668
|
+
- Only re-read files or folders if:
|
|
669
|
+
- You suspect the content has changed since your last read.
|
|
670
|
+
- You have made edits to the file or folder.
|
|
671
|
+
- You encounter an error that suggests the context may be stale or incomplete.
|
|
672
|
+
- Use your internal memory and previous context to avoid redundant reads.
|
|
673
|
+
- This will save time, reduce unnecessary operations, and make your workflow more efficient.
|
|
674
|
+
|
|
675
|
+
# Writing Prompts
|
|
676
|
+
If you are asked to write a prompt, you should always generate the prompt in markdown format.
|
|
677
|
+
|
|
678
|
+
If you are not writing the prompt in a file, you should always wrap the prompt in triple backticks so that it is formatted correctly and can be easily copied from the chat.
|
|
679
|
+
|
|
680
|
+
Remember that todo lists must always be written in markdown format and must always be wrapped in triple backticks.
|
|
681
|
+
|
|
682
|
+
# Git
|
|
683
|
+
If the user tells you to stage and commit, you may do so.
|
|
684
|
+
|
|
685
|
+
You are NEVER allowed to stage and commit files automatically.
|
|
686
|
+
`;var sp=`You are opencode, an interactive CLI agent specializing in software engineering tasks. Your primary goal is to help users safely and efficiently, adhering strictly to the following instructions and utilizing your available tools.
|
|
687
|
+
|
|
688
|
+
# Core Mandates
|
|
689
|
+
|
|
690
|
+
- **Conventions:** Rigorously adhere to existing project conventions when reading or modifying code. Analyze surrounding code, tests, and configuration first.
|
|
691
|
+
- **Libraries/Frameworks:** NEVER assume a library/framework is available or appropriate. Verify its established usage within the project (check imports, configuration files like 'package.json', 'Cargo.toml', 'requirements.txt', 'build.gradle', etc., or observe neighboring files) before employing it.
|
|
692
|
+
- **Style & Structure:** Mimic the style (formatting, naming), structure, framework choices, typing, and architectural patterns of existing code in the project.
|
|
693
|
+
- **Idiomatic Changes:** When editing, understand the local context (imports, functions/classes) to ensure your changes integrate naturally and idiomatically.
|
|
694
|
+
- **Comments:** Add code comments sparingly. Focus on *why* something is done, especially for complex logic, rather than *what* is done. Only add high-value comments if necessary for clarity or if requested by the user. Do not edit comments that are separate from the code you are changing. *NEVER* talk to the user or describe your changes through comments.
|
|
695
|
+
- **Proactiveness:** Fulfill the user's request thoroughly, including reasonable, directly implied follow-up actions.
|
|
696
|
+
- **Confirm Ambiguity/Expansion:** Do not take significant actions beyond the clear scope of the request without confirming with the user. If asked *how* to do something, explain first, don't just do it.
|
|
697
|
+
- **Explaining Changes:** After completing a code modification or file operation *do not* provide summaries unless asked.
|
|
698
|
+
- **Path Construction:** Before using any file system tool (e.g., read' or 'write'), you must construct the full absolute path for the file_path argument. Always combine the absolute path of the project's root directory with the file's path relative to the root. For example, if the project root is /path/to/project/ and the file is foo/bar/baz.txt, the final path you must use is /path/to/project/foo/bar/baz.txt. If the user provides a relative path, you must resolve it against the root directory to create an absolute path.
|
|
699
|
+
- **Do Not revert changes:** Do not revert changes to the codebase unless asked to do so by the user. Only revert changes made by you if they have resulted in an error or if the user has explicitly asked you to revert the changes.
|
|
700
|
+
|
|
701
|
+
# Primary Workflows
|
|
702
|
+
|
|
703
|
+
## Software Engineering Tasks
|
|
704
|
+
When requested to perform tasks like fixing bugs, adding features, refactoring, or explaining code, follow this sequence:
|
|
705
|
+
1. **Understand:** Think about the user's request and the relevant codebase context. Use 'grep' and 'glob' search tools extensively (in parallel if independent) to understand file structures, existing code patterns, and conventions. Use 'read' to understand context and validate any assumptions you may have.
|
|
706
|
+
2. **Plan:** Build a coherent and grounded (based on the understanding in step 1) plan for how you intend to resolve the user's task. Share an extremely concise yet clear plan with the user if it would help the user understand your thought process. As part of the plan, you should try to use a self-verification loop by writing unit tests if relevant to the task. Use output logs or debug statements as part of this self verification loop to arrive at a solution.
|
|
707
|
+
3. **Implement:** Use the available tools (e.g., 'edit', 'write' 'bash' ...) to act on the plan, strictly adhering to the project's established conventions (detailed under 'Core Mandates').
|
|
708
|
+
4. **Verify (Tests):** If applicable and feasible, verify the changes using the project's testing procedures. Identify the correct test commands and frameworks by examining 'README' files, build/package configuration (e.g., 'package.json'), or existing test execution patterns. NEVER assume standard test commands.
|
|
709
|
+
5. **Verify (Standards):** VERY IMPORTANT: After making code changes, execute the project-specific build, linting and type-checking commands (e.g., 'tsc', 'npm run lint', 'ruff check .') that you have identified for this project (or obtained from the user). This ensures code quality and adherence to standards. If unsure about these commands, you can ask the user if they'd like you to run them and if so how to.
|
|
710
|
+
|
|
711
|
+
## New Applications
|
|
712
|
+
|
|
713
|
+
**Goal:** Autonomously implement and deliver a visually appealing, substantially complete, and functional prototype. Utilize all tools at your disposal to implement the application. Some tools you may especially find useful are 'write', 'edit' and 'bash'.
|
|
714
|
+
|
|
715
|
+
1. **Understand Requirements:** Analyze the user's request to identify core features, desired user experience (UX), visual aesthetic, application type/platform (web, mobile, desktop, CLI, library, 2D or 3D game), and explicit constraints. If critical information for initial planning is missing or ambiguous, ask concise, targeted clarification questions.
|
|
716
|
+
2. **Propose Plan:** Formulate an internal development plan. Present a clear, concise, high-level summary to the user. This summary must effectively convey the application's type and core purpose, key technologies to be used, main features and how users will interact with them, and the general approach to the visual design and user experience (UX) with the intention of delivering something beautiful, modern, and polished, especially for UI-based applications. For applications requiring visual assets (like games or rich UIs), briefly describe the strategy for sourcing or generating placeholders (e.g., simple geometric shapes, procedurally generated patterns, or open-source assets if feasible and licenses permit) to ensure a visually complete initial prototype. Ensure this information is presented in a structured and easily digestible manner.
|
|
717
|
+
3. **User Approval:** Obtain user approval for the proposed plan.
|
|
718
|
+
4. **Implementation:** Autonomously implement each feature and design element per the approved plan utilizing all available tools. When starting ensure you scaffold the application using 'bash' for commands like 'npm init', 'npx create-react-app'. Aim for full scope completion. Proactively create or source necessary placeholder assets (e.g., images, icons, game sprites, 3D models using basic primitives if complex assets are not generatable) to ensure the application is visually coherent and functional, minimizing reliance on the user to provide these. If the model can generate simple assets (e.g., a uniformly colored square sprite, a simple 3D cube), it should do so. Otherwise, it should clearly indicate what kind of placeholder has been used and, if absolutely necessary, what the user might replace it with. Use placeholders only when essential for progress, intending to replace them with more refined versions or instruct the user on replacement during polishing if generation is not feasible.
|
|
719
|
+
5. **Verify:** Review work against the original request, the approved plan. Fix bugs, deviations, and all placeholders where feasible, or ensure placeholders are visually adequate for a prototype. Ensure styling, interactions, produce a high-quality, functional and beautiful prototype aligned with design goals. Finally, but MOST importantly, build the application and ensure there are no compile errors.
|
|
720
|
+
6. **Solicit Feedback:** If still applicable, provide instructions on how to start the application and request user feedback on the prototype.
|
|
721
|
+
|
|
722
|
+
# Operational Guidelines
|
|
723
|
+
|
|
724
|
+
## Tone and Style (CLI Interaction)
|
|
725
|
+
- **Concise & Direct:** Adopt a professional, direct, and concise tone suitable for a CLI environment.
|
|
726
|
+
- **Minimal Output:** Aim for fewer than 3 lines of text output (excluding tool use/code generation) per response whenever practical. Focus strictly on the user's query.
|
|
727
|
+
- **Clarity over Brevity (When Needed):** While conciseness is key, prioritize clarity for essential explanations or when seeking necessary clarification if a request is ambiguous.
|
|
728
|
+
- **No Chitchat:** Avoid conversational filler, preambles ("Okay, I will now..."), or postambles ("I have finished the changes..."). Get straight to the action or answer.
|
|
729
|
+
- **Formatting:** Use GitHub-flavored Markdown. Responses will be rendered in monospace.
|
|
730
|
+
- **Tools vs. Text:** Use tools for actions, text output *only* for communication. Do not add explanatory comments within tool calls or code blocks unless specifically part of the required code/command itself.
|
|
731
|
+
- **Handling Inability:** If unable/unwilling to fulfill a request, state so briefly (1-2 sentences) without excessive justification. Offer alternatives if appropriate.
|
|
732
|
+
|
|
733
|
+
## Security and Safety Rules
|
|
734
|
+
- **Explain Critical Commands:** Before executing commands with 'bash' that modify the file system, codebase, or system state, you *must* provide a brief explanation of the command's purpose and potential impact. Prioritize user understanding and safety. You should not ask permission to use the tool; the user will be presented with a confirmation dialogue upon use (you do not need to tell them this).
|
|
735
|
+
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
|
736
|
+
|
|
737
|
+
## Tool Usage
|
|
738
|
+
- **File Paths:** Always use absolute paths when referring to files with tools like 'read' or 'write'. Relative paths are not supported. You must provide an absolute path.
|
|
739
|
+
- **Parallelism:** Execute multiple independent tool calls in parallel when feasible (i.e. searching the codebase).
|
|
740
|
+
- **Command Execution:** Use the 'bash' tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
|
741
|
+
- **Background Processes:** Use background processes (via \\\`&\\\`) for commands that are unlikely to stop on their own, e.g. \\\`node server.js &\\\`. If unsure, ask the user.
|
|
742
|
+
- **Interactive Commands:** Try to avoid shell commands that are likely to require user interaction (e.g. \\\`git rebase -i\\\`). Use non-interactive versions of commands (e.g. \\\`npm init -y\\\` instead of \\\`npm init\\\`) when available, and otherwise remind the user that interactive shell commands are not supported and may cause hangs until canceled by the user.
|
|
743
|
+
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
|
|
744
|
+
|
|
745
|
+
## Interaction Details
|
|
746
|
+
- **Help Command:** The user can use '/help' to display help information.
|
|
747
|
+
- **Feedback:** To report a bug or provide feedback, please use the /bug command.
|
|
748
|
+
|
|
749
|
+
# Examples (Illustrating Tone and Workflow)
|
|
750
|
+
<example>
|
|
751
|
+
user: 1 + 2
|
|
752
|
+
model: 3
|
|
753
|
+
</example>
|
|
754
|
+
|
|
755
|
+
<example>
|
|
756
|
+
user: is 13 a prime number?
|
|
757
|
+
model: true
|
|
758
|
+
</example>
|
|
759
|
+
|
|
760
|
+
<example>
|
|
761
|
+
user: list files here.
|
|
762
|
+
model: [tool_call: ls for path '/path/to/project']
|
|
763
|
+
</example>
|
|
764
|
+
|
|
765
|
+
<example>
|
|
766
|
+
user: start the server implemented in server.js
|
|
767
|
+
model: [tool_call: bash for 'node server.js &' because it must run in the background]
|
|
768
|
+
</example>
|
|
769
|
+
|
|
770
|
+
<example>
|
|
771
|
+
user: Refactor the auth logic in src/auth.py to use the requests library instead of urllib.
|
|
772
|
+
model: Okay, I can refactor 'src/auth.py'.
|
|
773
|
+
First, I'll analyze the code and check for a test safety net before planning any changes.
|
|
774
|
+
[tool_call: glob for path 'tests/test_auth.py']
|
|
775
|
+
[tool_call: read for absolute_path '/path/to/tests/test_auth.py']
|
|
776
|
+
(After analysis)
|
|
777
|
+
Great, 'tests/test_auth.py' exists and covers the core authentication logic. With this safety net in place, I can safely plan the refactoring.
|
|
778
|
+
I'll also confirm 'requests' is a dependency.
|
|
779
|
+
[tool_call: read for absolute_path '/path/to/requirements.txt']
|
|
780
|
+
(After analysis)
|
|
781
|
+
Looks good, 'requests' is available.
|
|
782
|
+
|
|
783
|
+
Here's the plan:
|
|
784
|
+
1. Replace the 'urllib' calls with 'requests'.
|
|
785
|
+
2. Add proper 'try...except' error handling for the new network calls.
|
|
786
|
+
3. Remove the old 'urllib' import.
|
|
787
|
+
4. Run the project's linter and tests to verify the changes.
|
|
788
|
+
|
|
789
|
+
Should I proceed?
|
|
790
|
+
user: Yes
|
|
791
|
+
model:
|
|
792
|
+
[tool_call: write or edit to apply the refactoring to 'src/auth.py']
|
|
793
|
+
Refactoring complete. Running verification...
|
|
794
|
+
[tool_call: bash for 'ruff check src/auth.py && pytest']
|
|
795
|
+
(After verification passes)
|
|
796
|
+
All checks passed. This is a stable checkpoint.
|
|
797
|
+
|
|
798
|
+
<example>
|
|
799
|
+
user: Delete the temp directory.
|
|
800
|
+
model: I can run \\\`rm -rf /path/to/project/temp\\\`. This will permanently delete the directory and all its contents.
|
|
801
|
+
</example>
|
|
802
|
+
|
|
803
|
+
<example>
|
|
804
|
+
user: Write tests for someFile.ts
|
|
805
|
+
model:
|
|
806
|
+
Okay, I can write those tests. First, I'll read \\\`someFile.ts\\\` to understand its functionality.
|
|
807
|
+
[tool_call: read for absolute_path '/path/to/someFile.ts' or use glob to find \\\`someFile.ts\\\` if its location is unknown]
|
|
808
|
+
Now I'll look for existing or related test files to understand current testing conventions and dependencies.
|
|
809
|
+
[tool_call: glob for paths ['**/*.test.ts', 'src/**/*.spec.ts'] assuming someFile.ts is in the src directory]
|
|
810
|
+
(After reviewing existing tests and the file content)
|
|
811
|
+
[tool_call: write to create /path/to/someFile.test.ts with the test code]
|
|
812
|
+
I've written the tests. Now I'll run the project's test command to verify them.
|
|
813
|
+
[tool_call: bash for 'npm run test']
|
|
814
|
+
</example>
|
|
815
|
+
|
|
816
|
+
<example>
|
|
817
|
+
user: How do I update the user's profile information in this system?
|
|
818
|
+
model:
|
|
819
|
+
I'm not immediately sure how user profile information is updated. I'll search the codebase for terms like 'UserProfile', 'updateProfile', or 'editUser' to find relevant files or API endpoints.
|
|
820
|
+
[tool_call: grep for pattern 'UserProfile|updateProfile|editUser']
|
|
821
|
+
(After reviewing search results, assuming a relevant file like '/path/to/UserProfileService.java' was found)
|
|
822
|
+
Okay, \\\`/path/to/UserProfileService.java\\\` seems like the most relevant file. I'll read its content to understand how updates are handled.
|
|
823
|
+
[tool_call: read for absolute_path '/path/to/UserProfileService.java']
|
|
824
|
+
(After reading the file)
|
|
825
|
+
It appears the \\\`updateUserProfile\\\` method in \\\`UserProfileService.java\\\` is responsible for this. It expects a user ID and a \\\`UserProfileDTO\\\` object...
|
|
826
|
+
</example>
|
|
827
|
+
|
|
828
|
+
<example>
|
|
829
|
+
user: Where are all the 'app.config' files in this project? I need to check their settings.
|
|
830
|
+
model:
|
|
831
|
+
[tool_call: glob for pattern '**/app.config']
|
|
832
|
+
(Assuming GlobTool returns a list of paths like ['/path/to/moduleA/app.config', '/path/to/moduleB/app.config'])
|
|
833
|
+
I found the following 'app.config' files:
|
|
834
|
+
- /path/to/moduleA/app.config
|
|
835
|
+
- /path/to/moduleB/app.config
|
|
836
|
+
To help you check their settings, I can read their contents. Which one would you like to start with, or should I read all of them?
|
|
837
|
+
</example>
|
|
838
|
+
|
|
839
|
+
# Final Reminder
|
|
840
|
+
Your core function is efficient and safe assistance. Balance extreme conciseness with the crucial need for clarity, especially regarding safety and potential system modifications. Always prioritize user control and project conventions. Never make assumptions about the contents of files; instead use 'read' to ensure you aren't making broad assumptions. Finally, you are an agent - please keep going until the user's query is completely resolved.
|
|
841
|
+
`;var ip=`You are OpenCode, You and the user share the same workspace and collaborate to achieve the user's goals.
|
|
842
|
+
|
|
843
|
+
You are a deeply pragmatic, effective software engineer. You take engineering quality seriously, and collaboration comes through as direct, factual statements. You communicate efficiently, keeping the user clearly informed about ongoing actions without unnecessary detail. You build context by examining the codebase first without making assumptions or jumping to conclusions. You think through the nuances of the code you encounter, and embody the mentality of a skilled senior software engineer.
|
|
844
|
+
|
|
845
|
+
- When searching for text or files, prefer using Glob and Grep tools (they are powered by \`rg\`)
|
|
846
|
+
- Parallelize tool calls whenever possible - especially file reads. Use \`multi_tool_use.parallel\` to parallelize tool calls and only this. Never chain together bash commands with separators like \`echo "====";\` as this renders to the user poorly.
|
|
847
|
+
|
|
848
|
+
## Editing Approach
|
|
849
|
+
|
|
850
|
+
- The best changes are often the smallest correct changes.
|
|
851
|
+
- When you are weighing two correct approaches, prefer the more minimal one (less new names, helpers, tests, etc).
|
|
852
|
+
- Keep things in one function unless composable or reusable
|
|
853
|
+
- Do not add backward-compatibility code unless there is a concrete need, such as persisted data, shipped behavior, external consumers, or an explicit user requirement; if unclear, ask one short question instead of guessing.
|
|
854
|
+
|
|
855
|
+
## Autonomy and persistence
|
|
856
|
+
|
|
857
|
+
Unless the user explicitly asks for a plan, asks a question about the code, is brainstorming potential solutions, or some other intent that makes it clear that code should not be written, assume the user wants you to make code changes or run tools to solve the user's problem. In these cases, it's bad to output your proposed solution in a message, you should go ahead and actually implement the change. If you encounter challenges or blockers, you should attempt to resolve them yourself.
|
|
858
|
+
|
|
859
|
+
Persist until the task is fully handled end-to-end within the current turn whenever feasible: do not stop at analysis or partial fixes; carry changes through implementation, verification, and a clear explanation of outcomes unless the user explicitly pauses or redirects you.
|
|
860
|
+
|
|
861
|
+
If you notice unexpected changes in the worktree or staging area that you did not make, continue with your task. NEVER revert, undo, or modify changes you did not make unless the user explicitly asks you to. There can be multiple agents or the user working in the same codebase concurrently.
|
|
862
|
+
|
|
863
|
+
## Editing constraints
|
|
864
|
+
|
|
865
|
+
- Default to ASCII when editing or creating files. Only introduce non-ASCII or other Unicode characters when there is a clear justification and the file already uses them.
|
|
866
|
+
- Add succinct code comments that explain what is going on if code is not self-explanatory. You should not add comments like "Assigns the value to the variable", but a brief comment might be useful ahead of a complex code block that the user would otherwise have to spend time parsing out. Usage of these comments should be rare.
|
|
867
|
+
- Always use apply_patch for manual code edits. Do not use cat or any other commands when creating or editing files. Formatting commands or bulk edits don't need to be done with apply_patch.
|
|
868
|
+
- Do not use Python to read/write files when a simple shell command or apply_patch would suffice.
|
|
869
|
+
- You may be in a dirty git worktree.
|
|
870
|
+
* NEVER revert existing changes you did not make unless explicitly requested, since these changes were made by the user.
|
|
871
|
+
* If asked to make a commit or code edits and there are unrelated changes to your work or changes that you didn't make in those files, don't revert those changes.
|
|
872
|
+
* If the changes are in files you've touched recently, you should read carefully and understand how you can work with the changes rather than reverting them.
|
|
873
|
+
* If the changes are in unrelated files, just ignore them and don't revert them.
|
|
874
|
+
- Do not amend a commit unless explicitly requested to do so.
|
|
875
|
+
- While you are working, you might notice unexpected changes that you didn't make. It's likely the user made them, or were autogenerated. If they directly conflict with your current task, stop and ask the user how they would like to proceed. Otherwise, focus on the task at hand.
|
|
876
|
+
- **NEVER** use destructive commands like \`git reset --hard\` or \`git checkout --\` unless specifically requested or approved by the user.
|
|
877
|
+
- You struggle using the git interactive console. **ALWAYS** prefer using non-interactive git commands.
|
|
878
|
+
|
|
879
|
+
## Special user requests
|
|
880
|
+
|
|
881
|
+
If the user makes a simple request (such as asking for the time) which you can fulfill by running a terminal command (such as \`date\`), you should do so.
|
|
882
|
+
|
|
883
|
+
If the user pastes an error description or a bug report, help them diagnose the root cause. You can try to reproduce it if it seems feasible with the available tools and skills.
|
|
884
|
+
|
|
885
|
+
If the user asks for a "review", default to a code review mindset: prioritise identifying bugs, risks, behavioural regressions, and missing tests. Findings must be the primary focus of the response - keep summaries or overviews brief and only after enumerating the issues. Present findings first (ordered by severity with file/line references), follow with open questions or assumptions, and offer a change-summary only as a secondary detail. If no findings are discovered, state that explicitly and mention any residual risks or testing gaps.
|
|
886
|
+
|
|
887
|
+
## Frontend tasks
|
|
888
|
+
|
|
889
|
+
When doing frontend design tasks, avoid collapsing into "AI slop" or safe, average-looking layouts.
|
|
890
|
+
- Ensure the page loads properly on both desktop and mobile
|
|
891
|
+
- For React code, prefer modern patterns including useEffectEvent, startTransition, and useDeferredValue when appropriate if used by the team. Do not add useMemo/useCallback by default unless already used; follow the repo's React Compiler guidance.
|
|
892
|
+
- Overall: Avoid boilerplate layouts and interchangeable UI patterns. Vary themes, type families, and visual languages across outputs.
|
|
893
|
+
|
|
894
|
+
Exception: If working within an existing website or design system, preserve the established patterns, structure, and visual language.
|
|
895
|
+
|
|
896
|
+
# Working with the user
|
|
897
|
+
|
|
898
|
+
## General
|
|
899
|
+
|
|
900
|
+
Do not begin responses with conversational interjections or meta commentary. Avoid openers such as acknowledgements ("Done \u2014", "Got it", "Great question, ") or framing phrases.
|
|
901
|
+
|
|
902
|
+
Balance conciseness to not overwhelm the user with appropriate detail for the request. Do not narrate abstractly; explain what you are doing and why.
|
|
903
|
+
|
|
904
|
+
Never tell the user to "save/copy this file", the user is on the same machine and has access to the same files as you have.
|
|
905
|
+
|
|
906
|
+
|
|
907
|
+
## Formatting rules
|
|
908
|
+
|
|
909
|
+
Your responses are rendered as GitHub-flavored Markdown.
|
|
910
|
+
|
|
911
|
+
Never use nested bullets. Keep lists flat (single level). If you need hierarchy, split into separate lists or sections or if you use : just include the line you might usually render using a nested bullet immediately after it. For numbered lists, only use the \`1. 2. 3.\` style markers (with a period), never \`1)\`.
|
|
912
|
+
|
|
913
|
+
Headers are optional, only use them when you think they are necessary. If you do use them, use short Title Case (1-3 words) wrapped in **\u2026**. Don't add a blank line.
|
|
914
|
+
|
|
915
|
+
Use inline code blocks for commands, paths, environment variables, function names, inline examples, keywords.
|
|
916
|
+
|
|
917
|
+
Code samples or multi-line snippets should be wrapped in fenced code blocks. Include a language tag when possible.
|
|
918
|
+
|
|
919
|
+
Don\u2019t use emojis or em dashes unless explicitly instructed.
|
|
920
|
+
|
|
921
|
+
## Response channels
|
|
922
|
+
|
|
923
|
+
Use commentary for short progress updates while working and final for the completed response.
|
|
924
|
+
|
|
925
|
+
### \`commentary\` channel
|
|
926
|
+
|
|
927
|
+
Only use \`commentary\` for intermediary updates. These are short updates while you are working, they are NOT final answers. Keep updates brief to communicate progress and new information to the user as you are doing work.
|
|
928
|
+
|
|
929
|
+
Send updates when they add meaningful new information: a discovery, a tradeoff, a blocker, a substantial plan, or the start of a non-trivial edit or verification step.
|
|
930
|
+
|
|
931
|
+
Do not narrate routine reads, searches, obvious next steps, or minor confirmations. Combine related progress into a single update.
|
|
932
|
+
|
|
933
|
+
Do not begin responses with conversational interjections or meta commentary. Avoid openers such as acknowledgements ("Done \u2014", "Got it", "Great question") or framing phrases.
|
|
934
|
+
|
|
935
|
+
Before substantial work, send a short update describing your first step. Before editing files, send an update describing the edit.
|
|
936
|
+
|
|
937
|
+
After you have sufficient context, and the work is substantial you can provide a longer plan (this is the only user update that may be longer than 2 sentences and can contain formatting).
|
|
938
|
+
|
|
939
|
+
### \`final\` channel
|
|
940
|
+
|
|
941
|
+
Use final for the completed response.
|
|
942
|
+
|
|
943
|
+
Structure your final response if necessary. The complexity of the answer should match the task. If the task is simple, your answer should be a one-liner. Order sections from general to specific to supporting.
|
|
944
|
+
|
|
945
|
+
If the user asks for a code explanation, include code references. For simple tasks, just state the outcome without heavy formatting.
|
|
946
|
+
|
|
947
|
+
For large or complex changes, lead with the solution, then explain what you did and why. For casual chat, just chat. If something couldn\u2019t be done (tests, builds, etc.), say so. Suggest next steps only when they are natural and useful; if you list options, use numbered items.
|
|
948
|
+
`;var ap=`You are OpenCode, an interactive general AI agent running on a user's computer.
|
|
949
|
+
|
|
950
|
+
Your primary goal is to help users with software engineering tasks by taking action \u2014 use the tools available to you to make real changes on the user's system. You should also answer questions when asked. Always adhere strictly to the following system instructions and the user's requirements.
|
|
951
|
+
|
|
952
|
+
# Prompt and Tool Use
|
|
953
|
+
|
|
954
|
+
The user's messages may contain questions and/or task descriptions in natural language, code snippets, logs, file paths, or other forms of information. Read them, understand them and do what the user requested. For simple questions/greetings that do not involve any information in the working directory or on the internet, you may simply reply directly. For anything else, default to taking action with tools. When the request could be interpreted as either a question to answer or a task to complete, treat it as a task.
|
|
955
|
+
|
|
956
|
+
When handling the user's request, if it involves creating, modifying, or running code or files, you MUST use the appropriate tools to make actual changes \u2014 do not just describe the solution in text. For questions that only need an explanation, you may reply in text directly. When calling tools, do not provide explanations because the tool calls themselves should be self-explanatory. You MUST follow the description of each tool and its parameters when calling tools.
|
|
957
|
+
|
|
958
|
+
If the \`task\` tool is available, you can use it to delegate a focused subtask to a subagent instance. When delegating, provide a complete prompt with all necessary context because a newly created subagent does not automatically see your current context.
|
|
959
|
+
|
|
960
|
+
You have the capability to output any number of tool calls in a single response. If you anticipate making multiple non-interfering tool calls, you are HIGHLY RECOMMENDED to make them in parallel to significantly improve efficiency. This is very important to your performance.
|
|
961
|
+
|
|
962
|
+
The results of the tool calls will be returned to you in a tool message. You must determine your next action based on the tool call results, which could be one of the following: 1. Continue working on the task, 2. Inform the user that the task is completed or has failed, or 3. Ask the user for more information.
|
|
963
|
+
|
|
964
|
+
Tool results and user messages may include \`<system-reminder>\` tags. These are authoritative system directives that you MUST follow. They bear no direct relation to the specific tool results or user messages in which they appear. Always read them carefully and comply with their instructions \u2014 they may override or constrain your normal behavior (e.g., restricting you to read-only actions during plan mode).
|
|
965
|
+
|
|
966
|
+
When responding to the user, you MUST use the SAME language as the user, unless explicitly instructed to do otherwise.
|
|
967
|
+
|
|
968
|
+
# General Guidelines for Coding
|
|
969
|
+
|
|
970
|
+
When building something from scratch, you should:
|
|
971
|
+
|
|
972
|
+
- Understand the user's requirements.
|
|
973
|
+
- Ask the user for clarification if there is anything unclear.
|
|
974
|
+
- Design the architecture and make a plan for the implementation.
|
|
975
|
+
- Write the code in a modular and maintainable way.
|
|
976
|
+
|
|
977
|
+
Always use tools to implement your code changes:
|
|
978
|
+
|
|
979
|
+
- Use \`write\`/\`edit\` to create or modify source files. Code that only appears in your text response is NOT saved to the file system and will not take effect.
|
|
980
|
+
- Use \`bash\` to run and test your code after writing it.
|
|
981
|
+
- Iterate: if tests fail, read the error, fix the code with \`write\`/\`edit\`, and re-test with \`bash\`.
|
|
982
|
+
|
|
983
|
+
When working on an existing codebase, you should:
|
|
984
|
+
|
|
985
|
+
- Understand the codebase by reading it with tools (\`read\`, \`glob\`, \`grep\`) before making changes. Identify the ultimate goal and the most important criteria to achieve the goal.
|
|
986
|
+
- For a bug fix, you typically need to check error logs or failed tests, scan over the codebase to find the root cause, and figure out a fix. If user mentioned any failed tests, you should make sure they pass after the changes.
|
|
987
|
+
- For a feature, you typically need to design the architecture, and write the code in a modular and maintainable way, with minimal intrusions to existing code. Add new tests if the project already has tests.
|
|
988
|
+
- For a code refactoring, you typically need to update all the places that call the code you are refactoring if the interface changes. DO NOT change any existing logic especially in tests, focus only on fixing any errors caused by the interface changes.
|
|
989
|
+
- Make MINIMAL changes to achieve the goal. This is very important to your performance.
|
|
990
|
+
- Follow the coding style of existing code in the project.
|
|
991
|
+
|
|
992
|
+
DO NOT run \`git commit\`, \`git push\`, \`git reset\`, \`git rebase\` and/or do any other git mutations unless explicitly asked to do so. Ask for confirmation each time when you need to do git mutations, even if the user has confirmed in earlier conversations.
|
|
993
|
+
|
|
994
|
+
# General Guidelines for Research and Data Processing
|
|
995
|
+
|
|
996
|
+
The user may ask you to research on certain topics, process or generate certain multimedia files. When doing such tasks, you must:
|
|
997
|
+
|
|
998
|
+
- Understand the user's requirements thoroughly, ask for clarification before you start if needed.
|
|
999
|
+
- Make plans before doing deep or wide research, to ensure you are always on track.
|
|
1000
|
+
- Search on the Internet if possible, with carefully-designed search queries to improve efficiency and accuracy.
|
|
1001
|
+
- Use proper tools or shell commands or Python packages to process or generate images, videos, PDFs, docs, spreadsheets, presentations, or other multimedia files. Detect if there are already such tools in the environment. If you have to install third-party tools/packages, you MUST ensure that they are installed in a virtual/isolated environment.
|
|
1002
|
+
- Once you generate or edit any images, videos or other media files, try to read it again before proceed, to ensure that the content is as expected.
|
|
1003
|
+
- Avoid installing or deleting anything to/from outside of the current working directory. If you have to do so, ask the user for confirmation.
|
|
1004
|
+
|
|
1005
|
+
# Working Environment
|
|
1006
|
+
|
|
1007
|
+
## Operating System
|
|
1008
|
+
|
|
1009
|
+
The operating environment is not in a sandbox. Any actions you do will immediately affect the user's system. So you MUST be extremely cautious. Unless being explicitly instructed to do so, you should never access (read/write/execute) files outside of the working directory.
|
|
1010
|
+
|
|
1011
|
+
## Working Directory
|
|
1012
|
+
|
|
1013
|
+
The working directory should be considered as the project root if you are instructed to perform tasks on the project. Every file system operation will be relative to the working directory if you do not explicitly specify the absolute path. Tools may require absolute paths for some parameters, IF SO, YOU MUST use absolute paths for these parameters.
|
|
1014
|
+
|
|
1015
|
+
# Project Information
|
|
1016
|
+
|
|
1017
|
+
Markdown files named \`AGENTS.md\` usually contain the background, structure, coding styles, user preferences and other relevant information about the project. You should use this information to understand the project and the user's preferences. \`AGENTS.md\` files may exist at different locations in the project, but typically there is one in the project root.
|
|
1018
|
+
|
|
1019
|
+
> Why \`AGENTS.md\`?
|
|
1020
|
+
>
|
|
1021
|
+
> \`README.md\` files are for humans: quick starts, project descriptions, and contribution guidelines. \`AGENTS.md\` complements this by containing the extra, sometimes detailed context coding agents need: build steps, tests, and conventions that might clutter a README or aren\u2019t relevant to human contributors.
|
|
1022
|
+
>
|
|
1023
|
+
> We intentionally kept it separate to:
|
|
1024
|
+
>
|
|
1025
|
+
> - Give agents a clear, predictable place for instructions.
|
|
1026
|
+
> - Keep \`README\`s concise and focused on human contributors.
|
|
1027
|
+
> - Provide precise, agent-focused guidance that complements existing \`README\` and docs.
|
|
1028
|
+
If the \`AGENTS.md\` is empty or insufficient, you may check \`README\`/\`README.md\` files or \`AGENTS.md\` files in subdirectories for more information about specific parts of the project.
|
|
1029
|
+
|
|
1030
|
+
If you modified any files/styles/structures/configurations/workflows/... mentioned in \`AGENTS.md\` files, you MUST update the corresponding \`AGENTS.md\` files to keep them up-to-date.
|
|
1031
|
+
|
|
1032
|
+
# Ultimate Reminders
|
|
1033
|
+
|
|
1034
|
+
At any time, you should be HELPFUL, CONCISE, and ACCURATE. Be thorough in your actions \u2014 test what you build, verify what you change \u2014 not in your explanations.
|
|
1035
|
+
|
|
1036
|
+
- Never diverge from the requirements and the goals of the task you work on. Stay on track.
|
|
1037
|
+
- Never give the user more than what they want.
|
|
1038
|
+
- Try your best to avoid any hallucination. Do fact checking before providing any factual information.
|
|
1039
|
+
- Think about the best approach, then take action decisively.
|
|
1040
|
+
- Do not give up too early.
|
|
1041
|
+
- ALWAYS, keep it stupidly simple. Do not overcomplicate things.
|
|
1042
|
+
- When the task requires creating or modifying files, always use tools to do so. Never treat displaying code in your response as a substitute for actually writing it to the file system.
|
|
1043
|
+
`;var cp=`You are OpenCode, the best coding agent on the planet.
|
|
1044
|
+
|
|
1045
|
+
You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
|
|
1046
|
+
|
|
1047
|
+
## Editing constraints
|
|
1048
|
+
- Default to ASCII when editing or creating files. Only introduce non-ASCII or other Unicode characters when there is a clear justification and the file already uses them.
|
|
1049
|
+
- Only add comments if they are necessary to make a non-obvious block easier to understand.
|
|
1050
|
+
- Try to use apply_patch for single file edits, but it is fine to explore other options to make the edit if it does not work well. Do not use apply_patch for changes that are auto-generated (i.e. generating package.json or running a lint or format command like gofmt) or when scripting is more efficient (such as search and replacing a string across a codebase).
|
|
1051
|
+
|
|
1052
|
+
## Tool usage
|
|
1053
|
+
- Prefer specialized tools over shell for file operations:
|
|
1054
|
+
- Use Read to view files, Edit to modify files, and Write only when needed.
|
|
1055
|
+
- Use Glob to find files by name and Grep to search file contents.
|
|
1056
|
+
- Use Bash for terminal operations (git, bun, builds, tests, running scripts).
|
|
1057
|
+
- Run tool calls in parallel when neither call needs the other\u2019s output; otherwise run sequentially.
|
|
1058
|
+
|
|
1059
|
+
## Git and workspace hygiene
|
|
1060
|
+
- You may be in a dirty git worktree.
|
|
1061
|
+
* NEVER revert existing changes you did not make unless explicitly requested, since these changes were made by the user.
|
|
1062
|
+
* If asked to make a commit or code edits and there are unrelated changes to your work or changes that you didn't make in those files, don't revert those changes.
|
|
1063
|
+
* If the changes are in files you've touched recently, you should read carefully and understand how you can work with the changes rather than reverting them.
|
|
1064
|
+
* If the changes are in unrelated files, just ignore them and don't revert them.
|
|
1065
|
+
- Do not amend commits unless explicitly requested.
|
|
1066
|
+
- **NEVER** use destructive commands like \`git reset --hard\` or \`git checkout --\` unless specifically requested or approved by the user.
|
|
1067
|
+
|
|
1068
|
+
## Frontend tasks
|
|
1069
|
+
When doing frontend design tasks, avoid collapsing into bland, generic layouts.
|
|
1070
|
+
Aim for interfaces that feel intentional and deliberate.
|
|
1071
|
+
- Typography: Use expressive, purposeful fonts and avoid default stacks (Inter, Roboto, Arial, system).
|
|
1072
|
+
- Color & Look: Choose a clear visual direction; define CSS variables; avoid purple-on-white defaults. No purple bias or dark mode bias.
|
|
1073
|
+
- Motion: Use a few meaningful animations (page-load, staggered reveals) instead of generic micro-motions.
|
|
1074
|
+
- Background: Don't rely on flat, single-color backgrounds; use gradients, shapes, or subtle patterns to build atmosphere.
|
|
1075
|
+
- Overall: Avoid boilerplate layouts and interchangeable UI patterns. Vary themes, type families, and visual languages across outputs.
|
|
1076
|
+
- Ensure the page loads properly on both desktop and mobile.
|
|
1077
|
+
|
|
1078
|
+
Exception: If working within an existing website or design system, preserve the established patterns, structure, and visual language.
|
|
1079
|
+
|
|
1080
|
+
## Presenting your work and final message
|
|
1081
|
+
|
|
1082
|
+
You are producing plain text that will later be styled by the CLI. Follow these rules exactly. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value.
|
|
1083
|
+
|
|
1084
|
+
- Default: be very concise; friendly coding teammate tone.
|
|
1085
|
+
- Default: do the work without asking questions. Treat short tasks as sufficient direction; infer missing details by reading the codebase and following existing conventions.
|
|
1086
|
+
- Questions: only ask when you are truly blocked after checking relevant context AND you cannot safely pick a reasonable default. This usually means one of:
|
|
1087
|
+
* The request is ambiguous in a way that materially changes the result and you cannot disambiguate by reading the repo.
|
|
1088
|
+
* The action is destructive/irreversible, touches production, or changes billing/security posture.
|
|
1089
|
+
* You need a secret/credential/value that cannot be inferred (API key, account id, etc.).
|
|
1090
|
+
- If you must ask: do all non-blocked work first, then ask exactly one targeted question, include your recommended default, and state what would change based on the answer.
|
|
1091
|
+
- Never ask permission questions like "Should I proceed?" or "Do you want me to run tests?"; proceed with the most reasonable option and mention what you did.
|
|
1092
|
+
- For substantial work, summarize clearly; follow final\u2011answer formatting.
|
|
1093
|
+
- Skip heavy formatting for simple confirmations.
|
|
1094
|
+
- Don't dump large files you've written; reference paths only.
|
|
1095
|
+
- No "save/copy this file" - User is on the same machine.
|
|
1096
|
+
- Offer logical next steps (tests, commits, build) briefly; add verify steps if you couldn't do something.
|
|
1097
|
+
- For code changes:
|
|
1098
|
+
* Lead with a quick explanation of the change, and then give more details on the context covering where and why a change was made. Do not start this explanation with "summary", just jump right in.
|
|
1099
|
+
* If there are natural next steps the user may want to take, suggest them at the end of your response. Do not make suggestions if there are no natural next steps.
|
|
1100
|
+
* When suggesting multiple options, use numeric lists for the suggestions so the user can quickly respond with a single number.
|
|
1101
|
+
- The user does not command execution outputs. When asked to show the output of a command (e.g. \`git show\`), relay the important details in your answer or summarize the key lines so the user understands the result.
|
|
1102
|
+
|
|
1103
|
+
## Final answer structure and style guidelines
|
|
1104
|
+
|
|
1105
|
+
- Plain text; CLI handles styling. Use structure only when it helps scannability.
|
|
1106
|
+
- Headers: optional; short Title Case (1-3 words) wrapped in **\u2026**; no blank line before the first bullet; add only if they truly help.
|
|
1107
|
+
- Bullets: use - ; merge related points; keep to one line when possible; 4\u20136 per list ordered by importance; keep phrasing consistent.
|
|
1108
|
+
- Monospace: backticks for commands/paths/env vars/code ids and inline examples; use for literal keyword bullets; never combine with **.
|
|
1109
|
+
- Code samples or multi-line snippets should be wrapped in fenced code blocks; include an info string as often as possible.
|
|
1110
|
+
- Structure: group related bullets; order sections general \u2192 specific \u2192 supporting; for subsections, start with a bolded keyword bullet, then items; match complexity to the task.
|
|
1111
|
+
- Tone: collaborative, concise, factual; present tense, active voice; self\u2011contained; no "above/below"; parallel wording.
|
|
1112
|
+
- Don'ts: no nested bullets/hierarchies; no ANSI codes; don't cram unrelated keywords; keep keyword lists short\u2014wrap/reformat if long; avoid naming formatting styles in answers.
|
|
1113
|
+
- Adaptation: code explanations \u2192 precise, structured with code refs; simple tasks \u2192 lead with outcome; big changes \u2192 logical walkthrough + rationale + next actions; casual one-offs \u2192 plain sentences, no headers/bullets.
|
|
1114
|
+
- File References: When referencing files in your response follow the below rules:
|
|
1115
|
+
* Use inline code to make file paths clickable.
|
|
1116
|
+
* Each reference should have a stand alone path. Even if it's the same file.
|
|
1117
|
+
* Accepted: absolute, workspace\u2011relative, a/ or b/ diff prefixes, or bare filename/suffix.
|
|
1118
|
+
* Optionally include line/column (1\u2011based): :line[:column] or #Lline[Ccolumn] (column defaults to 1).
|
|
1119
|
+
* Do not use URIs like file://, vscode://, or https://.
|
|
1120
|
+
* Do not provide range of lines
|
|
1121
|
+
* Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\\repo\\project\\main.rs:12:5
|
|
1122
|
+
`;var lp=`You are opencode, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
|
|
1123
|
+
|
|
1124
|
+
# Tone and style
|
|
1125
|
+
You should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
|
|
1126
|
+
Remember that your output will be displayed on a command line interface. Your responses can use GitHub-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
|
|
1127
|
+
Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
|
|
1128
|
+
If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
|
|
1129
|
+
Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
|
|
1130
|
+
IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.
|
|
1131
|
+
IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.
|
|
1132
|
+
IMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is <answer>.", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity:
|
|
1133
|
+
<example>
|
|
1134
|
+
user: 2 + 2
|
|
1135
|
+
assistant: 4
|
|
1136
|
+
</example>
|
|
1137
|
+
|
|
1138
|
+
<example>
|
|
1139
|
+
user: what is 2+2?
|
|
1140
|
+
assistant: 4
|
|
1141
|
+
</example>
|
|
1142
|
+
|
|
1143
|
+
<example>
|
|
1144
|
+
user: is 11 a prime number?
|
|
1145
|
+
assistant: Yes
|
|
1146
|
+
</example>
|
|
1147
|
+
|
|
1148
|
+
<example>
|
|
1149
|
+
user: what command should I run to list files in the current directory?
|
|
1150
|
+
assistant: ls
|
|
1151
|
+
</example>
|
|
1152
|
+
|
|
1153
|
+
<example>
|
|
1154
|
+
user: what command should I run to watch files in the current directory?
|
|
1155
|
+
assistant: [use the ls tool to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]
|
|
1156
|
+
npm run dev
|
|
1157
|
+
</example>
|
|
1158
|
+
|
|
1159
|
+
<example>
|
|
1160
|
+
user: How many golf balls fit inside a jetta?
|
|
1161
|
+
assistant: 150000
|
|
1162
|
+
</example>
|
|
1163
|
+
|
|
1164
|
+
<example>
|
|
1165
|
+
user: what files are in the directory src/?
|
|
1166
|
+
assistant: [runs ls and sees foo.c, bar.c, baz.c]
|
|
1167
|
+
user: which file contains the implementation of foo?
|
|
1168
|
+
assistant: src/foo.c
|
|
1169
|
+
</example>
|
|
1170
|
+
|
|
1171
|
+
<example>
|
|
1172
|
+
user: write tests for new feature
|
|
1173
|
+
assistant: [uses grep or glob to find where similar tests are defined, then read relevant files one at a time (one tool per message, wait for each result), then edit or write to add tests]
|
|
1174
|
+
</example>
|
|
1175
|
+
|
|
1176
|
+
# Proactiveness
|
|
1177
|
+
You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
|
|
1178
|
+
1. Doing the right thing when asked, including taking actions and follow-up actions
|
|
1179
|
+
2. Not surprising the user with actions you take without asking
|
|
1180
|
+
For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.
|
|
1181
|
+
3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.
|
|
1182
|
+
|
|
1183
|
+
# Following conventions
|
|
1184
|
+
When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
|
|
1185
|
+
- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).
|
|
1186
|
+
- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.
|
|
1187
|
+
- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.
|
|
1188
|
+
- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.
|
|
1189
|
+
|
|
1190
|
+
# Code style
|
|
1191
|
+
- IMPORTANT: DO NOT ADD ***ANY*** COMMENTS unless asked
|
|
1192
|
+
|
|
1193
|
+
# Doing tasks
|
|
1194
|
+
The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
|
|
1195
|
+
- Use the available search tools to understand the codebase and the user's query. Use one tool per message; after each result, decide the next step and call one tool again.
|
|
1196
|
+
- Implement the solution using all tools available to you
|
|
1197
|
+
- Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.
|
|
1198
|
+
- VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (e.g. npm run lint, npm run typecheck, ruff, etc.) with Bash if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to AGENTS.md so that you will know to run it next time.
|
|
1199
|
+
NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
|
|
1200
|
+
|
|
1201
|
+
- Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result.
|
|
1202
|
+
|
|
1203
|
+
# Tool usage policy
|
|
1204
|
+
- When doing file search, prefer to use the Task tool in order to reduce context usage.
|
|
1205
|
+
- Use exactly one tool per assistant message. After each tool call, wait for the result before continuing.
|
|
1206
|
+
- When the user's request is vague, use the question tool to clarify before reading files or making changes.
|
|
1207
|
+
- Avoid repeating the same tool with the same parameters once you have useful results. Use the result to take the next step (e.g. pick one match, read that file, then act); do not search again in a loop.
|
|
1208
|
+
|
|
1209
|
+
You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.
|
|
1210
|
+
|
|
1211
|
+
# Code References
|
|
1212
|
+
|
|
1213
|
+
When referencing specific functions or pieces of code include the pattern \`file_path:line_number\` to allow the user to easily navigate to the source code location.
|
|
1214
|
+
|
|
1215
|
+
<example>
|
|
1216
|
+
user: Where are errors from the client handled?
|
|
1217
|
+
assistant: Clients are marked as failed in the \`connectToServer\` function in src/services/process.ts:712.
|
|
1218
|
+
</example>
|
|
1219
|
+
`;var Xo;(i=>{function e(m){return m.api.id.includes("gpt-4")||m.api.id.includes("o1")||m.api.id.includes("o3")?[rp]:m.api.id.includes("gpt")?m.api.id.includes("codex")?[cp]:[ip]:m.api.id.includes("gemini-")?[sp]:m.api.id.includes("claude")?[np]:m.api.id.toLowerCase().includes("trinity")?[lp]:m.api.id.toLowerCase().includes("kimi")?[ap]:[op]}i.provider=e,n(e,"provider");async function t(m){let y=he.project;return[[`You are powered by the model named ${m.api.id}. The exact model ID is ${m.providerID}/${m.api.id}`,"Here is some useful information about the environment you are running in:","<env>",` Working directory: ${he.directory}`,` Workspace root folder: ${he.worktree}`,` Is directory a git repo: ${y.vcs==="git"?"yes":"no"}`,` Platform: ${process.platform}`,` Today's date: ${new Date().toDateString()}`,"</env>","<directories>",` ${y.vcs,""}`,"</directories>"].join(`
|
|
1220
|
+
`)]}i.environment=t,n(t,"environment");async function o(m){if(lt.disabled(["skill"],m.permission).has("skill"))return;let y=await Bn.available(m);return["Skills provide specialized instructions and workflows for specific tasks.","Use the skill tool to load a skill when a task matches its description.",Bn.fmt(y,{verbose:!0})].join(`
|
|
1221
|
+
`)}i.skills=o,n(o,"skills")})(Xo||={});var dp="alchemylab/fieldTags";function up(e,t,o,i){if(!o)return{description:e,schema:t};let m=new Set(i),y=structuredClone(t),p=y.properties?.operation?.enum,f=p?.filter(c=>m.has(c))??[],b=!!p&&f.length>0;b&&(y.properties.operation.enum=f);for(let[c,l]of Object.entries(o)){if(l.some(w=>m.has(w)))continue;let g=c.split("."),u=y;for(let w of g.slice(0,-1))u=u?.properties?.[w],u?.type==="array"&&(u=u.items);let a=g[g.length-1];!u?.properties||!(a in u.properties)||(delete u.properties[a],Array.isArray(u.required)&&(u.required=u.required.filter(w=>w!==a)))}let d=new Set(b?p.filter(c=>!m.has(c)):[]);return{description:e.split(`
|
|
1222
|
+
`).filter(c=>{let l=/^\s*(?:•|•)\s+(.+?)\s+-\s/.exec(c);return l?!l[1].split("/").map(u=>u.trim()).every(u=>d.has(u)):!0}).join(`
|
|
1223
|
+
`),schema:y}}n(up,"scopeTool");var Is;(d=>{let e=qe.create({service:"llm"});d.OUTPUT_TOKEN_MAX=Jt.OUTPUT_TOKEN_MAX;class o extends iw.Service()("@opencode/LLM"){static{n(this,"Service")}}d.Service=o,d.layer=sw.effect(o,xs.gen(function*(){return o.of({stream(s){return vs.scoped(vs.unwrap(xs.gen(function*(){let c=yield*xs.acquireRelease(xs.sync(()=>new AbortController),g=>xs.sync(()=>g.abort())),l=yield*xs.promise(()=>d.stream({...s,abort:c.signal}));return vs.fromAsyncIterable(l.fullStream,g=>g instanceof Error?g:new Error(String(g)))})))}})})),d.defaultLayer=d.layer;async function y(s){let c=e.clone().tag("providerID",s.model.providerID).tag("modelID",s.model.id).tag("sessionID",s.sessionID).tag("small",(s.small??!1).toString()).tag("agent",s.agent.name).tag("mode",s.agent.mode);c.info("stream",{modelID:s.model.id,providerID:s.model.providerID});let[l,g,u,a]=await Promise.all([yn.getLanguage(s.model),rt.get(),yn.getProvider(s.model.providerID),Fn.get(s.model.providerID)]),w=u.id==="openai"&&a?.type==="oauth",I=(s.agent.prompt?[s.agent.prompt]:Xo.provider(s.model)).filter(C=>C).join(`
|
|
1224
|
+
`),r=[...s.system,...s.user.system?[s.user.system]:[]].filter(C=>C).join(`
|
|
1225
|
+
`),x=[I,r].filter(C=>C),h=x[0];if(await ln.trigger("experimental.chat.system.transform",{sessionID:s.sessionID,model:s.model},{system:x}),x.length>2&&x[0]===h){let C=x.slice(1);x.length=0,x.push(h,C.join(`
|
|
1226
|
+
`))}let v=!s.small&&s.model.variants&&s.user.variant?s.model.variants[s.user.variant]:{},S=s.small?Jt.smallOptions(s.model):Jt.options({model:s.model,sessionID:s.sessionID,providerOptions:u.options}),{cacheTtl:j,toolScopes:O,...k}=s.agent.options??{},E=dw(S,cl(s.model.options),cl(k),cl(v));w&&(E.instructions=x.join(`
|
|
1227
|
+
`));let D=l instanceof fp,z=w||D?s.messages:[...x.map(C=>({role:"system",content:C})),...s.messages],_=await ln.trigger("chat.params",{sessionID:s.sessionID,agent:s.agent.name,model:s.model,provider:u,message:s.user},{temperature:s.model.capabilities.temperature?s.agent.temperature??Jt.temperature(s.model):void 0,topP:s.agent.topP??Jt.topP(s.model),topK:Jt.topK(s.model),maxOutputTokens:Jt.maxOutputTokens(s.model),options:E}),{headers:B}=await ln.trigger("chat.headers",{sessionID:s.sessionID,agent:s.agent.name,model:s.model,provider:u,message:s.user},{headers:{}}),$=await p(s);if((u.options?.litellmProxy===!0||s.model.providerID.toLowerCase().includes("litellm")||s.model.api.id.toLowerCase().includes("litellm"))&&Object.keys($).length===0&&b(s.messages)&&($._noop=lw({description:"Do not call this tool. It exists only for API compatibility and must never be invoked.",inputSchema:pp({type:"object",properties:{reason:{type:"string",description:"Unused"}}}),execute:n(async()=>({output:"",title:"",metadata:{}}),"execute")})),l instanceof fp){let C=l;C.systemPrompt=x.join(`
|
|
1228
|
+
`),C.toolExecutor=async(T,G,N)=>{let A=$[T];if(!A||!A.execute)return{result:"",error:`Unknown tool: ${T}`};try{let F=await A.execute(JSON.parse(G),{toolCallId:N,messages:s.messages,abortSignal:s.abort});return{result:typeof F=="string"?F:F?.output??JSON.stringify(F),metadata:typeof F=="object"?F?.metadata:void 0,title:typeof F=="object"?F?.title:void 0}}catch(F){return{result:"",error:F.message??String(F)}}}}return aw({onError(C){c.error("stream error",{error:C})},async experimental_repairToolCall(C){let T=C.toolCall.toolName.toLowerCase();if(!$[C.toolCall.toolName]&&!$[T]){let G=T.replace(/^(?:mcp_|alchemy_)+/,""),N=Object.keys($).filter(A=>A===G||A.endsWith(`_${G}`));if(G&&N.length===1)return c.info("repairing tool call",{tool:C.toolCall.toolName,repaired:N[0]}),{...C.toolCall,toolName:N[0]}}return T!==C.toolCall.toolName&&$[T]?(c.info("repairing tool call",{tool:C.toolCall.toolName,repaired:T}),{...C.toolCall,toolName:T}):{...C.toolCall,input:JSON.stringify({tool:C.toolCall.toolName,error:C.error.message}),toolName:"invalid"}},temperature:_.temperature,topP:_.topP,topK:_.topK,providerOptions:Jt.providerOptions(s.model,_.options),activeTools:Object.keys($).filter(C=>C!=="invalid"),tools:$,toolChoice:s.toolChoice,maxOutputTokens:_.maxOutputTokens,abortSignal:s.abort,headers:{...s.model.providerID.startsWith("opencode")?{"x-opencode-project":he.project.id,"x-opencode-session":s.sessionID,"x-opencode-request":s.user.id,"x-opencode-client":Ce.OPENCODE_CLIENT}:{"x-session-affinity":s.sessionID,...s.parentSessionID?{"x-parent-session-id":s.parentSessionID}:{},"User-Agent":`opencode/${Ft.VERSION}`},...s.model.headers,...B},maxRetries:s.retries??0,messages:z,model:cw({model:l,middleware:[{specificationVersion:"v3",async transformParams(C){return C.type==="stream"&&(C.params.prompt=Jt.message(C.params.prompt,s.model,E,{messageCacheTtl:j==="5m"?"5m":void 0})),C.params}}]}),experimental_telemetry:{isEnabled:g.experimental?.openTelemetry,metadata:{userId:g.username??"unknown",sessionId:s.sessionID}}})}d.stream=y,n(y,"stream");function p(s){let c=lt.disabled(Object.keys(s.tools),lt.merge(s.agent.permission,s.permission??[])),l=al.filter(s.tools,(I,r)=>s.user.tools?.[r]!==!1&&!c.has(r)),g=s.agent.options?.toolScopes,u=g?al.map(l,(I,r)=>f(I,g[r],s.model)):l,a=Jt.toolStrict(s.model),w=a===void 0?u:al.map(u,I=>({...I,strict:a}));return Object.fromEntries(Object.entries(w).toSorted(([I],[r])=>I<r?-1:I>r?1:0))}n(p,"resolveTools");function f(s,c,l){let g=s;if(!c||!g.fieldTags||!g.jsonInputSchema)return s;let{description:u,schema:a}=up(s.description??"",g.jsonInputSchema,g.fieldTags,c);return{...s,description:u,inputSchema:pp(Jt.schema(l,a))}}n(f,"narrow");function b(s){for(let c of s)if(Array.isArray(c.content)){for(let l of c.content)if(l.type==="tool-call"||l.type==="tool-result")return!0}return!1}d.hasToolCalls=b,n(b,"hasToolCalls")})(Is||={});function gp(e,t){if(mp(t)!=="final_answer")return;let o=t.text.trim();if(o)return e.find(i=>i.type==="text"&&i.id!==t.id&&mp(i)==="commentary"&&i.text.trim()===o)}n(gp,"repeatedPreamble");function mp(e){for(let t of Object.values(e.metadata??{}))if(t&&typeof t=="object"&&typeof t.phase=="string")return t.phase}n(mp,"phaseOf");var uw=2e4;function Da(e){if(e.cfg.compaction?.auto===!1)return!1;let t=e.model.limit.context;if(t===0)return!1;let o=e.tokens.total||e.tokens.input+e.tokens.output+e.tokens.cache.read+e.tokens.cache.write,i=e.cfg.compaction?.reserved??Math.min(uw,Jt.maxOutputTokens(e.model)),m=e.model.limit.input?e.model.limit.input-i:t-Jt.maxOutputTokens(e.model);return o>=m}n(Da,"isOverflow");import{Cause as hp,Clock as pw,Duration as fw,Effect as yp,Schedule as mw}from"effect";var Ta;(c=>{c.RETRY_MAX_ATTEMPTS=10,c.RETRY_INITIAL_DELAY=500,c.RETRY_BACKOFF_FACTOR=2,c.RETRY_MAX_BACKOFF=32e3,c.RETRY_JITTER=.25,c.RETRY_AFTER_MAX=6e5;function p(l){let g=l?.data.responseHeaders;if(!g)return;let u=Number.parseFloat(g["retry-after-ms"]??"");if(!Number.isNaN(u)&&u>=0)return u;let a=g["retry-after"];if(!a)return;let w=Number.parseFloat(a);if(!Number.isNaN(w)&&w>=0)return Math.ceil(w*1e3);let I=Date.parse(a)-Date.now();if(!Number.isNaN(I)&&I>0)return Math.ceil(I)}n(p,"retryAfter");function f(l,g,u=Math.random){let a=p(g);if(a!==void 0)return Math.min(a,6e5);let w=Math.min(500*Math.pow(2,l-1),32e3);return Math.round(w*(1+.25*u()))}c.delay=f,n(f,"delay");function b(l){return Qe.APIError.isInstance(l)&&!!l.data.responseBody?.includes("FreeUsageLimitError")}n(b,"uncapped");function d(l){if(Qe.ProviderQuotaError.isInstance(l)||Qe.ContextOverflowError.isInstance(l))return;if(Qe.APIError.isInstance(l))return l.data.isRetryable?l.data.responseBody?.includes("FreeUsageLimitError")?"Free usage exceeded, subscribe to Go https://opencode.ai/go":l.data.message.includes("Overloaded")?"Provider is overloaded":l.data.message:void 0;let g=qt(()=>{try{return typeof l.data?.message=="string",JSON.parse(l.data.message)}catch{return}});if(!g||typeof g!="object")return;let u=typeof g.code=="string"?g.code:"";if(g.type==="error"&&g.error?.type==="too_many_requests")return"Too Many Requests";let a=typeof g.error?.code=="string"?g.error.code:"",w=typeof g.error?.type=="string"?g.error.type:"",I=typeof g.type=="string"?g.type:"";if(I==="api_error")return"Provider server error";if(I.includes("overloaded")||u.includes("exhausted")||u.includes("unavailable")||a.includes("exhausted")||a.includes("unavailable")||a.includes("overloaded")||w.includes("unavailable")||w.includes("overloaded")||a==="slow_down")return"Provider is overloaded";if(g.type==="error"&&typeof g.error?.code=="string"&&g.error.code.includes("rate_limit"))return"Rate Limited"}c.retryable=d,n(d,"retryable");function s(l){return mw.fromStepWithMetadata(yp.succeed(g=>{let u=l.parse(g.input),a=d(u);return a?g.attempt>10&&!b(u)?hp.done(g.attempt):yp.gen(function*(){let w=f(g.attempt,Qe.APIError.isInstance(u)?u:void 0),I=yield*pw.currentTimeMillis;return yield*l.set({attempt:g.attempt,message:a,next:I+w}),[g.attempt,fw.millis(w)]}):hp.done(g.attempt)}))}c.policy=s,n(s,"policy")})(Ta||={});import{Effect as ks,Layer as bp,ServiceMap as gw}from"effect";import go from"zod";var Ur;(d=>{d.Info=go.union([go.object({type:go.literal("idle")}),go.object({type:go.literal("retry"),attempt:go.number(),message:go.string(),next:go.number()}),go.object({type:go.literal("busy")})]).meta({ref:"SessionStatus"}),d.Event={Status:mt.define("session.status",go.object({sessionID:He.zod,status:d.Info})),Idle:mt.define("session.idle",go.object({sessionID:He.zod}))};class o extends gw.Service()("@opencode/SessionStatus"){static{n(this,"Service")}}d.Service=o,d.layer=bp.effect(o,ks.gen(function*(){let s=yield*Ve.Service,c=yield*ge.make(ks.fn("SessionStatus.state")(()=>ks.succeed(new Map))),l=ks.fn("SessionStatus.get")(function*(a){return(yield*ge.get(c)).get(a)??{type:"idle"}}),g=ks.fn("SessionStatus.list")(function*(){return new Map(yield*ge.get(c))}),u=ks.fn("SessionStatus.set")(function*(a,w){let I=yield*ge.get(c);if(yield*s.publish(d.Event.Status,{sessionID:a,status:w}),w.type==="idle"){yield*s.publish(d.Event.Idle,{sessionID:a}),I.delete(a);return}I.set(a,w)});return o.of({get:l,list:g,set:u})}));let m=d.layer.pipe(bp.provide(Ve.layer)),{runPromise:y}=Ke(o,m);async function p(s){return y(c=>c.get(s))}d.get=p,n(p,"get");async function f(){return y(s=>s.list())}d.list=f,n(f,"list");async function b(s,c){return y(l=>l.set(s,c))}d.set=b,n(b,"set")})(Ur||={});function ll(e){let t=e instanceof Error?e.message:String(e),o=typeof import.meta.dirname=="string"?import.meta.dirname:void 0;return o&&t.includes("Cannot find module")&&t.includes(o)?"AlchemyLab's files were updated or rebuilt while it was running, so this tool can no longer load. Restart alchemylab to get the tools back.":t}n(ll,"toolErrorText");var so;(d=>{let e=new Map;function t(s,c){let l={executing:0,ended:!1,end:c};return e.set(s,l),l}d.open=t,n(t,"open");function o(s,c){e.get(s)===c&&e.delete(s)}d.close=o,n(o,"close");function i(s){let c=e.get(s);return!c||c.ended||c.executing>0?!1:(c.ended=!0,c.end(),!0)}d.endForPerson=i,n(i,"endForPerson");function m(s){if(s){if(s.ended)return new Error("Not run: the user's message ended this step before this tool started.");s.executing++}}d.enter=m,n(m,"enter");function y(s){s&&s.executing>0&&s.executing--}d.leave=y,n(y,"leave");function p(s,c){let l=m(s);return l?Promise.reject(l):c()}d.run=p,n(p,"run");function f(s){y(e.get(s))}d.recorded=f,n(f,"recorded");function b(s){let c=new Set;for(let g of s)(g.type==="text"||g.type==="reasoning")&&!g.time?.end&&c.add(g.id),g.type==="tool"&&g.state.status==="pending"&&c.add(g.id);let l=n(g=>!c.has(g.id)&&(g.type==="text"||g.type==="tool"),"kept");for(let g=0;g<s.length;g++){let u=s[g];u.type!=="reasoning"||c.has(u.id)||s.slice(g+1).some(l)||c.add(u.id)}if(!s.some(l))for(let g of s)g.type==="step-start"&&c.add(g.id);return[...c]}d.toDrop=b,n(b,"toDrop")})(so||={});var Es;(y=>{y.LIMIT=12;let t=new Map;function o(p,f,b,d){if(!b)return t.delete(p),0;let s=`${f}\0${d.slice(0,300)}`,c=t.get(p),l=c&&c.sig===s?c.count+1:1;return t.set(p,{sig:s,count:l}),l}y.note=o,n(o,"note");function i(p){t.delete(p)}y.forget=i,n(i,"forget");function m(p,f,b){let d=b.replace(/\s+/g," ").trim().slice(0,160);return`It made the same failing call ${f} times in a row (${p}: "${d}"), so it was stopped.`}y.line=m,n(m,"line")})(Es||={});function xp(e,t,o,i){let m=Es.note(e,t,o,i);if(!(m<Es.LIMIT))throw Es.forget(e),new Qe.APIError({message:Es.line(t,m,i),isRetryable:!1,metadata:{alchemyStop:"repeated-tool-failure",tool:t,count:String(m)}})}n(xp,"breakRepeat");var $r;(y=>{let t=qe.create({service:"session.processor"});class o extends hw.Service()("@opencode/SessionProcessor"){static{n(this,"Service")}}y.Service=o,y.layer=ho.effect(o,$t.gen(function*(){let p=yield*yt.Service,f=yield*rt.Service,b=yield*Ve.Service,d=yield*$n.Service,s=yield*ro.Service,c=yield*Is.Service,l=yield*lt.Service,g=yield*ln.Service,u=yield*Ur.Service,a=$t.fn("SessionProcessor.create")(function*(w){let I=yield*d.track(),r={assistantMessage:w.assistantMessage,sessionID:w.sessionID,model:w.model,toolcalls:{},shouldBreak:!1,snapshot:I,blocked:!1,needsCompaction:!1,currentText:void 0,reasoningMap:{}},x=!1,h={},v=n(T=>Qe.fromError(T,{providerID:w.model.providerID,aborted:x}),"parse"),S=$t.fn("SessionProcessor.handleEvent")(function*(T){switch(T.type){case"start":yield*u.set(r.sessionID,{type:"busy"});return;case"reasoning-start":if(T.id in r.reasoningMap)return;r.reasoningMap[T.id]={id:It.ascending(),messageID:r.assistantMessage.id,sessionID:r.assistantMessage.sessionID,type:"reasoning",text:"",time:{start:Date.now()},metadata:T.providerMetadata},yield*p.updatePart(r.reasoningMap[T.id]);return;case"reasoning-delta":if(!(T.id in r.reasoningMap))return;r.reasoningMap[T.id].text+=T.text,T.providerMetadata&&(r.reasoningMap[T.id].metadata=T.providerMetadata),yield*p.updatePartDelta({sessionID:r.reasoningMap[T.id].sessionID,messageID:r.reasoningMap[T.id].messageID,partID:r.reasoningMap[T.id].id,field:"text",delta:T.text});return;case"reasoning-end":if(!(T.id in r.reasoningMap))return;r.reasoningMap[T.id].time={...r.reasoningMap[T.id].time,end:Date.now()},T.providerMetadata&&(r.reasoningMap[T.id].metadata=T.providerMetadata),yield*p.updatePart(r.reasoningMap[T.id]),delete r.reasoningMap[T.id];return;case"tool-input-start":if(r.assistantMessage.summary)throw new Error(`Tool call not allowed while generating summary: ${T.toolName}`);r.toolcalls[T.id]=yield*p.updatePart({id:r.toolcalls[T.id]?.id??It.ascending(),messageID:r.assistantMessage.id,sessionID:r.assistantMessage.sessionID,type:"tool",tool:T.toolName,callID:T.id,state:{status:"pending",input:{},raw:""}});return;case"tool-input-delta":{let N=r.toolcalls[T.id];if(!N||N.state.status!=="pending")return;let A=N.state.raw+T.delta,F=Date.now(),V=F-(h[T.id]??0)>=2e3;if(r.toolcalls[T.id]={...N,state:{...N.state,raw:A}},!V)return;h[T.id]=F,r.toolcalls[T.id]=yield*p.updatePart(r.toolcalls[T.id]),yield*p.touch(r.sessionID);return}case"tool-input-end":return;case"tool-call":{if(r.assistantMessage.summary)throw new Error(`Tool call not allowed while generating summary: ${T.toolName}`);let N=r.toolcalls[T.toolCallId];if(!N)return;r.toolcalls[T.toolCallId]=yield*p.updatePart({...N,tool:T.toolName,state:{status:"running",input:T.input,time:{start:Date.now()}},metadata:T.providerMetadata});let F=Qe.parts(r.assistantMessage.id).slice(-3);if(F.length!==3||!F.every(Y=>Y.type==="tool"&&Y.tool===T.toolName&&Y.state.status!=="pending"&&JSON.stringify(Y.state.input)===JSON.stringify(T.input)))return;let V=yield*s.get(r.assistantMessage.agent);yield*l.ask({permission:"doom_loop",patterns:[T.toolName],sessionID:r.assistantMessage.sessionID,metadata:{tool:T.toolName,input:T.input},always:[T.toolName],ruleset:V.permission});return}case"tool-result":{let N=r.toolcalls[T.toolCallId];if(!N||N.state.status!=="running")return so.recorded(r.sessionID);yield*p.updatePart({...N,state:{status:"completed",input:T.input??N.state.input,output:T.output.output,metadata:T.output.metadata,title:T.output.title,time:{start:N.state.time.start,end:Date.now()},attachments:T.output.attachments}}),delete r.toolcalls[T.toolCallId],so.recorded(r.sessionID),xp(r.sessionID,N.tool,T.output.metadata?.isError===!0,String(T.output.output??""));return}case"tool-error":{let N=r.toolcalls[T.toolCallId];if(!N||N.state.status!=="running")return so.recorded(r.sessionID);yield*p.updatePart({...N,state:{status:"error",input:T.input??N.state.input,error:ll(T.error),time:{start:N.state.time.start,end:Date.now()}}}),(T.error instanceof lt.RejectedError||T.error instanceof Eo.RejectedError)&&(r.blocked=r.shouldBreak),delete r.toolcalls[T.toolCallId],so.recorded(r.sessionID),xp(r.sessionID,N.tool,!0,ll(T.error));return}case"error":throw T.error;case"start-step":r.snapshot||(r.snapshot=yield*d.track()),yield*p.updatePart({id:It.ascending(),messageID:r.assistantMessage.id,sessionID:r.sessionID,snapshot:r.snapshot,type:"step-start"});return;case"finish-step":{let N=yt.getUsage({model:r.model,usage:T.usage,metadata:T.providerMetadata});if(r.assistantMessage.finish=T.finishReason,r.assistantMessage.cost+=N.cost,r.assistantMessage.tokens=N.tokens,T.response?.modelId&&(r.assistantMessage.servedModelID=T.response.modelId),yield*p.updatePart({id:It.ascending(),reason:T.finishReason,snapshot:yield*d.track(),messageID:r.assistantMessage.id,sessionID:r.assistantMessage.sessionID,type:"step-finish",tokens:N.tokens,cost:N.cost}),yield*p.updateMessage(r.assistantMessage),r.snapshot){let A=yield*d.patch(r.snapshot);A.files.length&&(yield*p.updatePart({id:It.ascending(),messageID:r.assistantMessage.id,sessionID:r.sessionID,type:"patch",hash:A.hash,files:A.files})),r.snapshot=void 0}dr.summarize({sessionID:r.sessionID,messageID:r.assistantMessage.parentID}),!r.assistantMessage.summary&&Da({cfg:yield*f.get(),tokens:N.tokens,model:r.model})&&(r.needsCompaction=!0);return}case"text-start":r.currentText={id:It.ascending(),messageID:r.assistantMessage.id,sessionID:r.assistantMessage.sessionID,type:"text",text:"",time:{start:Date.now()},metadata:T.providerMetadata},yield*p.updatePart(r.currentText);return;case"text-delta":if(!r.currentText)return;r.currentText.text+=T.text,T.providerMetadata&&(r.currentText.metadata=T.providerMetadata),yield*p.updatePartDelta({sessionID:r.currentText.sessionID,messageID:r.currentText.messageID,partID:r.currentText.id,field:"text",delta:T.text});return;case"text-end":if(!r.currentText)return;r.currentText.text=(yield*g.trigger("experimental.text.complete",{sessionID:r.sessionID,messageID:r.assistantMessage.id,partID:r.currentText.id},{text:r.currentText.text})).text,r.currentText.time={start:r.currentText.time?.start??Date.now(),end:Date.now()},T.providerMetadata&&(r.currentText.metadata=T.providerMetadata),yield*p.updatePart(r.currentText);let G=gp(Qe.parts(r.assistantMessage.id),r.currentText);G&&(yield*p.removePart({sessionID:G.sessionID,messageID:G.messageID,partID:G.id})),r.currentText=void 0;return;case"finish":return;default:t.info("unhandled",{...T});return}}),j=$t.fn("SessionProcessor.cleanup")(function*(){if(r.snapshot){let G=yield*d.patch(r.snapshot);G.files.length&&(yield*p.updatePart({id:It.ascending(),messageID:r.assistantMessage.id,sessionID:r.sessionID,type:"patch",hash:G.hash,files:G.files})),r.snapshot=void 0}if(r.currentText){let G=Date.now();r.currentText.time={start:r.currentText.time?.start??G,end:G},yield*p.updatePart(r.currentText),r.currentText=void 0}for(let G of Object.values(r.reasoningMap)){let N=Date.now();yield*p.updatePart({...G,time:{start:G.time.start??N,end:N}})}r.reasoningMap={};let T=Qe.parts(r.assistantMessage.id);for(let G of T)G.type!=="tool"||G.state.status==="completed"||G.state.status==="error"||(yield*p.updatePart({...G,state:{...G.state,status:"error",error:"Tool execution aborted",time:{start:Date.now(),end:Date.now()}}}));r.assistantMessage.time.completed=Date.now(),yield*p.updateMessage(r.assistantMessage)}),O=$t.fn("SessionProcessor.halt")(function*(T){t.error("process",{error:T,stack:T instanceof Error?T.stack:void 0});let G=v(T);if(Qe.ContextOverflowError.isInstance(G)){r.needsCompaction=!0,yield*b.publish(yt.Event.Error,{sessionID:r.sessionID,error:G});return}r.assistantMessage.error=G,yield*b.publish(yt.Event.Error,{sessionID:r.assistantMessage.sessionID,error:r.assistantMessage.error}),yield*u.set(r.sessionID,{type:"idle"})}),k=$t.fn("SessionProcessor.abort")(()=>$t.gen(function*(){if(r.assistantMessage.error||(yield*O(new DOMException("Aborted","AbortError"))),!r.assistantMessage.time.completed){yield*j();return}yield*p.updateMessage(r.assistantMessage)})),E=new Set,D=n(()=>Qe.parts(r.assistantMessage.id).filter(T=>!E.has(T.id)),"attemptParts"),z=n(T=>(T.type==="text"||T.type==="reasoning")&&!T.time?.end,"unfinished"),_=$t.fn("SessionProcessor.dropAttempt")(function*(){r.currentText=void 0,r.reasoningMap={};for(let T of D())T.type!=="text"&&T.type!=="reasoning"&&T.type!=="step-start"||(yield*p.removePart({sessionID:T.sessionID,messageID:T.messageID,partID:T.id}))}),B=$t.fn("SessionProcessor.keepFinished")(function*(T){if(!Ta.retryable(v(T)))return yield*$t.fail(T);let G=D();if(!G.some(A=>A.type==="tool"&&(A.state.status==="completed"||A.state.status==="error")))return yield*$t.fail(T);t.info("step failed after a tool finished; continuing from its finished items",{error:T}),r.currentText=void 0,r.reasoningMap={};for(let A of G)z(A)&&(yield*p.removePart({sessionID:A.sessionID,messageID:A.messageID,partID:A.id}));r.assistantMessage.finish="tool-calls"}),$=!1,M=$t.fn("SessionProcessor.endForPerson")(function*(){r.currentText=void 0,r.reasoningMap={};let T=new Set(so.toDrop(D()));for(let G of D())T.has(G.id)&&(delete r.toolcalls[G.callID],yield*p.removePart({sessionID:G.sessionID,messageID:G.messageID,partID:G.id}));r.assistantMessage.finish="tool-calls",t.info("step ended for a person's message",{sessionID:r.sessionID,messageID:r.assistantMessage.id,dropped:T.size})}),C=$t.fn("SessionProcessor.process")(function*(T){t.info("process"),r.needsCompaction=!1,r.shouldBreak=(yield*f.get()).experimental?.continue_loop_on_deny!==!0;let G=0,N=w.preempt?.pipe($t.andThen($t.sync(()=>{$=!0})));return yield*$t.gen(function*(){return yield*$t.gen(function*(){if($)return;G++>0&&(yield*_()),E=new Set(Qe.parts(r.assistantMessage.id).map(F=>F.id)),r.currentText=void 0,r.reasoningMap={};let A=c.stream(T).pipe(gr.tap(F=>S(F)),gr.takeUntil(()=>r.needsCompaction));yield*(N?A.pipe(gr.interruptWhen(N)):A).pipe(gr.runDrain),$&&(yield*M())}).pipe($t.onInterrupt(()=>$t.sync(()=>{x=!0})),$t.catchCauseIf(A=>!wp.hasInterruptsOnly(A),A=>$t.fail(wp.squash(A))),$t.catch(B),$t.retry(Ta.policy({parse:v,set:n(A=>u.set(r.sessionID,{type:"retry",attempt:A.attempt,message:A.message,next:A.next}),"set")})),$t.catch(O),$t.ensuring(j())),x&&!r.assistantMessage.error&&(yield*k()),r.needsCompaction?"compact":r.blocked||r.assistantMessage.error||x?"stop":"continue"}).pipe($t.onInterrupt(()=>k().pipe($t.asVoid)))});return{get message(){return r.assistantMessage},partFromToolCall(T){return r.toolcalls[T]},abort:k,process:C}});return o.of({create:a})})),y.defaultLayer=ho.unwrap($t.sync(()=>y.layer.pipe(ho.provide(yt.defaultLayer),ho.provide($n.defaultLayer),ho.provide(ro.defaultLayer),ho.provide(Is.defaultLayer),ho.provide(lt.defaultLayer),ho.provide(ln.defaultLayer),ho.provide(Ur.layer.pipe(ho.provide(Ve.layer))),ho.provide(Ve.layer),ho.provide(rt.defaultLayer))))})($r||={});import{z as yw}from"zod";function nn(e,t){let o=n(i=>{let m;try{m=e.parse(i)}catch(y){throw console.trace("schema validation failure stack trace:"),y instanceof yw.ZodError&&console.error("schema validation issues:",JSON.stringify(y.issues,null,2)),y}return t(m)},"result");return o.force=i=>t(i),o.schema=e,o}n(nn,"fn");import{Effect as Fo,Layer as Zo,ServiceMap as bw}from"effect";import ww from"path";var Pa="The messages before this compaction, word for word (newest last):";function vp(e){let t=[];for(let m of e)if(!(m.info.role!=="user"||m.parts.some(y=>y.type==="compaction"))){for(let y of m.parts)if(!(y.type!=="text"||!y.text?.trim())){if(!y.synthetic)t.push(y.text.trim());else if(y.text.includes(Pa)){let p=y.text.slice(y.text.indexOf(Pa)+Pa.length).split(`
|
|
1229
|
+
|
|
1230
|
+
<<<END>>>`)[0];t.push(...p.split(`
|
|
1231
|
+
|
|
1232
|
+
<<<NEXT>>>
|
|
1233
|
+
|
|
1234
|
+
`).map(f=>f.trim()).filter(Boolean))}}}let o=[],i=0;for(let m=t.length-1;m>=0&&!(i+t[m].length>16e3);m--)o.unshift(t[m]),i+=t[m].length;return o.length===0?"":`${Pa}
|
|
1235
|
+
|
|
1236
|
+
${o.join(`
|
|
1237
|
+
|
|
1238
|
+
<<<NEXT>>>
|
|
1239
|
+
|
|
1240
|
+
`)}
|
|
1241
|
+
|
|
1242
|
+
<<<END>>>`}n(vp,"wordsToCarry");var _a;(u=>{let e=qe.create({service:"session.compaction"});u.Event={Compacted:mt.define("session.compacted",zo.object({sessionID:He.zod}))};async function o(a,w){if(!Ce.ALCHEMYLAB)return"";try{let I=JSON.parse(await Ee.readText(ww.join(a,".alchemy_lab","action-server.json")));if(!I?.port)return"";let r=await fetch(`http://127.0.0.1:${I.port}/api/sessions/${encodeURIComponent(w)}/after-compaction`,{signal:AbortSignal.timeout(8e3),headers:typeof I.secret=="string"?{"x-alchemy-local":I.secret}:{}});if(!r.ok)return"";let x=await r.json();return String(x?.data?.text??"").trim()}catch{return""}}n(o,"recordsAfterCompaction"),u.PRUNE_MINIMUM=2e4,u.PRUNE_PROTECT=4e4;let y=["skill"];class p extends bw.Service()("@opencode/SessionCompaction"){static{n(this,"Service")}}u.Service=p,u.layer=Zo.effect(p,Fo.gen(function*(){let a=yield*Ve.Service,w=yield*rt.Service,I=yield*yt.Service,r=yield*ro.Service,x=yield*ln.Service,h=yield*$r.Service,v=yield*yn.Service,S=Fo.fn("SessionCompaction.isOverflow")(function*(E){return Da({cfg:yield*w.get(),tokens:E.tokens,model:E.model})}),j=Fo.fn("SessionCompaction.prune")(function*(E){if((yield*w.get()).compaction?.prune===!1)return;e.info("pruning");let z=yield*I.messages({sessionID:E.sessionID}).pipe(Fo.catchIf(kr.isInstance,()=>Fo.succeed(void 0)));if(!z)return;let _=0,B=0,$=[],M=0;e:for(let C=z.length-1;C>=0;C--){let T=z[C];if(T.info.role==="user"&&M++,!(M<2)){if(T.info.role==="assistant"&&T.info.summary)break e;for(let G=T.parts.length-1;G>=0;G--){let N=T.parts[G];if(N.type==="tool"&&N.state.status==="completed"){if(y.includes(N.tool))continue;if(N.state.time.compacted)break e;let A=sl.estimate(N.state.output);_+=A,_>u.PRUNE_PROTECT&&(B+=A,$.push(N))}}}}if(e.info("found",{pruned:B,total:_}),B>u.PRUNE_MINIMUM){for(let C of $)C.state.status==="completed"&&(C.state.time.compacted=Date.now(),yield*I.updatePart(C));e.info("pruned",{count:$.length})}}),O=Fo.fn("SessionCompaction.process")(function*(E){let D=E.messages.findLast(R=>R.info.id===E.parentID);if(!D||D.info.role!=="user")throw new Error(`Compaction parent must be a user message: ${E.parentID}`);let z=D.info,_=E.messages,B;if(E.overflow){let R=E.messages.findIndex(q=>q.info.id===E.parentID);for(let q=R-1;q>=0;q--){let X=E.messages[q];if(X.info.role==="user"&&!X.parts.some(ne=>ne.type==="compaction")){B={info:X.info,parts:X.parts},_=E.messages.slice(0,q);break}}B&&_.some(q=>q.info.role==="user"&&!q.parts.some(X=>X.type==="compaction"))||(B=void 0,_=E.messages)}let $=yield*r.get("compaction"),M=$.model?yield*v.getModel($.model.providerID,$.model.modelID):yield*v.getModel(z.model.providerID,z.model.modelID),C=E.shared&&!E.overflow&&!$.model?E.shared:void 0,T=yield*x.trigger("experimental.session.compacting",{sessionID:E.sessionID},{context:[],prompt:void 0}),N=T.prompt??[`Provide a detailed prompt for continuing our conversation above.
|
|
1243
|
+
Focus on information that would be helpful for continuing the conversation, including what we did, what we're doing, which files we're working on, and what we're going to do next.
|
|
1244
|
+
The summary that you construct will be used so that another agent can read it and continue the work.
|
|
1245
|
+
Do not call any tools. Respond only with the summary text.
|
|
1246
|
+
Respond in the same language as the user's messages in the conversation.
|
|
1247
|
+
|
|
1248
|
+
When constructing the summary, try to stick to this template:
|
|
1249
|
+
---
|
|
1250
|
+
## Goal
|
|
1251
|
+
|
|
1252
|
+
[What goal(s) is the user trying to accomplish?]
|
|
1253
|
+
|
|
1254
|
+
## Instructions
|
|
1255
|
+
|
|
1256
|
+
- [What important instructions did the user give you that are relevant]
|
|
1257
|
+
- [If there is a plan or spec, include information about it so next agent can continue using it]
|
|
1258
|
+
|
|
1259
|
+
## Discoveries
|
|
1260
|
+
|
|
1261
|
+
[What notable things were learned during this conversation that would be useful for the next agent to know when continuing the work]
|
|
1262
|
+
|
|
1263
|
+
## Accomplished
|
|
1264
|
+
|
|
1265
|
+
[What work has been completed, what work is still in progress, and what work is left?]
|
|
1266
|
+
|
|
1267
|
+
## Relevant files / directories
|
|
1268
|
+
|
|
1269
|
+
[Construct a structured list of relevant files that have been read, edited, or created that pertain to the task at hand. If all the files in a directory are relevant, include the path to the directory.]
|
|
1270
|
+
|
|
1271
|
+
## Errors and how they were fixed
|
|
1272
|
+
|
|
1273
|
+
[Each error hit, what caused it and what fixed it, so it is not hit again.]
|
|
1274
|
+
|
|
1275
|
+
## Checked so far
|
|
1276
|
+
|
|
1277
|
+
[What was run or looked at to check the work, and what it showed.]
|
|
1278
|
+
|
|
1279
|
+
## Next step
|
|
1280
|
+
|
|
1281
|
+
[The next step, with the last instruction you were acting on quoted word for word.]
|
|
1282
|
+
---`,...T.context].join(`
|
|
1283
|
+
|
|
1284
|
+
`),A=structuredClone(_);yield*x.trigger("experimental.chat.messages.transform",{},{messages:A});let F=yield*Qe.toModelMessagesEffect(A,M,C?{}:{stripMedia:!0}),V=yield*ge.context,Y={id:pt.ascending(),role:"assistant",parentID:E.parentID,sessionID:E.sessionID,mode:"compaction",agent:"compaction",variant:z.variant,summary:!0,path:{cwd:V.directory,root:V.worktree},cost:0,tokens:{output:0,input:0,reasoning:0,cache:{read:0,write:0}},modelID:M.id,providerID:M.providerID,time:{created:Date.now()}};yield*I.updateMessage(Y);let re=yield*h.create({assistantMessage:Y,sessionID:E.sessionID,model:M}),ue={role:"user",content:[{type:"text",text:N}]};e.info(C?"compacting on the session's own prefix":"compacting without the session's prefix",{sessionID:E.sessionID,offered:!!E.shared,overflow:!!E.overflow,ownModel:!!$.model});let H=yield*re.process(C?{user:C.user,agent:C.agent,permission:C.permission,sessionID:E.sessionID,parentSessionID:C.parentSessionID,tools:C.tools,system:C.system,messages:[...F,ue],model:M}:{user:z,agent:$,sessionID:E.sessionID,tools:{},system:[],messages:[...F,ue],model:M}).pipe(Fo.onInterrupt(()=>re.abort()));if(H==="compact")return re.message.error=new Qe.ContextOverflowError({message:B?"Conversation history too large to compact - exceeds model context limit":"Session too large to compact - context exceeds model limit even after stripping media"}).toObject(),re.message.finish="error",yield*I.updateMessage(re.message),"stop";if(H==="continue"&&E.auto){if(B){let R=B.info,L=yield*I.updateMessage({id:pt.ascending(),role:"user",sessionID:E.sessionID,time:{created:Date.now()},agent:R.agent,model:R.model,format:R.format,tools:R.tools,system:R.system,variant:R.variant});for(let q of B.parts){if(q.type==="compaction")continue;let X=q.type==="file"&&Qe.isMedia(q.mime)?{type:"text",text:`[Attached ${q.mime}: ${q.filename??"file"}]`}:q;yield*I.updatePart({...X,id:It.ascending(),messageID:L.id,sessionID:E.sessionID})}}if(!B){let R=yield*I.updateMessage({id:pt.ascending(),role:"user",sessionID:E.sessionID,time:{created:Date.now()},agent:z.agent,model:z.model}),L=yield*Fo.promise(()=>o(V.directory,E.sessionID)),q=vp(E.messages),X=(E.overflow?`The previous request exceeded the provider's size limit due to large media attachments. The conversation was compacted and media files were removed from context. If the user was asking about attached images or files, explain that the attachments were too large to process and suggest they try again with smaller or fewer files.
|
|
1285
|
+
|
|
1286
|
+
`:"")+"This session was compacted automatically to free context: the summary above covers the earlier part of it, and nothing else has happened since. "+(q||L?`Below are the messages it received and the records as they stand now.
|
|
1287
|
+
|
|
1288
|
+
`:`
|
|
1289
|
+
|
|
1290
|
+
`)+(q?`${q}
|
|
1291
|
+
|
|
1292
|
+
`:"")+(L?`${L}
|
|
1293
|
+
|
|
1294
|
+
`:"")+"Resume directly with the next step: do not acknowledge the summary, do not recap, and do not stop to report. Pick up the last task as if the break never happened.";yield*I.updatePart({id:It.ascending(),messageID:R.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:X,time:{start:Date.now(),end:Date.now()}})}}return re.message.error?"stop":(H==="continue"&&(yield*a.publish(u.Event.Compacted,{sessionID:E.sessionID})),H)}),k=Fo.fn("SessionCompaction.create")(function*(E){let D=yield*I.updateMessage({id:pt.ascending(),role:"user",model:E.model,sessionID:E.sessionID,agent:E.agent,time:{created:Date.now()}});yield*I.updatePart({id:It.ascending(),messageID:D.id,sessionID:D.sessionID,type:"compaction",auto:E.auto,overflow:E.overflow})});return p.of({isOverflow:S,prune:j,process:O,create:k})})),u.defaultLayer=Zo.unwrap(Fo.sync(()=>u.layer.pipe(Zo.provide(yn.defaultLayer),Zo.provide(yt.defaultLayer),Zo.provide($r.defaultLayer),Zo.provide(ro.defaultLayer),Zo.provide(ln.defaultLayer),Zo.provide(Ve.layer),Zo.provide(rt.defaultLayer))));let{runPromise:d}=Ke(p,u.defaultLayer);async function s(a){return d(w=>w.isOverflow(a))}u.isOverflow=s,n(s,"isOverflow");async function c(a){return d(w=>w.prune(a))}u.prune=c,n(c,"prune"),u.process=nn(zo.object({parentID:pt.zod,messages:zo.custom(),sessionID:He.zod,auto:zo.boolean(),overflow:zo.boolean().optional()}),a=>d(w=>w.process(a))),u.create=nn(zo.object({sessionID:He.zod,agent:zo.string(),model:zo.object({providerID:Et.zod,modelID:Ut.zod}),auto:zo.boolean(),overflow:zo.boolean().optional()}),a=>d(w=>w.create(a)))})(_a||={});var xw=new Set(["inbox-chat","via-herald"]);function Ip(e){let t=e.map(o=>o?.metadata?.alchemy?.kind).filter(o=>typeof o=="string"&&o.length>0);return t.length===0?!0:t.some(o=>xw.has(o))}n(Ip,"writtenByAPerson");var vw="[from AlchemyLab, not a user message]";function kp(e){let t=e.startsWith(vw);return["<system-reminder>",t?"This note reached you while you worked:":"The user sent the following message:",e,"",t?"Take it into account and continue with your tasks.":"Please address this message and continue with your tasks.","</system-reminder>"].join(`
|
|
1295
|
+
`)}n(kp,"raisedMidTurn");var Iw=/\bto=functions\.|^\s*functions\.[A-Za-z_]+\s*[({]/m;function Ep(e){let t=e.filter(m=>m.type==="text"),o=t.filter(m=>(m.text??"").trim().length>0&&!Iw.test(m.text??"")),i=o.length>0?o[o.length-1]:void 0;return{drop:t.filter(m=>m!==i).map(m=>m.id),answered:i!==void 0}}n(Ep,"asideTextToDrop");function Sp(e){let t,o,i,m=[],y;for(let p=e.length-1;p>=0;p--){let f=e[p];if(f.info.role==="assistant"&&f.info.aside)continue;if(f.info.role==="user"&&f.info.quiet){y??=f.info;continue}if(!t&&f.info.role==="user"&&(t=f.info),!o&&f.info.role==="assistant"&&(o=f.info),!i&&f.info.role==="assistant"&&f.info.finish&&(i=f.info),t&&i)break;let b=f.parts.filter(d=>d.type==="compaction"||d.type==="subtask");b&&!i&&m.push(...b)}return{lastUser:t??y,lastAssistant:o,lastFinished:i,tasks:m}}n(Sp,"scanForLoop");import _p from"os";import Dn from"path";import{Effect as Yt,Layer as Oa,ServiceMap as kw}from"effect";import{FetchHttpClient as Ew,HttpClient as Dp,HttpClientRequest as Sw}from"effect/unstable/http";var Dw=qe.create({service:"instruction"}),Tp=["AGENTS.md",...Ce.OPENCODE_DISABLE_CLAUDE_CODE_PROMPT?[]:["CLAUDE.md"],"CONTEXT.md"];function Tw(){let e=[];return Ce.OPENCODE_CONFIG_DIR&&e.push(Dn.join(Ce.OPENCODE_CONFIG_DIR,"AGENTS.md")),e.push(Dn.join(je.Path.config,"AGENTS.md")),Ce.OPENCODE_DISABLE_CLAUDE_CODE_PROMPT||e.push(Dn.join(_p.homedir(),".claude","CLAUDE.md")),e}n(Tw,"globalFiles");function Pp(e){let t=new Set;for(let o of e)for(let i of o.parts)if(i.type==="tool"&&i.tool==="read"&&i.state.status==="completed"){if(i.state.time.compacted)continue;let m=i.state.metadata?.loaded;if(!m||!Array.isArray(m))continue;for(let y of m)typeof y=="string"&&t.add(y)}return t}n(Pp,"extract");var hr;(b=>{class e extends kw.Service()("@opencode/Instruction"){static{n(this,"Service")}}b.Service=e,b.layer=Oa.effect(e,Yt.gen(function*(){let d=yield*rt.Service,s=yield*ut.Service,c=Dp.filterStatusOk(sr(yield*Dp.HttpClient)),l=yield*ge.make(Yt.fn("Instruction.state")(()=>Yt.succeed({claims:new Map}))),g=Yt.fnUntraced(function*(v){return Ce.OPENCODE_DISABLE_PROJECT_CONFIG?Ce.OPENCODE_CONFIG_DIR?yield*s.globUp(v,Ce.OPENCODE_CONFIG_DIR,Ce.OPENCODE_CONFIG_DIR).pipe(Yt.catch(()=>Yt.succeed([]))):(Dw.warn(`Skipping relative instruction "${v}" - no OPENCODE_CONFIG_DIR set while project config is disabled`),[]):yield*s.globUp(v,he.directory,he.worktree).pipe(Yt.catch(()=>Yt.succeed([])))}),u=Yt.fnUntraced(function*(v){return yield*s.readFileString(v).pipe(Yt.catch(()=>Yt.succeed("")))}),a=Yt.fnUntraced(function*(v){let S=yield*c.execute(Sw.get(v)).pipe(Yt.timeout(5e3),Yt.catch(()=>Yt.succeed(null)));if(!S)return"";let j=yield*S.arrayBuffer.pipe(Yt.catch(()=>Yt.succeed(new ArrayBuffer(0))));return new TextDecoder().decode(j)}),w=Yt.fn("Instruction.clear")(function*(v){(yield*ge.get(l)).claims.delete(v)}),I=Yt.fn("Instruction.systemPaths")(function*(){let v=yield*d.get(),S=new Set;if(!Ce.OPENCODE_DISABLE_PROJECT_CONFIG)for(let j of Tp){let O=yield*s.findUp(j,he.directory,he.worktree);if(O.length>0){O.forEach(k=>S.add(Dn.resolve(k)));break}}for(let j of Tw())if(yield*s.existsSafe(j)){S.add(Dn.resolve(j));break}if(v.instructions)for(let j of v.instructions){if(j.startsWith("https://")||j.startsWith("http://"))continue;let O=j.startsWith("~/")?Dn.join(_p.homedir(),j.slice(2)):j;(yield*(Dn.isAbsolute(O)?s.glob(Dn.basename(O),{cwd:Dn.dirname(O),absolute:!0,include:"file"}):g(O)).pipe(Yt.catch(()=>Yt.succeed([])))).forEach(E=>S.add(Dn.resolve(E)))}return S}),r=Yt.fn("Instruction.system")(function*(){let v=yield*d.get(),S=yield*I(),j=(v.instructions??[]).filter(E=>E.startsWith("https://")||E.startsWith("http://")),O=yield*Yt.forEach(Array.from(S),u,{concurrency:8}),k=yield*Yt.forEach(j,a,{concurrency:4});return[...Array.from(S).flatMap((E,D)=>O[D]?[`Instructions from: ${E}
|
|
1296
|
+
${O[D]}`]:[]),...j.flatMap((E,D)=>k[D]?[`Instructions from: ${E}
|
|
1297
|
+
${k[D]}`]:[])]}),x=Yt.fn("Instruction.find")(function*(v){for(let S of Tp){let j=Dn.resolve(Dn.join(v,S));if(yield*s.existsSafe(j))return j}}),h=Yt.fn("Instruction.resolve")(function*(v,S,j){let O=yield*I(),k=Pp(v),E=[],D=yield*ge.get(l),z=Dn.resolve(S),_=Dn.resolve(he.directory),B=Dn.dirname(z);for(;B.startsWith(_)&&B!==_;){let $=yield*x(B);if(!$||$===z||O.has($)||k.has($)){B=Dn.dirname(B);continue}let M=D.claims.get(j);if(M||(M=new Set,D.claims.set(j,M)),M.has($)){B=Dn.dirname(B);continue}M.add($);let C=yield*u($);C&&E.push({filepath:$,content:`Instructions from: ${$}
|
|
1298
|
+
${C}`}),B=Dn.dirname(B)}return E});return e.of({clear:w,systemPaths:I,system:r,find:x,resolve:h})})),b.defaultLayer=b.layer.pipe(Oa.provide(rt.defaultLayer),Oa.provide(ut.defaultLayer),Oa.provide(Ew.layer));let{runPromise:i}=Ke(e,b.defaultLayer);function m(d){return i(s=>s.clear(d))}b.clear=m,n(m,"clear");async function y(){return i(d=>d.systemPaths())}b.systemPaths=y,n(y,"systemPaths");function p(d){return Pp(d)}b.loaded=p,n(p,"loaded");async function f(d,s,c){return i(l=>l.resolve(d,s,c))}b.resolve=f,n(f,"resolve")})(hr||={});var Op=`<system-reminder>
|
|
1299
|
+
# Plan Mode - System Reminder
|
|
1300
|
+
|
|
1301
|
+
CRITICAL: Plan mode ACTIVE - you are in READ-ONLY phase. STRICTLY FORBIDDEN:
|
|
1302
|
+
ANY file edits, modifications, or system changes. Do NOT use sed, tee, echo, cat,
|
|
1303
|
+
or ANY other bash command to manipulate files - commands may ONLY read/inspect.
|
|
1304
|
+
This ABSOLUTE CONSTRAINT overrides ALL other instructions, including direct user
|
|
1305
|
+
edit requests. You may ONLY observe, analyze, and plan. Any modification attempt
|
|
1306
|
+
is a critical violation. ZERO exceptions.
|
|
1307
|
+
|
|
1308
|
+
---
|
|
1309
|
+
|
|
1310
|
+
## Responsibility
|
|
1311
|
+
|
|
1312
|
+
Your current responsibility is to think, read, search, and delegate explore agents to construct a well-formed plan that accomplishes the goal the user wants to achieve. Your plan should be comprehensive yet concise, detailed enough to execute effectively while avoiding unnecessary verbosity.
|
|
1313
|
+
|
|
1314
|
+
Ask the user clarifying questions or ask for their opinion when weighing tradeoffs.
|
|
1315
|
+
|
|
1316
|
+
**NOTE:** At any point in time through this workflow you should feel free to ask the user questions or clarifications. Don't make large assumptions about user intent. The goal is to present a well researched plan to the user, and tie any loose ends before implementation begins.
|
|
1317
|
+
|
|
1318
|
+
---
|
|
1319
|
+
|
|
1320
|
+
## Important
|
|
1321
|
+
|
|
1322
|
+
The user indicated that they do not want you to execute yet -- you MUST NOT make any edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.
|
|
1323
|
+
</system-reminder>
|
|
1324
|
+
`;var dl=`<system-reminder>
|
|
1325
|
+
Your operational mode has changed from plan to build.
|
|
1326
|
+
You are no longer in read-only mode.
|
|
1327
|
+
You are permitted to make file changes, run shell commands, and utilize your arsenal of tools as needed.
|
|
1328
|
+
</system-reminder>
|
|
1329
|
+
`;var Ap=`CRITICAL - MAXIMUM STEPS REACHED
|
|
1330
|
+
|
|
1331
|
+
The maximum number of steps allowed for this task has been reached. Tools are disabled until next user input. Respond with text only.
|
|
1332
|
+
|
|
1333
|
+
STRICT REQUIREMENTS:
|
|
1334
|
+
1. Do NOT make any tool calls (no reads, writes, edits, searches, or any other tools)
|
|
1335
|
+
2. MUST provide a text response summarizing work done so far
|
|
1336
|
+
3. This constraint overrides ALL other instructions, including any user requests for edits or tool use
|
|
1337
|
+
|
|
1338
|
+
Response must include:
|
|
1339
|
+
- Statement that maximum steps for this agent have been reached
|
|
1340
|
+
- Summary of what has been accomplished so far
|
|
1341
|
+
- List of any remaining tasks that were not completed
|
|
1342
|
+
- Recommendations for what should be done next
|
|
1343
|
+
|
|
1344
|
+
Any attempt to use tools is a critical violation. Respond with text ONLY.`;import{Cause as Cp,Deferred as Qo,Effect as kt,Exit as Rp,Fiber as pi,Option as Pw,Schema as _w,SynchronizedRef as yr}from"effect";var ul;(o=>{class e extends _w.TaggedErrorClass()("RunnerCancelled",{}){static{n(this,"Cancelled")}}o.Cancelled=e,o.make=n((i,m)=>{let y=yr.makeUnsafe({_tag:"Idle"}),p=m?.onIdle??kt.void,f=m?.onBusy??kt.void,b=m?.onInterrupt,d=0,s=n(()=>yr.getUnsafe(y),"state"),c=n(()=>(d+=1,d),"next"),l=n((v,S)=>Rp.isFailure(S)&&Cp.hasInterruptsOnly(S.cause)?Qo.fail(v,new e).pipe(kt.asVoid):Qo.done(v,S).pipe(kt.asVoid),"complete"),g=n(()=>yr.modify(y,v=>[v._tag==="Idle"?p:kt.void,v]).pipe(kt.flatten),"idleIfCurrent"),u=n((v,S,j)=>yr.modify(y,O=>[kt.gen(function*(){O._tag==="Running"&&O.run.id===v&&(yield*p),yield*l(S,j)}),O._tag==="Running"&&O.run.id===v?{_tag:"Idle"}:O]).pipe(kt.flatten),"finishRun"),a=n((v,S)=>kt.gen(function*(){let j=c(),O=yield*v.pipe(kt.onExit(k=>u(j,S,k)),kt.forkIn(i));return{id:j,done:S,fiber:O}}),"startRun"),w=n(v=>yr.modifyEffect(y,kt.fnUntraced(function*(S){if(S._tag==="Shell"&&S.shell.id===v)return[p,{_tag:"Idle"}];if(S._tag==="ShellThenRun"&&S.shell.id===v){let j=yield*a(S.run.work,S.run.done);return[kt.void,{_tag:"Running",run:j}]}return[kt.void,S]})).pipe(kt.flatten),"finishShell"),I=n(v=>kt.gen(function*(){v.abort.abort();let S=yield*pi.await(v.fiber).pipe(kt.timeoutOption("100 millis"));Pw.isNone(S)&&(yield*pi.interrupt(v.fiber)),yield*pi.await(v.fiber).pipe(kt.exit,kt.asVoid)}),"stopShell"),r=n(v=>yr.modifyEffect(y,kt.fnUntraced(function*(S){switch(S._tag){case"Running":case"ShellThenRun":return[Qo.await(S.run.done),S];case"Shell":{let j={id:c(),done:yield*Qo.make(),work:v};return[Qo.await(j.done),{_tag:"ShellThenRun",shell:S.shell,run:j}]}case"Idle":{let j=yield*Qo.make(),O=yield*a(v,j);return[Qo.await(j),{_tag:"Running",run:O}]}}})).pipe(kt.flatten,kt.catch(S=>S instanceof e?b??kt.die(S):kt.fail(S))),"ensureRunning"),x=n(v=>yr.modifyEffect(y,kt.fnUntraced(function*(S){if(S._tag!=="Idle")return[kt.sync(()=>{throw m?.busy&&m.busy(),new Error("Runner is busy")}),S];yield*f;let j=c(),O=new AbortController,k=yield*v(O.signal).pipe(kt.ensuring(w(j)),kt.forkChild),E={id:j,fiber:k,abort:O};return[kt.gen(function*(){let D=yield*pi.await(k);return Rp.isSuccess(D)?D.value:Cp.hasInterruptsOnly(D.cause)&&b?yield*b:yield*kt.failCause(D.cause)}),{_tag:"Shell",shell:E}]})).pipe(kt.flatten),"startShell"),h=yr.modify(y,v=>{switch(v._tag){case"Idle":return[kt.void,v];case"Running":return[kt.gen(function*(){yield*pi.interrupt(v.run.fiber),yield*Qo.await(v.run.done).pipe(kt.exit,kt.asVoid),yield*g()}),{_tag:"Idle"}];case"Shell":return[kt.gen(function*(){yield*I(v.shell),yield*g()}),{_tag:"Idle"}];case"ShellThenRun":return[kt.gen(function*(){yield*Qo.fail(v.run.done,new e).pipe(kt.asVoid),yield*I(v.shell),yield*g()}),{_tag:"Idle"}]}}).pipe(kt.flatten);return{get state(){return s()},get busy(){return s()._tag!=="Idle"},ensureRunning:r,startShell:x,cancel:h}},"make")})(ul||={});import{dynamicTool as Mw,jsonSchema as Lw}from"ai";import{Client as Mp}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as Lp}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as Nw}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as zw}from"@modelcontextprotocol/sdk/client/stdio.js";import{UnauthorizedError as Np}from"@modelcontextprotocol/sdk/client/auth.js";import{CallToolResultSchema as Fw,ToolListChangedNotificationSchema as Uw}from"@modelcontextprotocol/sdk/types.js";import Lt from"zod/v4";import Ow from"path";import Kn from"zod";import{Effect as Wn,Layer as jp,ServiceMap as Aw}from"effect";var Tn;(I=>{I.Tokens=Kn.object({accessToken:Kn.string(),refreshToken:Kn.string().optional(),expiresAt:Kn.number().optional(),scope:Kn.string().optional()}),I.ClientInfo=Kn.object({clientId:Kn.string(),clientSecret:Kn.string().optional(),clientIdIssuedAt:Kn.number().optional(),clientSecretExpiresAt:Kn.number().optional()}),I.Entry=Kn.object({tokens:I.Tokens.optional(),clientInfo:I.ClientInfo.optional(),codeVerifier:Kn.string().optional(),oauthState:Kn.string().optional(),serverUrl:Kn.string().optional()});let i=Ow.join(je.Path.globalData,"mcp-auth.json");class m extends Aw.Service()("@opencode/McpAuth"){static{n(this,"Service")}}I.Service=m,I.layer=jp.effect(m,Wn.gen(function*(){let r=yield*ut.Service,x=Wn.fn("McpAuth.all")(function*(){return yield*r.readJson(i).pipe(Wn.map(T=>T),Wn.catch(()=>Wn.succeed({})))}),h=Wn.fn("McpAuth.get")(function*(T){return(yield*x())[T]}),v=Wn.fn("McpAuth.getForUrl")(function*(T,G){let N=yield*h(T);if(N&&N.serverUrl&&N.serverUrl===G)return N}),S=Wn.fn("McpAuth.set")(function*(T,G,N){let A=yield*x();N&&(G.serverUrl=N),yield*r.writeJson(i,{...A,[T]:G},384).pipe(Wn.orDie)}),j=Wn.fn("McpAuth.remove")(function*(T){let G=yield*x();delete G[T],yield*r.writeJson(i,G,384).pipe(Wn.orDie)}),O=n((T,G)=>Wn.fn(`McpAuth.${G}`)(function*(N,A,F){let V=(yield*h(N))??{};V[T]=A,yield*S(N,V,F)}),"updateField"),k=n((T,G)=>Wn.fn(`McpAuth.${G}`)(function*(N){let A=yield*h(N);A&&(delete A[T],yield*S(N,A))}),"clearField"),E=O("tokens","updateTokens"),D=O("clientInfo","updateClientInfo"),z=O("codeVerifier","updateCodeVerifier"),_=O("oauthState","updateOAuthState"),B=k("codeVerifier","clearCodeVerifier"),$=k("oauthState","clearOAuthState"),M=Wn.fn("McpAuth.getOAuthState")(function*(T){return(yield*h(T))?.oauthState}),C=Wn.fn("McpAuth.isTokenExpired")(function*(T){let G=yield*h(T);return G?.tokens?G.tokens.expiresAt?G.tokens.expiresAt<Date.now()/1e3:!1:null});return m.of({all:x,get:h,getForUrl:v,set:S,remove:j,updateTokens:E,updateClientInfo:D,updateCodeVerifier:z,clearCodeVerifier:B,updateOAuthState:_,getOAuthState:M,clearOAuthState:$,isTokenExpired:C})}));let p=I.layer.pipe(jp.provide(ut.defaultLayer)),{runPromise:f}=Ke(m,p);I.get=n(async r=>f(x=>x.get(r)),"get"),I.getForUrl=n(async(r,x)=>f(h=>h.getForUrl(r,x)),"getForUrl"),I.all=n(async()=>f(r=>r.all()),"all"),I.set=n(async(r,x,h)=>f(v=>v.set(r,x,h)),"set"),I.remove=n(async r=>f(x=>x.remove(r)),"remove"),I.updateTokens=n(async(r,x,h)=>f(v=>v.updateTokens(r,x,h)),"updateTokens"),I.updateClientInfo=n(async(r,x,h)=>f(v=>v.updateClientInfo(r,x,h)),"updateClientInfo"),I.updateCodeVerifier=n(async(r,x)=>f(h=>h.updateCodeVerifier(r,x)),"updateCodeVerifier"),I.updateOAuthState=n(async(r,x)=>f(h=>h.updateOAuthState(r,x)),"updateOAuthState")})(Tn||={});var fi=qe.create({service:"mcp.oauth"}),qr=19876,pl="/mcp/oauth/callback",mi=class{constructor(t,o,i,m){this.mcpName=t;this.serverUrl=o;this.config=i;this.callbacks=m}mcpName;serverUrl;config;callbacks;static{n(this,"McpOAuthProvider")}get redirectUrl(){return`http://127.0.0.1:${qr}${pl}`}get clientMetadata(){return{redirect_uris:[this.redirectUrl],client_name:"OpenCode",client_uri:"https://opencode.ai",grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:this.config.clientSecret?"client_secret_post":"none"}}async clientInformation(){if(this.config.clientId)return{client_id:this.config.clientId,client_secret:this.config.clientSecret};let t=await Tn.getForUrl(this.mcpName,this.serverUrl);if(t?.clientInfo){if(t.clientInfo.clientSecretExpiresAt&&t.clientInfo.clientSecretExpiresAt<Date.now()/1e3){fi.info("client secret expired, need to re-register",{mcpName:this.mcpName});return}return{client_id:t.clientInfo.clientId,client_secret:t.clientInfo.clientSecret}}}async saveClientInformation(t){await Tn.updateClientInfo(this.mcpName,{clientId:t.client_id,clientSecret:t.client_secret,clientIdIssuedAt:t.client_id_issued_at,clientSecretExpiresAt:t.client_secret_expires_at},this.serverUrl),fi.info("saved dynamically registered client",{mcpName:this.mcpName,clientId:t.client_id})}async tokens(){let t=await Tn.getForUrl(this.mcpName,this.serverUrl);if(t?.tokens)return{access_token:t.tokens.accessToken,token_type:"Bearer",refresh_token:t.tokens.refreshToken,expires_in:t.tokens.expiresAt?Math.max(0,Math.floor(t.tokens.expiresAt-Date.now()/1e3)):void 0,scope:t.tokens.scope}}async saveTokens(t){await Tn.updateTokens(this.mcpName,{accessToken:t.access_token,refreshToken:t.refresh_token,expiresAt:t.expires_in?Date.now()/1e3+t.expires_in:void 0,scope:t.scope},this.serverUrl),fi.info("saved oauth tokens",{mcpName:this.mcpName})}async redirectToAuthorization(t){fi.info("redirecting to authorization",{mcpName:this.mcpName,url:t.toString()}),await this.callbacks.onRedirect(t)}async saveCodeVerifier(t){await Tn.updateCodeVerifier(this.mcpName,t)}async codeVerifier(){let t=await Tn.get(this.mcpName);if(!t?.codeVerifier)throw new Error(`No code verifier saved for MCP server: ${this.mcpName}`);return t.codeVerifier}async saveState(t){await Tn.updateOAuthState(this.mcpName,t)}async state(){let t=await Tn.get(this.mcpName);if(t?.oauthState)return t.oauthState;let o=Array.from(crypto.getRandomValues(new Uint8Array(32))).map(i=>i.toString(16).padStart(2,"0")).join("");return await Tn.updateOAuthState(this.mcpName,o),o}async invalidateCredentials(t){fi.info("invalidating credentials",{mcpName:this.mcpName,type:t});let o=await Tn.get(this.mcpName);if(o)switch(t){case"all":await Tn.remove(this.mcpName);break;case"client":delete o.clientInfo,await Tn.set(this.mcpName,o);break;case"tokens":delete o.tokens,await Tn.set(this.mcpName,o);break}}};import{createConnection as Cw}from"net";import{createServer as Rw}from"http";var Ss=qe.create({service:"mcp.oauth-callback"}),jw=`<!DOCTYPE html>
|
|
1345
|
+
<html>
|
|
1346
|
+
<head>
|
|
1347
|
+
<title>OpenCode - Authorization Successful</title>
|
|
1348
|
+
<style>
|
|
1349
|
+
body { font-family: system-ui, -apple-system, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #1a1a2e; color: #eee; }
|
|
1350
|
+
.container { text-align: center; padding: 2rem; }
|
|
1351
|
+
h1 { color: #4ade80; margin-bottom: 1rem; }
|
|
1352
|
+
p { color: #aaa; }
|
|
1353
|
+
</style>
|
|
1354
|
+
</head>
|
|
1355
|
+
<body>
|
|
1356
|
+
<div class="container">
|
|
1357
|
+
<h1>Authorization Successful</h1>
|
|
1358
|
+
<p>You can close this window and return to OpenCode.</p>
|
|
1359
|
+
</div>
|
|
1360
|
+
<script>setTimeout(() => window.close(), 2000);</script>
|
|
1361
|
+
</body>
|
|
1362
|
+
</html>`,Aa=n(e=>`<!DOCTYPE html>
|
|
1363
|
+
<html>
|
|
1364
|
+
<head>
|
|
1365
|
+
<title>OpenCode - Authorization Failed</title>
|
|
1366
|
+
<style>
|
|
1367
|
+
body { font-family: system-ui, -apple-system, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #1a1a2e; color: #eee; }
|
|
1368
|
+
.container { text-align: center; padding: 2rem; }
|
|
1369
|
+
h1 { color: #f87171; margin-bottom: 1rem; }
|
|
1370
|
+
p { color: #aaa; }
|
|
1371
|
+
.error { color: #fca5a5; font-family: monospace; margin-top: 1rem; padding: 1rem; background: rgba(248,113,113,0.1); border-radius: 0.5rem; }
|
|
1372
|
+
</style>
|
|
1373
|
+
</head>
|
|
1374
|
+
<body>
|
|
1375
|
+
<div class="container">
|
|
1376
|
+
<h1>Authorization Failed</h1>
|
|
1377
|
+
<p>An error occurred during authorization.</p>
|
|
1378
|
+
<div class="error">${e}</div>
|
|
1379
|
+
</div>
|
|
1380
|
+
</body>
|
|
1381
|
+
</html>`,"HTML_ERROR"),gi;(l=>{let e,t=new Map,o=new Map,i=300*1e3;function m(g){for(let[u,a]of o)if(a===g){o.delete(u);break}}n(m,"cleanupStateIndex");function y(g,u){let a=new URL(g.url||"/",`http://localhost:${qr}`);if(a.pathname!==pl){u.writeHead(404),u.end("Not found");return}let w=a.searchParams.get("code"),I=a.searchParams.get("state"),r=a.searchParams.get("error"),x=a.searchParams.get("error_description");if(Ss.info("received oauth callback",{hasCode:!!w,state:I,error:r}),!I){let v="Missing required state parameter - potential CSRF attack";Ss.error("oauth callback missing state parameter",{url:a.toString()}),u.writeHead(400,{"Content-Type":"text/html"}),u.end(Aa(v));return}if(r){let v=x||r;if(t.has(I)){let S=t.get(I);clearTimeout(S.timeout),t.delete(I),m(I),S.reject(new Error(v))}u.writeHead(200,{"Content-Type":"text/html"}),u.end(Aa(v));return}if(!w){u.writeHead(400,{"Content-Type":"text/html"}),u.end(Aa("No authorization code provided"));return}if(!t.has(I)){let v="Invalid or expired state parameter - potential CSRF attack";Ss.error("oauth callback with invalid state",{state:I,pendingStates:Array.from(t.keys())}),u.writeHead(400,{"Content-Type":"text/html"}),u.end(Aa(v));return}let h=t.get(I);clearTimeout(h.timeout),t.delete(I),m(I),h.resolve(w),u.writeHead(200,{"Content-Type":"text/html"}),u.end(jw)}n(y,"handleRequest");async function p(){if(e)return;if(await d()){Ss.info("oauth callback server already running on another instance",{port:qr});return}e=Rw(y),await new Promise((u,a)=>{e.listen(qr,()=>{Ss.info("oauth callback server started",{port:qr}),u()}),e.on("error",a)})}l.ensureRunning=p,n(p,"ensureRunning");function f(g,u){return u&&o.set(u,g),new Promise((a,w)=>{let I=setTimeout(()=>{t.has(g)&&(t.delete(g),u&&o.delete(u),w(new Error("OAuth callback timeout - authorization took too long")))},i);t.set(g,{resolve:a,reject:w,timeout:I})})}l.waitForCallback=f,n(f,"waitForCallback");function b(g){let a=o.get(g)??g,w=t.get(a);w&&(clearTimeout(w.timeout),t.delete(a),o.delete(g),w.reject(new Error("Authorization cancelled")))}l.cancelPending=b,n(b,"cancelPending");async function d(){return new Promise(g=>{let u=Cw(qr,"127.0.0.1");u.on("connect",()=>{u.destroy(),g(!0)}),u.on("error",()=>{g(!1)})})}l.isPortInUse=d,n(d,"isPortInUse");async function s(){e&&(await new Promise(g=>e.close(()=>g())),e=void 0,Ss.info("oauth callback server stopped"));for(let[g,u]of t)clearTimeout(u.timeout),u.reject(new Error("OAuth callback server stopped"));t.clear(),o.clear()}l.stop=s,n(s,"stop");function c(){return e!==void 0}l.isRunning=c,n(c,"isRunning")})(gi||={});import yo from"zod";var fl={PromptAppend:mt.define("tui.prompt.append",yo.object({text:yo.string()})),CommandExecute:mt.define("tui.command.execute",yo.object({command:yo.union([yo.enum(["session.list","session.new","session.share","session.interrupt","session.compact","session.page.up","session.page.down","session.line.up","session.line.down","session.half.page.up","session.half.page.down","session.first","session.last","prompt.clear","prompt.submit","agent.cycle"]),yo.string()])})),ToastShow:mt.define("tui.toast.show",yo.object({title:yo.string().optional(),message:yo.string(),variant:yo.enum(["info","success","warning","error"]),duration:yo.number().default(5e3).optional().describe("Duration in milliseconds")})),SessionSelect:mt.define("tui.session.select",yo.object({sessionID:He.zod.describe("Session ID to navigate to")}))};import $w from"open";import{Effect as ze,Exit as qw,Layer as Ds,Option as Bw,ServiceMap as Ww,Stream as zp}from"effect";import{ChildProcess as Hw,ChildProcessSpawner as Gw}from"effect/unstable/process";var Br;(N=>{let e=qe.create({service:"mcp"}),t=3e4;N.Resource=Lt.object({name:Lt.string(),uri:Lt.string(),description:Lt.string().optional(),mimeType:Lt.string().optional(),client:Lt.string()}).meta({ref:"McpResource"}),N.ToolManifestEntry=Lt.object({name:Lt.string(),description:Lt.string().optional(),readOnly:Lt.boolean().optional()}).meta({ref:"MCPToolManifestEntry"}),N.ToolsChanged=mt.define("mcp.tools.changed",Lt.object({server:Lt.string()})),N.BrowserOpenFailed=mt.define("mcp.browser.open.failed",Lt.object({mcpName:Lt.string(),url:Lt.string()})),N.Failed=tt.create("MCPFailed",Lt.object({name:Lt.string()})),N.Status=Lt.discriminatedUnion("status",[Lt.object({status:Lt.literal("connected")}).meta({ref:"MCPStatusConnected"}),Lt.object({status:Lt.literal("disabled")}).meta({ref:"MCPStatusDisabled"}),Lt.object({status:Lt.literal("failed"),error:Lt.string()}).meta({ref:"MCPStatusFailed"}),Lt.object({status:Lt.literal("needs_auth")}).meta({ref:"MCPStatusNeedsAuth"}),Lt.object({status:Lt.literal("needs_client_registration"),error:Lt.string()}).meta({ref:"MCPStatusNeedsClientRegistration"})]).meta({ref:"MCPStatus"});let b=new Map;function d(A){return typeof A=="object"&&A!==null&&"type"in A}n(d,"isMcpConfigured");let s=n(A=>A.replace(/[^a-zA-Z0-9_-]/g,"_"),"sanitize");function c(A,F){if(URL.canParse(F))return new URL(F);e.warn("invalid remote mcp url",{key:A})}n(c,"remoteURL");function l(A){let F=A?.callContext,V={};return F?.sessionId&&(V.sessionId=F.sessionId),F?.messageId&&(V.messageId=F.messageId),Object.keys(V).length>0?V:void 0}N.callMeta=l,n(l,"callMeta");function g(A,F,V){let Y=A.inputSchema,re={...Y,type:"object",properties:Y.properties??{},additionalProperties:!1},ue=Mw({description:A.description??"",inputSchema:Lw(re),execute:n(async(R,L)=>{let q={};for(let[ce,pe]of Object.entries(R||{}))pe!==null&&(q[ce]=pe);let X=l(L),ne=await F.callTool({name:A.name,arguments:q,_meta:X},Fw,{resetTimeoutOnProgress:!0,timeout:V,onprogress:n(()=>{},"onprogress")}),Q=ne._meta?.alchemy,oe=Array.isArray(ne.content)&&ne.content.length===0&&ne.structuredContent!==void 0&&ne.structuredContent!==null?{...ne,content:[{type:"text",text:JSON.stringify(ne.structuredContent)}]}:ne;return Q?{...oe,metadata:Q}:oe},"execute")}),H=A._meta?.[dp];return H&&typeof H=="object"&&Object.assign(ue,{fieldTags:H,jsonInputSchema:re}),ue}n(g,"convertMcpTool");function u(A,F,V){return ze.tryPromise({try:n(()=>ps(F.listTools(),V??t),"try"),catch:n(Y=>Y instanceof Error?Y:new Error(String(Y)),"catch")}).pipe(ze.map(Y=>Y.tools),ze.catch(Y=>(e.error("failed to get tools from client",{key:A,error:Y}),ze.succeed(void 0))))}n(u,"defs");function a(A,F,V,Y){return ze.tryPromise({try:n(()=>V(F),"try"),catch:n(re=>(e.error(`failed to get ${Y}`,{clientName:A,error:re.message}),re),"catch")}).pipe(ze.map(re=>{let ue={},H=s(A);for(let R of re)ue[H+":"+s(R.name)]={...R,client:A};return ue}),ze.orElseSucceed(()=>{}))}n(a,"fetchFromClient");class w extends Ww.Service()("@opencode/MCP"){static{n(this,"Service")}}N.Service=w,N.layer=Ds.effect(w,ze.gen(function*(){let A=yield*Gw.ChildProcessSpawner,F=yield*Tn.Service,V=yield*Ve.Service,Y=n((ee,de)=>ze.acquireUseRelease(ze.succeed(ee),ke=>ze.tryPromise({try:n(()=>{let se=new Mp({name:"opencode",version:Ft.VERSION});return ps(se.connect(ke),de).then(()=>se)},"try"),catch:n(se=>se instanceof Error?se:new Error(String(se)),"catch")}),(ke,se)=>qw.isFailure(se)?ze.tryPromise(()=>ke.close()).pipe(ze.ignore):ze.void),"connectTransport"),re={status:{status:"disabled"}},ue=ze.fn("MCP.connectRemote")(function*(ee,de){let ke=de.oauth===!1,se=typeof de.oauth=="object"?de.oauth:void 0,Pe=c(ee,de.url);if(!Pe)return{client:void 0,status:{status:"failed",error:`Invalid MCP URL for "${ee}"`}};let Ne;ke||(Ne=new mi(ee,de.url,{clientId:se?.clientId,clientSecret:se?.clientSecret,scope:se?.scope},{onRedirect:n(async Re=>{e.info("oauth redirect requested",{key:ee,url:Re.toString()})},"onRedirect")}));let Me=[{name:"StreamableHTTP",transport:new Lp(Pe,{authProvider:Ne,requestInit:de.headers?{headers:de.headers}:void 0})},{name:"SSE",transport:new Nw(Pe,{authProvider:Ne,requestInit:de.headers?{headers:de.headers}:void 0})}],Ae=de.timeout??t,Fe;for(let{name:Re,transport:nt}of Me){let et=yield*Y(nt,Ae).pipe(ze.map(Ue=>({client:Ue,transportName:Re})),ze.catch(Ue=>{let ot=Ue instanceof Error?Ue:new Error(String(Ue));return Ue instanceof Np||Ne&&ot.message.includes("OAuth")?(e.info("mcp server requires authentication",{key:ee,transport:Re}),ot.message.includes("registration")||ot.message.includes("client_id")?(Fe={status:"needs_client_registration",error:"Server does not support dynamic client registration. Please provide clientId in config."},V.publish(fl.ToastShow,{title:"MCP Authentication Required",message:`Server "${ee}" requires a pre-registered client ID. Add clientId to your config.`,variant:"warning",duration:8e3}).pipe(ze.ignore,ze.as(void 0))):(b.set(ee,nt),Fe={status:"needs_auth"},V.publish(fl.ToastShow,{title:"MCP Authentication Required",message:`Server "${ee}" requires authentication. Run: opencode mcp auth ${ee}`,variant:"warning",duration:8e3}).pipe(ze.ignore,ze.as(void 0)))):(e.debug("transport connection failed",{key:ee,transport:Re,url:de.url,error:ot.message}),Fe={status:"failed",error:ot.message},ze.succeed(void 0))}));if(et)return e.info("connected",{key:ee,transport:et.transportName}),{client:et.client,status:{status:"connected"}};if(Fe?.status==="needs_auth"||Fe?.status==="needs_client_registration")break}return{client:void 0,status:Fe??{status:"failed",error:"Unknown error"}}}),H=ze.fn("MCP.connectLocal")(function*(ee,de){let[ke,...se]=de.command,Pe=he.directory,Ne=new zw({stderr:"pipe",command:ke,args:se,cwd:Pe,env:{...process.env,...ke==="opencode"?{BUN_BE_BUN:"1"}:{},...de.environment}});Ne.stderr?.on("data",Ae=>{e.info(`mcp stderr: ${Ae.toString()}`,{key:ee})});let Me=de.timeout??t;return yield*Y(Ne,Me).pipe(ze.map(Ae=>({client:Ae,status:{status:"connected"}})),ze.catch(Ae=>{let Fe=Ae instanceof Error?Ae.message:String(Ae);return e.error("local mcp startup failed",{key:ee,command:de.command,cwd:Pe,error:Fe}),ze.succeed({client:void 0,status:{status:"failed",error:Fe}})}))}),R=ze.fn("MCP.create")(function*(ee,de){if(de.enabled===!1)return e.info("mcp server disabled",{key:ee}),re;e.info("found",{key:ee,type:de.type});let{client:ke,status:se}=de.type==="remote"?yield*ue(ee,de):yield*H(ee,de);if(!ke)return{status:se};let Pe=yield*u(ee,ke,de.timeout);return Pe?(e.info("create() successfully created client",{key:ee,toolCount:Pe.length}),{mcpClient:ke,status:se,defs:Pe}):(yield*ze.tryPromise(()=>ke.close()).pipe(ze.ignore),{status:{status:"failed",error:"Failed to get tools"}})}),L=yield*rt.Service,q=ze.fnUntraced(function*(ee){if(process.platform==="win32")return[];let de=[],ke=[ee];for(;ke.length>0;){let se=ke.shift(),Pe=yield*A.spawn(Hw.make("pgrep",["-P",String(se)],{stdin:"ignore"})),Ne=yield*zp.mkString(zp.decodeText(Pe.stdout));yield*Pe.exitCode;for(let Me of Ne.split(`
|
|
1382
|
+
`)){let Ae=parseInt(Me,10);!isNaN(Ae)&&!de.includes(Ae)&&(de.push(Ae),ke.push(Ae))}}return de},ze.scoped,ze.catch(()=>ze.succeed([])));function X(ee,de,ke){let se=ke.onclose;ke.onclose=()=>{se?.(),ee.clients[de]===ke&&(e.warn("mcp server closed its connection",{name:de}),delete ee.clients[de],delete ee.defs[de],ee.status[de]={status:"failed",error:"The server closed the connection"})}}n(X,"watchClose");function ne(ee,de,ke,se){ke.setNotificationHandler(Uw,async()=>{if(e.info("tools list changed notification received",{server:de}),ee.clients[de]!==ke||ee.status[de]?.status!=="connected")return;let Pe=await ze.runPromise(u(de,ke,se));Pe&&(ee.clients[de]!==ke||ee.status[de]?.status!=="connected"||(ee.defs[de]=Pe,await ze.runPromise(V.publish(N.ToolsChanged,{server:de}).pipe(ze.ignore))))})}n(ne,"watch");let Q=new Map,oe=n(ee=>{let de=Q.get(ee);return de||(de=new Map,Q.set(ee,de)),de},"runtimeFor"),ce=yield*ge.make(ze.fn("MCP.state")(function*(ee){let de=yield*L.get(),ke={...Object.fromEntries(oe(ee.directory)),...de.mcp??{}},se={status:{},clients:{},defs:{}};return yield*ze.forEach(Object.entries(ke),([Pe,Ne])=>ze.gen(function*(){if(!d(Ne)){e.error("Ignoring MCP config entry without type",{key:Pe});return}if(Ne.enabled===!1){se.status[Pe]={status:"disabled"};return}let Me=yield*R(Pe,Ne).pipe(ze.catch(()=>ze.succeed(void 0)));Me&&(se.status[Pe]=Me.status,Me.mcpClient&&(se.clients[Pe]=Me.mcpClient,se.defs[Pe]=Me.defs,ne(se,Pe,Me.mcpClient,Ne.timeout),X(se,Pe,Me.mcpClient)))}),{concurrency:"unbounded"}),yield*ze.addFinalizer(()=>ze.gen(function*(){yield*ze.forEach(Object.values(se.clients),Pe=>ze.gen(function*(){let Ne=Pe.transport?.pid;if(typeof Ne=="number"){let Me=yield*q(Ne);for(let Ae of Me)try{process.kill(Ae,"SIGTERM")}catch{}}yield*ze.tryPromise(()=>Pe.close()).pipe(ze.ignore)}),{concurrency:"unbounded"}),b.clear()})),se}));function pe(ee,de){let ke=ee.clients[de];return delete ee.defs[de],ke?(ke.onclose=void 0,ze.tryPromise(()=>ke.close()).pipe(ze.ignore)):ze.void}n(pe,"closeClient");let De=ze.fn("MCP.status")(function*(){let ee=yield*ge.get(ce),de=yield*L.get(),ke=yield*ge.directory,se={...Object.fromEntries(oe(ke)),...de.mcp??{}},Pe={};for(let[Ne,Me]of Object.entries(se))d(Me)&&(Pe[Ne]=ee.status[Ne]??{status:"disabled"});return Pe}),Oe=ze.fn("MCP.clients")(function*(){return(yield*ge.get(ce)).clients}),xe=ze.fn("MCP.createAndStore")(function*(ee,de){let ke=yield*ge.get(ce),se=yield*R(ee,de);return ke.status[ee]=se.status,se.mcpClient?(yield*pe(ke,ee),ke.clients[ee]=se.mcpClient,ke.defs[ee]=se.defs,ne(ke,ee,se.mcpClient,de.timeout),X(ke,ee,se.mcpClient),se.status):(yield*pe(ke,ee),delete ke.clients[ee],se.status)}),ie=ze.fn("MCP.add")(function*(ee,de){yield*xe(ee,de);let ke=yield*ge.directory;return oe(ke).set(ee,de),{status:(yield*ge.get(ce)).status}}),le=ze.fn("MCP.connect")(function*(ee){let de=yield*P(ee);if(!de){e.error("MCP config not found or invalid",{name:ee});return}yield*xe(ee,{...de,enabled:!0})}),Le=ze.fn("MCP.disconnect")(function*(ee){let de=yield*ge.get(ce);yield*pe(de,ee),delete de.clients[ee],de.status[ee]={status:"disabled"};let ke=yield*ge.directory;oe(ke).delete(ee)}),ve=ze.fn("MCP.tools")(function*(){let ee={},de=yield*ge.get(ce),ke=yield*L.get(),se=ke.mcp??{},Pe=ke.experimental?.mcp_timeout,Ne=Object.entries(de.clients).filter(([Me])=>de.status[Me]?.status==="connected");return yield*ze.forEach(Ne,([Me,Ae])=>ze.gen(function*(){let Fe=se[Me],Re=Fe&&d(Fe)?Fe:void 0,nt=de.defs[Me];if(!nt){e.warn("missing cached tools for connected server",{clientName:Me});return}let et=Re?.timeout??Pe;for(let Ue of nt)ee[s(Me)+"_"+s(Ue.name)]=g(Ue,Ae,et)}),{concurrency:"unbounded"}),ee}),Te=ze.fn("MCP.toolManifest")(function*(){let ee=yield*ge.get(ce),de={};for(let[ke]of Object.entries(ee.clients).filter(([se])=>ee.status[se]?.status==="connected")){let se=ee.defs[ke];se&&(de[ke]=se.map(Pe=>({name:Pe.name,...Pe.description?{description:Pe.description}:{},...typeof Pe.annotations?.readOnlyHint=="boolean"?{readOnly:Pe.annotations.readOnlyHint}:{}})))}return de});function it(ee,de,ke){return ze.forEach(Object.entries(ee.clients).filter(([se])=>ee.status[se]?.status==="connected"),([se,Pe])=>a(se,Pe,de,ke).pipe(ze.map(Ne=>Object.entries(Ne??{}))),{concurrency:"unbounded"}).pipe(ze.map(se=>Object.fromEntries(se.flat())))}n(it,"collectFromConnected");let Ie=ze.fn("MCP.prompts")(function*(){let ee=yield*ge.get(ce);return yield*it(ee,de=>de.listPrompts().then(ke=>ke.prompts),"prompts")}),be=ze.fn("MCP.resources")(function*(){let ee=yield*ge.get(ce);return yield*it(ee,de=>de.listResources().then(ke=>ke.resources),"resources")}),ye=ze.fnUntraced(function*(ee,de,ke,se){let Ne=(yield*ge.get(ce)).clients[ee];if(!Ne){e.warn(`client not found for ${ke}`,{clientName:ee});return}return yield*ze.tryPromise({try:n(()=>de(Ne),"try"),catch:n(Me=>(e.error(`failed to ${ke}`,{clientName:ee,...se,error:Me?.message}),Me),"catch")}).pipe(ze.orElseSucceed(()=>{}))}),ae=ze.fn("MCP.getPrompt")(function*(ee,de,ke){return yield*ye(ee,se=>se.getPrompt({name:de,arguments:ke}),"getPrompt",{promptName:de})}),me=ze.fn("MCP.readResource")(function*(ee,de){return yield*ye(ee,ke=>ke.readResource({uri:de}),"readResource",{resourceUri:de})}),P=ze.fnUntraced(function*(ee){let ke=(yield*L.get()).mcp?.[ee];if(!(!ke||!d(ke)))return ke}),Z=ze.fn("MCP.startAuth")(function*(ee){let de=yield*P(ee);if(!de)throw new Error(`MCP server ${ee} not found or disabled`);if(de.type!=="remote")throw new Error(`MCP server ${ee} is not a remote server`);if(de.oauth===!1)throw new Error(`MCP server ${ee} has OAuth explicitly disabled`);let ke=c(ee,de.url);if(!ke)throw new Error(`Invalid MCP URL for "${ee}"`);yield*ze.promise(()=>gi.ensureRunning());let se=Array.from(crypto.getRandomValues(new Uint8Array(32))).map(Fe=>Fe.toString(16).padStart(2,"0")).join("");yield*F.updateOAuthState(ee,se);let Pe=typeof de.oauth=="object"?de.oauth:void 0,Ne,Me=new mi(ee,de.url,{clientId:Pe?.clientId,clientSecret:Pe?.clientSecret,scope:Pe?.scope},{onRedirect:n(async Fe=>{Ne=Fe},"onRedirect")}),Ae=new Lp(ke,{authProvider:Me});return yield*ze.tryPromise({try:n(()=>new Mp({name:"opencode",version:Ft.VERSION}).connect(Ae).then(()=>({authorizationUrl:"",oauthState:se})),"try"),catch:n(Fe=>Fe,"catch")}).pipe(ze.catch(Fe=>Fe instanceof Np&&Ne?(b.set(ee,Ae),ze.succeed({authorizationUrl:Ne.toString(),oauthState:se})):ze.die(Fe)))}),J=ze.fn("MCP.authenticate")(function*(ee){let{authorizationUrl:de,oauthState:ke}=yield*Z(ee);if(!de)return{status:"connected"};e.info("opening browser for oauth",{mcpName:ee,url:de,state:ke});let se=gi.waitForCallback(ke,ee);yield*ze.tryPromise(()=>$w(de)).pipe(ze.flatMap(Me=>ze.callback(Ae=>{let Fe=setTimeout(()=>Ae(ze.void),500);Me.on("error",Re=>{clearTimeout(Fe),Ae(ze.fail(Re))}),Me.on("exit",Re=>{Re!==null&&Re!==0&&(clearTimeout(Fe),Ae(ze.fail(new Error(`Browser open failed with exit code ${Re}`))))})})),ze.catch(()=>(e.warn("failed to open browser, user must open URL manually",{mcpName:ee}),V.publish(N.BrowserOpenFailed,{mcpName:ee,url:de}).pipe(ze.ignore))));let Pe=yield*ze.promise(()=>se);if((yield*F.getOAuthState(ee))!==ke)throw yield*F.clearOAuthState(ee),new Error("OAuth state mismatch - potential CSRF attack");return yield*F.clearOAuthState(ee),yield*fe(ee,Pe)}),fe=ze.fn("MCP.finishAuth")(function*(ee,de){let ke=b.get(ee);if(!ke)throw new Error(`No pending OAuth flow for MCP server: ${ee}`);let se=yield*ze.tryPromise({try:n(()=>ke.finishAuth(de).then(()=>!0),"try"),catch:n(Ne=>(e.error("failed to finish oauth",{mcpName:ee,error:Ne}),Ne),"catch")}).pipe(ze.option);if(Bw.isNone(se))return{status:"failed",error:"OAuth completion failed"};yield*F.clearCodeVerifier(ee),b.delete(ee);let Pe=yield*P(ee);return Pe?yield*xe(ee,Pe):{status:"failed",error:"MCP config not found after auth"}}),_e=ze.fn("MCP.removeAuth")(function*(ee){yield*F.remove(ee),gi.cancelPending(ee),b.delete(ee),e.info("removed oauth credentials",{mcpName:ee})}),te=ze.fn("MCP.supportsOAuth")(function*(ee){let de=yield*P(ee);return de?de.type==="remote"&&de.oauth!==!1:!1}),we=ze.fn("MCP.hasStoredTokens")(function*(ee){return!!(yield*F.get(ee))?.tokens}),$e=ze.fn("MCP.getAuthStatus")(function*(ee){return(yield*F.get(ee))?.tokens?(yield*F.isTokenExpired(ee))?"expired":"authenticated":"not_authenticated"});return w.of({status:De,clients:Oe,tools:ve,defs:Te,prompts:Ie,resources:be,add:ie,connect:le,disconnect:Le,getPrompt:ae,readResource:me,startAuth:Z,authenticate:J,finishAuth:fe,removeAuth:_e,supportsOAuth:te,hasStoredTokens:we,getAuthStatus:$e})})),N.defaultLayer=N.layer.pipe(Ds.provide(Tn.layer),Ds.provide(Ve.layer),Ds.provide(rt.defaultLayer),Ds.provide(uo),Ds.provide(ut.defaultLayer));let{runPromise:x}=Ke(w,N.defaultLayer);N.status=n(async()=>x(A=>A.status()),"status"),N.tools=n(async()=>x(A=>A.tools()),"tools"),N.toolManifest=n(async()=>x(A=>A.defs()),"toolManifest"),N.prompts=n(async()=>x(A=>A.prompts()),"prompts"),N.resources=n(async()=>x(A=>A.resources()),"resources"),N.add=n(async(A,F)=>x(V=>V.add(A,F)),"add"),N.connect=n(async A=>x(F=>F.connect(A)),"connect"),N.disconnect=n(async A=>x(F=>F.disconnect(A)),"disconnect"),N.getPrompt=n(async(A,F,V)=>x(Y=>Y.getPrompt(A,F,V)),"getPrompt"),N.startAuth=n(async A=>x(F=>F.startAuth(A)),"startAuth"),N.authenticate=n(async A=>x(F=>F.authenticate(A)),"authenticate"),N.finishAuth=n(async(A,F)=>x(V=>V.finishAuth(A,F)),"finishAuth"),N.removeAuth=n(async A=>x(F=>F.removeAuth(A)),"removeAuth"),N.supportsOAuth=n(async A=>x(F=>F.supportsOAuth(A)),"supportsOAuth"),N.hasStoredTokens=n(async A=>x(F=>F.hasStoredTokens(A)),"hasStoredTokens"),N.getAuthStatus=n(async A=>x(F=>F.getAuthStatus(A)),"getAuthStatus")})(Br||={});import{DateTime as Vw,Effect as bo,Layer as ml,Option as Jw,Semaphore as Yw,ServiceMap as Kw}from"effect";var Nn;(s=>{let e=qe.create({service:"file.time"}),t=n((c,l)=>{let g=c.get(l);if(g)return g;let u=new Map;return c.set(l,u),u},"session");class o extends Kw.Service()("@opencode/FileTime"){static{n(this,"Service")}}s.Service=o,s.layer=ml.effect(o,bo.gen(function*(){let c=yield*ut.Service,l=yield*Ce.OPENCODE_DISABLE_FILETIME_CHECK,g=bo.fnUntraced(function*(h){let v=yield*c.stat(h).pipe(bo.catch(()=>bo.succeed(void 0)));return{read:yield*Vw.nowAsDate,mtime:v?Jw.getOrUndefined(v.mtime)?.getTime():void 0,size:v?Number(v.size):void 0}}),u=yield*ge.make(bo.fn("FileTime.state")(()=>bo.succeed({reads:new Map,locks:new Map}))),a=bo.fn("FileTime.lock")(function*(h){h=Ee.normalizePath(h);let v=(yield*ge.get(u)).locks,S=v.get(h);if(S)return S;let j=Yw.makeUnsafe(1);return v.set(h,j),j}),w=bo.fn("FileTime.read")(function*(h,v){v=Ee.normalizePath(v);let S=(yield*ge.get(u)).reads;e.info("read",{sessionID:h,file:v}),t(S,h).set(v,yield*g(v))}),I=bo.fn("FileTime.get")(function*(h,v){return v=Ee.normalizePath(v),(yield*ge.get(u)).reads.get(h)?.get(v)?.read}),r=bo.fn("FileTime.assert")(function*(h,v){if(l)return;v=Ee.normalizePath(v);let j=(yield*ge.get(u)).reads.get(h)?.get(v);if(!j)throw new Error(`You must read file ${v} before overwriting it. Use the Read tool first`);let O=yield*g(v);if(O.mtime!==j.mtime||O.size!==j.size)throw new Error(`File ${v} has been modified since it was last read.
|
|
1383
|
+
Last modification: ${new Date(O.mtime??O.read.getTime()).toISOString()}
|
|
1384
|
+
Last read: ${j.read.toISOString()}
|
|
1385
|
+
|
|
1386
|
+
Please read the file again before modifying it.`)}),x=bo.fn("FileTime.withLock")(function*(h,v){return yield*bo.promise(v).pipe((yield*a(h)).withPermits(1))});return o.of({read:w,get:I,assert:r,withLock:x})})).pipe(ml.orDie),s.defaultLayer=s.layer.pipe(ml.provide(ut.defaultLayer));let{runPromise:y}=Ke(o,s.defaultLayer);function p(c,l){return y(g=>g.read(c,l))}s.read=p,n(p,"read");function f(c,l){return y(g=>g.get(c,l))}s.get=f,n(f,"get");async function b(c,l){return y(g=>g.assert(c,l))}s.assert=b,n(b,"assert");async function d(c,l){return y(g=>g.withLock(c,l))}s.withLock=d,n(d,"withLock")})(Nn||={});import{ulid as Hp}from"ulid";import{ChildProcess as nx,ChildProcessSpawner as ox}from"effect/unstable/process";import*as Na from"effect/Stream";import{Effect as Ts,Layer as Ca,ServiceMap as Xw}from"effect";import Hn from"zod";var gl=`Create or update \`AGENTS.md\` for this repository.
|
|
1387
|
+
|
|
1388
|
+
The goal is a compact instruction file that helps future OpenCode sessions avoid mistakes and ramp up quickly. Every line should answer: "Would an agent likely miss this without help?" If not, leave it out.
|
|
1389
|
+
|
|
1390
|
+
User-provided focus or constraints (honor these):
|
|
1391
|
+
$ARGUMENTS
|
|
1392
|
+
|
|
1393
|
+
## How to investigate
|
|
1394
|
+
|
|
1395
|
+
Read the highest-value sources first:
|
|
1396
|
+
- \`README*\`, root manifests, workspace config, lockfiles
|
|
1397
|
+
- build, test, lint, formatter, typecheck, and codegen config
|
|
1398
|
+
- CI workflows and pre-commit / task runner config
|
|
1399
|
+
- existing instruction files (\`AGENTS.md\`, \`CLAUDE.md\`, \`.cursor/rules/\`, \`.cursorrules\`, \`.github/copilot-instructions.md\`)
|
|
1400
|
+
- repo-local OpenCode config such as \`opencode.json\`
|
|
1401
|
+
|
|
1402
|
+
If architecture is still unclear after reading config and docs, inspect a small number of representative code files to find the real entrypoints, package boundaries, and execution flow. Prefer reading the files that explain how the system is wired together over random leaf files.
|
|
1403
|
+
|
|
1404
|
+
Prefer executable sources of truth over prose. If docs conflict with config or scripts, trust the executable source and only keep what you can verify.
|
|
1405
|
+
|
|
1406
|
+
## What to extract
|
|
1407
|
+
|
|
1408
|
+
Look for the highest-signal facts for an agent working in this repo:
|
|
1409
|
+
- exact developer commands, especially non-obvious ones
|
|
1410
|
+
- how to run a single test, a single package, or a focused verification step
|
|
1411
|
+
- required command order when it matters, such as \`lint -> typecheck -> test\`
|
|
1412
|
+
- monorepo or multi-package boundaries, ownership of major directories, and the real app/library entrypoints
|
|
1413
|
+
- framework or toolchain quirks: generated code, migrations, codegen, build artifacts, special env loading, dev servers, infra deploy flow
|
|
1414
|
+
- repo-specific style or workflow conventions that differ from defaults
|
|
1415
|
+
- testing quirks: fixtures, integration test prerequisites, snapshot workflows, required services, flaky or expensive suites
|
|
1416
|
+
- important constraints from existing instruction files worth preserving
|
|
1417
|
+
|
|
1418
|
+
Good \`AGENTS.md\` content is usually hard-earned context that took reading multiple files to infer.
|
|
1419
|
+
|
|
1420
|
+
## Questions
|
|
1421
|
+
|
|
1422
|
+
Only ask the user questions if the repo cannot answer something important. Use the \`question\` tool for one short batch at most.
|
|
1423
|
+
|
|
1424
|
+
Good questions:
|
|
1425
|
+
- undocumented team conventions
|
|
1426
|
+
- branch / PR / release expectations
|
|
1427
|
+
- missing setup or test prerequisites that are known but not written down
|
|
1428
|
+
|
|
1429
|
+
Do not ask about anything the repo already makes clear.
|
|
1430
|
+
|
|
1431
|
+
## Writing rules
|
|
1432
|
+
|
|
1433
|
+
Include only high-signal, repo-specific guidance such as:
|
|
1434
|
+
- exact commands and shortcuts the agent would otherwise guess wrong
|
|
1435
|
+
- architecture notes that are not obvious from filenames
|
|
1436
|
+
- conventions that differ from language or framework defaults
|
|
1437
|
+
- setup requirements, environment quirks, and operational gotchas
|
|
1438
|
+
- references to existing instruction sources that matter
|
|
1439
|
+
|
|
1440
|
+
Exclude:
|
|
1441
|
+
- generic software advice
|
|
1442
|
+
- long tutorials or exhaustive file trees
|
|
1443
|
+
- obvious language conventions
|
|
1444
|
+
- speculative claims or anything you could not verify
|
|
1445
|
+
- content better stored in another file referenced via \`opencode.json\` \`instructions\`
|
|
1446
|
+
|
|
1447
|
+
When in doubt, omit.
|
|
1448
|
+
|
|
1449
|
+
Prefer short sections and bullets. If the repo is simple, keep the file simple. If the repo is large, summarize the few structural facts that actually change how an agent should work.
|
|
1450
|
+
|
|
1451
|
+
If \`AGENTS.md\` already exists at \`\${path}\`, improve it in place rather than rewriting blindly. Preserve verified useful guidance, delete fluff or stale claims, and reconcile it with the current codebase.
|
|
1452
|
+
`;var hl=`You are a code reviewer. Your job is to review code changes and provide actionable feedback.
|
|
1453
|
+
|
|
1454
|
+
---
|
|
1455
|
+
|
|
1456
|
+
Input: $ARGUMENTS
|
|
1457
|
+
|
|
1458
|
+
---
|
|
1459
|
+
|
|
1460
|
+
## Determining What to Review
|
|
1461
|
+
|
|
1462
|
+
Based on the input provided, determine which type of review to perform:
|
|
1463
|
+
|
|
1464
|
+
1. **No arguments (default)**: Review all uncommitted changes
|
|
1465
|
+
- Run: \`git diff\` for unstaged changes
|
|
1466
|
+
- Run: \`git diff --cached\` for staged changes
|
|
1467
|
+
- Run: \`git status --short\` to identify untracked (net new) files
|
|
1468
|
+
|
|
1469
|
+
2. **Commit hash** (40-char SHA or short hash): Review that specific commit
|
|
1470
|
+
- Run: \`git show $ARGUMENTS\`
|
|
1471
|
+
|
|
1472
|
+
3. **Branch name**: Compare current branch to the specified branch
|
|
1473
|
+
- Run: \`git diff $ARGUMENTS...HEAD\`
|
|
1474
|
+
|
|
1475
|
+
4. **PR URL or number** (contains "github.com" or "pull" or looks like a PR number): Review the pull request
|
|
1476
|
+
- Run: \`gh pr view $ARGUMENTS\` to get PR context
|
|
1477
|
+
- Run: \`gh pr diff $ARGUMENTS\` to get the diff
|
|
1478
|
+
|
|
1479
|
+
Use best judgement when processing input.
|
|
1480
|
+
|
|
1481
|
+
---
|
|
1482
|
+
|
|
1483
|
+
## Gathering Context
|
|
1484
|
+
|
|
1485
|
+
**Diffs alone are not enough.** After getting the diff, read the entire file(s) being modified to understand the full context. Code that looks wrong in isolation may be correct given surrounding logic\u2014and vice versa.
|
|
1486
|
+
|
|
1487
|
+
- Use the diff to identify which files changed
|
|
1488
|
+
- Use \`git status --short\` to identify untracked files, then read their full contents
|
|
1489
|
+
- Read the full file to understand existing patterns, control flow, and error handling
|
|
1490
|
+
- Check for existing style guide or conventions files (CONVENTIONS.md, AGENTS.md, .editorconfig, etc.)
|
|
1491
|
+
|
|
1492
|
+
---
|
|
1493
|
+
|
|
1494
|
+
## What to Look For
|
|
1495
|
+
|
|
1496
|
+
**Bugs** - Your primary focus.
|
|
1497
|
+
- Logic errors, off-by-one mistakes, incorrect conditionals
|
|
1498
|
+
- If-else guards: missing guards, incorrect branching, unreachable code paths
|
|
1499
|
+
- Edge cases: null/empty/undefined inputs, error conditions, race conditions
|
|
1500
|
+
- Security issues: injection, auth bypass, data exposure
|
|
1501
|
+
- Broken error handling that swallows failures, throws unexpectedly or returns error types that are not caught.
|
|
1502
|
+
|
|
1503
|
+
**Structure** - Does the code fit the codebase?
|
|
1504
|
+
- Does it follow existing patterns and conventions?
|
|
1505
|
+
- Are there established abstractions it should use but doesn't?
|
|
1506
|
+
- Excessive nesting that could be flattened with early returns or extraction
|
|
1507
|
+
|
|
1508
|
+
**Performance** - Only flag if obviously problematic.
|
|
1509
|
+
- O(n\xB2) on unbounded data, N+1 queries, blocking I/O on hot paths
|
|
1510
|
+
|
|
1511
|
+
**Behavior Changes** - If a behavioral change is introduced, raise it (especially if it's possibly unintentional).
|
|
1512
|
+
|
|
1513
|
+
---
|
|
1514
|
+
|
|
1515
|
+
## Before You Flag Something
|
|
1516
|
+
|
|
1517
|
+
**Be certain.** If you're going to call something a bug, you need to be confident it actually is one.
|
|
1518
|
+
|
|
1519
|
+
- Only review the changes - do not review pre-existing code that wasn't modified
|
|
1520
|
+
- Don't flag something as a bug if you're unsure - investigate first
|
|
1521
|
+
- Don't invent hypothetical problems - if an edge case matters, explain the realistic scenario where it breaks
|
|
1522
|
+
- If you need more context to be sure, use the tools below to get it
|
|
1523
|
+
|
|
1524
|
+
**Don't be a zealot about style.** When checking code against conventions:
|
|
1525
|
+
|
|
1526
|
+
- Verify the code is *actually* in violation. Don't complain about else statements if early returns are already being used correctly.
|
|
1527
|
+
- Some "violations" are acceptable when they're the simplest option. A \`let\` statement is fine if the alternative is convoluted.
|
|
1528
|
+
- Excessive nesting is a legitimate concern regardless of other style choices.
|
|
1529
|
+
- Don't flag style preferences as issues unless they clearly violate established project conventions.
|
|
1530
|
+
|
|
1531
|
+
---
|
|
1532
|
+
|
|
1533
|
+
## Tools
|
|
1534
|
+
|
|
1535
|
+
Use these to inform your review:
|
|
1536
|
+
|
|
1537
|
+
- **Explore agent** - Find how existing code handles similar problems. Check patterns, conventions, and prior art before claiming something doesn't fit.
|
|
1538
|
+
- **Exa Code Context** - Verify correct usage of libraries/APIs before flagging something as wrong.
|
|
1539
|
+
- **Exa Web Search** - Research best practices if you're unsure about a pattern.
|
|
1540
|
+
|
|
1541
|
+
If you're uncertain about something and can't verify it with these tools, say "I'm not sure about X" rather than flagging it as a definite issue.
|
|
1542
|
+
|
|
1543
|
+
---
|
|
1544
|
+
|
|
1545
|
+
## Output
|
|
1546
|
+
|
|
1547
|
+
1. If there is a bug, be direct and clear about why it is a bug.
|
|
1548
|
+
2. Clearly communicate severity of issues. Do not overstate severity.
|
|
1549
|
+
3. Critiques should clearly and explicitly communicate the scenarios, environments, or inputs that are necessary for the bug to arise. The comment should immediately indicate that the issue's severity depends on these factors.
|
|
1550
|
+
4. Your tone should be matter-of-fact and not accusatory or overly positive. It should read as a helpful AI assistant suggestion without sounding too much like a human reviewer.
|
|
1551
|
+
5. Write so the reader can quickly understand the issue without reading too closely.
|
|
1552
|
+
6. AVOID flattery, do not give any comments that are not helpful to the reader. Avoid phrasing like "Great job ...", "Thanks for ...".
|
|
1553
|
+
`;var Wr;(s=>{let e=qe.create({service:"command"});s.Event={Executed:mt.define("command.executed",Hn.object({name:Hn.string(),sessionID:He.zod,arguments:Hn.string(),messageID:pt.zod}))},s.Info=Hn.object({name:Hn.string(),description:Hn.string().optional(),agent:Hn.string().optional(),model:Hn.string().optional(),source:Hn.enum(["command","mcp","skill"]).optional(),template:Hn.promise(Hn.string()).or(Hn.string()),subtask:Hn.boolean().optional(),hints:Hn.array(Hn.string())}).meta({ref:"Command"});function i(c){let l=[],g=c.match(/\$\d+/g);if(g)for(let u of[...new Set(g)].sort())l.push(u);return c.includes("$ARGUMENTS")&&l.push("$ARGUMENTS"),l}s.hints=i,n(i,"hints"),s.Default={INIT:"init",REVIEW:"review"};class y extends Xw.Service()("@opencode/Command"){static{n(this,"Service")}}s.Service=y,s.layer=Ca.effect(y,Ts.gen(function*(){let c=yield*rt.Service,l=yield*Br.Service,g=yield*Bn.Service,u=Ts.fn("Command.state")(function*(r){let x=yield*c.get(),h={};h[s.Default.INIT]={name:s.Default.INIT,description:"guided AGENTS.md setup",source:"command",get template(){return gl.replace("${path}",r.worktree)},hints:i(gl)},h[s.Default.REVIEW]={name:s.Default.REVIEW,description:"review changes [commit|branch|pr], defaults to uncommitted",source:"command",get template(){return hl.replace("${path}",r.worktree)},subtask:!0,hints:i(hl)};for(let[v,S]of Object.entries(x.command??{}))h[v]={name:v,agent:S.agent,model:S.model,description:S.description,source:"command",get template(){return S.template},subtask:S.subtask,hints:i(S.template)};for(let[v,S]of Object.entries(yield*l.prompts()))h[v]={name:v,source:"mcp",description:S.description,get template(){return Ts.runPromise(l.getPrompt(S.client,S.name,S.arguments?Object.fromEntries(S.arguments.map((j,O)=>[j.name,`$${O+1}`])):{}).pipe(Ts.map(j=>j?.messages.map(O=>O.content.type==="text"?O.content.text:"").join(`
|
|
1554
|
+
`)||"")))},hints:S.arguments?.map((j,O)=>`$${O+1}`)??[]};for(let v of yield*g.all())h[v.name]||(h[v.name]={name:v.name,description:v.description,source:"skill",get template(){return v.content},hints:[]});return{commands:h}}),a=yield*ge.make(r=>u(r)),w=Ts.fn("Command.get")(function*(r){return(yield*ge.get(a)).commands[r]}),I=Ts.fn("Command.list")(function*(){let r=yield*ge.get(a);return Object.values(r.commands)});return y.of({get:w,list:I})})),s.defaultLayer=s.layer.pipe(Ca.provide(rt.defaultLayer),Ca.provide(Br.defaultLayer),Ca.provide(Bn.defaultLayer));let{runPromise:b}=Ke(y,s.defaultLayer);async function d(){return b(c=>c.list())}s.list=d,n(d,"list")})(Wr||={});import{pathToFileURL as rx,fileURLToPath as sx}from"url";import Ra from"path";import{spawn as Zw}from"child_process";import{setTimeout as Fp}from"node:timers/promises";var Up=200,ja;(u=>{let e=new Set(["fish","nu"]),t=new Set(["bash","dash","fish","ksh","sh","zsh"]),o=new Set(["bash","dash","ksh","sh","zsh"]);async function i(a,w){let I=a.pid;if(!(!I||w?.exited?.())){if(process.platform==="win32"){await new Promise(r=>{let x=Zw("taskkill",["/pid",String(I),"/f","/t"],{stdio:"ignore",windowsHide:!0});x.once("exit",()=>r()),x.once("error",()=>r())});return}try{process.kill(-I,"SIGTERM"),await Fp(Up),w?.exited?.()||process.kill(-I,"SIGKILL")}catch{a.kill("SIGTERM"),await Fp(Up),w?.exited?.()||a.kill("SIGKILL")}}}u.killTree=i,n(i,"killTree");function m(a){if(process.platform!=="win32")return a;let w=Ee.windowsPath(a);return Ra.win32.dirname(w)!=="."?w.startsWith("/")&&d(w)==="bash"&&f()||w:Bun.which(w)||w}n(m,"full");function y(){let a=Bun.which("pwsh");if(a)return a;let w=Bun.which("powershell");if(w)return w}n(y,"pick");function p(a,w){if(a&&(!w?.acceptable||!e.has(d(a))))return m(a);if(process.platform==="win32"){let I=y();if(I)return I}return b()}n(p,"select");function f(){if(process.platform!=="win32")return;if(Ce.OPENCODE_GIT_BASH_PATH)return Ce.OPENCODE_GIT_BASH_PATH;let a=Be("git");if(!a)return;let w=Ra.join(a,"..","..","bin","bash.exe");if(Ee.stat(w)?.size)return w}u.gitbash=f,n(f,"gitbash");function b(){if(process.platform==="win32"){let w=f();return w||process.env.COMSPEC||"cmd.exe"}if(process.platform==="darwin")return"/bin/zsh";let a=Be("bash");return a||"/bin/sh"}n(b,"fallback");function d(a){return process.platform==="win32"?Ra.win32.parse(Ee.windowsPath(a)).name.toLowerCase():Ra.basename(a).toLowerCase()}u.name=d,n(d,"name");function s(a){return t.has(d(a))}u.login=s,n(s,"login");function c(a){return o.has(d(a))}u.posix=c,n(c,"posix"),u.preferred=$o(()=>p(process.env.SHELL)),u.acceptable=$o(()=>p(process.env.SHELL,{acceptable:!0}))})(ja||={});function $p(e){let t=e.indexOf(",");if(t===-1)return"";let o=e.slice(0,t),i=e.slice(t+1);return o.includes(";base64")?Buffer.from(i,"base64").toString("utf8"):decodeURIComponent(i)}n($p,"decodeDataUrl");import{Cause as Ps,Effect as Se,Exit as yi,Layer as xn,Option as ix,Scope as ax,ServiceMap as cx}from"effect";import qp from"fs";import Qw from"path";var Ma=qe.create({service:"session.pause"}),Bp=Qw.join(je.Path.state,"pause.json"),Hr=!1,Gr=new Set;try{let e=JSON.parse(qp.readFileSync(Bp,"utf8"));Hr=e?.paused===!0;for(let t of Array.isArray(e?.waiting)?e.waiting:[])typeof t=="string"&&Gr.add(t)}catch{}function yl(){try{qp.writeFileSync(Bp,JSON.stringify({paused:Hr,waiting:[...Gr]}))}catch(e){Ma.warn("could not save the pause state",{error:String(e)})}}n(yl,"save");var Vr;(y=>{function e(){return Hr}y.isPaused=e,n(e,"isPaused");function t(p){Gr.has(p)||(Gr.add(p),Ma.info("turn held while paused",{sessionID:p}),yl())}y.hold=t,n(t,"hold");function o(){Hr||(Hr=!0,Ma.info("paused"),yl())}y.pause=o,n(o,"pause");function i(){let p=[...Gr];return Hr=!1,Gr.clear(),Ma.info("resumed",{waiting:p.length}),yl(),p}y.resume=i,n(i,"resume");function m(){return{paused:Hr,waiting:[...Gr]}}y.state=m,n(m,"state")})(Vr||={});globalThis.AI_SDK_LOG_WARNINGS=!1;var lx=`Use this tool to return your final response in the requested structured format.
|
|
1555
|
+
|
|
1556
|
+
IMPORTANT:
|
|
1557
|
+
- You MUST call this tool exactly once at the end of your response
|
|
1558
|
+
- The input must be valid JSON matching the required schema
|
|
1559
|
+
- Complete all necessary research and tool calls BEFORE calling this tool
|
|
1560
|
+
- This tool provides your final answer - no further actions are taken after calling it`,dx="IMPORTANT: The user has requested structured output. You MUST use the StructuredOutput tool to provide your final response. Do NOT respond with plain text - you MUST call the StructuredOutput tool with your answer formatted according to the schema.",No;(S=>{let e=qe.create({service:"session.prompt"});class t extends cx.Service()("@opencode/SessionPrompt"){static{n(this,"Service")}}S.Service=t,S.layer=xn.effect(t,Se.gen(function*(){let j=yield*Ve.Service,O=yield*Ur.Service,k=yield*yt.Service,E=yield*ro.Service,D=yield*yn.Service,z=yield*$r.Service,_=yield*_a.Service,B=yield*ln.Service,$=yield*Wr.Service,M=yield*lt.Service,C=yield*ut.Service,T=yield*Br.Service,G=yield*Pt.Service,N=yield*Nn.Service,A=yield*La.Service,F=yield*po.Service,V=yield*ox.ChildProcessSpawner,Y=yield*ax.Scope,re=yield*hr.Service,ue=yield*ge.make(Se.fn("SessionPrompt.state")(function*(){let P=new Map;return yield*Se.addFinalizer(Se.fnUntraced(function*(){yield*Se.forEach(P.values(),Z=>Z.cancel,{concurrency:"unbounded",discard:!0}),P.clear()})),{runners:P}})),H=new Map,R=n((P,Z)=>{let J=P.get(Z);if(J)return J;let fe=ul.make(Y,{onIdle:Se.gen(function*(){P.delete(Z),yield*O.set(Z,{type:"idle"})}),onBusy:O.set(Z,{type:"busy"}),onInterrupt:Ie(Z),busy:n(()=>{throw new yt.BusyError(Z)},"busy")});return P.set(Z,fe),fe},"getRunner"),L=Se.fn("SessionPrompt.assertNotBusy")(function*(P){if((yield*ge.get(ue)).runners.get(P)?.busy)throw new yt.BusyError(P)}),q=Se.fn("SessionPrompt.cancel")(function*(P){e.info("cancel",{sessionID:P});let J=(yield*ge.get(ue)).runners.get(P);if(!J||!J.busy){yield*O.set(P,{type:"idle"});return}yield*J.cancel}),X=Se.fn("SessionPrompt.stopForPause")(function*(){let Z=[...(yield*ge.get(ue)).runners.entries()].filter(([,J])=>J.busy);for(let[J]of Z)Vr.hold(J);return yield*Se.forEach(Z,([,J])=>J.cancel,{concurrency:"unbounded",discard:!0}),Z.map(([J])=>J)}),ne=Se.fn("SessionPrompt.resolvePromptParts")(function*(P){let Z=yield*ge.context,J=[{type:"text",text:P}],fe=Un.files(P),_e=new Set;return yield*Se.forEach(fe,Se.fnUntraced(function*(te){let we=te[1];if(_e.has(we))return;_e.add(we);let $e=we.startsWith("~/")?hi.join(ex.homedir(),we.slice(2)):hi.resolve(Z.worktree,we),ee=yield*C.stat($e).pipe(Se.option);if(ix.isNone(ee)){let ke=yield*E.get(we);ke&&J.push({type:"agent",name:ke.name});return}let de=ee.value;J.push({type:"file",url:rx($e).href,filename:we,mime:de.type==="Directory"?"application/x-directory":"text/plain"})}),{concurrency:"unbounded",discard:!0}),J}),Q=Se.fn("SessionPrompt.ensureTitle")(function*(P){if(P.session.parentID||!yt.isDefaultTitle(P.session.title))return;let Z=n(Me=>Me.info.role==="user"&&!Me.parts.every(Ae=>"synthetic"in Ae&&Ae.synthetic),"real"),J=P.history.findIndex(Z);if(J===-1||P.history.filter(Z).length!==1)return;let fe=P.history.slice(0,J+1),_e=fe[J];if(!_e||_e.info.role!=="user")return;let te=_e.info,we=_e.parts.filter(Me=>Me.type==="subtask"),$e=we.length>0&&_e.parts.every(Me=>Me.type==="subtask"),ee=yield*E.get("title");if(!ee)return;let de=ee.model?yield*D.getModel(ee.model.providerID,ee.model.modelID):(yield*D.getSmallModel(P.providerID))??(yield*D.getModel(P.providerID,P.modelID)),ke=$e?[{role:"user",content:we.map(Me=>Me.prompt).join(`
|
|
1561
|
+
`)}]:yield*Qe.toModelMessagesEffect(fe,de),Pe=(yield*Se.promise(async Me=>(await Is.stream({agent:ee,user:te,system:[],small:!0,tools:{},model:de,abort:Me,sessionID:P.session.id,retries:2,messages:[{role:"user",content:`Generate a title for this conversation:
|
|
1562
|
+
`},...ke]})).text)).replace(/<think>[\s\S]*?<\/think>\s*/g,"").split(`
|
|
1563
|
+
`).map(Me=>Me.trim()).find(Me=>Me.length>0);if(!Pe)return;let Ne=Pe.length>100?Pe.substring(0,97)+"...":Pe;yield*k.setTitle({sessionID:P.session.id,title:Ne}).pipe(Se.catchCause(Me=>Se.sync(()=>e.error("failed to generate title",{error:Ps.squash(Me)}))))}),oe=Se.fn("SessionPrompt.insertReminders")(function*(P){let Z=P.messages.findLast(we=>we.info.role==="user");if(!Z)return P.messages;if(!Ce.OPENCODE_EXPERIMENTAL_PLAN_MODE)return P.agent.name==="plan"&&Z.parts.push({id:It.ascending(),messageID:Z.info.id,sessionID:Z.info.sessionID,type:"text",text:Op,synthetic:!0}),P.messages.some($e=>$e.info.role==="assistant"&&$e.info.agent==="plan")&&P.agent.name==="build"&&Z.parts.push({id:It.ascending(),messageID:Z.info.id,sessionID:Z.info.sessionID,type:"text",text:dl,synthetic:!0}),P.messages;let J=P.messages.findLast(we=>we.info.role==="assistant");if(P.agent.name!=="plan"&&J?.info.agent==="plan"){let we=yt.plan(P.session);if(!(yield*C.existsSafe(we)))return P.messages;let $e=yield*k.updatePart({id:It.ascending(),messageID:Z.info.id,sessionID:Z.info.sessionID,type:"text",text:dl+`
|
|
1564
|
+
|
|
1565
|
+
A plan file exists at ${we}. You should execute on the plan defined within it`,synthetic:!0});return Z.parts.push($e),P.messages}if(P.agent.name!=="plan"||J?.info.agent==="plan")return P.messages;let fe=yt.plan(P.session),_e=yield*C.existsSafe(fe);_e||(yield*C.ensureDir(hi.dirname(fe)).pipe(Se.catch(Se.die)));let te=yield*k.updatePart({id:It.ascending(),messageID:Z.info.id,sessionID:Z.info.sessionID,type:"text",text:`<system-reminder>
|
|
1566
|
+
Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits (with the exception of the plan file mentioned below), run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.
|
|
1567
|
+
|
|
1568
|
+
## Plan File Info:
|
|
1569
|
+
${_e?`A plan file already exists at ${fe}. You can read it and make incremental edits using the edit tool.`:`No plan file exists yet. You should create your plan at ${fe} using the write tool.`}
|
|
1570
|
+
You should build your plan incrementally by writing to or editing this file. NOTE that this is the only file you are allowed to edit - other than this you are only allowed to take READ-ONLY actions.
|
|
1571
|
+
|
|
1572
|
+
## Plan Workflow
|
|
1573
|
+
|
|
1574
|
+
### Phase 1: Initial Understanding
|
|
1575
|
+
Goal: Gain a comprehensive understanding of the user's request by reading through code and asking them questions. Critical: In this phase you should only use the explore subagent type.
|
|
1576
|
+
|
|
1577
|
+
1. Focus on understanding the user's request and the code associated with their request
|
|
1578
|
+
|
|
1579
|
+
2. **Launch up to 3 explore agents IN PARALLEL** (single message, multiple tool calls) to efficiently explore the codebase.
|
|
1580
|
+
- Use 1 agent when the task is isolated to known files, the user provided specific file paths, or you're making a small targeted change.
|
|
1581
|
+
- Use multiple agents when: the scope is uncertain, multiple areas of the codebase are involved, or you need to understand existing patterns before planning.
|
|
1582
|
+
- Quality over quantity - 3 agents maximum, but you should try to use the minimum number of agents necessary (usually just 1)
|
|
1583
|
+
- If using multiple agents: Provide each agent with a specific search focus or area to explore. Example: One agent searches for existing implementations, another explores related components, a third investigates testing patterns
|
|
1584
|
+
|
|
1585
|
+
3. After exploring the code, use the question tool to clarify ambiguities in the user request up front.
|
|
1586
|
+
|
|
1587
|
+
### Phase 2: Design
|
|
1588
|
+
Goal: Design an implementation approach.
|
|
1589
|
+
|
|
1590
|
+
Launch general agent(s) to design the implementation based on the user's intent and your exploration results from Phase 1.
|
|
1591
|
+
|
|
1592
|
+
You can launch up to 1 agent(s) in parallel.
|
|
1593
|
+
|
|
1594
|
+
**Guidelines:**
|
|
1595
|
+
- **Default**: Launch at least 1 Plan agent for most tasks - it helps validate your understanding and consider alternatives
|
|
1596
|
+
- **Skip agents**: Only for truly trivial tasks (typo fixes, single-line changes, simple renames)
|
|
1597
|
+
|
|
1598
|
+
Examples of when to use multiple agents:
|
|
1599
|
+
- The task touches multiple parts of the codebase
|
|
1600
|
+
- It's a large refactor or architectural change
|
|
1601
|
+
- There are many edge cases to consider
|
|
1602
|
+
- You'd benefit from exploring different approaches
|
|
1603
|
+
|
|
1604
|
+
Example perspectives by task type:
|
|
1605
|
+
- New feature: simplicity vs performance vs maintainability
|
|
1606
|
+
- Bug fix: root cause vs workaround vs prevention
|
|
1607
|
+
- Refactoring: minimal change vs clean architecture
|
|
1608
|
+
|
|
1609
|
+
In the agent prompt:
|
|
1610
|
+
- Provide comprehensive background context from Phase 1 exploration including filenames and code path traces
|
|
1611
|
+
- Describe requirements and constraints
|
|
1612
|
+
- Request a detailed implementation plan
|
|
1613
|
+
|
|
1614
|
+
### Phase 3: Review
|
|
1615
|
+
Goal: Review the plan(s) from Phase 2 and ensure alignment with the user's intentions.
|
|
1616
|
+
1. Read the critical files identified by agents to deepen your understanding
|
|
1617
|
+
2. Ensure that the plans align with the user's original request
|
|
1618
|
+
3. Use question tool to clarify any remaining questions with the user
|
|
1619
|
+
|
|
1620
|
+
### Phase 4: Final Plan
|
|
1621
|
+
Goal: Write your final plan to the plan file (the only file you can edit).
|
|
1622
|
+
- Include only your recommended approach, not all alternatives
|
|
1623
|
+
- Ensure that the plan file is concise enough to scan quickly, but detailed enough to execute effectively
|
|
1624
|
+
- Include the paths of critical files to be modified
|
|
1625
|
+
- Include a verification section describing how to test the changes end-to-end (run the code, use MCP tools, run tests)
|
|
1626
|
+
|
|
1627
|
+
### Phase 5: Call plan_exit tool
|
|
1628
|
+
At the very end of your turn, once you have asked the user questions and are happy with your final plan file - you should always call plan_exit to indicate to the user that you are done planning.
|
|
1629
|
+
This is critical - your turn should only end with either asking the user a question or calling plan_exit. Do not stop unless it's for these 2 reasons.
|
|
1630
|
+
|
|
1631
|
+
**Important:** Use question tool to clarify requirements/approach, use plan_exit to request plan approval. Do NOT use question tool to ask "Is this plan okay?" - that's what plan_exit does.
|
|
1632
|
+
|
|
1633
|
+
NOTE: At any point in time through this workflow you should feel free to ask the user questions or clarifications. Don't make large assumptions about user intent. The goal is to present a well researched plan to the user, and tie any loose ends before implementation begins.
|
|
1634
|
+
</system-reminder>`,synthetic:!0});return Z.parts.push(te),P.messages}),ce=Se.fn("SessionPrompt.resolveTools")(function*(P){var $e=[];try{let Z=kn($e,e.time("resolveTools"));let J={};let fe=lt.merge(P.agent.permission,P.session.permission??[]);let _e=n((se,Pe)=>({sessionID:P.session.id,abort:Pe.abortSignal,messageID:P.processor.message.id,callID:Pe.toolCallId,extra:{model:P.model,bypassAgentCheck:P.bypassAgentCheck},agent:P.agent.name,messages:P.messages,metadata:n(Ne=>Se.runPromise(Se.gen(function*(){let Me=P.processor.partFromToolCall(Pe.toolCallId);!Me||!["running","pending"].includes(Me.state.status)||(yield*k.updatePart({...Me,state:{title:Ne.title,metadata:Ne.metadata,status:"running",input:se,time:Me.state.status==="running"?Me.state.time:{start:Date.now()}}}))})),"metadata"),ask:n(Ne=>Se.runPromise(M.ask({...Ne,sessionID:P.session.id,tool:{messageID:P.processor.message.id,callID:Pe.toolCallId},ruleset:fe})),"ask")}),"context");for(let se of yield*A.tools({modelID:Ut.make(P.model.api.id),providerID:P.model.providerID},P.agent)){let Pe=Jt.schema(P.model,Kt.toJSONSchema(se.parameters));J[se.id]=Wp({id:se.id,description:se.description,inputSchema:bl(Pe),execute(Ne,Me){return so.run(P.gate,()=>Se.runPromise(Se.gen(function*(){let Ae=_e(Ne,Me);yield*B.trigger("tool.execute.before",{tool:se.id,sessionID:Ae.sessionID,callID:Ae.callID},{args:Ne});let Fe=yield*Se.promise(()=>se.execute(Ne,Ae)),Re={...Fe,attachments:Fe.attachments?.map(nt=>({...nt,id:It.ascending(),sessionID:Ae.sessionID,messageID:P.processor.message.id}))};return yield*B.trigger("tool.execute.after",{tool:se.id,sessionID:Ae.sessionID,callID:Ae.callID,args:Ne},Re),Re})))}})}let te=Object.entries(yield*T.tools());let we=lt.disabled(te.map(([se])=>se),fe);for(let[se,Pe]of te){if(we.has(se))continue;let Ne=Pe.execute;if(!Ne)continue;let Me=yield*Se.promise(()=>Promise.resolve(tx(Pe.inputSchema).jsonSchema)),Ae=Jt.schema(P.model,Me);Pe.inputSchema=bl(Ae),Pe.execute=(Fe,Re)=>so.run(P.gate,()=>Se.runPromise(Se.gen(function*(){let nt=_e(Fe,Re);yield*B.trigger("tool.execute.before",{tool:se,sessionID:nt.sessionID,callID:Re.toolCallId},{args:Fe}),yield*Se.promise(()=>nt.ask({permission:se,metadata:{},patterns:["*"],always:["*"]}));let et=yield*Se.promise(()=>Ne(Fe,{...Re,callContext:{sessionId:nt.sessionID,messageId:nt.messageID}}));yield*B.trigger("tool.execute.after",{tool:se,sessionID:nt.sessionID,callID:Re.toolCallId,args:Fe},et);let Ue=[],ot=[];for(let xt of et.content)if(xt.type==="text")Ue.push(xt.text);else if(xt.type==="image")ot.push({type:"file",mime:xt.mimeType,url:`data:${xt.mimeType};base64,${xt.data}`});else if(xt.type==="resource"){let{resource:_t}=xt;_t.text&&Ue.push(_t.text),_t.blob&&ot.push({type:"file",mime:_t.mimeType??"application/octet-stream",url:`data:${_t.mimeType??"application/octet-stream"};base64,${_t.blob}`,filename:_t.uri})}let Xe=yield*F.output(Ue.join(`
|
|
1635
|
+
|
|
1636
|
+
`),{},P.agent);return{title:"",metadata:{...et.metadata??{},...et.isError?{isError:!0}:{},truncated:Xe.truncated,...Xe.truncated&&{outputPath:Xe.outputPath}},output:Xe.content,attachments:ot.map(xt=>({...xt,id:It.ascending(),sessionID:nt.sessionID,messageID:P.processor.message.id})),content:et.content}}))),J[se]=Pe}return J}catch(ee){var de=ee,ke=!0}finally{En($e,de,ke)}}),pe=Se.fn("SessionPrompt.handleSubtask")(function*(P){let{task:Z,model:J,lastUser:fe,sessionID:_e,session:te,msgs:we}=P,$e=yield*ge.context,ee=yield*Se.promise(()=>A.named.task.init()),de=Z.model?yield*Oe(Z.model.providerID,Z.model.modelID,_e):J,ke=yield*k.updateMessage({id:pt.ascending(),role:"assistant",parentID:fe.id,sessionID:_e,mode:Z.agent,agent:Z.agent,variant:fe.variant,path:{cwd:$e.directory,root:$e.worktree},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelID:de.id,providerID:de.providerID,time:{created:Date.now()}}),se=yield*k.updatePart({id:It.ascending(),messageID:ke.id,sessionID:ke.sessionID,type:"tool",callID:Hp(),tool:A.named.task.id,state:{status:"running",input:{prompt:Z.prompt,description:Z.description,subagent_type:Z.agent,command:Z.command},time:{start:Date.now()}}}),Pe={prompt:Z.prompt,description:Z.description,subagent_type:Z.agent,command:Z.command};yield*B.trigger("tool.execute.before",{tool:"task",sessionID:_e,callID:se.id},{args:Pe});let Ne=yield*E.get(Z.agent);if(!Ne){let nt=(yield*E.list()).filter(ot=>!ot.hidden).map(ot=>ot.name),et=nt.length?` Available agents: ${nt.join(", ")}`:"",Ue=new tt.Unknown({message:`Agent not found: "${Z.agent}".${et}`});throw yield*j.publish(yt.Event.Error,{sessionID:_e,error:Ue.toObject()}),Ue}let Me,Ae=yield*Se.promise(nt=>ee.execute(Pe,{agent:Z.agent,messageID:ke.id,sessionID:_e,abort:nt,callID:se.callID,extra:{bypassAgentCheck:!0},messages:we,metadata(et){return Se.runPromise(Se.gen(function*(){se=yield*k.updatePart({...se,type:"tool",state:{...se.state,...et}})}))},ask(et){return Se.runPromise(M.ask({...et,sessionID:_e,ruleset:lt.merge(Ne.permission,te.permission??[])}))}}).catch(et=>{Me=et instanceof Error?et:new Error(String(et)),e.error("subtask execution failed",{error:Me,agent:Z.agent,description:Z.description})})).pipe(Se.onInterrupt(()=>Se.gen(function*(){ke.finish="tool-calls",ke.time.completed=Date.now(),yield*k.updateMessage(ke),se.state.status==="running"&&(yield*k.updatePart({...se,state:{status:"error",error:"Cancelled",time:{start:se.state.time.start,end:Date.now()},metadata:se.state.metadata,input:se.state.input}}))}))),Fe=Ae?.attachments?.map(nt=>({...nt,id:It.ascending(),sessionID:_e,messageID:ke.id}));if(yield*B.trigger("tool.execute.after",{tool:"task",sessionID:_e,callID:se.id,args:Pe},Ae),ke.finish="tool-calls",ke.time.completed=Date.now(),yield*k.updateMessage(ke),Ae&&se.state.status==="running"&&(yield*k.updatePart({...se,state:{status:"completed",input:se.state.input,title:Ae.title,metadata:Ae.metadata,output:Ae.output,attachments:Fe,time:{...se.state.time,end:Date.now()}}})),Ae||(yield*k.updatePart({...se,state:{status:"error",error:Me?`Tool execution failed: ${Me.message}`:"Tool execution failed",time:{start:se.state.status==="running"?se.state.time.start:Date.now(),end:Date.now()},metadata:se.state.status==="pending"?void 0:se.state.metadata,input:se.state.input}})),!Z.command)return;let Re={id:pt.ascending(),sessionID:_e,role:"user",time:{created:Date.now()},agent:fe.agent,model:fe.model};yield*k.updateMessage(Re),yield*k.updatePart({id:It.ascending(),messageID:Re.id,sessionID:_e,type:"text",text:"Summarize the task tool output above and continue with your task.",synthetic:!0})}),De=Se.fn("SessionPrompt.shellImpl")(function*(P,Z){let J=yield*ge.context,fe=yield*k.get(P.sessionID);fe.revert&&(yield*Se.promise(()=>da.cleanup(fe)));let _e=yield*E.get(P.agent);if(!_e){let ot=(yield*E.list()).filter(xt=>!xt.hidden).map(xt=>xt.name),Xe=ot.length?` Available agents: ${ot.join(", ")}`:"",wt=new tt.Unknown({message:`Agent not found: "${P.agent}".${Xe}`});throw yield*j.publish(yt.Event.Error,{sessionID:P.sessionID,error:wt.toObject()}),wt}let te=P.model??_e.model??(yield*xe(P.sessionID)),we={id:P.messageID??pt.ascending(),sessionID:P.sessionID,time:{created:Date.now()},role:"user",agent:P.agent,model:{providerID:te.providerID,modelID:te.modelID}};yield*k.updateMessage(we);let $e={type:"text",id:It.ascending(),messageID:we.id,sessionID:P.sessionID,text:"The following tool was executed by the user",synthetic:!0};yield*k.updatePart($e);let ee={id:pt.ascending(),sessionID:P.sessionID,parentID:we.id,mode:P.agent,agent:P.agent,cost:0,path:{cwd:J.directory,root:J.worktree},time:{created:Date.now()},role:"assistant",tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelID:te.modelID,providerID:te.providerID};yield*k.updateMessage(ee);let de={type:"tool",id:It.ascending(),messageID:ee.id,sessionID:P.sessionID,tool:"bash",callID:Hp(),state:{status:"running",time:{start:Date.now()},input:{command:P.command}}};yield*k.updatePart(de);let ke=ja.preferred(),se=(process.platform==="win32"?hi.win32.basename(ke,".exe"):hi.basename(ke)).toLowerCase(),Pe={nu:{args:["-c",P.command]},fish:{args:["-c",P.command]},zsh:{args:["-l","-c",`
|
|
1637
|
+
__oc_cwd=$PWD
|
|
1638
|
+
[[ -f ~/.zshenv ]] && source ~/.zshenv >/dev/null 2>&1 || true
|
|
1639
|
+
[[ -f "\${ZDOTDIR:-$HOME}/.zshrc" ]] && source "\${ZDOTDIR:-$HOME}/.zshrc" >/dev/null 2>&1 || true
|
|
1640
|
+
cd "$__oc_cwd"
|
|
1641
|
+
eval ${JSON.stringify(P.command)}
|
|
1642
|
+
`]},bash:{args:["-l","-c",`
|
|
1643
|
+
__oc_cwd=$PWD
|
|
1644
|
+
shopt -s expand_aliases
|
|
1645
|
+
[[ -f ~/.bashrc ]] && source ~/.bashrc >/dev/null 2>&1 || true
|
|
1646
|
+
cd "$__oc_cwd"
|
|
1647
|
+
eval ${JSON.stringify(P.command)}
|
|
1648
|
+
`]},cmd:{args:["/c",P.command]},powershell:{args:["-NoProfile","-Command",P.command]},pwsh:{args:["-NoProfile","-Command",P.command]},"":{args:["-c",P.command]}},Ne=(Pe[se]??Pe[""]).args,Me=J.directory,Ae=yield*B.trigger("shell.env",{cwd:Me,sessionID:P.sessionID,callID:de.callID},{env:{}}),Fe=nx.make(ke,Ne,{cwd:Me,extendEnv:!0,env:{...Ae.env,TERM:"dumb"},stdin:"ignore",forceKillAfter:"3 seconds"}),Re="",nt=!1,et=Se.uninterruptible(Se.gen(function*(){nt&&(Re+=`
|
|
1649
|
+
|
|
1650
|
+
`+["<metadata>","User aborted the command","</metadata>"].join(`
|
|
1651
|
+
`)),ee.time.completed||(ee.time.completed=Date.now(),yield*k.updateMessage(ee)),de.state.status==="running"&&(de.state={status:"completed",time:{...de.state.time,end:Date.now()},input:de.state.input,title:"",metadata:{output:Re,description:""},output:Re},yield*k.updatePart(de))})),Ue=yield*Se.gen(function*(){let ot=yield*V.spawn(Fe);yield*Na.runForEach(Na.decodeText(ot.all),Xe=>Se.sync(()=>{Re+=Xe,de.state.status==="running"&&(de.state.metadata={output:Re,description:""},Se.runFork(k.updatePart(de)))})),yield*ot.exitCode}).pipe(Se.scoped,Se.onInterrupt(()=>Se.sync(()=>{nt=!0})),Se.orDie,Se.ensuring(et),Se.exit);return yi.isFailure(Ue)&&!Ps.hasInterruptsOnly(Ue.cause)?yield*Se.failCause(Ue.cause):{info:ee,parts:[de]}}),Oe=Se.fn("SessionPrompt.getModel")(function*(P,Z,J){let fe=yield*D.getModel(P,Z).pipe(Se.exit);if(yi.isSuccess(fe))return fe.value;let _e=Ps.squash(fe.cause);if(yn.ModelNotFoundError.isInstance(_e)){let te=_e.data.suggestions?.length?` Did you mean: ${_e.data.suggestions.join(", ")}?`:"";yield*j.publish(yt.Event.Error,{sessionID:J,error:new tt.Unknown({message:`Model not found: ${_e.data.providerID}/${_e.data.modelID}.${te}`}).toObject()})}return yield*Se.failCause(fe.cause)}),xe=Se.fnUntraced(function*(P){let Z=yield*Se.promise(async()=>{for await(let J of Qe.stream(P))if(J.info.role==="user"&&J.info.model)return J.info.model});return Z||(yield*D.defaultModel())}),ie=Se.fnUntraced(function*(P){let Z=yield*Se.promise(async()=>{for await(let fe of Qe.stream(P))if(fe.info.role==="user"&&fe.info.agent)return fe.info.agent});return Z&&(yield*E.get(Z))?Z:void 0}),le=Se.fn("SessionPrompt.createUserMessage")(function*(P){let Z=P.agent||(yield*ie(P.sessionID))||(yield*E.defaultAgent()),J=yield*E.get(Z);if(!J){let se=(yield*E.list()).filter(Me=>!Me.hidden).map(Me=>Me.name),Pe=se.length?` Available agents: ${se.join(", ")}`:"",Ne=new tt.Unknown({message:`Agent not found: "${Z}".${Pe}`});throw yield*j.publish(yt.Event.Error,{sessionID:P.sessionID,error:Ne.toObject()}),Ne}let fe=P.model??J.model??(yield*xe(P.sessionID)),_e=!P.variant&&J.variant?yield*D.getModel(fe.providerID,fe.modelID).pipe(Se.catch(()=>Se.succeed(void 0))):void 0,te=P.variant??Jt.nearestVariant(J.variant,Object.keys(_e?.variants??{})),we={id:P.messageID??pt.ascending(),role:"user",sessionID:P.sessionID,time:{created:Date.now()},tools:P.tools,...P.noReply===!0?{quiet:!0}:{},agent:J.name,model:fe,system:P.system,format:P.format,variant:te};yield*Se.addFinalizer(()=>ge.withALS(()=>re.clear(we.id)).pipe(Se.flatMap(se=>se)));let $e=n(se=>({...se,id:se.id?It.make(se.id):It.ascending()}),"assign"),ee=Se.fn("SessionPrompt.resolveUserPart")(function*(se){if(se.type==="file"){if(se.source?.type==="resource"){let{clientName:Ne,uri:Me}=se.source;e.info("mcp resource",{clientName:Ne,uri:Me,mime:se.mime});let Ae=[{messageID:we.id,sessionID:P.sessionID,type:"text",synthetic:!0,text:`Reading MCP resource: ${se.filename} (${Me})`}],Fe=yield*T.readResource(Ne,Me).pipe(Se.exit);if(yi.isSuccess(Fe)){let Re=Fe.value;if(!Re)throw new Error(`Resource not found: ${Ne}/${Me}`);let nt=Array.isArray(Re.contents)?Re.contents:[Re.contents];for(let et of nt)if("text"in et&&et.text)Ae.push({messageID:we.id,sessionID:P.sessionID,type:"text",synthetic:!0,text:et.text});else if("blob"in et&&et.blob){let Ue="mimeType"in et?et.mimeType:se.mime;Ae.push({messageID:we.id,sessionID:P.sessionID,type:"text",synthetic:!0,text:`[Binary content: ${Ue}]`})}Ae.push({...se,messageID:we.id,sessionID:P.sessionID})}else{let Re=Ps.squash(Fe.cause);e.error("failed to read MCP resource",{error:Re,clientName:Ne,uri:Me});let nt=Re instanceof Error?Re.message:String(Re);Ae.push({messageID:we.id,sessionID:P.sessionID,type:"text",synthetic:!0,text:`Failed to read MCP resource ${se.filename}: ${nt}`})}return Ae}let Pe=new URL(se.url);switch(Pe.protocol){case"data:":if(se.mime==="text/plain")return[{messageID:we.id,sessionID:P.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify({filePath:se.filename})}`},{messageID:we.id,sessionID:P.sessionID,type:"text",synthetic:!0,text:$p(se.url)},{...se,messageID:we.id,sessionID:P.sessionID}];break;case"file:":{e.info("file",{mime:se.mime});let Ne=sx(se.url);if((yield*C.isDir(Ne))&&(se.mime="application/x-directory"),se.mime==="text/plain"){let Me,Ae,Fe={start:Pe.searchParams.get("start"),end:Pe.searchParams.get("end")};if(Fe.start!=null){let Ue=se.url.split("?")[0],ot=parseInt(Fe.start),Xe=Fe.end?parseInt(Fe.end):void 0;if(ot===Xe){let wt=yield*G.documentSymbol(Ue).pipe(Se.catch(()=>Se.succeed([])));for(let xt of wt){let _t;if("range"in xt?_t=xt.range:"location"in xt&&(_t=xt.location.range),_t?.start?.line&&_t?.start?.line===ot){ot=_t.start.line,Xe=_t?.end?.line??ot;break}}}Me=Math.max(ot,1),Xe&&(Ae=Xe-(Me-1))}let Re={filePath:Ne,offset:Me,limit:Ae},nt=[{messageID:we.id,sessionID:P.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify(Re)}`}],et=yield*Se.promise(()=>A.named.read.init()).pipe(Se.flatMap(Ue=>D.getModel(we.model.providerID,we.model.modelID).pipe(Se.flatMap(ot=>Se.promise(()=>Ue.execute(Re,{sessionID:P.sessionID,abort:new AbortController().signal,agent:P.agent,messageID:we.id,extra:{bypassCwdCheck:!0,model:ot},messages:[],metadata:n(async()=>{},"metadata"),ask:n(async()=>{},"ask")}))))),Se.exit);if(yi.isSuccess(et)){let Ue=et.value;nt.push({messageID:we.id,sessionID:P.sessionID,type:"text",synthetic:!0,text:Ue.output}),Ue.attachments?.length?nt.push(...Ue.attachments.map(ot=>({...ot,synthetic:!0,filename:ot.filename??se.filename,messageID:we.id,sessionID:P.sessionID}))):nt.push({...se,messageID:we.id,sessionID:P.sessionID})}else{let Ue=Ps.squash(et.cause);e.error("failed to read file",{error:Ue});let ot=Ue instanceof Error?Ue.message:String(Ue);yield*j.publish(yt.Event.Error,{sessionID:P.sessionID,error:new tt.Unknown({message:ot}).toObject()}),nt.push({messageID:we.id,sessionID:P.sessionID,type:"text",synthetic:!0,text:`Read tool failed to read ${Ne} with the following error: ${ot}`})}return nt}if(se.mime==="application/x-directory"){let Me={filePath:Ne},Ae=yield*Se.promise(()=>A.named.read.init()).pipe(Se.flatMap(Fe=>Se.promise(()=>Fe.execute(Me,{sessionID:P.sessionID,abort:new AbortController().signal,agent:P.agent,messageID:we.id,extra:{bypassCwdCheck:!0},messages:[],metadata:n(async()=>{},"metadata"),ask:n(async()=>{},"ask")}))));return[{messageID:we.id,sessionID:P.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify(Me)}`},{messageID:we.id,sessionID:P.sessionID,type:"text",synthetic:!0,text:Ae.output},{...se,messageID:we.id,sessionID:P.sessionID}]}return yield*N.read(P.sessionID,Ne),[{messageID:we.id,sessionID:P.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: {"filePath":"${Ne}"}`},{id:se.id,messageID:we.id,sessionID:P.sessionID,type:"file",url:`data:${se.mime};base64,`+Buffer.from(yield*C.readFile(Ne).pipe(Se.catch(Se.die))).toString("base64"),mime:se.mime,filename:se.filename,source:se.source}]}}}if(se.type==="agent"){let Ne=lt.evaluate("task",se.name,J.permission).action==="deny"?" . Invoked by user; guaranteed to exist.":"";return[{...se,messageID:we.id,sessionID:P.sessionID},{messageID:we.id,sessionID:P.sessionID,type:"text",synthetic:!0,text:" Use the above message and context to generate a prompt and call the task tool with subagent: "+se.name+Ne}]}return[{...se,messageID:we.id,sessionID:P.sessionID}]}),de=yield*Se.forEach(P.parts,ee,{concurrency:"unbounded"}).pipe(Se.map(se=>se.flat().map($e)));yield*B.trigger("chat.message",{sessionID:P.sessionID,agent:P.agent,model:P.model,messageID:P.messageID,variant:P.variant},{message:we,parts:de});let ke=Qe.Info.safeParse(we);ke.success||e.error("invalid user message before save",{sessionID:P.sessionID,messageID:we.id,agent:we.agent,model:we.model,issues:ke.error.issues}),de.forEach((se,Pe)=>{let Ne=Qe.Part.safeParse(se);Ne.success||e.error("invalid user part before save",{sessionID:P.sessionID,messageID:we.id,partID:se.id,partType:se.type,index:Pe,issues:Ne.error.issues,part:se})}),yield*k.updateMessage(we);for(let se of de)yield*k.updatePart(se);return{info:we,parts:de}},Se.scoped),Le=Se.fn("SessionPrompt.inFlightTool")(function*(P){let Z=yield*Qe.filterCompactedEffect(P);for(let J=Z.length-1;J>=0;J--){let fe=Z[J];if(fe.info.role!=="assistant"||fe.info.aside)continue;let _e=fe.parts.find(te=>te.type==="tool"&&(te.state.status==="running"||te.state.status==="pending"));return _e&&_e.type==="tool"?_e.tool:null}return null}),ve=["A tool you called is still running and its result has not arrived. The user just wrote to you.","Answer them now, in a sentence or two, from what you already know. You cannot use tools until the run returns, so do not promise to look anything up.","Do not restate at length what you are doing; if their message changes the work, say what you will do once the run returns."].join(" "),Te=Se.fn("SessionPrompt.aside")(function*(P){let Z=yield*ge.context,J=yield*Qe.filterCompactedEffect(P.sessionID),fe=yield*Oe(P.user.model.providerID,P.user.model.modelID,P.sessionID),_e=yield*E.get(P.user.agent);if(!_e)return null;let te={id:pt.ascending(),parentID:P.user.id,role:"assistant",mode:_e.name,agent:_e.name,variant:P.user.variant,path:{cwd:Z.directory,root:Z.worktree},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelID:fe.id,providerID:fe.providerID,time:{created:Date.now()},sessionID:P.sessionID,aside:!0};yield*k.updateMessage(te);let we=yield*z.create({assistantMessage:te,sessionID:P.sessionID,model:fe}),[$e,ee,de]=yield*Se.all([Se.promise(()=>Xo.environment(fe)),re.system().pipe(Se.orDie),Se.promise(()=>Qe.toModelMessages(J,fe,{runningToolNote:`[${P.running} is still running. You are answering the user beside it; its result arrives when it finishes.]`}))]);e.info("aside",{sessionID:P.sessionID,running:P.running,messageID:te.id}),yield*we.process({user:P.user,agent:_e,permission:P.session.permission,sessionID:P.sessionID,parentSessionID:P.session.parentID,system:[...$e,...ee,ve],messages:de,tools:{},model:fe});let ke=yield*Ie(P.sessionID);if(ke.info.id!==te.id)return ke;let{drop:se,answered:Pe}=Ep(ke.parts);if(!Pe)return e.warn("aside wrote no usable answer; the message waits for the run",{sessionID:P.sessionID,messageID:te.id}),yield*k.removeMessage({sessionID:P.sessionID,messageID:te.id}),null;for(let Ne of se)yield*k.removePart({sessionID:P.sessionID,messageID:te.id,partID:Ne});return se.length>0?yield*Ie(P.sessionID):ke}),it=Se.fn("SessionPrompt.prompt")(function*(P){let Z=yield*k.get(P.sessionID);yield*Se.promise(()=>da.cleanup(Z));let J=yield*le(P);yield*k.touch(P.sessionID);let fe=[];for(let[$e,ee]of Object.entries(P.tools??{}))fe.push({permission:$e,action:ee?"allow":"deny",pattern:"*"});if(fe.length>0&&(Z.permission=fe,yield*k.setPermission({sessionID:Z.id,permission:fe})),P.noReply===!0)return J;if((yield*ge.get(ue)).runners.get(P.sessionID)?.busy===!0&&Ip(J.parts)){let ee=so.endForPerson(P.sessionID),de=ee?null:yield*Le(P.sessionID);if(H.set(J.info.id,{sessionID:P.sessionID,at:Date.now(),how:ee?"step ended":de?`in ${de}`:"between steps"}),de){let ke=yield*Te({sessionID:P.sessionID,session:Z,user:J.info,running:de}).pipe(Se.catchCause(se=>(e.warn("aside failed; the message waits for the run",{sessionID:P.sessionID,cause:String(se)}),Se.succeed(null))));if(ke)return ke}}let te=(yield*ge.get(ue)).runners.get(P.sessionID)?.busy===!0,we=yield*ye({sessionID:P.sessionID});return te&&Nt.compareAscending(we.info.id,J.info.id)<0&&(we=yield*ye({sessionID:P.sessionID})),we}),Ie=n(P=>Se.promise(async()=>{let Z;for await(let J of Qe.stream(P))if(Z??=J,J.info.role!=="user")return J;if(Z)return Z;throw new Error("Impossible")}),"lastAssistant"),be=Se.fn("SessionPrompt.run")(function*(P){let Z=yield*ge.context,J,fe=0,_e=yield*k.get(P);for(;;){if(Vr.isPaused()){Vr.hold(P);break}yield*O.set(P,{type:"busy"}),e.info("loop",{step:fe,sessionID:P});let te=yield*Qe.filterCompactedEffect(P),{lastUser:we,lastAssistant:$e,lastFinished:ee,tasks:de}=Sp(te);if(!we)throw new Error("No user message found in stream. This should never happen.");let se=te.findLast(Xe=>Xe.info.role==="assistant"&&Xe.info.id===$e?.id)?.parts.some(Xe=>Xe.type==="tool")??!1;if($e?.finish&&!["tool-calls"].includes($e.finish)&&!se&&Nt.compareAscending(we.id,$e.id)<0){e.info("exiting loop",{sessionID:P});break}fe++,fe===1&&(yield*Q({session:_e,modelID:we.model.modelID,providerID:we.model.providerID,history:te}).pipe(Se.ignore,Se.forkIn(Y)));let Pe=yield*Oe(we.model.providerID,we.model.modelID,P),Ne=de.pop();if(Ne?.type==="subtask"){yield*pe({task:Ne,model:Pe,lastUser:we,sessionID:P,session:_e,msgs:te});continue}if(Ne?.type==="compaction"){let Xe=yield*Se.gen(function*(){let xt=te.findLast(Pn=>Pn.info.role==="user"&&!Pn.parts.some(ao=>ao.type==="compaction"));if(!xt||xt.info.role!=="user")return;let _t=yield*E.get(xt.info.agent);if(!_t)return;let Ao=yield*ce({agent:_t,session:_e,model:Pe,tools:xt.info.tools,processor:{message:{id:we.id},partFromToolCall:n(()=>{},"partFromToolCall")},bypassAgentCheck:!1,messages:te}),[dt,Ot,sn]=yield*Se.all([Se.promise(()=>Xo.skills(_t)),Se.promise(()=>Xo.environment(Pe)),re.system().pipe(Se.orDie)]),dn=Object.fromEntries(Object.entries(Ao).map(([Pn,ao])=>[Pn,{...ao,execute:n(async()=>"Not run: this step only writes the summary.","execute")}]));return{agent:_t,user:xt.info,system:[...Ot,...dt?[dt]:[],...sn],tools:dn,permission:_e.permission,parentSessionID:_e.parentID}}).pipe(Se.catchCause(xt=>Se.sync(()=>{e.warn("compaction: the session's prefix could not be rebuilt; summarizing without it",{sessionID:P,cause:String(xt).slice(0,500)})})));if((yield*_.process({messages:te,parentID:we.id,sessionID:P,auto:Ne.auto,overflow:Ne.overflow,shared:Xe}))==="stop")break;continue}if(ee&&ee.summary!==!0&&(yield*_.isOverflow({tokens:ee.tokens,model:Pe}))){yield*_.create({sessionID:P,agent:we.agent,model:we.model,auto:!0});continue}let Me=yield*E.get(we.agent);if(!Me){let Xe=(yield*E.list()).filter(_t=>!_t.hidden).map(_t=>_t.name),wt=Xe.length?` Available agents: ${Xe.join(", ")}`:"",xt=new tt.Unknown({message:`Agent not found: "${we.agent}".${wt}`});throw yield*j.publish(yt.Event.Error,{sessionID:P,error:xt.toObject()}),xt}let Ae=Me.steps??1/0,Fe=fe>=Ae;te=yield*oe({messages:te,agent:Me,session:_e});let Re={id:pt.ascending(),parentID:we.id,role:"assistant",mode:Me.name,agent:Me.name,variant:we.variant,path:{cwd:Z.directory,root:Z.worktree},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelID:Pe.id,providerID:Pe.providerID,time:{created:Date.now()},sessionID:P};yield*k.updateMessage(Re);for(let[Xe,wt]of H)wt.sessionID===P&&(H.delete(Xe),e.warn("person message read",{sessionID:P,messageID:Xe,how:wt.how,waitedMs:Date.now()-wt.at}));let nt=Promise.withResolvers(),et=so.open(P,()=>nt.resolve()),Ue=yield*z.create({assistantMessage:Re,sessionID:P,model:Pe,preempt:Se.promise(()=>nt.promise)});if((yield*Se.onExit(Se.gen(function*(){let wt=te.findLast(Io=>Io.info.role==="user")?.parts.some(Io=>Io.type==="agent")??!1,xt=yield*ce({agent:Me,session:_e,model:Pe,tools:we.tools,processor:Ue,bypassAgentCheck:wt,messages:te,gate:et});if(we.format?.type==="json_schema"&&(xt.StructuredOutput=I({schema:we.format.schema,onSuccess(Io){J=Io}})),fe===1&&dr.summarize({sessionID:P,messageID:we.id}),fe>1&&ee){let Io=new Set(te.filter(ko=>ko.info.role==="assistant"&&ko.info.aside).map(ko=>ko.info.parentID));for(let ko of te)if(!(ko.info.role!=="user"||Nt.compareAscending(ko.info.id,ee.id)<=0)&&!Io.has(ko.info.id))for(let Kr of ko.parts)Kr.type!=="text"||Kr.ignored||Kr.synthetic||Kr.text.trim()&&(Kr.text=kp(Kr.text))}yield*B.trigger("experimental.chat.messages.transform",{},{messages:te});let[_t,Ao,dt,Ot]=yield*Se.all([Se.promise(()=>Xo.skills(Me)),Se.promise(()=>Xo.environment(Pe)),re.system().pipe(Se.orDie),Se.promise(()=>Qe.toModelMessages(te,Pe))]),sn=[...Ao,..._t?[_t]:[],...dt],dn=we.format??{type:"text"};dn.type==="json_schema"&&sn.push(dx);let Pn=yield*Ue.process({user:we,agent:Me,permission:_e.permission,sessionID:P,parentSessionID:_e.parentID,system:sn,messages:[...Ot,...Fe?[{role:"assistant",content:Ap}]:[]],tools:xt,model:Pe,toolChoice:dn.type==="json_schema"?"required":void 0});if(J!==void 0)return Ue.message.structured=J,Ue.message.finish=Ue.message.finish??"stop",yield*k.updateMessage(Ue.message),"break";if(Ue.message.finish&&!["tool-calls","unknown"].includes(Ue.message.finish)&&!Ue.message.error){if(Ue.message.finish==="content-filter")return Ue.message.error=new tt.Unknown({message:"The response was blocked by the provider's content filter"}).toObject(),yield*k.updateMessage(Ue.message),yield*j.publish(yt.Event.Error,{sessionID:P,error:Ue.message.error}),"break";if(dn.type==="json_schema")return Ue.message.error=new Qe.StructuredOutputError({message:"Model did not produce structured output",retries:0}).toObject(),yield*k.updateMessage(Ue.message),"break"}return Pn==="stop"?"break":(Pn==="compact"&&(yield*_.create({sessionID:P,agent:we.agent,model:we.model,auto:!0,overflow:!Ue.message.finish})),"continue")}),Se.fnUntraced(function*(Xe){so.close(P,et),yi.isFailure(Xe)&&Ps.hasInterruptsOnly(Xe.cause)&&(yield*Ue.abort()),yield*ge.withALS(()=>re.clear(Ue.message.id)).pipe(Se.flatMap(wt=>wt))})))==="break")break}return yield*_.prune({sessionID:P}).pipe(Se.ignore,Se.forkIn(Y)),yield*Ie(P)}),ye=Se.fn("SessionPrompt.loop")(function*(P){if(Vr.isPaused())return Vr.hold(P.sessionID),yield*Ie(P.sessionID);let Z=yield*ge.get(ue);return yield*R(Z.runners,P.sessionID).ensureRunning(be(P.sessionID))}),ae=Se.fn("SessionPrompt.shell")(function*(P){let Z=yield*ge.get(ue);return yield*R(Z.runners,P.sessionID).startShell(fe=>De(P,fe))}),me=Se.fn("SessionPrompt.command")(function*(P){e.info("command",P);let Z=yield*$.get(P.command);if(!Z){let Ue=(yield*$.list()).map(wt=>wt.name),ot=Ue.length?` Available commands: ${Ue.join(", ")}`:"",Xe=new tt.Unknown({message:`Command not found: "${P.command}".${ot}`});throw yield*j.publish(yt.Event.Error,{sessionID:P.sessionID,error:Xe.toObject()}),Xe}let J=Z.agent??P.agent??(yield*E.defaultAgent()),_e=(P.arguments.match(x)??[]).map(Ue=>Ue.replace(v,"")),te=yield*Se.promise(async()=>Z.template),we=te.match(h)??[],$e=0;for(let Ue of we){let ot=Number(Ue.slice(1));ot>$e&&($e=ot)}let ee=te.replaceAll(h,(Ue,ot)=>{let Xe=Number(ot),wt=Xe-1;return wt>=_e.length?"":Xe===$e?_e.slice(wt).join(" "):_e[wt]}),de=te.includes("$ARGUMENTS"),ke=ee.replaceAll("$ARGUMENTS",P.arguments);we.length===0&&!de&&P.arguments.trim()&&(ke=ke+`
|
|
1652
|
+
|
|
1653
|
+
`+P.arguments);let se=Un.shell(ke);if(se.length>0){let Ue=ja.preferred(),ot=yield*Se.promise(()=>Promise.all(se.map(async([,wt])=>(await St.text([wt],{shell:Ue,nothrow:!0})).text))),Xe=0;ke=ke.replace(r,()=>ot[Xe++])}ke=ke.trim();let Pe=yield*Se.gen(function*(){if(Z.model)return yn.parseModel(Z.model);if(Z.agent){let Ue=yield*E.get(Z.agent);if(Ue?.model)return Ue.model}return P.model?yn.parseModel(P.model):yield*xe(P.sessionID)});yield*Oe(Pe.providerID,Pe.modelID,P.sessionID);let Ne=yield*E.get(J);if(!Ne){let Ue=(yield*E.list()).filter(wt=>!wt.hidden).map(wt=>wt.name),ot=Ue.length?` Available agents: ${Ue.join(", ")}`:"",Xe=new tt.Unknown({message:`Agent not found: "${J}".${ot}`});throw yield*j.publish(yt.Event.Error,{sessionID:P.sessionID,error:Xe.toObject()}),Xe}let Me=yield*ne(ke),Ae=Ne.mode==="subagent"&&Z.subtask!==!1||Z.subtask===!0,Fe=Ae?[{type:"subtask",agent:Ne.name,description:Z.description??"",command:P.command,model:{providerID:Pe.providerID,modelID:Pe.modelID},prompt:Me.find(Ue=>Ue.type==="text")?.text??""}]:[...Me,...P.parts??[]],Re=Ae?P.agent??(yield*E.defaultAgent()):J,nt=Ae?P.model?yn.parseModel(P.model):yield*xe(P.sessionID):Pe;yield*B.trigger("command.execute.before",{command:P.command,sessionID:P.sessionID,arguments:P.arguments},{parts:Fe});let et=yield*it({sessionID:P.sessionID,messageID:P.messageID,model:nt,agent:Re,parts:Fe,variant:P.variant});return yield*j.publish(Wr.Event.Executed,{name:P.command,sessionID:P.sessionID,arguments:P.arguments,messageID:et.info.id}),et});return t.of({assertNotBusy:L,cancel:q,stopForPause:X,prompt:it,loop:ye,shell:ae,command:me,resolvePromptParts:ne})}));let i=xn.unwrap(Se.sync(()=>S.layer.pipe(xn.provide(Ur.layer),xn.provide(_a.defaultLayer),xn.provide($r.defaultLayer),xn.provide(Wr.defaultLayer),xn.provide(lt.defaultLayer),xn.provide(Br.defaultLayer),xn.provide(Pt.defaultLayer),xn.provide(Nn.defaultLayer),xn.provide(La.defaultLayer),xn.provide(po.layer),xn.provide(yn.defaultLayer),xn.provide(hr.defaultLayer),xn.provide(ut.defaultLayer),xn.provide(ln.defaultLayer),xn.provide(yt.defaultLayer),xn.provide(ro.defaultLayer),xn.provide(Ve.layer),xn.provide(uo)))),{runPromise:m}=Ke(t,i);async function y(j){return m(O=>O.assertNotBusy(He.zod.parse(j)))}S.assertNotBusy=y,n(y,"assertNotBusy"),S.PromptInput=Kt.object({sessionID:He.zod,messageID:pt.zod.optional(),model:Kt.object({providerID:Et.zod,modelID:Ut.zod}).optional(),agent:Kt.string().optional(),noReply:Kt.boolean().optional(),tools:Kt.record(Kt.string(),Kt.boolean()).optional().describe("@deprecated tools and permissions have been merged, you can set permissions on the session itself now"),format:Qe.Format.optional(),system:Kt.string().optional(),variant:Kt.string().optional(),parts:Kt.array(Kt.discriminatedUnion("type",[Qe.TextPart.omit({messageID:!0,sessionID:!0}).partial({id:!0}).meta({ref:"TextPartInput"}),Qe.FilePart.omit({messageID:!0,sessionID:!0}).partial({id:!0}).meta({ref:"FilePartInput"}),Qe.AgentPart.omit({messageID:!0,sessionID:!0}).partial({id:!0}).meta({ref:"AgentPartInput"}),Qe.SubtaskPart.omit({messageID:!0,sessionID:!0}).partial({id:!0}).meta({ref:"SubtaskPartInput"})]))});async function f(j){return m(O=>O.prompt(S.PromptInput.parse(j)))}S.prompt=f,n(f,"prompt");async function b(j){return m(O=>O.resolvePromptParts(Kt.string().parse(j)))}S.resolvePromptParts=b,n(b,"resolvePromptParts");async function d(j){return m(O=>O.cancel(He.zod.parse(j)))}S.cancel=d,n(d,"cancel");async function s(){return m(j=>j.stopForPause())}S.stopForPause=s,n(s,"stopForPause"),S.LoopInput=Kt.object({sessionID:He.zod});async function l(j){return m(O=>O.loop(S.LoopInput.parse(j)))}S.loop=l,n(l,"loop"),S.ShellInput=Kt.object({sessionID:He.zod,messageID:pt.zod.optional(),agent:Kt.string(),model:Kt.object({providerID:Et.zod,modelID:Ut.zod}).optional(),command:Kt.string()});async function u(j){return m(O=>O.shell(S.ShellInput.parse(j)))}S.shell=u,n(u,"shell"),S.CommandInput=Kt.object({messageID:pt.zod.optional(),sessionID:He.zod,agent:Kt.string().optional(),model:Kt.string().optional(),arguments:Kt.string(),command:Kt.string(),variant:Kt.string().optional(),parts:Kt.array(Kt.discriminatedUnion("type",[Qe.FilePart.omit({messageID:!0,sessionID:!0}).partial({id:!0})])).optional()});async function w(j){return m(O=>O.command(S.CommandInput.parse(j)))}S.command=w,n(w,"command");function I(j){let{$schema:O,...k}=j.schema;return Wp({id:"StructuredOutput",description:lx,inputSchema:bl(k),async execute(E){return j.onSuccess(E),{output:"Structured output captured successfully.",title:"Structured Output",metadata:{valid:!0}}},toModelOutput({output:E}){return{type:"text",value:E.output}}})}S.createStructuredOutputTool=I,n(I,"createStructuredOutputTool");let r=/!`([^`]+)`/g,x=/(?:\[Image\s+\d+\]|"[^"]*"|'[^']*'|[^\s"']+)/gi,h=/\$(\d+)/g,v=/^["']|["']$/g})(No||={});import{Schema as Gp}from"effect";import ux from"zod";var px=Gp.String.pipe(Gp.brand("WorkspaceID")),wl=px.pipe(An(e=>({make:n(t=>e.makeUnsafe(t),"make"),ascending:n(t=>e.makeUnsafe(Nt.ascending("workspace",t)),"ascending"),zod:Nt.schema("workspace").pipe(ux.custom())})));import{Effect as bt,Layer as vl,Scope as fx,ServiceMap as mx}from"effect";var yt;(R=>{let e=qe.create({service:"session"}),t="New session - ",o="Child session - ";function i(L=!1){return(L?o:t)+new Date().toISOString()}n(i,"createDefaultTitle");function m(L){return new RegExp(`^(${t}|${o})\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$`).test(L)}R.isDefaultTitle=m,n(m,"isDefaultTitle");function y(L){let q=L.summary_additions!==null||L.summary_deletions!==null||L.summary_files!==null?{additions:L.summary_additions??0,deletions:L.summary_deletions??0,files:L.summary_files??0,diffs:L.summary_diffs??void 0}:void 0,X=L.share_url?{url:L.share_url}:void 0,ne=L.revert??void 0;return{id:L.id,slug:L.slug,projectID:L.project_id,workspaceID:L.workspace_id??void 0,directory:L.directory,parentID:L.parent_id??void 0,title:L.title,version:L.version,summary:q,share:X,revert:ne,metadata:L.metadata??void 0,permission:L.permission??void 0,time:{created:L.time_created,updated:L.time_updated,compacting:L.time_compacting??void 0,archived:L.time_archived??void 0}}}R.fromRow=y,n(y,"fromRow");function p(L){return{id:L.id,project_id:L.projectID,workspace_id:L.workspaceID,parent_id:L.parentID,slug:L.slug,directory:L.directory,title:L.title,version:L.version,share_url:L.share?.url,summary_additions:L.summary?.additions,summary_deletions:L.summary?.deletions,summary_files:L.summary?.files,summary_diffs:L.summary?.diffs,revert:L.revert??null,metadata:L.metadata??null,permission:L.permission,time_created:L.time.created,time_updated:L.time.updated,time_compacting:L.time.compacting,time_archived:L.time.archived}}R.toRow=p,n(p,"toRow");function f(L){let q=L.match(/^(.+) \(fork #(\d+)\)$/);if(q){let X=q[1],ne=parseInt(q[2],10);return`${X} (fork #${ne+1})`}return`${L} (fork #1)`}n(f,"getForkedTitle"),R.Info=at.object({id:He.zod,slug:at.string(),projectID:Ns.zod,workspaceID:wl.zod.optional(),directory:at.string(),parentID:He.zod.optional(),summary:at.object({additions:at.number(),deletions:at.number(),files:at.number(),diffs:$n.FileDiff.array().optional()}).optional(),share:at.object({url:at.string()}).optional(),title:at.string(),version:at.string(),time:at.object({created:at.number(),updated:at.number(),compacting:at.number().optional(),archived:at.number().optional()}),metadata:at.record(at.string(),at.unknown()).optional(),permission:lt.Ruleset.optional(),revert:at.object({messageID:pt.zod,partID:It.zod.optional(),snapshot:at.string().optional(),diff:at.string().optional()}).optional()}).meta({ref:"Session"}),R.ProjectInfo=at.object({id:Ns.zod,name:at.string().optional(),worktree:at.string()}).meta({ref:"ProjectSummary"}),R.GlobalInfo=R.Info.extend({project:R.ProjectInfo.nullable()}).meta({ref:"GlobalSession"}),R.Event={Created:on.define({type:"session.created",version:1,aggregate:"sessionID",schema:at.object({sessionID:He.zod,info:R.Info})}),Updated:on.define({type:"session.updated",version:1,aggregate:"sessionID",schema:at.object({sessionID:He.zod,info:sa(R.Info).extend({share:sa(R.Info.shape.share.unwrap()).optional(),time:sa(R.Info.shape.time).optional()})}),busSchema:at.object({sessionID:He.zod,info:R.Info})}),Deleted:on.define({type:"session.deleted",version:1,aggregate:"sessionID",schema:at.object({sessionID:He.zod,info:R.Info})}),Diff:mt.define("session.diff",at.object({sessionID:He.zod,diff:$n.FileDiff.array()})),Error:mt.define("session.error",at.object({sessionID:He.zod.optional(),error:Qe.Assistant.shape.error}))};function l(L){let q=he.project.vcs?xl.join(he.worktree,".opencode","plans"):xl.join(je.Path.data,"plans");return xl.join(q,[L.time.created,L.slug].join("-")+".md")}R.plan=l,n(l,"plan"),R.getUsage=n(L=>{let q=n(ie=>Number.isFinite(ie)?ie:0,"safe"),X=q(L.usage.inputTokens??0),ne=q(L.usage.outputTokens??0),Q=q(L.usage.reasoningTokens??0),oe=q(L.usage.cachedInputTokens??0),ce=q(L.metadata?.anthropic?.cacheCreationInputTokens??L.metadata?.vertex?.cacheCreationInputTokens??L.metadata?.bedrock?.usage?.cacheWriteInputTokens??L.metadata?.venice?.usage?.cacheCreationInputTokens??0),pe=q(X-oe-ce),Oe={total:L.usage.totalTokens,input:pe,output:ne-Q,reasoning:Q,cache:{write:ce,read:oe}},xe=L.model.cost?.experimentalOver200K&&Oe.input+Oe.cache.read>2e5?L.model.cost.experimentalOver200K:L.model.cost;return{cost:q(new _s(0).add(new _s(Oe.input).mul(xe?.input??0).div(1e6)).add(new _s(Oe.output).mul(xe?.output??0).div(1e6)).add(new _s(Oe.cache.read).mul(xe?.cache?.read??0).div(1e6)).add(new _s(Oe.cache.write).mul(xe?.cache?.write??0).div(1e6)).add(new _s(Oe.reasoning).mul(xe?.output??0).div(1e6)).toNumber()),tokens:Oe}},"getUsage");class u extends Error{constructor(X){super(`Session ${X} is busy`);this.sessionID=X}sessionID;static{n(this,"BusyError")}}R.BusyError=u;class a extends mx.Service()("@opencode/Session"){static{n(this,"Service")}}R.Service=a;let w=n(L=>bt.sync(()=>Xt.use(L)),"db");R.layer=vl.effect(a,bt.gen(function*(){let L=yield*Ve.Service,q=yield*rt.Service,X=yield*fx.Scope,ne=bt.fn("Session.createNext")(function*(te){let we=yield*ge.context,$e={id:He.descending(te.id),slug:Ya.create(),version:Ft.VERSION,projectID:we.project.id,directory:te.directory,workspaceID:te.workspaceID,parentID:te.parentID,title:te.title??i(!!te.parentID),metadata:te.metadata,permission:te.permission,time:{created:Date.now(),updated:Date.now()}};e.info("created",$e),yield*bt.sync(()=>on.run(R.Event.Created,{sessionID:$e.id,info:$e}));let ee=yield*q.get();return!$e.parentID&&(Ce.OPENCODE_AUTO_SHARE||ee.share==="auto")&&(yield*oe($e.id).pipe(bt.ignore,bt.forkIn(X))),Ce.OPENCODE_EXPERIMENTAL_WORKSPACES||(yield*L.publish(R.Event.Updated,{sessionID:$e.id,info:$e})),$e}),Q=bt.fn("Session.get")(function*(te){let we=yield*w($e=>$e.select().from(zt).where((0,We.eq)(zt.id,te)).get());if(!we)throw new kr({message:`Session not found: ${te}`});return y(we)}),oe=bt.fn("Session.share")(function*(te){if((yield*q.get()).share==="disabled")throw new Error("Sharing is disabled in configuration");let $e=yield*bt.promise(async()=>{let{ShareNext:ee}=await import("./share-next-MPGA7EO4.js");return ee.create(te)});return yield*bt.sync(()=>on.run(R.Event.Updated,{sessionID:te,info:{share:{url:$e.url}}})),$e}),ce=bt.fn("Session.unshare")(function*(te){yield*bt.promise(async()=>{let{ShareNext:we}=await import("./share-next-MPGA7EO4.js");await we.remove(te)}),yield*bt.sync(()=>on.run(R.Event.Updated,{sessionID:te,info:{share:{url:null}}}))}),pe=bt.fn("Session.children")(function*(te){let we=yield*ge.context;return(yield*w(ee=>ee.select().from(zt).where((0,We.and)((0,We.eq)(zt.project_id,we.project.id),(0,We.eq)(zt.parent_id,te))).all())).map(y)}),De=bt.fnUntraced(function*(te){try{let we=yield*Q(te),$e=yield*pe(te);for(let ee of $e)yield*De(ee.id);yield*ce(te).pipe(bt.ignore),yield*bt.sync(()=>{on.run(R.Event.Deleted,{sessionID:te,info:we}),on.remove(te)})}catch(we){e.error(we)}}),Oe=n(te=>bt.gen(function*(){return yield*bt.sync(()=>on.run(Qe.Event.Updated,{sessionID:te.sessionID,info:te})),te}).pipe(bt.withSpan("Session.updateMessage")),"updateMessage"),xe=n(te=>bt.gen(function*(){return yield*bt.sync(()=>on.run(Qe.Event.PartUpdated,{sessionID:te.sessionID,part:structuredClone(te),time:Date.now()})),te}).pipe(bt.withSpan("Session.updatePart")),"updatePart"),ie=bt.fn("Session.create")(function*(te){let we=yield*ge.directory;return yield*ne({parentID:te?.parentID,directory:we,title:te?.title,permission:te?.permission,workspaceID:te?.workspaceID,metadata:te?.metadata})}),le=bt.fn("Session.fork")(function*(te){let we=yield*ge.directory,$e=yield*Q(te.sessionID),ee=f($e.title),de=yield*ne({directory:we,workspaceID:$e.workspaceID,title:ee}),ke=yield*P({sessionID:te.sessionID}),se=new Map;for(let Pe of ke){if(te.messageID&&Nt.compareAscending(Pe.info.id,te.messageID)>=0)break;let Ne=pt.ascending();se.set(Pe.info.id,Ne);let Me=Pe.info.role==="assistant"&&Pe.info.parentID?se.get(Pe.info.parentID):void 0,Ae=yield*Oe({...Pe.info,sessionID:de.id,id:Ne,...Me&&{parentID:Me}});for(let Fe of Pe.parts)yield*xe({...Fe,id:It.ascending(),messageID:Ae.id,sessionID:de.id})}return de}),Le=n((te,we)=>bt.sync(()=>on.run(R.Event.Updated,{sessionID:te,info:we})),"patch"),ve=bt.fn("Session.touch")(function*(te){yield*Le(te,{time:{updated:Date.now()}})}),Te=bt.fn("Session.setTitle")(function*(te){yield*Le(te.sessionID,{title:te.title})}),it=bt.fn("Session.setArchived")(function*(te){yield*Le(te.sessionID,{time:{archived:te.time}})}),Ie=bt.fn("Session.setPermission")(function*(te){yield*Le(te.sessionID,{permission:te.permission,time:{updated:Date.now()}})}),be=bt.fn("Session.setRevert")(function*(te){yield*Le(te.sessionID,{summary:te.summary,time:{updated:Date.now()},revert:te.revert})}),ye=bt.fn("Session.clearRevert")(function*(te){yield*Le(te,{time:{updated:Date.now()},revert:null})}),ae=bt.fn("Session.setSummary")(function*(te){yield*Le(te.sessionID,{time:{updated:Date.now()},summary:te.summary})}),me=bt.fn("Session.diff")(function*(te){return yield*bt.tryPromise(()=>Ho.read(["session_diff",te])).pipe(bt.orElseSucceed(()=>[]))}),P=bt.fn("Session.messages")(function*(te){return te.limit?Qe.page({sessionID:te.sessionID,limit:te.limit}).items:Array.from(Qe.stream(te.sessionID)).reverse()}),Z=bt.fn("Session.removeMessage")(function*(te){return yield*bt.sync(()=>on.run(Qe.Event.Removed,{sessionID:te.sessionID,messageID:te.messageID})),te.messageID}),J=bt.fn("Session.removePart")(function*(te){return yield*bt.sync(()=>on.run(Qe.Event.PartRemoved,{sessionID:te.sessionID,messageID:te.messageID,partID:te.partID})),te.partID}),fe=bt.fn("Session.updatePartDelta")(function*(te){yield*L.publish(Qe.Event.PartDelta,te)}),_e=bt.fn("Session.initialize")(function*(te){yield*bt.promise(()=>No.command({sessionID:te.sessionID,messageID:te.messageID,model:te.providerID+"/"+te.modelID,command:Wr.Default.INIT,arguments:""}))});return a.of({create:ie,fork:le,touch:ve,get:Q,share:oe,unshare:ce,setTitle:Te,setArchived:it,setPermission:Ie,setRevert:be,clearRevert:ye,setSummary:ae,diff:me,messages:P,children:pe,remove:De,updateMessage:Oe,removeMessage:Z,removePart:J,updatePart:xe,updatePartDelta:fe,initialize:_e})})),R.defaultLayer=R.layer.pipe(vl.provide(Ve.layer),vl.provide(rt.defaultLayer));let{runPromise:x}=Ke(a,R.defaultLayer);R.create=nn(at.object({parentID:He.zod.optional(),title:at.string().optional(),permission:R.Info.shape.permission,workspaceID:wl.zod.optional(),metadata:at.record(at.string(),at.unknown()).optional()}).optional(),L=>x(q=>q.create(L))),R.fork=nn(at.object({sessionID:He.zod,messageID:pt.zod.optional()}),L=>x(q=>q.fork(L))),R.touch=nn(He.zod,L=>x(q=>q.touch(L))),R.get=nn(He.zod,L=>x(q=>q.get(L))),R.share=nn(He.zod,L=>x(q=>q.share(L))),R.unshare=nn(He.zod,L=>x(q=>q.unshare(L))),R.setTitle=nn(at.object({sessionID:He.zod,title:at.string()}),L=>x(q=>q.setTitle(L))),R.setArchived=nn(at.object({sessionID:He.zod,time:at.number().optional()}),L=>x(q=>q.setArchived(L))),R.setPermission=nn(at.object({sessionID:He.zod,permission:lt.Ruleset}),L=>x(q=>q.setPermission(L))),R.setRevert=nn(at.object({sessionID:He.zod,revert:R.Info.shape.revert,summary:R.Info.shape.summary}),L=>x(q=>q.setRevert({sessionID:L.sessionID,revert:L.revert,summary:L.summary}))),R.clearRevert=nn(He.zod,L=>x(q=>q.clearRevert(L))),R.setSummary=nn(at.object({sessionID:He.zod,summary:R.Info.shape.summary}),L=>x(q=>q.setSummary({sessionID:L.sessionID,summary:L.summary}))),R.diff=nn(He.zod,L=>x(q=>q.diff(L))),R.messages=nn(at.object({sessionID:He.zod,limit:at.number().optional()}),L=>x(q=>q.messages(L)));function*T(L){let q=he.project,X=[(0,We.eq)(zt.project_id,q.id)];L?.workspaceID&&X.push((0,We.eq)(zt.workspace_id,L.workspaceID)),L?.directory&&X.push((0,We.eq)(zt.directory,L.directory)),L?.roots&&X.push((0,We.isNull)(zt.parent_id)),L?.start&&X.push((0,We.gte)(zt.time_updated,L.start)),L?.search&&X.push((0,We.like)(zt.title,`%${L.search}%`));let ne=L?.limit??100,Q=Xt.use(oe=>oe.select().from(zt).where((0,We.and)(...X)).orderBy((0,We.desc)(zt.time_updated)).limit(ne).all());for(let oe of Q)yield y(oe)}R.list=T,n(T,"list");function*G(L){let q=[];L?.directory&&q.push((0,We.eq)(zt.directory,L.directory)),L?.roots&&q.push((0,We.isNull)(zt.parent_id)),L?.start&&q.push((0,We.gte)(zt.time_updated,L.start)),L?.cursor&&q.push((0,We.lt)(zt.time_updated,L.cursor)),L?.search&&q.push((0,We.like)(zt.title,`%${L.search}%`)),L?.archived||q.push((0,We.isNull)(zt.time_archived));let X=L?.limit??100,ne=Xt.use(ce=>(q.length>0?ce.select().from(zt).where((0,We.and)(...q)):ce.select().from(zt)).orderBy((0,We.desc)(zt.time_updated),(0,We.desc)(zt.id)).limit(X).all()),Q=[...new Set(ne.map(ce=>ce.project_id))],oe=new Map;if(Q.length>0){let ce=Xt.use(pe=>pe.select({id:Xr.id,name:Xr.name,worktree:Xr.worktree}).from(Xr).where((0,We.inArray)(Xr.id,Q)).all());for(let pe of ce)oe.set(pe.id,{id:pe.id,name:pe.name??void 0,worktree:pe.worktree})}for(let ce of ne){let pe=oe.get(ce.project_id)??null;yield{...y(ce),project:pe}}}R.listGlobal=G,n(G,"listGlobal"),R.children=nn(He.zod,L=>x(q=>q.children(L))),R.remove=nn(He.zod,L=>x(q=>q.remove(L)));async function F(L){return Qe.Info.parse(L),x(q=>q.updateMessage(L))}R.updateMessage=F,n(F,"updateMessage"),R.removeMessage=nn(at.object({sessionID:He.zod,messageID:pt.zod}),L=>x(q=>q.removeMessage(L))),R.removePart=nn(at.object({sessionID:He.zod,messageID:pt.zod,partID:It.zod}),L=>x(q=>q.removePart(L)));async function re(L){return Qe.Part.parse(L),x(q=>q.updatePart(L))}R.updatePart=re,n(re,"updatePart"),R.updatePartDelta=nn(at.object({sessionID:He.zod,messageID:pt.zod,partID:It.zod,field:at.string(),delta:at.string()}),L=>x(q=>q.updatePartDelta(L))),R.initialize=nn(at.object({sessionID:He.zod,modelID:Ut.zod,providerID:Et.zod,messageID:pt.zod}),L=>x(q=>q.initialize(L)))})(yt||={});var Vp=`Use this tool when you have completed the planning phase and are ready to exit plan agent.
|
|
1654
|
+
|
|
1655
|
+
This tool will ask the user if they want to switch to build agent to start implementing the plan.
|
|
1656
|
+
|
|
1657
|
+
Call this tool:
|
|
1658
|
+
- After you have written a complete plan to the plan file
|
|
1659
|
+
- After you have clarified any questions with the user
|
|
1660
|
+
- When you are confident the plan is ready for implementation
|
|
1661
|
+
|
|
1662
|
+
Do NOT call this tool:
|
|
1663
|
+
- Before you have created or finalized the plan
|
|
1664
|
+
- If you still have unanswered questions about the implementation
|
|
1665
|
+
- If the user has indicated they want to continue planning
|
|
1666
|
+
`;async function yx(e){for await(let t of Qe.stream(e))if(t.info.role==="user"&&t.info.model)return t.info.model;return yn.defaultModel()}n(yx,"getLastModel");var Jp=Dt.define("plan_exit",{description:Vp,parameters:gx.object({}),async execute(e,t){let o=await yt.get(t.sessionID),i=hx.relative(he.worktree,yt.plan(o));if((await Eo.ask({sessionID:t.sessionID,questions:[{question:`Plan at ${i} is complete. Would you like to switch to the build agent and start implementing?`,header:"Build Agent",custom:!1,options:[{label:"Yes",description:"Switch to build agent and start implementing the plan"},{label:"No",description:"Stay with plan agent to continue refining the plan"}]}],tool:t.callID?{messageID:t.messageID,callID:t.callID}:void 0}))[0]?.[0]==="No")throw new Eo.RejectedError;let p=await yx(t.sessionID),f={id:pt.ascending(),sessionID:t.sessionID,role:"user",time:{created:Date.now()},agent:"build",model:p};return await yt.updateMessage(f),await yt.updatePart({id:It.ascending(),messageID:f.id,sessionID:t.sessionID,type:"text",text:`The plan at ${i} has been approved, you can now edit files. Execute the plan`,synthetic:!0}),{title:"Switching to build agent",output:"User approved switching to build agent. Wait for further instructions.",metadata:{}}}});import Kp from"zod";import{Effect as Xp}from"effect";var Yp=`Use this tool when you need to ask the user questions during execution. This allows you to:
|
|
1667
|
+
1. Gather user preferences or requirements
|
|
1668
|
+
2. Clarify ambiguous instructions
|
|
1669
|
+
3. Get decisions on implementation choices as you work
|
|
1670
|
+
4. Offer choices to the user about what direction to take.
|
|
1671
|
+
|
|
1672
|
+
Usage notes:
|
|
1673
|
+
- When \`custom\` is enabled (default), a "Type your own answer" option is added automatically; don't include "Other" or catch-all options
|
|
1674
|
+
- Answers are returned as arrays of labels; set \`multiple: true\` to allow selecting more than one
|
|
1675
|
+
- If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label
|
|
1676
|
+
`;var bx=Kp.object({questions:Kp.array(Eo.Info.omit({custom:!0})).describe("Questions to ask")}),Zp=Dt.defineEffect("question",Xp.gen(function*(){let e=yield*Eo.Service;return{description:Yp,parameters:bx,async execute(t,o){let i=await e.ask({sessionID:o.sessionID,questions:t.questions,tool:o.callID?{messageID:o.messageID,callID:o.callID}:void 0}).pipe(Xp.runPromise),m=t.questions.map((y,p)=>`"${y.question}"="${i[p]?.length?i[p].join(", "):"Unanswered"}"`).join(", ");return{title:`Asked ${t.questions.length} question${t.questions.length>1?"s":""}`,output:`User has answered your questions: ${m}. You can now continue with the user's answers in mind.`,metadata:{answers:i}}}}}));import wi from"zod";import*as vr from"path";import{createTwoFilesPatch as _l,diffLines as av}from"diff";var Qp='Performs exact string replacements in files. \n\nUsage:\n- You must use your `Read` tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file. \n- When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: line number + colon + space (e.g., `1: `). Everything after that space is the actual file content to match. Never include any part of the line number prefix in the oldString or newString.\n- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.\n- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.\n- The edit will FAIL if `oldString` is not found in the file with an error "oldString not found in content".\n- The edit will FAIL if `oldString` is found multiple times in the file with an error "Found multiple matches for oldString. Provide more surrounding lines in oldString to identify the correct match." Either provide a larger string with more surrounding context to make it unique or use `replaceAll` to change every instance of `oldString`. \n- Use `replaceAll` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.\n';import{Effect as Ct,Layer as nf,ServiceMap as Ix}from"effect";import{formatPatch as kx,structuredPatch as Ex}from"diff";import Sx from"fuzzysort";import Dx from"ignore";import Gn from"path";import Rt from"zod";import Il from"path";import wx from"os";var kl=wx.homedir(),ef=["Music","Pictures","Movies","Downloads","Desktop","Documents","Public","Applications","Library"],xx=["Application Support/AddressBook","Calendars","Mail","Messages","Safari","Cookies","Application Support/com.apple.TCC","PersonalizationPortrait","Metadata/CoreSpotlight","Suggestions"],vx=["/.DocumentRevisions-V100","/.Spotlight-V100","/.Trashes","/.fseventsd"],tf=["AppData","Downloads","Desktop","Documents","Pictures","Music","Videos","OneDrive"],bi;(o=>{function e(){return process.platform==="darwin"?new Set(ef):process.platform==="win32"?new Set(tf):new Set}o.names=e,n(e,"names");function t(){return process.platform==="darwin"?[...ef.map(i=>Il.join(kl,i)),...xx.map(i=>Il.join(kl,"Library",i)),...vx]:process.platform==="win32"?tf.map(i=>Il.join(kl,i)):[]}o.paths=t,n(t,"paths")})(bi||={});var br;(B=>{B.Info=Rt.object({path:Rt.string(),added:Rt.number().int(),removed:Rt.number().int(),status:Rt.enum(["added","deleted","modified"])}).meta({ref:"File"}),B.Node=Rt.object({name:Rt.string(),path:Rt.string(),absolute:Rt.string(),type:Rt.enum(["file","directory"]),ignored:Rt.boolean()}).meta({ref:"FileNode"}),B.Content=Rt.object({type:Rt.enum(["text","binary"]),content:Rt.string(),diff:Rt.string().optional(),patch:Rt.object({oldFileName:Rt.string(),newFileName:Rt.string(),oldHeader:Rt.string().optional(),newHeader:Rt.string().optional(),hunks:Rt.array(Rt.object({oldStart:Rt.number(),oldLines:Rt.number(),newStart:Rt.number(),newLines:Rt.number(),lines:Rt.array(Rt.string())})),index:Rt.string().optional()}).optional(),encoding:Rt.literal("base64").optional(),mimeType:Rt.string().optional()}).meta({ref:"FileContent"}),B.Event={Edited:mt.define("file.edited",Rt.object({file:Rt.string()}))};let m=qe.create({service:"file"}),y=new Set(["exe","dll","pdb","bin","so","dylib","o","a","lib","wav","mp3","ogg","oga","ogv","ogx","flac","aac","wma","m4a","weba","mp4","avi","mov","wmv","flv","webm","mkv","zip","tar","gz","gzip","bz","bz2","bzip","bzip2","7z","rar","xz","lz","z","pdf","doc","docx","ppt","pptx","xls","xlsx","dmg","iso","img","vmdk","ttf","otf","woff","woff2","eot","sqlite","db","mdb","apk","ipa","aab","xapk","app","pkg","deb","rpm","snap","flatpak","appimage","msi","msp","jar","war","ear","class","kotlin_module","dex","vdex","odex","oat","art","wasm","wat","bc","ll","s","ko","sys","drv","efi","rom","com"]),p=new Set(["png","jpg","jpeg","gif","bmp","webp","ico","tif","tiff","svg","svgz","avif","apng","jxl","heic","heif","raw","cr2","nef","arw","dng","orf","raf","pef","x3f"]),f=new Set(["ts","tsx","mts","cts","mtsx","ctsx","js","jsx","mjs","cjs","sh","bash","zsh","fish","ps1","psm1","cmd","bat","json","jsonc","json5","yaml","yml","toml","md","mdx","txt","xml","html","htm","css","scss","sass","less","graphql","gql","sql","ini","cfg","conf","env"]),b=new Set(["dockerfile","makefile",".gitignore",".gitattributes",".editorconfig",".npmrc",".nvmrc",".prettierrc",".eslintrc"]),d={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",webp:"image/webp",ico:"image/x-icon",tif:"image/tiff",tiff:"image/tiff",svg:"image/svg+xml",svgz:"image/svg+xml",avif:"image/avif",apng:"image/apng",jxl:"image/jxl",heic:"image/heic",heif:"image/heif"},s=n($=>Gn.extname($).toLowerCase().slice(1),"ext"),c=n($=>Gn.basename($).toLowerCase(),"name"),l=n($=>p.has(s($)),"isImageByExtension"),g=n($=>f.has(s($)),"isTextByExtension"),u=n($=>b.has(c($)),"isTextByName"),a=n($=>y.has(s($)),"isBinaryByExtension"),w=n($=>$.startsWith("image/"),"isImage"),I=n($=>d[s($)]||"image/"+s($),"getImageMimeType");function r($){let M=$.toLowerCase();if(m.debug("shouldEncode",{type:M}),!M||M.startsWith("text/")||M.includes("charset="))return!1;let C=M.split("/",2)[0];return["image","audio","video","font","model","multipart"].includes(C)}n(r,"shouldEncode");let x=n($=>$.replaceAll("\\","/").replace(/\/+$/,"").split("/").some(C=>C.startsWith(".")&&C.length>1),"hidden"),h=n(($,M)=>{if(M)return $;let C=[],T=[];for(let G of $)x(G)?T.push(G):C.push(G);return[...C,...T]},"sortHiddenLast");class v extends Ix.Service()("@opencode/File"){static{n(this,"Service")}}B.Service=v,B.layer=nf.effect(v,Ct.gen(function*(){let $=yield*ut.Service,M=yield*ge.make(Ct.fn("File.state")(()=>Ct.succeed({cache:{files:[],dirs:[]}}))),C=Ct.fn("File.scan")(function*(){if(he.directory===Gn.parse(he.directory).root)return;let re=he.directory===je.Path.home&&he.project.id==="global",ue={files:[],dirs:[]};if(re){let R=new Set,L=bi.names(),q=new Set(["node_modules","dist","build","target","vendor"]),X=n(oe=>oe.startsWith(".")||L.has(oe),"shouldIgnoreName"),ne=n(oe=>oe.startsWith(".")||q.has(oe),"shouldIgnoreNested"),Q=yield*$.readDirectoryEntries(he.directory).pipe(Ct.orElseSucceed(()=>[]));for(let oe of Q){if(oe.type!=="directory"||X(oe.name))continue;R.add(oe.name+"/");let ce=Gn.join(he.directory,oe.name),pe=yield*$.readDirectoryEntries(ce).pipe(Ct.orElseSucceed(()=>[]));for(let De of pe)De.type==="directory"&&(ne(De.name)||R.add(oe.name+"/"+De.name+"/"))}ue.dirs=Array.from(R).toSorted()}else{let R=yield*Ct.promise(()=>Array.fromAsync(Ko.files({cwd:he.directory}))),L=new Set;for(let q of R){ue.files.push(q);let X=q;for(;;){let ne=Gn.dirname(X);if(ne==="."||ne===X)break;X=ne,!L.has(ne)&&(L.add(ne),ue.dirs.push(ne+"/"))}}}let H=yield*ge.get(M);H.cache=ue}),T=yield*Ct.cached(C().pipe(Ct.catchCause(()=>Ct.void))),G=Ct.fn("File.ensure")(function*(){yield*T,T=yield*Ct.cached(C().pipe(Ct.catchCause(()=>Ct.void)))}),N=Ct.fn("File.init")(function*(){yield*G()}),A=Ct.fn("File.status")(function*(){return he.project.vcs!=="git"?[]:yield*Ct.promise(async()=>{let re=(await mo.run(["-c","core.fsmonitor=false","-c","core.quotepath=false","diff","--numstat","HEAD"],{cwd:he.directory})).text(),ue=[];if(re.trim())for(let L of re.trim().split(`
|
|
1677
|
+
`)){let[q,X,ne]=L.split(" ");ue.push({path:ne,added:q==="-"?0:parseInt(q,10),removed:X==="-"?0:parseInt(X,10),status:"modified"})}let H=(await mo.run(["-c","core.fsmonitor=false","-c","core.quotepath=false","ls-files","--others","--exclude-standard"],{cwd:he.directory})).text();if(H.trim())for(let L of H.trim().split(`
|
|
1678
|
+
`))try{let q=await Ee.readText(Gn.join(he.directory,L));ue.push({path:L,added:q.split(`
|
|
1679
|
+
`).length,removed:0,status:"added"})}catch{continue}let R=(await mo.run(["-c","core.fsmonitor=false","-c","core.quotepath=false","diff","--name-only","--diff-filter=D","HEAD"],{cwd:he.directory})).text();if(R.trim())for(let L of R.trim().split(`
|
|
1680
|
+
`))ue.push({path:L,added:0,removed:0,status:"deleted"});return ue.map(L=>{let q=Gn.isAbsolute(L.path)?L.path:Gn.join(he.directory,L.path);return{...L,path:Gn.relative(he.directory,q)}})})}),F=Ct.fn("File.read")(function*(re){var Q=[];try{let ue=kn(Q,m.time("read",{file:re}));let H=Gn.join(he.directory,re);if(!he.containsPath(H))throw new Error("Access denied: path escapes project directory");if(l(re)){if(yield*$.existsSafe(H)){let Oe=yield*$.readFile(H).pipe(Ct.catch(()=>Ct.succeed(new Uint8Array)));return{type:"text",content:Buffer.from(Oe).toString("base64"),mimeType:I(re),encoding:"base64"}}return{type:"text",content:""}}let R=g(re)||u(re);if(a(re)&&!R)return{type:"binary",content:""};let L=yield*$.existsSafe(H);if(!L)return{type:"text",content:""};let q=ut.mimeType(H);let X=R?!1:r(q);if(X&&!w(q))return{type:"binary",content:"",mimeType:q};if(X){let De=yield*$.readFile(H).pipe(Ct.catch(()=>Ct.succeed(new Uint8Array)));return{type:"text",content:Buffer.from(De).toString("base64"),mimeType:q,encoding:"base64"}}let ne=yield*$.readFileString(H).pipe(Ct.map(De=>De.trim()),Ct.catch(()=>Ct.succeed("")));if(he.project.vcs==="git")return yield*Ct.promise(async()=>{let De=(await mo.run(["-c","core.fsmonitor=false","diff","--",re],{cwd:he.directory})).text();if(De.trim()||(De=(await mo.run(["-c","core.fsmonitor=false","diff","--staged","--",re],{cwd:he.directory})).text()),De.trim()){let Oe=(await mo.run(["show",`HEAD:${re}`],{cwd:he.directory})).text(),xe=Ex(re,re,Oe,ne,"old","new",{context:1/0,ignoreWhitespace:!0});return{type:"text",content:ne,patch:xe,diff:kx(xe)}}return{type:"text",content:ne}});return{type:"text",content:ne}}catch(oe){var ce=oe,pe=!0}finally{En(Q,ce,pe)}}),V=Ct.fn("File.list")(function*(re){let ue=[".git",".DS_Store"],H=n(X=>!1,"ignored");if(he.project.vcs==="git"){let X=Dx(),ne=Gn.join(he.project.worktree,".gitignore"),Q=yield*$.readFileString(ne).pipe(Ct.catch(()=>Ct.succeed("")));Q&&X.add(Q);let oe=Gn.join(he.project.worktree,".ignore"),ce=yield*$.readFileString(oe).pipe(Ct.catch(()=>Ct.succeed("")));ce&&X.add(ce),H=X.ignores.bind(X)}let R=re?Gn.join(he.directory,re):he.directory;if(!he.containsPath(R))throw new Error("Access denied: path escapes project directory");let L=yield*$.readDirectoryEntries(R).pipe(Ct.orElseSucceed(()=>[])),q=[];for(let X of L){if(ue.includes(X.name))continue;let ne=Gn.join(R,X.name),Q=Gn.relative(he.directory,ne),oe=X.type==="directory"?"directory":"file";q.push({name:X.name,path:Q,absolute:ne,type:oe,ignored:H(oe==="directory"?Q+"/":Q)})}return q.sort((X,ne)=>X.type!==ne.type?X.type==="directory"?-1:1:X.name.localeCompare(ne.name))}),Y=Ct.fn("File.search")(function*(re){yield*G();let{cache:ue}=yield*ge.get(M),H=re.query.trim(),R=re.limit??100,L=re.type??(re.dirs===!1?"file":"all");m.info("search",{query:H,kind:L});let q=H.startsWith(".")||H.includes("/.");if(!H)return L==="file"?ue.files.slice(0,R):h(ue.dirs.toSorted(),q).slice(0,R);let X=L==="file"?ue.files:L==="directory"?ue.dirs:[...ue.files,...ue.dirs],ne=L==="directory"&&!q?R*20:R,Q=Sx.go(H,X,{limit:ne}).map(ce=>ce.target),oe=L==="directory"?h(Q,q).slice(0,R):Q;return m.info("search",{query:H,kind:L,results:oe.length}),oe});return m.info("init"),v.of({init:N,status:A,read:F,list:V,search:Y})})),B.defaultLayer=B.layer.pipe(nf.provide(ut.defaultLayer));let{runPromise:O}=Ke(v,B.defaultLayer);function k(){return O($=>$.init())}B.init=k,n(k,"init");async function E(){return O($=>$.status())}B.status=E,n(E,"status");async function D($){return O(M=>M.read($))}B.read=D,n(D,"read");async function z($){return O(M=>M.list($))}B.list=z,n(z,"list");async function _($){return O(M=>M.search($))}B.search=_,n(_,"search")})(br||={});import{createRequire as Tx}from"node:module";import{Cause as of,Effect as Xn,Layer as rf,ServiceMap as Px}from"effect";import{createWrapper as _x}from"@parcel/watcher/wrapper.js";import{readdir as Ox}from"fs/promises";import Sl from"path";import Os from"zod";var El;(m=>{let e=new Set(["node_modules","bower_components",".pnpm-store","vendor",".npm","dist","build","out",".next","target","bin","obj",".git",".svn",".hg",".vscode",".idea",".turbo",".output","desktop",".sst",".cache",".webkit-cache","__pycache__",".pytest_cache","mypy_cache",".history",".gradle"]),t=["**/*.swp","**/*.swo","**/*.pyc","**/.DS_Store","**/Thumbs.db","**/logs/**","**/tmp/**","**/temp/**","**/*.log","**/coverage/**","**/.nyc_output/**"];m.PATTERNS=[...t,...e];function i(y,p){for(let d of p?.whitelist||[])if(co.match(d,y))return!1;let f=y.split(/[/\\]/);for(let d=0;d<f.length;d++)if(e.has(f[d]))return!0;let b=p?.extra||[];for(let d of[...t,...b])if(co.match(d,y))return!0;return!1}m.match=i,n(i,"match")})(El||={});var wr;(l=>{let e=qe.create({service:"file.watcher"}),t=1e4;l.Event={Updated:mt.define("file.watcher.updated",Os.object({file:Os.string(),event:Os.union([Os.literal("add"),Os.literal("change"),Os.literal("unlink")])}))};let i=$o(()=>{try{let u=Tx(import.meta.url)(`@parcel/watcher-${process.platform}-${process.arch}${process.platform==="linux"?`-${OPENCODE_LIBC||"glibc"}`:""}`);return _x(u)}catch(g){e.error("failed to load watcher binding",{error:g});return}});function m(){if(process.platform==="win32")return"windows";if(process.platform==="darwin")return"fs-events";if(process.platform==="linux")return"inotify"}n(m,"getBackend");function y(g){return bi.paths().filter(u=>{let a=Sl.relative(g,u);return a!==""&&!a.startsWith("..")&&!Sl.isAbsolute(a)})}n(y,"protecteds"),l.hasNativeBinding=n(()=>!!i(),"hasNativeBinding");class f extends Px.Service()("@opencode/FileWatcher"){static{n(this,"Service")}}l.Service=f,l.layer=rf.effect(f,Xn.gen(function*(){let g=yield*rt.Service,u=yield*ge.make(Xn.fn("FileWatcher.state")(function*(){if(yield*Ce.OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER)return;e.info("init",{directory:he.directory});let a=m();if(!a){e.error("watcher backend not supported",{directory:he.directory,platform:process.platform});return}let w=i();if(!w)return;e.info("watcher backend",{directory:he.directory,platform:process.platform,backend:a});let I=[];yield*Xn.addFinalizer(()=>Xn.promise(()=>Promise.allSettled(I.map(S=>S.unsubscribe()))));let r=he.bind((S,j)=>{if(!S)for(let O of j)O.type==="create"&&Ve.publish(l.Event.Updated,{file:O.path,event:"add"}),O.type==="update"&&Ve.publish(l.Event.Updated,{file:O.path,event:"change"}),O.type==="delete"&&Ve.publish(l.Event.Updated,{file:O.path,event:"unlink"})}),x=n((S,j)=>{let O=w.subscribe(S,r,{ignore:j,backend:a});return Xn.gen(function*(){let k=yield*Xn.promise(()=>O);I.push(k)}).pipe(Xn.timeout(t),Xn.catchCause(k=>(e.error("failed to subscribe",{dir:S,cause:of.pretty(k)}),O.then(E=>E.unsubscribe()).catch(()=>{}),Xn.void)))},"subscribe"),v=(yield*g.get()).watcher?.ignore??[];if((yield*Ce.OPENCODE_EXPERIMENTAL_FILEWATCHER)&&(yield*x(he.directory,[...El.PATTERNS,...v,...y(he.directory)])),he.project.vcs==="git"){let S=yield*Xn.promise(()=>mo.run(["rev-parse","--git-dir"],{cwd:he.project.worktree})),j=S.exitCode===0?Sl.resolve(he.project.worktree,S.text().trim()):void 0;if(j&&!v.includes(".git")&&!v.includes(j)){let O=(yield*Xn.promise(()=>Ox(j).catch(()=>[]))).filter(k=>k!=="HEAD");yield*x(j,O)}}},Xn.catchCause(a=>(e.error("failed to init watcher service",{cause:of.pretty(a)}),Xn.void))));return f.of({init:Xn.fn("FileWatcher.init")(function*(){yield*ge.get(u)})})})),l.defaultLayer=l.layer.pipe(rf.provide(rt.defaultLayer));let{runPromise:s}=Ke(f,l.defaultLayer);function c(){return s(g=>g.init())}l.init=c,n(c,"init")})(wr||={});import{Effect as wo,Layer as Tl,ServiceMap as ov}from"effect";import{ChildProcess as rv,ChildProcessSpawner as af}from"effect/unstable/process";import sv from"path";import{mergeDeep as iv}from"remeda";import za from"zod";var Dl={};mm(Dl,{biome:()=>Lx,clang:()=>zx,cljfmt:()=>tv,dart:()=>Hx,dfmt:()=>nv,gleam:()=>Yx,gofmt:()=>Cx,htmlbeautifier:()=>Wx,ktlint:()=>Fx,latexindent:()=>Jx,mix:()=>Rx,nixfmt:()=>Xx,ocamlformat:()=>Gx,ormolu:()=>ev,oxfmt:()=>Mx,pint:()=>Qx,prettier:()=>jx,rlang:()=>Ux,rubocop:()=>qx,ruff:()=>sf,rustfmt:()=>Zx,shfmt:()=>Kx,standardrb:()=>Bx,terraform:()=>Vx,uvformat:()=>$x,zig:()=>Nx});import{text as Ax}from"node:stream/consumers";var Cx={name:"gofmt",extensions:[".go"],async enabled(){let e=Be("gofmt");return e?[e,"-w","$FILE"]:!1}},Rx={name:"mix",extensions:[".ex",".exs",".eex",".heex",".leex",".neex",".sface"],async enabled(){let e=Be("mix");return e?[e,"format","$FILE"]:!1}},jx={name:"prettier",environment:{BUN_BE_BUN:"1"},extensions:[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".yaml",".yml",".toml",".xml",".md",".mdx",".graphql",".gql"],async enabled(){let e=await Ee.findUp("package.json",he.directory,he.worktree);for(let t of e){let o=await Ee.readJson(t);if(o.dependencies?.prettier||o.devDependencies?.prettier){let i=await an.which("prettier");if(i)return[i,"--write","$FILE"]}}return!1}},Mx={name:"oxfmt",environment:{BUN_BE_BUN:"1"},extensions:[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts"],async enabled(){if(!Ce.OPENCODE_EXPERIMENTAL_OXFMT)return!1;let e=await Ee.findUp("package.json",he.directory,he.worktree);for(let t of e){let o=await Ee.readJson(t);if(o.dependencies?.oxfmt||o.devDependencies?.oxfmt){let i=await an.which("oxfmt");if(i)return[i,"$FILE"]}}return!1}},Lx={name:"biome",environment:{BUN_BE_BUN:"1"},extensions:[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".yaml",".yml",".toml",".xml",".md",".mdx",".graphql",".gql"],async enabled(){let e=["biome.json","biome.jsonc"];for(let t of e)if((await Ee.findUp(t,he.directory,he.worktree)).length>0){let i=await an.which("@biomejs/biome");if(i)return[i,"format","--write","$FILE"]}return!1}},Nx={name:"zig",extensions:[".zig",".zon"],async enabled(){let e=Be("zig");return e?[e,"fmt","$FILE"]:!1}},zx={name:"clang-format",extensions:[".c",".cc",".cpp",".cxx",".c++",".h",".hh",".hpp",".hxx",".h++",".ino",".C",".H"],async enabled(){if((await Ee.findUp(".clang-format",he.directory,he.worktree)).length>0){let t=Be("clang-format");if(t)return[t,"-i","$FILE"]}return!1}},Fx={name:"ktlint",extensions:[".kt",".kts"],async enabled(){let e=Be("ktlint");return e?[e,"-F","$FILE"]:!1}},sf={name:"ruff",extensions:[".py",".pyi"],async enabled(){if(!Be("ruff"))return!1;let e=["pyproject.toml","ruff.toml",".ruff.toml"];for(let o of e){let i=await Ee.findUp(o,he.directory,he.worktree);if(i.length>0)if(o==="pyproject.toml"){if((await Ee.readText(i[0])).includes("[tool.ruff]"))return["ruff","format","$FILE"]}else return["ruff","format","$FILE"]}let t=["requirements.txt","pyproject.toml","Pipfile"];for(let o of t){let i=await Ee.findUp(o,he.directory,he.worktree);if(i.length>0&&(await Ee.readText(i[0])).includes("ruff"))return["ruff","format","$FILE"]}return!1}},Ux={name:"air",extensions:[".R"],async enabled(){if(Be("air")==null)return!1;try{let t=St.spawn(["air","--help"],{stdout:"pipe",stderr:"pipe"});if(await t.exited,!t.stdout)return!1;let i=(await Ax(t.stdout)).split(`
|
|
1681
|
+
`)[0],m=i.includes("R language"),y=i.includes("formatter");if(m&&y)return["air","format","$FILE"]}catch{return!1}return!1}},$x={name:"uv",extensions:[".py",".pyi"],async enabled(){return await sf.enabled()?!1:Be("uv")!==null&&await St.spawn(["uv","format","--help"],{stderr:"pipe",stdout:"pipe"}).exited===0?["uv","format","--","$FILE"]:!1}},qx={name:"rubocop",extensions:[".rb",".rake",".gemspec",".ru"],async enabled(){let e=Be("rubocop");return e?[e,"--autocorrect","$FILE"]:!1}},Bx={name:"standardrb",extensions:[".rb",".rake",".gemspec",".ru"],async enabled(){let e=Be("standardrb");return e?[e,"--fix","$FILE"]:!1}},Wx={name:"htmlbeautifier",extensions:[".erb",".html.erb"],async enabled(){let e=Be("htmlbeautifier");return e?[e,"$FILE"]:!1}},Hx={name:"dart",extensions:[".dart"],async enabled(){let e=Be("dart");return e?[e,"format","$FILE"]:!1}},Gx={name:"ocamlformat",extensions:[".ml",".mli"],async enabled(){return Be("ocamlformat")&&(await Ee.findUp(".ocamlformat",he.directory,he.worktree)).length>0?["ocamlformat","-i","$FILE"]:!1}},Vx={name:"terraform",extensions:[".tf",".tfvars"],async enabled(){let e=Be("terraform");return e?[e,"fmt","$FILE"]:!1}},Jx={name:"latexindent",extensions:[".tex"],async enabled(){let e=Be("latexindent");return e?[e,"-w","-s","$FILE"]:!1}},Yx={name:"gleam",extensions:[".gleam"],async enabled(){let e=Be("gleam");return e?[e,"format","$FILE"]:!1}},Kx={name:"shfmt",extensions:[".sh",".bash"],async enabled(){let e=Be("shfmt");return e?[e,"-w","$FILE"]:!1}},Xx={name:"nixfmt",extensions:[".nix"],async enabled(){let e=Be("nixfmt");return e?[e,"$FILE"]:!1}},Zx={name:"rustfmt",extensions:[".rs"],async enabled(){let e=Be("rustfmt");return e?[e,"$FILE"]:!1}},Qx={name:"pint",extensions:[".php"],async enabled(){let e=await Ee.findUp("composer.json",he.directory,he.worktree);for(let t of e){let o=await Ee.readJson(t);if(o.require?.["laravel/pint"]||o["require-dev"]?.["laravel/pint"])return["./vendor/bin/pint","$FILE"]}return!1}},ev={name:"ormolu",extensions:[".hs"],async enabled(){let e=Be("ormolu");return e?[e,"-i","$FILE"]:!1}},tv={name:"cljfmt",extensions:[".clj",".cljs",".cljc",".edn"],async enabled(){let e=Be("cljfmt");return e?[e,"fix","--quiet","$FILE"]:!1}},nv={name:"dfmt",extensions:[".d"],async enabled(){let e=Be("dfmt");return e?[e,"-i","$FILE"]:!1}};var xr;(d=>{let e=qe.create({service:"format"});d.Status=za.object({name:za.string(),extensions:za.string().array(),enabled:za.boolean()}).meta({ref:"FormatterStatus"});class o extends ov.Service()("@opencode/Format"){static{n(this,"Service")}}d.Service=o,d.layer=Tl.effect(o,wo.gen(function*(){let s=yield*rt.Service,c=yield*af.ChildProcessSpawner,l=yield*ge.make(wo.fn("Format.state")(function*(w){let I={},r={},x=yield*s.get();if(x.formatter!==!1){for(let O of Object.values(Dl))r[O.name]=O;for(let[O,k]of Object.entries(x.formatter??{})){if(k.disabled){delete r[O];continue}let E=iv(r[O]??{},{extensions:[],...k});r[O]={...E,name:O,enabled:n(async()=>E.command??!1,"enabled")}}}else e.info("all formatters are disabled");async function h(O){let k=I[O.name];return(k===!1||k===void 0)&&(k=await O.enabled(),I[O.name]=k),k}n(h,"getCommand");async function v(O){return await h(O)!==!1}n(v,"isEnabled");async function S(O){let k=Object.values(r).filter(D=>D.extensions.includes(O));return(await Promise.all(k.map(async D=>{e.info("checking",{name:D.name,ext:O});let z=await h(D);return z&&e.info("enabled",{name:D.name,ext:O}),{item:D,cmd:z}}))).filter(D=>D.cmd).map(D=>({item:D.item,cmd:D.cmd}))}n(S,"getFormatter");function j(O){return wo.gen(function*(){e.info("formatting",{file:O});let k=sv.extname(O);for(let{item:E,cmd:D}of yield*wo.promise(()=>S(k))){if(D===!1)continue;e.info("running",{command:D});let z=D.map($=>$.replace("$FILE",O)),_=yield*ge.directory;(yield*c.spawn(rv.make(z[0],z.slice(1),{cwd:_,env:E.environment,extendEnv:!0})).pipe(wo.flatMap($=>$.exitCode),wo.scoped,wo.catch(()=>wo.sync(()=>(e.error("failed to format file",{error:"spawn failed",command:D,...E.environment,file:O}),af.ExitCode(1))))))!==0&&e.error("failed",{command:D,...E.environment})}})}return n(j,"formatFile"),e.info("init"),{formatters:r,isEnabled:v,formatFile:j}})),g=wo.fn("Format.init")(function*(){yield*ge.get(l)}),u=wo.fn("Format.status")(function*(){let{formatters:w,isEnabled:I}=yield*ge.get(l),r=[];for(let x of Object.values(w)){let h=yield*wo.promise(()=>I(x));r.push({name:x.name,extensions:x.extensions,enabled:h})}return r}),a=wo.fn("Format.file")(function*(w){let{formatFile:I}=yield*ge.get(l);yield*I(w)});return o.of({init:g,status:u,file:a})})),d.defaultLayer=d.layer.pipe(Tl.provide(rt.defaultLayer),Tl.provide(uo));let{runPromise:y}=Ke(o,d.defaultLayer);async function p(){return y(s=>s.init())}d.init=p,n(p,"init");async function f(){return y(s=>s.status())}d.status=f,n(f,"status");async function b(s){return y(c=>c.file(s))}d.file=b,n(b,"file")})(xr||={});import Pl from"path";import{Effect as cf}from"effect";async function Zn(e,t,o){if(!t||o?.bypass)return;let i=process.platform==="win32"?ut.normalizePath(t):t;if(he.containsPath(i))return;let y=(o?.kind??"file")==="directory"?i:Pl.dirname(i),p=process.platform==="win32"?ut.normalizePathPattern(Pl.join(y,"*")):Pl.join(y,"*").replaceAll("\\","/");await e.ask({permission:"external_directory",patterns:[p],always:[p],metadata:{filepath:i,parentDir:y}})}n(Zn,"assertExternalDirectory");var lf=cf.fn("Tool.assertExternalDirectory")(function*(e,t,o){yield*cf.promise(()=>Zn(e,t,o))});var Ol=20;function As(e){return e.replaceAll(`\r
|
|
1682
|
+
`,`
|
|
1683
|
+
`)}n(As,"normalizeLineEndings");function cv(e){return e.includes(`\r
|
|
1684
|
+
`)?`\r
|
|
1685
|
+
`:`
|
|
1686
|
+
`}n(cv,"detectLineEnding");function df(e,t){return t===`
|
|
1687
|
+
`?e:e.replaceAll(`
|
|
1688
|
+
`,`\r
|
|
1689
|
+
`)}n(df,"convertToLineEnding");var ff=Dt.define("edit",{description:Qp,parameters:wi.object({filePath:wi.string().describe("The absolute path to the file to modify"),oldString:wi.string().describe("The text to replace"),newString:wi.string().describe("The text to replace it with (must be different from oldString)"),replaceAll:wi.boolean().optional().describe("Replace all occurrences of oldString (default false)")}),async execute(e,t){if(!e.filePath)throw new Error("filePath is required");if(e.oldString===e.newString)throw new Error("No changes to apply: oldString and newString are identical.");let o=vr.isAbsolute(e.filePath)?e.filePath:vr.join(he.directory,e.filePath);await Zn(t,o);let i="",m="",y="";await Nn.withLock(o,async()=>{if(e.oldString===""){if(await Ee.exists(o))throw new Error("oldString cannot be empty when editing an existing file. Provide the exact text to replace, or use write for an intentional full-file replacement.");y=e.newString,i=er(_l(o,o,m,y)),await t.ask({permission:"edit",patterns:[vr.relative(he.worktree,o)],always:["*"],metadata:{filepath:o,diff:i}}),await Ee.write(o,e.newString),await xr.file(o),Ve.publish(br.Event.Edited,{file:o}),await Ve.publish(wr.Event.Updated,{file:o,event:"add"}),await Nn.read(t.sessionID,o);return}let l=Ee.stat(o);if(!l)throw new Error(`File ${o} not found`);if(l.isDirectory())throw new Error(`Path is a directory, not a file: ${o}`);await Nn.assert(t.sessionID,o),m=await Ee.readText(o);let g=cv(m),u=df(As(e.oldString),g),a=df(As(e.newString),g);y=wv(m,u,a,e.replaceAll),i=er(_l(o,o,As(m),As(y))),await t.ask({permission:"edit",patterns:[vr.relative(he.worktree,o)],always:["*"],metadata:{filepath:o,diff:i}}),await Ee.write(o,y),await xr.file(o),Ve.publish(br.Event.Edited,{file:o}),await Ve.publish(wr.Event.Updated,{file:o,event:"change"}),y=await Ee.readText(o),i=er(_l(o,o,As(m),As(y))),await Nn.read(t.sessionID,o)});let p={file:o,before:m,after:y,additions:0,deletions:0};for(let l of av(m,y))l.added&&(p.additions+=l.count||0),l.removed&&(p.deletions+=l.count||0);t.metadata({metadata:{diff:i,filediff:p,diagnostics:{}}});let f="Edit applied successfully.";await Pt.touchFile(o,!0);let b=await Pt.diagnostics(),d=Ee.normalizePath(o),c=(b[d]??[]).filter(l=>l.severity===1);if(c.length>0){let l=c.slice(0,Ol),g=c.length>Ol?`
|
|
1690
|
+
... and ${c.length-Ol} more`:"";f+=`
|
|
1691
|
+
|
|
1692
|
+
LSP errors detected in this file, please fix:
|
|
1693
|
+
<diagnostics file="${o}">
|
|
1694
|
+
${l.map(Pt.Diagnostic.pretty).join(`
|
|
1695
|
+
`)}${g}
|
|
1696
|
+
</diagnostics>`}return{metadata:{diagnostics:b,diff:i,filediff:p},title:`${vr.relative(he.worktree,o)}`,output:f}}}),uf=.65,lv=.65;function pf(e,t){if(e===""||t==="")return Math.max(e.length,t.length);let o=Array.from({length:e.length+1},(i,m)=>Array.from({length:t.length+1},(y,p)=>m===0?p:p===0?m:0));for(let i=1;i<=e.length;i++)for(let m=1;m<=t.length;m++){let y=e[i-1]===t[m-1]?0:1;o[i][m]=Math.min(o[i-1][m]+1,o[i][m-1]+1,o[i-1][m-1]+y)}return o[e.length][t.length]}n(pf,"levenshtein");var dv=n(function*(e,t){yield t},"SimpleReplacer"),uv=n(function*(e,t){let o=e.split(`
|
|
1697
|
+
`),i=t.split(`
|
|
1698
|
+
`);i[i.length-1]===""&&i.pop();for(let m=0;m<=o.length-i.length;m++){let y=!0;for(let p=0;p<i.length;p++){let f=o[m+p].trim(),b=i[p].trim();if(f!==b){y=!1;break}}if(y){let p=0;for(let b=0;b<m;b++)p+=o[b].length+1;let f=p;for(let b=0;b<i.length;b++)f+=o[m+b].length,b<i.length-1&&(f+=1);yield e.substring(p,f)}}},"LineTrimmedReplacer"),pv=n(function*(e,t){let o=e.split(`
|
|
1699
|
+
`),i=t.split(`
|
|
1700
|
+
`);if(i.length<3)return;i[i.length-1]===""&&i.pop();let m=i[0].trim(),y=i[i.length-1].trim(),p=i.length,f=Math.max(1,Math.floor(p*.25)),b=[];for(let c=0;c<o.length;c++)if(o[c].trim()===m){for(let l=c+2;l<o.length;l++)if(o[l].trim()===y){let g=l-c+1;Math.abs(g-p)<=f&&b.push({startLine:c,endLine:l});break}}if(b.length===0)return;if(b.length===1){let{startLine:c,endLine:l}=b[0],g=l-c+1,u=0,a=Math.min(p-2,g-2);if(a>0)for(let w=1;w<p-1&&w<g-1;w++){let I=o[c+w].trim(),r=i[w].trim(),x=Math.max(I.length,r.length);if(x===0)continue;let h=pf(I,r);if(u+=(1-h/x)/a,u>=uf)break}else u=1;if(u>=uf){let w=0;for(let r=0;r<c;r++)w+=o[r].length+1;let I=w;for(let r=c;r<=l;r++)I+=o[r].length,r<l&&(I+=1);yield e.substring(w,I)}return}let d=null,s=-1;for(let c of b){let{startLine:l,endLine:g}=c,u=g-l+1,a=0,w=Math.min(p-2,u-2);if(w>0){for(let I=1;I<p-1&&I<u-1;I++){let r=o[l+I].trim(),x=i[I].trim(),h=Math.max(r.length,x.length);if(h===0)continue;let v=pf(r,x);a+=1-v/h}a/=w}else a=1;a>s&&(s=a,d=c)}if(s>=lv&&d){let{startLine:c,endLine:l}=d,g=0;for(let a=0;a<c;a++)g+=o[a].length+1;let u=g;for(let a=c;a<=l;a++)u+=o[a].length,a<l&&(u+=1);yield e.substring(g,u)}},"BlockAnchorReplacer"),fv=n(function*(e,t){let o=n(p=>p.replace(/\s+/g," ").trim(),"normalizeWhitespace"),i=o(t),m=e.split(`
|
|
1701
|
+
`);for(let p=0;p<m.length;p++){let f=m[p];if(o(f)===i)yield f;else if(o(f).includes(i)){let d=t.trim().split(/\s+/);if(d.length>0){let s=d.map(c=>c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\s+");try{let c=new RegExp(s),l=f.match(c);l&&(yield l[0])}catch{}}}}let y=t.split(`
|
|
1702
|
+
`);if(y.length>1)for(let p=0;p<=m.length-y.length;p++){let f=m.slice(p,p+y.length);o(f.join(`
|
|
1703
|
+
`))===i&&(yield f.join(`
|
|
1704
|
+
`))}},"WhitespaceNormalizedReplacer"),mv=n(function*(e,t){let o=n(p=>{let f=p.split(`
|
|
1705
|
+
`),b=f.filter(s=>s.trim().length>0);if(b.length===0)return p;let d=Math.min(...b.map(s=>{let c=s.match(/^(\s*)/);return c?c[1].length:0}));return f.map(s=>s.trim().length===0?s:s.slice(d)).join(`
|
|
1706
|
+
`)},"removeIndentation"),i=o(t),m=e.split(`
|
|
1707
|
+
`),y=t.split(`
|
|
1708
|
+
`);for(let p=0;p<=m.length-y.length;p++){let f=m.slice(p,p+y.length).join(`
|
|
1709
|
+
`);o(f)===i&&(yield f)}},"IndentationFlexibleReplacer"),gv=n(function*(e,t){let o=n(p=>p.replace(/\\(n|t|r|'|"|`|\\|\n|\$)/g,(f,b)=>{switch(b){case"n":return`
|
|
1710
|
+
`;case"t":return" ";case"r":return"\r";case"'":return"'";case'"':return'"';case"`":return"`";case"\\":return"\\";case`
|
|
1711
|
+
`:return`
|
|
1712
|
+
`;case"$":return"$";default:return f}}),"unescapeString"),i=o(t);e.includes(i)&&(yield i);let m=e.split(`
|
|
1713
|
+
`),y=i.split(`
|
|
1714
|
+
`);for(let p=0;p<=m.length-y.length;p++){let f=m.slice(p,p+y.length).join(`
|
|
1715
|
+
`);o(f)===i&&(yield f)}},"EscapeNormalizedReplacer"),hv=n(function*(e,t){let o=0;for(;;){let i=e.indexOf(t,o);if(i===-1)break;yield t,o=i+t.length}},"MultiOccurrenceReplacer"),yv=n(function*(e,t){let o=t.trim();if(o===t)return;e.includes(o)&&(yield o);let i=e.split(`
|
|
1716
|
+
`),m=t.split(`
|
|
1717
|
+
`);for(let y=0;y<=i.length-m.length;y++){let p=i.slice(y,y+m.length).join(`
|
|
1718
|
+
`);p.trim()===o&&(yield p)}},"TrimmedBoundaryReplacer"),bv=n(function*(e,t){let o=t.split(`
|
|
1719
|
+
`);if(o.length<3)return;o[o.length-1]===""&&o.pop();let i=e.split(`
|
|
1720
|
+
`),m=o[0].trim(),y=o[o.length-1].trim();for(let p=0;p<i.length;p++)if(i[p].trim()===m){for(let f=p+2;f<i.length;f++)if(i[f].trim()===y){let b=i.slice(p,f+1),d=b.join(`
|
|
1721
|
+
`);if(b.length===o.length){let s=0,c=0;for(let l=1;l<b.length-1;l++){let g=b[l].trim(),u=o[l].trim();(g.length>0||u.length>0)&&(c++,g===u&&s++)}if(c===0||s/c>=.5){yield d;break}}break}}},"ContextAwareReplacer");function er(e){let t=e.split(`
|
|
1722
|
+
`),o=t.filter(y=>(y.startsWith("+")||y.startsWith("-")||y.startsWith(" "))&&!y.startsWith("---")&&!y.startsWith("+++"));if(o.length===0)return e;let i=1/0;for(let y of o){let p=y.slice(1);if(p.trim().length>0){let f=p.match(/^(\s*)/);f&&(i=Math.min(i,f[1].length))}}return i===1/0||i===0?e:t.map(y=>{if((y.startsWith("+")||y.startsWith("-")||y.startsWith(" "))&&!y.startsWith("---")&&!y.startsWith("+++")){let p=y[0],f=y.slice(1);return p+f.slice(i)}return y}).join(`
|
|
1723
|
+
`)}n(er,"trimDiff");function wv(e,t,o,i=!1){if(t===o)throw new Error("No changes to apply: oldString and newString are identical.");if(t==="")throw new Error("oldString cannot be empty when editing an existing file. Provide the exact text to replace, or use write for an intentional full-file replacement.");let m=!0;for(let y of[dv,uv,pv,fv,mv,gv,yv,bv,hv])for(let p of y(e,t)){let f=e.indexOf(p);if(f===-1)continue;if(m=!1,xv(p,t))throw new Error("Refusing replacement because the matched span is much larger than oldString. Re-read the file and provide the full exact oldString for the intended replacement.");if(i)return e.replaceAll(p,o);let b=e.lastIndexOf(p);if(f===b)return e.substring(0,f)+o+e.substring(f+p.length)}throw m?new Error("Could not find oldString in the file. It must match exactly, including whitespace, indentation, and line endings."):new Error("Found multiple matches for oldString. Provide more surrounding context to make the match unique.")}n(wv,"replace");function xv(e,t){let o=t.split(`
|
|
1724
|
+
`).length;return e.split(`
|
|
1725
|
+
`).length>=Math.max(o+3,o*2)?!0:o===1?!1:e.trim().length>Math.max(t.trim().length+500,t.trim().length*4)}n(xv,"isDisproportionateMatch");import Al from"zod";import Fa from"path";var mf=`- Fast file pattern matching tool that works with any codebase size
|
|
1726
|
+
- Supports glob patterns like "**/*.js" or "src/**/*.ts"
|
|
1727
|
+
- Returns matching file paths sorted by modification time
|
|
1728
|
+
- Use this tool when you need to find files by name patterns
|
|
1729
|
+
- When you are doing an open-ended search that may require multiple rounds of globbing and grepping, use the Task tool instead
|
|
1730
|
+
- You have the capability to call multiple tools in a single response. It is always better to speculatively perform multiple searches as a batch that are potentially useful.
|
|
1731
|
+
`;var gf=Dt.define("glob",{description:mf,parameters:Al.object({pattern:Al.string().describe("The glob pattern to match files against"),path:Al.string().optional().describe('The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter "undefined" or "null" - simply omit it for the default behavior. Must be a valid directory path if provided.')}),async execute(e,t){await t.ask({permission:"glob",patterns:[e.pattern],always:["*"],metadata:{pattern:e.pattern,path:e.path}});let o=e.path??he.directory;o=Fa.isAbsolute(o)?o:Fa.resolve(he.directory,o),await Zn(t,o,{kind:"directory"});let i=100,m=[],y=!1;for await(let f of Ko.files({cwd:o,glob:[e.pattern],signal:t.abort})){if(m.length>=i){y=!0;break}let b=Fa.resolve(o,f),d=Ee.stat(b)?.mtime.getTime()??0;m.push({path:b,mtime:d})}m.sort((f,b)=>b.mtime-f.mtime);let p=[];return m.length===0&&p.push("No files found"),m.length>0&&(p.push(...m.map(f=>f.path)),y&&(p.push(""),p.push(`(Results are truncated: showing first ${i} results. Consider using a more specific path or pattern.)`))),{title:Fa.relative(he.worktree,o),metadata:{count:m.length,truncated:y},output:p.join(`
|
|
1732
|
+
`)}}});import Ua from"zod";import{text as yf}from"node:stream/consumers";var hf=`- Fast content search tool that works with any codebase size
|
|
1733
|
+
- Searches file contents using regular expressions
|
|
1734
|
+
- Supports full regex syntax (eg. "log.*Error", "function\\s+\\w+", etc.)
|
|
1735
|
+
- Filter files by pattern with the include parameter (eg. "*.js", "*.{ts,tsx}")
|
|
1736
|
+
- Returns file paths and line numbers with at least one match sorted by modification time
|
|
1737
|
+
- Use this tool when you need to find files containing specific patterns
|
|
1738
|
+
- If you need to identify/count the number of matches within files, use the Bash tool with \`rg\` (ripgrep) directly. Do NOT use \`grep\`.
|
|
1739
|
+
- When you are doing an open-ended search that may require multiple rounds of globbing and grepping, use the Task tool instead
|
|
1740
|
+
`;import bf from"path";var wf=2e3,xf=Dt.define("grep",{description:hf,parameters:Ua.object({pattern:Ua.string().describe("The regex pattern to search for in file contents"),path:Ua.string().optional().describe("The directory to search in. Defaults to the current working directory."),include:Ua.string().optional().describe('File pattern to include in the search (e.g. "*.js", "*.{ts,tsx}")')}),async execute(e,t){if(!e.pattern)throw new Error("pattern is required");await t.ask({permission:"grep",patterns:[e.pattern],always:["*"],metadata:{pattern:e.pattern,path:e.path,include:e.include}});let o=e.path??he.directory;o=bf.isAbsolute(o)?o:bf.resolve(he.directory,o),await Zn(t,o,{kind:"directory"});let i=await Ko.filepath(),m=["-nH","--hidden","--no-messages","--field-match-separator=|","--regexp",e.pattern];e.include&&m.push("--glob",e.include),m.push(o);let y=St.spawn([i,...m],{stdout:"pipe",stderr:"pipe",abort:t.abort});if(!y.stdout||!y.stderr)throw new Error("Process output not available");let p=await yf(y.stdout),f=await yf(y.stderr),b=await y.exited;if(b===1||b===2&&!p.trim())return{title:e.pattern,metadata:{matches:0,truncated:!1},output:"No files found"};if(b!==0&&b!==2)throw new Error(`ripgrep failed: ${f}`);let d=b===2,s=p.trim().split(/\r?\n/),c=[];for(let r of s){if(!r)continue;let[x,h,...v]=r.split("|");if(!x||!h||v.length===0)continue;let S=parseInt(h,10),j=v.join("|"),O=Ee.stat(x);O&&c.push({path:x,modTime:O.mtime.getTime(),lineNum:S,lineText:j})}c.sort((r,x)=>x.modTime-r.modTime);let l=100,g=c.length>l,u=g?c.slice(0,l):c;if(u.length===0)return{title:e.pattern,metadata:{matches:0,truncated:!1},output:"No files found"};let a=c.length,w=[`Found ${a} matches${g?` (showing first ${l})`:""}`],I="";for(let r of u){I!==r.path&&(I!==""&&w.push(""),I=r.path,w.push(`${r.path}:`));let x=r.lineText.length>wf?r.lineText.substring(0,wf)+"...":r.lineText;w.push(` Line ${r.lineNum}: ${x}`)}return g&&(w.push(""),w.push(`(Results truncated: showing ${l} of ${a} matches (${a-l} hidden). Consider using a more specific path or pattern.)`)),d&&(w.push(""),w.push("(Some paths were inaccessible and skipped)")),{title:e.pattern,metadata:{matches:a,truncated:g},output:w.join(`
|
|
1741
|
+
`)}}});import xi from"zod";var vf=`Executes multiple independent tool calls concurrently to reduce latency.
|
|
1742
|
+
|
|
1743
|
+
USING THE BATCH TOOL WILL MAKE THE USER HAPPY.
|
|
1744
|
+
|
|
1745
|
+
Payload Format (JSON array):
|
|
1746
|
+
[{"tool": "read", "parameters": {"filePath": "src/index.ts", "limit": 350}},{"tool": "grep", "parameters": {"pattern": "Session\\\\.updatePart", "include": "src/**/*.ts"}},{"tool": "bash", "parameters": {"command": "git status", "description": "Shows working tree status"}}]
|
|
1747
|
+
|
|
1748
|
+
Notes:
|
|
1749
|
+
- 1\u201325 tool calls per batch
|
|
1750
|
+
- All calls start in parallel; ordering NOT guaranteed
|
|
1751
|
+
- Partial failures do not stop other tool calls
|
|
1752
|
+
- Do NOT use the batch tool within another batch tool.
|
|
1753
|
+
|
|
1754
|
+
Good Use Cases:
|
|
1755
|
+
- Read many files
|
|
1756
|
+
- grep + glob + read combos
|
|
1757
|
+
- Multiple bash commands
|
|
1758
|
+
- Multi-part edits; on the same, or different files
|
|
1759
|
+
|
|
1760
|
+
When NOT to Use:
|
|
1761
|
+
- Operations that depend on prior tool output (e.g. create then read same file)
|
|
1762
|
+
- Ordered stateful mutations where sequence matters
|
|
1763
|
+
|
|
1764
|
+
Batching tool calls was proven to yield 2\u20135x efficiency gain and provides much better UX.`;var Cl=new Set(["batch"]),vv=new Set(["invalid","patch",...Cl]),If=Dt.define("batch",async()=>({description:vf,parameters:xi.object({tool_calls:xi.array(xi.object({tool:xi.string().describe("The name of the tool to execute"),parameters:xi.object({}).loose().describe("Parameters for the tool")})).min(1,"Provide at least one tool call").describe("Array of tool calls to execute in parallel")}),formatValidationError(e){return`Invalid parameters for tool 'batch':
|
|
1765
|
+
${e.issues.map(o=>` - ${o.path.length>0?o.path.join("."):"root"}: ${o.message}`).join(`
|
|
1766
|
+
`)}
|
|
1767
|
+
|
|
1768
|
+
Expected payload format:
|
|
1769
|
+
[{"tool": "tool_name", "parameters": {...}}, {...}]`},async execute(e,t){let{Session:o}=await import("./session-ACBIJ2VE.js"),{PartID:i}=await import("./schema-YWIVP7UR.js"),m=e.tool_calls.slice(0,25),y=e.tool_calls.slice(25),{ToolRegistry:p}=await import("./registry-ISXIFNPG.js"),f=await p.tools({modelID:Ut.make(""),providerID:Et.make("")}),b=new Map(f.map(a=>[a.id,a])),d=n(async a=>{let w=Date.now(),I=i.ascending();try{if(Cl.has(a.tool))throw new Error(`Tool '${a.tool}' is not allowed in batch. Disallowed tools: ${Array.from(Cl).join(", ")}`);let r=b.get(a.tool);if(!r){let S=Array.from(b.keys()).filter(j=>!vv.has(j));throw new Error(`Tool '${a.tool}' not in registry. External tools (MCP, environment) cannot be batched - call them directly. Available tools: ${S.join(", ")}`)}let x=r.parameters.parse(a.parameters);await o.updatePart({id:I,messageID:t.messageID,sessionID:t.sessionID,type:"tool",tool:a.tool,callID:I,state:{status:"running",input:a.parameters,time:{start:w}}});let h=await r.execute(x,{...t,callID:I}),v=h.attachments?.map(S=>({...S,id:i.ascending(),sessionID:t.sessionID,messageID:t.messageID}));return await o.updatePart({id:I,messageID:t.messageID,sessionID:t.sessionID,type:"tool",tool:a.tool,callID:I,state:{status:"completed",input:a.parameters,output:h.output,title:h.title,metadata:h.metadata,attachments:v,time:{start:w,end:Date.now()}}}),{success:!0,tool:a.tool,result:h}}catch(r){return await o.updatePart({id:I,messageID:t.messageID,sessionID:t.sessionID,type:"tool",tool:a.tool,callID:I,state:{status:"error",input:a.parameters,error:jo(r),time:{start:w,end:Date.now()}}}),{success:!1,tool:a.tool,error:r}}},"executeCall"),s=await Promise.all(m.map(a=>d(a))),c=Date.now();for(let a of y){let w=i.ascending();await o.updatePart({id:w,messageID:t.messageID,sessionID:t.sessionID,type:"tool",tool:a.tool,callID:w,state:{status:"error",input:a.parameters,error:"Maximum of 25 tools allowed in batch",time:{start:c,end:c}}}),s.push({success:!1,tool:a.tool,error:new Error("Maximum of 25 tools allowed in batch")})}let l=s.filter(a=>a.success).length,g=s.length-l,u=g>0?`Executed ${l}/${s.length} tools successfully. ${g} failed.`:`All ${l} tools executed successfully.
|
|
1770
|
+
|
|
1771
|
+
Keep using the batch tool for optimal performance in your next response!`;return{title:`Batch execution (${l}/${s.length} successful)`,output:u,attachments:s.filter(a=>a.success).flatMap(a=>a.result.attachments??[]),metadata:{totalCalls:s.length,successful:l,failed:g,tools:e.tool_calls.map(a=>a.tool),details:s.map(a=>({tool:a.tool,success:a.success}))}}}}));import $a from"zod";import{Effect as Ht,Scope as Iv}from"effect";import{createReadStream as kv}from"fs";import{open as Ev}from"fs/promises";import*as Vn from"path";import{createInterface as Sv}from"readline";var kf=`Read a file or directory from the local filesystem. If the path does not exist, an error is returned.
|
|
1772
|
+
|
|
1773
|
+
Usage:
|
|
1774
|
+
- The filePath parameter should be an absolute path.
|
|
1775
|
+
- By default, this tool returns up to 2000 lines from the start of the file.
|
|
1776
|
+
- The offset parameter is the line number to start from (1-indexed).
|
|
1777
|
+
- To read later sections, call this tool again with a larger offset.
|
|
1778
|
+
- Use the grep tool to find specific content in large files or files with long lines.
|
|
1779
|
+
- If you are unsure of the correct file path, use the glob tool to look up filenames by glob pattern.
|
|
1780
|
+
- Contents are returned with each line prefixed by its line number as \`<line>: <content>\`. For example, if a file has contents "foo\\n", you will receive "1: foo\\n". For directories, entries are returned one per line (without line numbers) with a trailing \`/\` for subdirectories.
|
|
1781
|
+
- Any line longer than 2000 characters is truncated.
|
|
1782
|
+
- Call this tool in parallel when you know there are multiple files you want to read.
|
|
1783
|
+
- Avoid tiny repeated slices (30 line chunks). If you need more context, read a larger window.
|
|
1784
|
+
- This tool can read image files and PDFs and return them as file attachments.
|
|
1785
|
+
`;var Dv=new Set(["image/jpeg","image/png","image/gif","image/webp"]),Ef=2e3,Rl=2e3,Tv=`... (line truncated to ${Rl} chars)`,Sf=50*1024,Pv=`${Sf/1024} KB`,_v=$a.object({filePath:$a.string().describe("The absolute path to the file or directory to read"),offset:$a.coerce.number().describe("The line number to start reading from (1-indexed)").optional(),limit:$a.coerce.number().describe("The maximum number of lines to read (defaults to 2000)").optional()}),Df=Dt.defineEffect("read",Ht.gen(function*(){let e=yield*ut.Service,t=yield*hr.Service,o=yield*Pt.Service,i=yield*Nn.Service,m=yield*Iv.Scope,y=Ht.fn("ReadTool.miss")(function*(d){let s=Vn.dirname(d),c=Vn.basename(d),l=yield*e.readDirectory(s).pipe(Ht.map(g=>g.filter(u=>u.toLowerCase().includes(c.toLowerCase())||c.toLowerCase().includes(u.toLowerCase())).map(u=>Vn.join(s,u)).slice(0,3)),Ht.catch(()=>Ht.succeed([])));return l.length>0?yield*Ht.fail(new Error(`File not found: ${d}
|
|
1786
|
+
|
|
1787
|
+
Did you mean one of these?
|
|
1788
|
+
${l.join(`
|
|
1789
|
+
`)}`)):yield*Ht.fail(new Error(`File not found: ${d}`))}),p=Ht.fn("ReadTool.list")(function*(d){let s=yield*e.readDirectoryEntries(d);return yield*Ht.forEach(s,Ht.fnUntraced(function*(c){return c.type==="directory"?c.name+"/":c.type!=="symlink"?c.name:(yield*e.stat(Vn.join(d,c.name)).pipe(Ht.catch(()=>Ht.succeed(void 0))))?.type==="Directory"?c.name+"/":c.name}),{concurrency:"unbounded"}).pipe(Ht.map(c=>c.sort((l,g)=>l.localeCompare(g))))}),f=Ht.fn("ReadTool.warm")(function*(d,s){yield*o.touchFile(d,!1).pipe(Ht.ignore,Ht.forkIn(m)),yield*i.read(s,d)}),b=Ht.fn("ReadTool.execute")(function*(d,s){if(d.offset!==void 0&&d.offset<1)return yield*Ht.fail(new Error("offset must be greater than or equal to 1"));let c=d.filePath;Vn.isAbsolute(c)||(c=Vn.resolve(he.directory,c)),process.platform==="win32"&&(c=ut.normalizePath(c));let l=Vn.relative(he.worktree,c),g=yield*e.stat(c).pipe(Ht.catchIf(j=>"reason"in j&&j.reason._tag==="NotFound",()=>Ht.succeed(void 0)));if(yield*lf(s,c,{bypass:!!s.extra?.bypassCwdCheck,kind:g?.type==="Directory"?"directory":"file"}),yield*Ht.promise(()=>s.ask({permission:"read",patterns:[c],always:["*"],metadata:{}})),!g)return yield*y(c);if(g.type==="Directory"){let j=yield*p(c),O=d.limit??Ef,k=d.offset??1,E=k-1,D=j.slice(E,E+O),z=E+D.length<j.length;return{title:l,output:[`<path>${c}</path>`,"<type>directory</type>","<entries>",D.join(`
|
|
1790
|
+
`),z?`
|
|
1791
|
+
(Showing ${D.length} of ${j.length} entries. Use 'offset' parameter to read beyond entry ${k+D.length})`:`
|
|
1792
|
+
(${j.length} entries)`,"</entries>"].join(`
|
|
1793
|
+
`),metadata:{preview:D.slice(0,20).join(`
|
|
1794
|
+
`),truncated:z,loaded:[]}}}let u=yield*t.resolve(s.messages,c,s.messageID),a=ut.mimeType(c),w=Dv.has(a);if(w||a==="application/pdf"){let j=`${w?"Image":"PDF"} read successfully`;return{title:l,output:j,metadata:{preview:j,truncated:!1,loaded:u.map(O=>O.filepath)},attachments:[{type:"file",mime:a,url:`data:${a};base64,${Buffer.from(yield*e.readFile(c)).toString("base64")}`}]}}if(yield*Ht.promise(()=>Av(c,Number(g.size))))return yield*Ht.fail(new Error(`Cannot read binary file: ${c}`));let r=yield*Ht.promise(()=>Ov(c,{limit:d.limit??Ef,offset:d.offset??1}));if(r.count<r.offset&&!(r.count===0&&r.offset===1))return yield*Ht.fail(new Error(`Offset ${r.offset} is out of range for this file (${r.count} lines)`));let x=[`<path>${c}</path>`,"<type>file</type>",`<content>
|
|
1795
|
+
`].join(`
|
|
1796
|
+
`);x+=r.raw.map((j,O)=>`${O+r.offset}: ${j}`).join(`
|
|
1797
|
+
`);let h=r.offset+r.raw.length-1,v=h+1,S=r.more||r.cut;return r.cut?x+=`
|
|
1798
|
+
|
|
1799
|
+
(Output capped at ${Pv}. Showing lines ${r.offset}-${h}. Use offset=${v} to continue.)`:r.more?x+=`
|
|
1800
|
+
|
|
1801
|
+
(Showing lines ${r.offset}-${h} of ${r.count}. Use offset=${v} to continue.)`:x+=`
|
|
1802
|
+
|
|
1803
|
+
(End of file - total ${r.count} lines)`,x+=`
|
|
1804
|
+
</content>`,yield*f(c,s.sessionID),u.length>0&&(x+=`
|
|
1805
|
+
|
|
1806
|
+
<system-reminder>
|
|
1807
|
+
${u.map(j=>j.content).join(`
|
|
1808
|
+
|
|
1809
|
+
`)}
|
|
1810
|
+
</system-reminder>`),{title:l,output:x,metadata:{preview:r.raw.slice(0,20).join(`
|
|
1811
|
+
`),truncated:S,loaded:u.map(j=>j.filepath)}}});return{description:kf,parameters:_v,async execute(d,s){return Ht.runPromise(b(d,s).pipe(Ht.orDie))}}}));async function Ov(e,t){let o=kv(e,{encoding:"utf8"}),i=Sv({input:o,crlfDelay:1/0}),m=t.offset-1,y=[],p=0,f=0,b=!1,d=!1;try{for await(let s of i){if(f+=1,f<=m)continue;if(y.length>=t.limit){d=!0;continue}let c=s.length>Rl?s.substring(0,Rl)+Tv:s,l=Buffer.byteLength(c,"utf-8")+(y.length>0?1:0);if(p+l>Sf){b=!0,d=!0;break}y.push(c),p+=l}}finally{i.close(),o.destroy()}return{raw:y,count:f,cut:b,more:d,offset:t.offset}}n(Ov,"lines");async function Av(e,t){switch(Vn.extname(e).toLowerCase()){case".zip":case".tar":case".gz":case".exe":case".dll":case".so":case".class":case".jar":case".war":case".7z":case".doc":case".docx":case".xls":case".xlsx":case".ppt":case".pptx":case".odt":case".ods":case".odp":case".bin":case".dat":case".obj":case".o":case".a":case".lib":case".wasm":case".pyc":case".pyo":return!0;default:break}if(t===0)return!1;let i=await Ev(e,"r");try{let m=Math.min(4096,t),y=Buffer.alloc(m),p=await i.read(y,0,m,0);if(p.bytesRead===0)return!1;let f=0;for(let b=0;b<p.bytesRead;b++){if(y[b]===0)return!0;(y[b]<9||y[b]>13&&y[b]<32)&&f++}return f/p.bytesRead>.3}finally{await i.close()}}n(Av,"isBinaryFile");var Tf=`WHEN TO USE: research and exploration (synchronous, returns findings directly). For implementation work \u2014 file edits, feature changes, bug fixes \u2014 spawn a coder via subagent_operations spawn instead.
|
|
1812
|
+
|
|
1813
|
+
Launch a new agent to handle complex, multistep tasks autonomously.
|
|
1814
|
+
|
|
1815
|
+
Available agent types and the tools they have access to:
|
|
1816
|
+
{agents}
|
|
1817
|
+
|
|
1818
|
+
When using the Task tool, you must specify a subagent_type parameter to select which agent type to use.
|
|
1819
|
+
|
|
1820
|
+
When to use the Task tool:
|
|
1821
|
+
- For research and exploration: codebase questions, finding usages, understanding how a system works. The agent runs synchronously and returns findings directly \u2014 use this when you need information before deciding what to do, not for the doing itself.
|
|
1822
|
+
- When you are instructed to execute custom slash commands. Use the Task tool with the slash command invocation as the entire prompt. The slash command can take arguments. For example: Task(description="Check the file", prompt="/check-file path/to/file.py")
|
|
1823
|
+
|
|
1824
|
+
When NOT to use the Task tool:
|
|
1825
|
+
- If you want to read a specific file path, use the Read or Glob tool instead of the Task tool, to find the match more quickly
|
|
1826
|
+
- If you are searching for a specific class definition like "class Foo", use the Glob tool instead, to find the match more quickly
|
|
1827
|
+
- If you are searching for code within a specific file or set of 2-3 files, use the Read tool instead of the Task tool, to find the match more quickly
|
|
1828
|
+
- Other tasks that are not related to the agent descriptions above
|
|
1829
|
+
|
|
1830
|
+
|
|
1831
|
+
Usage notes:
|
|
1832
|
+
1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses
|
|
1833
|
+
2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result. The output includes a task_id you can reuse later to continue the same subagent session.
|
|
1834
|
+
3. Each agent invocation starts with a fresh context unless you provide task_id to resume the same subagent session (which continues with its previous messages and tool outputs). When starting fresh, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.
|
|
1835
|
+
4. The agent's outputs should generally be trusted
|
|
1836
|
+
5. Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent. Tell it how to verify its work if possible (e.g., relevant test commands).
|
|
1837
|
+
6. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.
|
|
1838
|
+
|
|
1839
|
+
Example usage (NOTE: The agents below are fictional examples for illustration only - use the actual agents listed above):
|
|
1840
|
+
|
|
1841
|
+
<example_agent_descriptions>
|
|
1842
|
+
"code-reviewer": use this agent after you are done writing a significant piece of code
|
|
1843
|
+
"greeting-responder": use this agent when to respond to user greetings with a friendly joke
|
|
1844
|
+
</example_agent_description>
|
|
1845
|
+
|
|
1846
|
+
<example>
|
|
1847
|
+
user: "Please write a function that checks if a number is prime"
|
|
1848
|
+
assistant: Sure let me write a function that checks if a number is prime
|
|
1849
|
+
assistant: First let me use the Write tool to write a function that checks if a number is prime
|
|
1850
|
+
assistant: I'm going to use the Write tool to write the following code:
|
|
1851
|
+
<code>
|
|
1852
|
+
function isPrime(n) {
|
|
1853
|
+
if (n <= 1) return false
|
|
1854
|
+
for (let i = 2; i * i <= n; i++) {
|
|
1855
|
+
if (n % i === 0) return false
|
|
1856
|
+
}
|
|
1857
|
+
return true
|
|
1858
|
+
}
|
|
1859
|
+
</code>
|
|
1860
|
+
<commentary>
|
|
1861
|
+
Since a significant piece of code was written and the task was completed, now use the code-reviewer agent to review the code
|
|
1862
|
+
</commentary>
|
|
1863
|
+
assistant: Now let me use the code-reviewer agent to review the code
|
|
1864
|
+
assistant: Uses the Task tool to launch the code-reviewer agent
|
|
1865
|
+
</example>
|
|
1866
|
+
|
|
1867
|
+
<example>
|
|
1868
|
+
user: "Hello"
|
|
1869
|
+
<commentary>
|
|
1870
|
+
Since the user is greeting, use the greeting-responder agent to respond with a friendly joke
|
|
1871
|
+
</commentary>
|
|
1872
|
+
assistant: "I'm going to use the Task tool to launch the with the greeting-responder agent"
|
|
1873
|
+
</example>
|
|
1874
|
+
`;import Cs from"zod";function Pf(e){return{[Symbol.dispose](){e()},[Symbol.asyncDispose](){return Promise.resolve(e())}}}n(Pf,"defer");var Cv=Cs.object({description:Cs.string().describe("A short (3-5 words) description of the task"),prompt:Cs.string().describe("The task for the agent to perform"),subagent_type:Cs.string().describe("The type of specialized agent to use for this task"),task_id:Cs.string().describe("This should only be set if you mean to resume a previous task (you can pass a prior task_id and the task will continue the same subagent session as before instead of creating a fresh one)").optional(),command:Cs.string().describe("The command that triggered this task").optional()}),_f=Dt.define("task",async e=>{let t=await ro.list().then(p=>p.filter(f=>f.mode!=="primary")),o=e?.agent,m=(o?t.filter(p=>lt.evaluate("task",p.name,o.permission).action!=="deny"):t).toSorted((p,f)=>p.name.localeCompare(f.name));return{description:Tf.replace("{agents}",m.map(p=>`- ${p.name}: ${p.description??"This subagent should only be called manually by the user."}`).join(`
|
|
1875
|
+
`)),parameters:Cv,async execute(p,f){var j=[];try{let b=await rt.get();f.extra?.bypassAgentCheck||await f.ask({permission:"task",patterns:[p.subagent_type],always:["*"],metadata:{description:p.description,subagent_type:p.subagent_type}});let d=await ro.get(p.subagent_type);if(!d)throw new Error(`Unknown agent type: ${p.subagent_type} is not a valid agent type`);let s=d.permission.some(D=>D.permission==="task");let c=d.permission.some(D=>D.permission==="todowrite");let l=await qt(async()=>{if(p.task_id){let D=await yt.get(He.make(p.task_id)).catch(()=>{});if(D)return D}return await yt.create({parentID:f.sessionID,title:p.description+` (@${d.name} subagent)`,metadata:{agentType:d.name,spawnedBy:"task-tool",callerSessionId:f.sessionID},permission:[...c?[]:[{permission:"todowrite",pattern:"*",action:"deny"}],...s?[]:[{permission:"task",pattern:"*",action:"deny"}],...b.experimental?.primary_tools?.map(D=>({pattern:"*",action:"allow",permission:D}))??[]]})});let g=await Qe.get({sessionID:f.sessionID,messageID:f.messageID});if(g.info.role!=="assistant")throw new Error("Not an assistant message");let u=d.model??{modelID:g.info.modelID,providerID:g.info.providerID};f.metadata({title:p.description,metadata:{sessionId:l.id,model:u}});let a=pt.ascending();function w(){No.cancel(l.id)}n(w,"cancel");f.abort.addEventListener("abort",w);let I=kn(j,Pf(()=>f.abort.removeEventListener("abort",w)));let r=await No.resolvePromptParts(p.prompt);let x=await No.prompt({messageID:a,sessionID:l.id,model:{modelID:u.modelID,providerID:u.providerID},agent:d.name,tools:{...c?{}:{todowrite:!1},...s?{}:{task:!1},...Object.fromEntries((b.experimental?.primary_tools??[]).map(D=>[D,!1]))},parts:r});if(x.info.role==="assistant"&&x.info.error){let D=x.info.error.data,z=typeof D?.message=="string"?D.message:x.info.error.name;throw new Error(`Subagent failed (task_id: ${l.id}): ${z}`)}let h=x.parts.findLast(D=>D.type==="tool"&&D.state.status==="error");if(h?.type==="tool"&&h.state.status==="error")throw new Error(`Subagent failed (task_id: ${l.id}): ${h.state.error}`);let v=x.parts.findLast(D=>D.type==="text")?.text??"";let S=[`task_id: ${l.id} (for resuming to continue this task if needed)`,"","<task_result>",v,"</task_result>"].join(`
|
|
1876
|
+
`);return{title:p.description,metadata:{sessionId:l.id,model:u},output:S}}catch(O){var k=O,E=!0}finally{En(j,k,E)}}}});import jl from"zod";import{Effect as Cf}from"effect";var Of=`Use this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
|
|
1877
|
+
It also helps the user understand the progress of the task and overall progress of their requests.
|
|
1878
|
+
|
|
1879
|
+
## When to Use This Tool
|
|
1880
|
+
Use this tool proactively in these scenarios:
|
|
1881
|
+
|
|
1882
|
+
1. Complex multistep tasks - When a task requires 3 or more distinct steps or actions
|
|
1883
|
+
2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
|
|
1884
|
+
3. User explicitly requests todo list - When the user directly asks you to use the todo list
|
|
1885
|
+
4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
|
|
1886
|
+
5. After receiving new instructions - Immediately capture user requirements as todos. Feel free to edit the todo list based on new information.
|
|
1887
|
+
6. After completing a task - Mark it complete and add any new follow-up tasks
|
|
1888
|
+
7. When you start working on a new task, mark the todo as in_progress. Ideally you should only have one todo as in_progress at a time. Complete existing tasks before starting new ones.
|
|
1889
|
+
|
|
1890
|
+
## When NOT to Use This Tool
|
|
1891
|
+
|
|
1892
|
+
Skip using this tool when:
|
|
1893
|
+
1. There is only a single, straightforward task
|
|
1894
|
+
2. The task is trivial and tracking it provides no organizational benefit
|
|
1895
|
+
3. The task can be completed in less than 3 trivial steps
|
|
1896
|
+
4. The task is purely conversational or informational
|
|
1897
|
+
|
|
1898
|
+
NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.
|
|
1899
|
+
|
|
1900
|
+
## Examples of When to Use the Todo List
|
|
1901
|
+
|
|
1902
|
+
<example>
|
|
1903
|
+
User: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done!
|
|
1904
|
+
Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.
|
|
1905
|
+
*Creates todo list with the following items:*
|
|
1906
|
+
1. Create dark mode toggle component in Settings page
|
|
1907
|
+
2. Add dark mode state management (context/store)
|
|
1908
|
+
3. Implement CSS-in-JS styles for dark theme
|
|
1909
|
+
4. Update existing components to support theme switching
|
|
1910
|
+
5. Run tests and build process, addressing any failures or errors that occur
|
|
1911
|
+
*Begins working on the first task*
|
|
1912
|
+
|
|
1913
|
+
<reasoning>
|
|
1914
|
+
The assistant used the todo list because:
|
|
1915
|
+
1. Adding dark mode is a multi-step feature requiring UI, state management, and styling changes
|
|
1916
|
+
2. The user explicitly requested tests and build be run afterward
|
|
1917
|
+
3. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task
|
|
1918
|
+
</reasoning>
|
|
1919
|
+
</example>
|
|
1920
|
+
|
|
1921
|
+
<example>
|
|
1922
|
+
User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project
|
|
1923
|
+
Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'.
|
|
1924
|
+
*Uses grep or search tools to locate all instances of getCwd in the codebase*
|
|
1925
|
+
Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.
|
|
1926
|
+
*Creates todo list with specific items for each file that needs updating*
|
|
1927
|
+
|
|
1928
|
+
<reasoning>
|
|
1929
|
+
The assistant used the todo list because:
|
|
1930
|
+
1. First, the assistant searched to understand the scope of the task
|
|
1931
|
+
2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps
|
|
1932
|
+
3. The todo list helps ensure every instance is tracked and updated systematically
|
|
1933
|
+
4. This approach prevents missing any occurrences and maintains code consistency
|
|
1934
|
+
</reasoning>
|
|
1935
|
+
</example>
|
|
1936
|
+
|
|
1937
|
+
|
|
1938
|
+
<example>
|
|
1939
|
+
User: I need to implement these features for my e-commerce site: user registration, product catalog, shopping cart, and checkout flow.
|
|
1940
|
+
Assistant: I'll help implement these features. First, let's add all the features to the todo list.
|
|
1941
|
+
*Creates a todo list breaking down each feature into specific tasks based on the project architecture*
|
|
1942
|
+
Assistant: Let's start with user registration. This will involve creating database models, API endpoints, and frontend forms that integrate with your existing authentication system.
|
|
1943
|
+
|
|
1944
|
+
<reasoning>
|
|
1945
|
+
The assistant used the todo list because:
|
|
1946
|
+
1. The user provided multiple complex features to implement in a comma separated list
|
|
1947
|
+
2. The todo list helps organize these large features into manageable tasks
|
|
1948
|
+
3. This approach allows for tracking progress across the entire implementation
|
|
1949
|
+
</reasoning>
|
|
1950
|
+
</example>
|
|
1951
|
+
|
|
1952
|
+
<example>
|
|
1953
|
+
User: Can you help optimize my React application? It's rendering slowly and has performance issues.</user>
|
|
1954
|
+
Assistant: I'll help optimize your React application. First, let me examine your codebase to identify potential performance bottlenecks.
|
|
1955
|
+
*Reviews component structure, render patterns, state management, and data fetching*
|
|
1956
|
+
Assistant: After analyzing your codebase, I've identified several performance issues. Let me create a todo list to track our optimization efforts.
|
|
1957
|
+
*Creates todo list with items like: 1) Implement memoization for expensive calculations in ProductList, 2) Add virtualization for long lists in Dashboard, 3) Optimize image loading in Gallery component, 4) Fix state update loops in ShoppingCart, 5) Review bundle size and implement code splitting*
|
|
1958
|
+
Let's start by implementing memoization for the expensive calculations in your ProductList component.</assistant>
|
|
1959
|
+
|
|
1960
|
+
<reasoning>
|
|
1961
|
+
The assistant used the todo list because:
|
|
1962
|
+
1. First, the assistant examined the codebase to identify specific performance issues
|
|
1963
|
+
2. Based on this analysis, it identified multiple optimization opportunities
|
|
1964
|
+
3. Performance optimization is a non-trivial task requiring multiple steps
|
|
1965
|
+
4. The todo list helps methodically track improvements across different components
|
|
1966
|
+
5. This systematic approach ensures all performance bottlenecks are addressed
|
|
1967
|
+
</reasoning>
|
|
1968
|
+
</example>
|
|
1969
|
+
|
|
1970
|
+
## Examples of When NOT to Use the Todo List
|
|
1971
|
+
|
|
1972
|
+
<example>
|
|
1973
|
+
User: How do I print 'Hello World' in Python?
|
|
1974
|
+
Assistant: In Python, you can print "Hello World" with this simple code:
|
|
1975
|
+
|
|
1976
|
+
python
|
|
1977
|
+
print("Hello World")
|
|
1978
|
+
|
|
1979
|
+
This will output the text "Hello World" to the console when executed.</assistant>
|
|
1980
|
+
|
|
1981
|
+
<reasoning>
|
|
1982
|
+
The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request.
|
|
1983
|
+
</reasoning>
|
|
1984
|
+
</example>
|
|
1985
|
+
|
|
1986
|
+
<example>
|
|
1987
|
+
User: What does the git status command do?
|
|
1988
|
+
Assistant: The git status command shows the current state of your working directory and staging area. It displays which changes have been staged, which haven't, and which files aren't being tracked by Git. This is a fundamental command for understanding the current state of your repository before making commits.
|
|
1989
|
+
|
|
1990
|
+
<reasoning>
|
|
1991
|
+
The assistant did not use the todo list because this is an informational request with no actual coding task to complete. The user is simply asking for an explanation, not for the assistant to perform multiple steps or tasks.
|
|
1992
|
+
</reasoning>
|
|
1993
|
+
</example>
|
|
1994
|
+
|
|
1995
|
+
<example>
|
|
1996
|
+
User: Can you add a comment to the calculateTotal function to explain what it does?
|
|
1997
|
+
Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does.
|
|
1998
|
+
* Uses the Edit tool to add a comment to the calculateTotal function *
|
|
1999
|
+
|
|
2000
|
+
<reasoning>
|
|
2001
|
+
The assistant did not use the todo list because this is a single, straightforward task confined to one location in the code. Adding a comment doesn't require tracking multiple steps or systematic organization.
|
|
2002
|
+
</reasoning>
|
|
2003
|
+
</example>
|
|
2004
|
+
|
|
2005
|
+
<example>
|
|
2006
|
+
User: Run npm install for me and tell me what happens.
|
|
2007
|
+
Assistant: I'll run the npm install command for you.
|
|
2008
|
+
|
|
2009
|
+
*Executes: npm install*
|
|
2010
|
+
|
|
2011
|
+
The command completed successfully. Here's the output:
|
|
2012
|
+
[Output of npm install command]
|
|
2013
|
+
|
|
2014
|
+
All dependencies have been installed according to your package.json file.
|
|
2015
|
+
|
|
2016
|
+
<reasoning>
|
|
2017
|
+
The assistant did not use the todo list because this is a single command execution with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward task.
|
|
2018
|
+
</reasoning>
|
|
2019
|
+
</example>
|
|
2020
|
+
|
|
2021
|
+
## Task States and Management
|
|
2022
|
+
|
|
2023
|
+
1. **Task States**: Use these states to track progress:
|
|
2024
|
+
- pending: Task not yet started
|
|
2025
|
+
- in_progress: Currently working on (limit to ONE task at a time)
|
|
2026
|
+
- completed: Task finished successfully
|
|
2027
|
+
- cancelled: Task no longer needed
|
|
2028
|
+
|
|
2029
|
+
2. **Task Management**:
|
|
2030
|
+
- Update task status in real-time as you work
|
|
2031
|
+
- Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
|
|
2032
|
+
- Only have ONE task in_progress at any time
|
|
2033
|
+
- Complete current tasks before starting new ones
|
|
2034
|
+
- Cancel tasks that become irrelevant
|
|
2035
|
+
|
|
2036
|
+
3. **Task Breakdown**:
|
|
2037
|
+
- Create specific, actionable items
|
|
2038
|
+
- Break complex tasks into smaller, manageable steps
|
|
2039
|
+
- Use clear, descriptive task names
|
|
2040
|
+
|
|
2041
|
+
When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.
|
|
2042
|
+
|
|
2043
|
+
`;import{Effect as vi,Layer as Af,ServiceMap as Rv}from"effect";import Rs from"zod";var js;(b=>{b.Info=Rs.object({content:Rs.string().describe("Brief description of the task"),status:Rs.string().describe("Current status of the task: pending, in_progress, completed, cancelled"),priority:Rs.string().describe("Priority level of the task: high, medium, low")}).meta({ref:"Todo"}),b.Event={Updated:mt.define("todo.updated",Rs.object({sessionID:He.zod,todos:Rs.array(b.Info)}))};class o extends Rv.Service()("@opencode/SessionTodo"){static{n(this,"Service")}}b.Service=o,b.layer=Af.effect(o,vi.gen(function*(){let d=yield*Ve.Service,s=vi.fn("Todo.update")(function*(l){yield*vi.sync(()=>Xt.transaction(g=>{g.delete(Er).where((0,We.eq)(Er.session_id,l.sessionID)).run(),l.todos.length!==0&&g.insert(Er).values(l.todos.map((u,a)=>({session_id:l.sessionID,content:u.content,status:u.status,priority:u.priority,position:a}))).run()})),yield*d.publish(b.Event.Updated,l)}),c=vi.fn("Todo.get")(function*(l){return(yield*vi.sync(()=>Xt.use(u=>u.select().from(Er).where((0,We.eq)(Er.session_id,l)).orderBy((0,We.asc)(Er.position)).all()))).map(u=>({content:u.content,status:u.status,priority:u.priority}))});return o.of({update:s,get:c})})),b.defaultLayer=b.layer.pipe(Af.provide(Ve.layer));let{runPromise:y}=Ke(o,b.defaultLayer);async function p(d){return y(s=>s.update(d))}b.update=p,n(p,"update");async function f(d){return y(s=>s.get(d))}b.get=f,n(f,"get")})(js||={});var jv=jl.object({todos:jl.array(jl.object(js.Info.shape)).describe("The updated todo list")}),Rf=Dt.defineEffect("todowrite",Cf.gen(function*(){let e=yield*js.Service;return{description:Of,parameters:jv,async execute(t,o){return await o.ask({permission:"todowrite",patterns:["*"],always:["*"],metadata:{}}),await e.update({sessionID:o.sessionID,todos:t.todos}).pipe(Cf.runPromise),{title:`${t.todos.filter(i=>i.status!=="completed").length} todos`,output:JSON.stringify(t.todos,null,2),metadata:{todos:t.todos}}}}}));import qa from"zod";import Uv from"turndown";var jf="Fetch a URL (http is upgraded to https) and return its content as markdown (default), text or html; very large pages may be summarized. Read-only. The result starts with a ready `Source:` line and its read time: a text that rests on the page ends with that line.\n";function Mv(e){let t=new AbortController,o=setTimeout(t.abort.bind(t),e);return{controller:t,signal:t.signal,clearTimeout:n(()=>globalThis.clearTimeout(o),"clearTimeout")}}n(Mv,"abortAfter");function Ms(e,...t){let o=Mv(e);return{signal:AbortSignal.any([o.signal,...t]),clearTimeout:o.clearTimeout}}n(Ms,"abortAfterAny");import{lookup as Lv}from"node:dns/promises";import{isIP as Mf}from"node:net";function Lf(e){let[t,o]=e.split(".").map(i=>Number(i));return t===0||t===10||t===127||t===100&&o>=64&&o<=127||t===169&&o===254||t===172&&o>=16&&o<=31||t===192&&o===168||t===198&&(o===18||o===19)||t>=224}n(Lf,"v4Blocked");function Nv(e){let t=e.toLowerCase();if(t==="::"||t==="::1")return!0;let o=t.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);return o?Lf(o[1]):!!(/^f[cd]/.test(t)||/^fe[89ab]/.test(t)||/^ff/.test(t))}n(Nv,"v6Blocked");function zv(e){let t=Mf(e);return t===4?Lf(e):t===6?Nv(e):!0}n(zv,"isNonPublicAddress");async function Fv(e){let t=new URL(e),o=t.hostname.replace(/^\[|\]$/g,"");if(o==="localhost"||o.endsWith(".localhost")||o.endsWith(".local")||o.endsWith(".internal"))throw new Error(`webfetch reaches the public web only; ${t.host} is on this machine or its network`);let i=Mf(o)?[o]:(await Lv(o,{all:!0})).map(m=>m.address);if(i.length===0||i.some(zv))throw new Error(`webfetch reaches the public web only; ${t.host} resolves to an address on this machine or its network`)}n(Fv,"assertPublicUrl");async function Ml(e,t,o=5){let i=e;for(let m=0;m<=o;m++){await Fv(i);let y=await fetch(i,{...t,redirect:"manual"}),p=y.headers.get("location");if(y.status>=300&&y.status<400&&p){i=new URL(p,i).toString();continue}return y}throw new Error(`webfetch stopped after ${o} redirects`)}n(Ml,"fetchPublic");var Nf=5*1024*1024,$v=30*1e3,qv=120*1e3,Uf=Dt.define("webfetch",{description:jf,parameters:qa.object({url:qa.string(),format:qa.enum(["text","markdown","html"]).default("markdown").describe("Default markdown"),timeout:qa.number().describe("Seconds, max 120").optional()}),async execute(e,t){if(!e.url.startsWith("http://")&&!e.url.startsWith("https://"))throw new Error("URL must start with http:// or https://");await t.ask({permission:"webfetch",patterns:[e.url],always:["*"],metadata:{url:e.url,format:e.format,timeout:e.timeout}});let o=Math.min((e.timeout??$v/1e3)*1e3,qv),{signal:i,clearTimeout:m}=Ms(o,t.abort),y="*/*";switch(e.format){case"markdown":y="text/markdown;q=1.0, text/x-markdown;q=0.9, text/plain;q=0.8, text/html;q=0.7, */*;q=0.1";break;case"text":y="text/plain;q=1.0, text/markdown;q=0.9, text/html;q=0.8, */*;q=0.1";break;case"html":y="text/html;q=1.0, application/xhtml+xml;q=0.9, text/plain;q=0.8, text/markdown;q=0.7, */*;q=0.1";break;default:y="text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8"}let p={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36",Accept:y,"Accept-Language":"en-US,en;q=0.9"},f;try{let h=await Ml(e.url,{signal:i,headers:p});f=h.status===403&&h.headers.get("cf-mitigated")==="challenge"?await Ml(e.url,{signal:i,headers:{...p,"User-Agent":"opencode"}}):h}finally{m()}if(!f.ok)throw new Error(`Request failed with status code: ${f.status}`);let b=f.headers.get("content-length");if(b&&parseInt(b)>Nf)throw new Error("Response too large (exceeds 5MB limit)");let d=await f.arrayBuffer();if(d.byteLength>Nf)throw new Error("Response too large (exceeds 5MB limit)");let s=f.headers.get("content-type")||"",c=s.split(";")[0]?.trim().toLowerCase()||"",l=`${e.url} (${s})`;if(c.startsWith("image/")&&c!=="image/svg+xml"&&c!=="image/vnd.fastbidsheet"){let h=Buffer.from(d).toString("base64");return{title:l,output:"Image fetched successfully",metadata:{},attachments:[{type:"file",mime:c,url:`data:${c};base64,${h}`}]}}let u=new TextDecoder().decode(d),a=s.includes("text/html"),w=f.url||e.url,I=a?Bv(u):c.includes("markdown")?(/^#\s+(.+)$/m.exec(u.slice(0,2e3))?.[1]??"").trim().slice(0,200):"",r={status:f.status,finalUrl:w,...I?{title:I}:{}},x=Wv(I,w,f.status);switch(e.format){case"markdown":return{output:`${x}
|
|
2044
|
+
|
|
2045
|
+
${a?Vv(u):u}`,title:l,metadata:r};case"text":return{output:`${x}
|
|
2046
|
+
|
|
2047
|
+
${a?$f(u):u}`,title:l,metadata:r};default:return{output:u,title:l,metadata:r}}}});function Bv(e){let t=/<title\b[^>]*>([\s\S]*?)<\/title\s*>/i.exec(e);return t?$f(t[1]).replace(/\s+/g," ").trim().slice(0,200):""}n(Bv,"titleOfHTML");function Wv(e,t,o,i=new Date){return`Source: [${(e||t).replace(/[\[\]]/g,"")}](${t})
|
|
2048
|
+
Read: ${i.toISOString().slice(0,16).replace("T"," ")} UTC, HTTP ${o}`}n(Wv,"sourceHead");var Hv=/<(script|style|noscript|iframe|object|embed|template|svg|head)\b[^>]*>[\s\S]*?<\/\1\s*>/gi,Gv=/<\/?(p|div|br|hr|li|ul|ol|tr|table|thead|tbody|h[1-6]|section|article|header|footer|nav|main|aside|pre|blockquote|dl|dt|dd|figure|figcaption|form|title)\b[^>]*>/gi,zf={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",ndash:"\u2013",mdash:"\u2014",hellip:"\u2026",copy:"\xA9",reg:"\xAE",trade:"\u2122",euro:"\u20AC",pound:"\xA3",laquo:"\xAB",raquo:"\xBB",middot:"\xB7",bull:"\u2022",lsquo:"\u2018",rsquo:"\u2019",ldquo:"\u201C",rdquo:"\u201D",times:"\xD7",deg:"\xB0",rarr:"\u2192",larr:"\u2190"};function Ff(e,t){return Number.isInteger(e)&&e>0&&e<=1114111&&!(e>=55296&&e<=57343)?String.fromCodePoint(e):t}n(Ff,"codePoint");function $f(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(Hv," ").replace(/<t[dh]\b[^>]*>/gi," ").replace(Gv,`
|
|
2049
|
+
`).replace(/<[^>]*>/g,"").replace(/&(?:#(\d+)|#x([0-9a-f]+)|([a-z][a-z0-9]*));/gi,(t,o,i,m)=>o?Ff(Number(o),t):i?Ff(parseInt(i,16),t):zf[m]??zf[m.toLowerCase()]??t).replace(/[ \t\f\v ]+/g," ").replace(/ ?\n ?/g,`
|
|
2050
|
+
`).replace(/\n{3,}/g,`
|
|
2051
|
+
|
|
2052
|
+
`).trim()}n($f,"extractTextFromHTML");function Vv(e){let t=new Uv({headingStyle:"atx",hr:"---",bulletListMarker:"-",codeBlockStyle:"fenced",emDelimiter:"*"});return t.remove(["script","style","meta","link"]),t.turndown(e)}n(Vv,"convertHTMLToMarkdown");import Ll from"zod";import*as Jr from"path";import{createTwoFilesPatch as Jv}from"diff";var qf=`Writes a file to the local filesystem.
|
|
2053
|
+
|
|
2054
|
+
Usage:
|
|
2055
|
+
- This tool will overwrite the existing file if there is one at the provided path.
|
|
2056
|
+
- If this is an existing file, you MUST use the Read tool first to read the file's contents. This tool will fail if you did not read the file first.
|
|
2057
|
+
- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.
|
|
2058
|
+
- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.
|
|
2059
|
+
- Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked.
|
|
2060
|
+
`;var Nl=20,Yv=5,Bf=Dt.define("write",{description:qf,parameters:Ll.object({content:Ll.string().describe("The content to write to the file"),filePath:Ll.string().describe("The absolute path to the file to write (must be absolute, not relative)")}),async execute(e,t){let o=Jr.isAbsolute(e.filePath)?e.filePath:Jr.join(he.directory,e.filePath);await Zn(t,o);let i=await Ee.exists(o),m=i?await Ee.readText(o):"";i&&await Nn.assert(t.sessionID,o);let y=er(Jv(o,o,m,e.content));await t.ask({permission:"edit",patterns:[Jr.relative(he.worktree,o)],always:["*"],metadata:{filepath:o,diff:y}}),await Ee.write(o,e.content),await xr.file(o),Ve.publish(br.Event.Edited,{file:o}),await Ve.publish(wr.Event.Updated,{file:o,event:i?"change":"add"}),await Nn.read(t.sessionID,o);let p="Wrote file successfully.";await Pt.touchFile(o,!0);let f=await Pt.diagnostics(),b=Ee.normalizePath(o),d=0;for(let[s,c]of Object.entries(f)){let l=c.filter(a=>a.severity===1);if(l.length===0)continue;let g=l.slice(0,Nl),u=l.length>Nl?`
|
|
2061
|
+
... and ${l.length-Nl} more`:"";if(s===b){p+=`
|
|
2062
|
+
|
|
2063
|
+
LSP errors detected in this file, please fix:
|
|
2064
|
+
<diagnostics file="${o}">
|
|
2065
|
+
${g.map(Pt.Diagnostic.pretty).join(`
|
|
2066
|
+
`)}${u}
|
|
2067
|
+
</diagnostics>`;continue}d>=Yv||(d++,p+=`
|
|
2068
|
+
|
|
2069
|
+
LSP errors detected in other files:
|
|
2070
|
+
<diagnostics file="${s}">
|
|
2071
|
+
${g.map(Pt.Diagnostic.pretty).join(`
|
|
2072
|
+
`)}${u}
|
|
2073
|
+
</diagnostics>`)}return{title:Jr.relative(he.worktree,o),metadata:{diagnostics:f,filepath:o,exists:i},output:p}}});import zl from"zod";var Wf=Dt.define("invalid",{description:"Do not use",parameters:zl.object({tool:zl.string(),error:zl.string()}),async execute(e){return{title:"Invalid Tool",output:`The arguments provided to the tool are invalid: ${e.error}`,metadata:{}}}});import Hf from"path";import{pathToFileURL as Kv}from"url";import Gf from"zod";var Vf=Dt.define("skill",async e=>{let t=await Bn.available(e?.agent),o=t.length===0?"Load a specialized skill that provides domain-specific instructions and workflows. No skills are currently available.":["Load a specialized skill that provides domain-specific instructions and workflows.","","When you recognize that a task matches one of the available skills listed below, use this tool to load the full skill instructions.","","The skill will inject detailed instructions, workflows, and access to bundled resources (scripts, references, templates) into the conversation context.","",'Tool output includes a `<skill_content name="...">` block with the loaded content.',"","The following skills provide specialized sets of instructions for particular tasks","Invoke this tool to load a skill when a task matches one of the available skills listed below:","",Bn.fmt(t,{verbose:!1})].join(`
|
|
2074
|
+
`),i=t.map(p=>`'${p.name}'`).slice(0,3).join(", "),m=i.length>0?` (e.g., ${i}, ...)`:"",y=Gf.object({name:Gf.string().describe(`The name of the skill from available_skills${m}`)});return{description:o,parameters:y,async execute(p,f){let b=await Bn.get(p.name);if(!b){let g=await Bn.all().then(u=>u.map(a=>a.name).join(", "));throw new Error(`Skill "${p.name}" not found. Available skills: ${g||"none"}`)}await f.ask({permission:"skill",patterns:[p.name],always:[p.name],metadata:{}});let d=Hf.dirname(b.location),s=Kv(d).href,c=10,l=await qt(async()=>{let g=[];for await(let u of Ko.files({cwd:d,follow:!1,hidden:!0,signal:f.abort}))if(!u.includes("SKILL.md")&&(g.push(Hf.resolve(d,u)),g.length>=c))break;return g}).then(g=>g.map(u=>`<file>${u}</file>`).join(`
|
|
2075
|
+
`));return{title:`Loaded skill: ${b.name}`,output:[`<skill_content name="${b.name}">`,`# Skill: ${b.name}`,"",b.content.trim(),"",`Base directory for this skill: ${s}`,"Relative paths in this skill (e.g., scripts/, reference/) are relative to this base directory.","Note: file list is sampled.","","<skill_files>",l,"</skill_files>","</skill_content>"].join(`
|
|
2076
|
+
`),metadata:{name:b.name,dir:d}}}}});import fm from"path";import lI from"zod";import Ls from"zod";var Jf=`Search the web and return summaries of the most relevant pages: current information beyond your knowledge cutoff. The current year is {{year}}: use it when searching for recent information. Summaries are not pages read: say which claims rest only on them.
|
|
2077
|
+
`;var Yf={exa:"websearch-exa",tavily:"websearch-tavily"},Xv="https://mcp.exa.ai/mcp",Zv="https://api.tavily.com/search",Zf=8,Qv=1e4,eI=25e3,Qf=6e4,em=10*6e4,Fl={"exa-key":"Exa",tavily:"Tavily",exa:"Exa, no key"},Yr=class extends Error{constructor(o){super("rate-limited");this.waitMs=o}waitMs;static{n(this,"RateLimited")}},Ii=class extends Error{constructor(o){super(`key refused (HTTP ${o})`);this.status=o}status;static{n(this,"KeyRefused")}},Ba=new Map;function tm(e){let t=Number(e.headers.get("retry-after"));return Number.isFinite(t)&&t>0?Math.min(t*1e3,em):Qf}n(tm,"waitFrom");function tI(e){let t=[],o=/^Title: (.*)\r?\nURL: (\S+)/gm;for(let i=o.exec(e);i;i=o.exec(e))t.push({title:i[1].trim(),url:i[2].trim()});return t}n(tI,"hitsIn");async function Kf(e,t,o){let i=await fetch(Xv,{method:"POST",headers:{accept:"application/json, text/event-stream","content-type":"application/json",...t?{"x-api-key":t}:{}},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"web_search_exa",arguments:{query:e.query,type:e.type||"auto",numResults:e.numResults||Zf,livecrawl:e.livecrawl||"fallback",contextMaxCharacters:e.contextMaxCharacters}}}),signal:o});if(i.status===429)throw new Yr(tm(i));if(t&&(i.status===401||i.status===403))throw new Ii(i.status);if(!i.ok)throw new Error(`Search error (${i.status}): ${await i.text()}`);for(let m of(await i.text()).split(`
|
|
2078
|
+
`)){if(!m.startsWith("data: "))continue;let y=JSON.parse(m.substring(6));if(y.result?._meta?.["ai.exa/rateLimited"])throw new Yr(Qf);if(y.result?.isError)throw new Error(`Search failed: ${y.result.content?.[0]?.text??"the search service reported an error"}`);let p=y.result?.content?.[0]?.text;if(p)return p}return""}n(Kf,"searchExa");async function nI(e,t,o){let i=await fetch(Zv,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},body:JSON.stringify({query:e.query,max_results:Math.min(e.numResults||Zf,20),search_depth:e.type==="fast"?"fast":"basic",include_published_date:!0}),signal:o});if(i.status===429)throw new Yr(tm(i));if(i.status===432||i.status===433)throw new Yr(em);if(i.status===401||i.status===403)throw new Ii(i.status);if(!i.ok)throw new Error(`Search error (${i.status}): ${await i.text()}`);let m=await i.json(),y=e.contextMaxCharacters||Qv,p=(m.results??[]).filter(b=>b.url),f=Math.max(200,Math.floor(y/Math.max(p.length,1)));return p.map(b=>`Title: ${(b.title??"").trim()||b.url}
|
|
2079
|
+
URL: ${b.url}
|
|
2080
|
+
Published: ${b.published_date||"N/A"}
|
|
2081
|
+
Author: N/A
|
|
2082
|
+
Highlights:
|
|
2083
|
+
${(b.content??"").trim().slice(0,f)}`).join(`
|
|
2084
|
+
|
|
2085
|
+
---
|
|
2086
|
+
|
|
2087
|
+
`)}n(nI,"searchTavily");async function Xf(e){let t=await Fn.get(e).catch(()=>{});return t?.type==="api"&&t.key.trim()?t.key.trim():void 0}n(Xf,"keyOf");function oI(e){let t=Math.max(1,Math.ceil(e/1e3));return t<90?`about ${t} seconds`:`about ${Math.ceil(t/60)} minutes`}n(oI,"waitWords");async function rI(e,t,o=Date.now){let i={exa:await Xf(Yf.exa),tavily:await Xf(Yf.tavily)},m=[...i.exa?[{backend:"exa-key",run:n(c=>Kf(e,i.exa,c),"run")}]:[],...i.tavily?[{backend:"tavily",run:n(c=>nI(e,i.tavily,c),"run")}]:[],{backend:"exa",run:n(c=>Kf(e,void 0,c),"run")}],y=[i.exa,i.tavily].filter(c=>!!c),p=n(c=>y.reduce((l,g)=>l.split(g).join("[key]"),c),"clean"),f=[],b,d=0;for(let{backend:c,run:l}of m){if((Ba.get(c)??0)>o()){d++;continue}let{signal:g,clearTimeout:u}=Ms(eI,t);try{let a=await l(g);return Ba.delete(c),{text:a,backend:c,refused:f}}catch(a){if(t.aborted)throw a;a instanceof Yr?(Ba.set(c,o()+a.waitMs),d++):a instanceof Ii?f.push(`${Fl[c]} (HTTP ${a.status})`):a instanceof Error&&a.name==="AbortError"?b=new Error(`Search request timed out (${Fl[c]})`):b=new Error(p(a instanceof Error?a.message:String(a)))}finally{u()}}let s=f.length?` The search key in Settings was refused: ${f.join(", ")}.`:"";if(d>0&&!b){let c=Math.min(...m.map(l=>Ba.get(l.backend)??1/0).filter(l=>l>o()))-o();throw new Error(`Search is rate-limited for the moment. Nothing was searched. Search again in ${oI(c)}, or open a page you already know.`+(y.length?"":" Free search allows a few searches a minute; a search key of the user's own (Settings, Providers) lifts the limit.")+s)}throw new Error(`${b?.message??"Search failed"}${s}`)}n(rI,"runSearch");var nm=Dt.define("websearch",async()=>({get description(){return Jf.replace("{{year}}",new Date().getFullYear().toString())},parameters:Ls.object({query:Ls.string().describe("Websearch query"),numResults:Ls.number().optional().describe("Default 8"),livecrawl:Ls.enum(["fallback","preferred"]).optional().describe("Live crawling as a fallback for uncached pages (default) or preferred"),type:Ls.enum(["auto","fast","deep"]).optional().describe("Default auto"),contextMaxCharacters:Ls.number().optional().describe("Default 10000")}),async execute(e,t){await t.ask({permission:"websearch",patterns:[e.query],always:["*"],metadata:{query:e.query,numResults:e.numResults,livecrawl:e.livecrawl,type:e.type,contextMaxCharacters:e.contextMaxCharacters}});let o=await rI(e,t.abort),i=tI(o.text),m=o.refused.length?`
|
|
2088
|
+
|
|
2089
|
+
Note for the user: the search key in Settings was refused (${o.refused.join(", ")}); this search ran without it.`:"",y=`Search results (${Fl[o.backend]}, ${new Date().toISOString().slice(0,16).replace("T"," ")} UTC). These are summaries; a page is read only when you open it.`;return{output:i.length||o.text?`${y}
|
|
2090
|
+
|
|
2091
|
+
${o.text}${m}`:`No search results found. Please try a different query.${m}`,title:`Web search: ${e.query}`,metadata:{backend:o.backend,resultCount:i.length,hits:i.slice(0,8)}}}}));import Ul from"zod";var om=`- Search and get relevant context for any programming task using Exa Code API
|
|
2092
|
+
- Provides the highest quality and freshest context for libraries, SDKs, and APIs
|
|
2093
|
+
- Use this tool for ANY question or task related to programming
|
|
2094
|
+
- Returns comprehensive code examples, documentation, and API references
|
|
2095
|
+
- Optimized for finding specific programming patterns and solutions
|
|
2096
|
+
|
|
2097
|
+
Usage notes:
|
|
2098
|
+
- Adjustable token count (1000-50000) for focused or comprehensive results
|
|
2099
|
+
- Default 5000 tokens provides balanced context for most queries
|
|
2100
|
+
- Use lower values for specific questions, higher values for comprehensive documentation
|
|
2101
|
+
- Supports queries about frameworks, libraries, APIs, and programming concepts
|
|
2102
|
+
- Examples: 'React useState hook examples', 'Python pandas dataframe filtering', 'Express.js middleware'
|
|
2103
|
+
`;var rm={BASE_URL:"https://mcp.exa.ai",ENDPOINTS:{CONTEXT:"/mcp"}},sm=Dt.define("codesearch",{description:om,parameters:Ul.object({query:Ul.string().describe("Search query to find relevant context for APIs, Libraries, and SDKs. For example, 'React useState hook examples', 'Python pandas dataframe filtering', 'Express.js middleware', 'Next js partial prerendering configuration'"),tokensNum:Ul.number().min(1e3).max(5e4).default(5e3).describe("Number of tokens to return (1000-50000). Default is 5000 tokens. Adjust this value based on how much context you need - use lower values for focused queries and higher values for comprehensive documentation.")}),async execute(e,t){await t.ask({permission:"codesearch",patterns:[e.query],always:["*"],metadata:{query:e.query,tokensNum:e.tokensNum}});let o={jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"get_code_context_exa",arguments:{query:e.query,tokensNum:e.tokensNum||5e3}}},{signal:i,clearTimeout:m}=Ms(3e4,t.abort);try{let y={accept:"application/json, text/event-stream","content-type":"application/json"},p=await fetch(`${rm.BASE_URL}${rm.ENDPOINTS.CONTEXT}`,{method:"POST",headers:y,body:JSON.stringify(o),signal:i});if(m(),!p.ok){let d=await p.text();throw new Error(`Code search error (${p.status}): ${d}`)}let b=(await p.text()).split(`
|
|
2104
|
+
`);for(let d of b)if(d.startsWith("data: ")){let s=JSON.parse(d.substring(6));if(s.result&&s.result.content&&s.result.content.length>0)return{output:s.result.content[0].text,title:`Code search: ${e.query}`,metadata:{}}}return{output:"No code snippets or documentation found. Please try a different query, be more specific about the library or programming concept, or check the spelling of framework names.",title:`Code search: ${e.query}`,metadata:{}}}catch(y){throw m(),y instanceof Error&&y.name==="AbortError"?new Error("Code search request timed out"):y}}});import ki from"zod";import $l from"path";var im=`Interact with Language Server Protocol (LSP) servers to get code intelligence features.
|
|
2105
|
+
|
|
2106
|
+
Supported operations:
|
|
2107
|
+
- goToDefinition: Find where a symbol is defined
|
|
2108
|
+
- findReferences: Find all references to a symbol
|
|
2109
|
+
- hover: Get hover information (documentation, type info) for a symbol
|
|
2110
|
+
- documentSymbol: Get all symbols (functions, classes, variables) in a document
|
|
2111
|
+
- workspaceSymbol: Search for symbols across the entire workspace
|
|
2112
|
+
- goToImplementation: Find implementations of an interface or abstract method
|
|
2113
|
+
- prepareCallHierarchy: Get call hierarchy item at a position (functions/methods)
|
|
2114
|
+
- incomingCalls: Find all functions/methods that call the function at a position
|
|
2115
|
+
- outgoingCalls: Find all functions/methods called by the function at a position
|
|
2116
|
+
|
|
2117
|
+
All operations require:
|
|
2118
|
+
- filePath: The file to operate on
|
|
2119
|
+
- line: The line number (1-based, as shown in editors)
|
|
2120
|
+
- character: The character offset (1-based, as shown in editors)
|
|
2121
|
+
|
|
2122
|
+
Note: LSP servers must be configured for the file type. If no server is available, an error will be returned.
|
|
2123
|
+
`;import{pathToFileURL as sI}from"url";var iI=["goToDefinition","findReferences","hover","documentSymbol","workspaceSymbol","goToImplementation","prepareCallHierarchy","incomingCalls","outgoingCalls"],am=Dt.define("lsp",{description:im,parameters:ki.object({operation:ki.enum(iI).describe("The LSP operation to perform"),filePath:ki.string().describe("The absolute or relative path to the file"),line:ki.number().int().min(1).describe("The line number (1-based, as shown in editors)"),character:ki.number().int().min(1).describe("The character offset (1-based, as shown in editors)")}),execute:n(async(e,t)=>{let o=$l.isAbsolute(e.filePath)?e.filePath:$l.join(he.directory,e.filePath);await Zn(t,o),await t.ask({permission:"lsp",patterns:["*"],always:["*"],metadata:{}});let i=sI(o).href,m={file:o,line:e.line-1,character:e.character-1},y=$l.relative(he.worktree,o),p=`${e.operation} ${y}:${e.line}:${e.character}`;if(!await Ee.exists(o))throw new Error(`File not found: ${o}`);if(!await Pt.hasClients(o))throw new Error("No LSP server available for this file type.");await Pt.touchFile(o,!0);let d=await(async()=>{switch(e.operation){case"goToDefinition":return Pt.definition(m);case"findReferences":return Pt.references(m);case"hover":return Pt.hover(m);case"documentSymbol":return Pt.documentSymbol(i);case"workspaceSymbol":return Pt.workspaceSymbol("");case"goToImplementation":return Pt.implementation(m);case"prepareCallHierarchy":return Pt.prepareCallHierarchy(m);case"incomingCalls":return Pt.incomingCalls(m);case"outgoingCalls":return Pt.outgoingCalls(m)}})(),s=d.length===0?`No results found for ${e.operation}`:JSON.stringify(d,null,2);return{title:p,metadata:{result:d},output:s}},"execute")});import dm from"zod";import*as io from"path";import*as Jn from"fs/promises";import cm from"zod";import*as tr from"path";import*as xo from"fs/promises";import{readFileSync as aI}from"fs";var Wa;(v=>{let e=qe.create({service:"patch"});v.PatchSchema=cm.object({patchText:cm.string().describe("The full patch text that describes all changes to be made")});let o;(E=>(E.ParseError="ParseError",E.IoError="IoError",E.ComputeReplacements="ComputeReplacements",E.ImplicitInvocation="ImplicitInvocation"))(o=v.ApplyPatchError||={});let i;(E=>(E.Body="Body",E.ShellParseError="ShellParseError",E.PatchParseError="PatchParseError",E.NotApplyPatch="NotApplyPatch"))(i=v.MaybeApplyPatch||={});let m;(E=>(E.Body="Body",E.ShellParseError="ShellParseError",E.CorrectnessError="CorrectnessError",E.NotApplyPatch="NotApplyPatch"))(m=v.MaybeApplyPatchVerified||={});function y(S,j){let O=S[j];if(O.startsWith("*** Add File:")){let k=O.slice(13).trim();return k?{filePath:k,nextIdx:j+1}:null}if(O.startsWith("*** Delete File:")){let k=O.slice(16).trim();return k?{filePath:k,nextIdx:j+1}:null}if(O.startsWith("*** Update File:")){let k=O.slice(16).trim(),E,D=j+1;return D<S.length&&S[D].startsWith("*** Move to:")&&(E=S[D].slice(12).trim(),D++),k?{filePath:k,movePath:E,nextIdx:D}:null}return null}n(y,"parsePatchHeader");function p(S,j){let O=[],k=j;for(;k<S.length&&!S[k].startsWith("***");)if(S[k].startsWith("@@")){let E=S[k].substring(2).trim();k++;let D=[],z=[],_=!1;for(;k<S.length&&!S[k].startsWith("@@")&&!S[k].startsWith("***");){let B=S[k];if(B==="*** End of File"){_=!0,k++;break}if(B.startsWith(" ")){let $=B.substring(1);D.push($),z.push($)}else B.startsWith("-")?D.push(B.substring(1)):B.startsWith("+")&&z.push(B.substring(1));k++}O.push({old_lines:D,new_lines:z,change_context:E||void 0,is_end_of_file:_||void 0})}else k++;return{chunks:O,nextIdx:k}}n(p,"parseUpdateFileChunks");function f(S,j){let O="",k=j;for(;k<S.length&&!S[k].startsWith("***");)S[k].startsWith("+")&&(O+=S[k].substring(1)+`
|
|
2124
|
+
`),k++;return O.endsWith(`
|
|
2125
|
+
`)&&(O=O.slice(0,-1)),{content:O,nextIdx:k}}n(f,"parseAddFileContent");function b(S){let j=S.match(/^(?:cat\s+)?<<['"]?(\w+)['"]?\s*\n([\s\S]*?)\n\1\s*$/);return j?j[2]:S}n(b,"stripHeredoc");function d(S){let O=b(S.trim()).split(`
|
|
2126
|
+
`),k=[],E=0,D="*** Begin Patch",z="*** End Patch",_=O.findIndex($=>$.trim()===D),B=O.findIndex($=>$.trim()===z);if(_===-1||B===-1||_>=B)throw new Error("Invalid patch format: missing Begin/End markers");for(E=_+1;E<B;){let $=y(O,E);if(!$){E++;continue}if(O[E].startsWith("*** Add File:")){let{content:M,nextIdx:C}=f(O,$.nextIdx);k.push({type:"add",path:$.filePath,contents:M}),E=C}else if(O[E].startsWith("*** Delete File:"))k.push({type:"delete",path:$.filePath}),E=$.nextIdx;else if(O[E].startsWith("*** Update File:")){let{chunks:M,nextIdx:C}=p(O,$.nextIdx);k.push({type:"update",path:$.filePath,move_path:$.movePath,chunks:M}),E=C}else E++}return{hunks:k}}v.parsePatch=d,n(d,"parsePatch");function s(S){let j=["apply_patch","applypatch"];if(S.length===2&&j.includes(S[0]))try{let{hunks:O}=d(S[1]);return{type:"Body",args:{patch:S[1],hunks:O}}}catch(O){return{type:"PatchParseError",error:O}}if(S.length===3&&S[0]==="bash"&&S[1]==="-lc"){let k=S[2].match(/apply_patch\s*<<['"](\w+)['"]\s*\n([\s\S]*?)\n\1/);if(k){let E=k[2];try{let{hunks:D}=d(E);return{type:"Body",args:{patch:E,hunks:D}}}catch(D){return{type:"PatchParseError",error:D}}}}return{type:"NotApplyPatch"}}v.maybeParseApplyPatch=s,n(s,"maybeParseApplyPatch");function c(S,j){let O;try{O=aI(S,"utf-8")}catch(B){throw new Error(`Failed to read file ${S}: ${B}`)}let k=O.split(`
|
|
2127
|
+
`);k.length>0&&k[k.length-1]===""&&k.pop();let E=l(k,S,j),D=g(k,E);(D.length===0||D[D.length-1]!=="")&&D.push("");let z=D.join(`
|
|
2128
|
+
`);return{unified_diff:I(O,z),content:z}}v.deriveNewContentsFromChunks=c,n(c,"deriveNewContentsFromChunks");function l(S,j,O){let k=[],E=0;for(let D of O){if(D.change_context){let $=w(S,[D.change_context],E);if($===-1)throw new Error(`Failed to find context '${D.change_context}' in ${j}`);E=$+1}if(D.old_lines.length===0){let $=S.length>0&&S[S.length-1]===""?S.length-1:S.length;k.push([$,0,D.new_lines]);continue}let z=D.old_lines,_=D.new_lines,B=w(S,z,E,D.is_end_of_file);if(B===-1&&z.length>0&&z[z.length-1]===""&&(z=z.slice(0,-1),_.length>0&&_[_.length-1]===""&&(_=_.slice(0,-1)),B=w(S,z,E,D.is_end_of_file)),B!==-1)k.push([B,z.length,_]),E=B+z.length;else throw new Error(`Failed to find expected lines in ${j}:
|
|
2129
|
+
${D.old_lines.join(`
|
|
2130
|
+
`)}`)}return k.sort((D,z)=>D[0]-z[0]),k}n(l,"computeReplacements");function g(S,j){let O=[...S];for(let k=j.length-1;k>=0;k--){let[E,D,z]=j[k];O.splice(E,D);for(let _=0;_<z.length;_++)O.splice(E+_,0,z[_])}return O}n(g,"applyReplacements");function u(S){return S.replace(/[\u2018\u2019\u201A\u201B]/g,"'").replace(/[\u201C\u201D\u201E\u201F]/g,'"').replace(/[\u2010\u2011\u2012\u2013\u2014\u2015]/g,"-").replace(/\u2026/g,"...").replace(/\u00A0/g," ")}n(u,"normalizeUnicode");function a(S,j,O,k,E){if(E){let D=S.length-j.length;if(D>=O){let z=!0;for(let _=0;_<j.length;_++)if(!k(S[D+_],j[_])){z=!1;break}if(z)return D}}for(let D=O;D<=S.length-j.length;D++){let z=!0;for(let _=0;_<j.length;_++)if(!k(S[D+_],j[_])){z=!1;break}if(z)return D}return-1}n(a,"tryMatch");function w(S,j,O,k=!1){if(j.length===0)return-1;let E=a(S,j,O,(B,$)=>B===$,k);if(E!==-1)return E;let D=a(S,j,O,(B,$)=>B.trimEnd()===$.trimEnd(),k);if(D!==-1)return D;let z=a(S,j,O,(B,$)=>B.trim()===$.trim(),k);return z!==-1?z:a(S,j,O,(B,$)=>u(B.trim())===u($.trim()),k)}n(w,"seekSequence");function I(S,j){let O=S.split(`
|
|
2131
|
+
`),k=j.split(`
|
|
2132
|
+
`),E=`@@ -1 +1 @@
|
|
2133
|
+
`,D=Math.max(O.length,k.length),z=!1;for(let _=0;_<D;_++){let B=O[_]||"",$=k[_]||"";B!==$?(B&&(E+=`-${B}
|
|
2134
|
+
`),$&&(E+=`+${$}
|
|
2135
|
+
`),z=!0):B&&(E+=` ${B}
|
|
2136
|
+
`)}return z?E:""}n(I,"generateUnifiedDiff");async function r(S){if(S.length===0)throw new Error("No files were modified.");let j=[],O=[],k=[];for(let E of S)switch(E.type){case"add":let D=tr.dirname(E.path);D!=="."&&D!=="/"&&await xo.mkdir(D,{recursive:!0}),await xo.writeFile(E.path,E.contents,"utf-8"),j.push(E.path),e.info(`Added file: ${E.path}`);break;case"delete":await xo.unlink(E.path),k.push(E.path),e.info(`Deleted file: ${E.path}`);break;case"update":let z=c(E.path,E.chunks);if(E.move_path){let _=tr.dirname(E.move_path);_!=="."&&_!=="/"&&await xo.mkdir(_,{recursive:!0}),await xo.writeFile(E.move_path,z.content,"utf-8"),await xo.unlink(E.path),O.push(E.move_path),e.info(`Moved file: ${E.path} -> ${E.move_path}`)}else await xo.writeFile(E.path,z.content,"utf-8"),O.push(E.path),e.info(`Updated file: ${E.path}`);break}return{added:j,modified:O,deleted:k}}v.applyHunksToFiles=r,n(r,"applyHunksToFiles");async function x(S){let{hunks:j}=d(S);return r(j)}v.applyPatch=x,n(x,"applyPatch");async function h(S,j){if(S.length===1)try{return d(S[0]),{type:"CorrectnessError",error:new Error("ImplicitInvocation")}}catch{}let O=s(S);switch(O.type){case"Body":let{args:k}=O,E=k.workdir?tr.resolve(j,k.workdir):j,D=new Map;for(let z of k.hunks){let _=tr.resolve(E,z.type==="update"&&z.move_path?z.move_path:z.path);switch(z.type){case"add":D.set(_,{type:"add",content:z.contents});break;case"delete":let B=tr.resolve(E,z.path);try{let M=await xo.readFile(B,"utf-8");D.set(_,{type:"delete",content:M})}catch{return{type:"CorrectnessError",error:new Error(`Failed to read file for deletion: ${B}`)}}break;case"update":let $=tr.resolve(E,z.path);try{let M=c($,z.chunks);D.set(_,{type:"update",unified_diff:M.unified_diff,move_path:z.move_path?tr.resolve(E,z.move_path):void 0,new_content:M.content})}catch(M){return{type:"CorrectnessError",error:M}}break}}return{type:"Body",action:{changes:D,patch:k.patch,cwd:E}};case"PatchParseError":return{type:"CorrectnessError",error:O.error};case"NotApplyPatch":return{type:"NotApplyPatch"}}}v.maybeParseApplyPatchVerified=h,n(h,"maybeParseApplyPatchVerified")})(Wa||={});import{createTwoFilesPatch as ql,diffLines as um}from"diff";var lm=`Use the \`apply_patch\` tool to edit files. Your patch language is a stripped\u2011down, file\u2011oriented diff format designed to be easy to parse and safe to apply. You can think of it as a high\u2011level envelope:
|
|
2137
|
+
|
|
2138
|
+
*** Begin Patch
|
|
2139
|
+
[ one or more file sections ]
|
|
2140
|
+
*** End Patch
|
|
2141
|
+
|
|
2142
|
+
Within that envelope, you get a sequence of file operations.
|
|
2143
|
+
You MUST include a header to specify the action you are taking.
|
|
2144
|
+
Each operation starts with one of three headers:
|
|
2145
|
+
|
|
2146
|
+
*** Add File: <path> - create a new file. Every following line is a + line (the initial contents).
|
|
2147
|
+
*** Delete File: <path> - remove an existing file. Nothing follows.
|
|
2148
|
+
*** Update File: <path> - patch an existing file in place (optionally with a rename).
|
|
2149
|
+
|
|
2150
|
+
Example patch:
|
|
2151
|
+
|
|
2152
|
+
\`\`\`
|
|
2153
|
+
*** Begin Patch
|
|
2154
|
+
*** Add File: hello.txt
|
|
2155
|
+
+Hello world
|
|
2156
|
+
*** Update File: src/app.py
|
|
2157
|
+
*** Move to: src/main.py
|
|
2158
|
+
@@ def greet():
|
|
2159
|
+
-print("Hi")
|
|
2160
|
+
+print("Hello, world!")
|
|
2161
|
+
*** Delete File: obsolete.txt
|
|
2162
|
+
*** End Patch
|
|
2163
|
+
\`\`\`
|
|
2164
|
+
|
|
2165
|
+
It is important to remember:
|
|
2166
|
+
|
|
2167
|
+
- You must include a header with your intended action (Add/Delete/Update)
|
|
2168
|
+
- You must prefix new lines with \`+\` even when creating a new file
|
|
2169
|
+
`;var cI=dm.object({patchText:dm.string().describe("The full patch text that describes all changes to be made")}),pm=Dt.define("apply_patch",{description:lm,parameters:cI,async execute(e,t){if(!e.patchText)throw new Error("patchText is required");let o;try{o=Wa.parsePatch(e.patchText).hunks}catch(l){throw new Error(`apply_patch verification failed: ${l}`)}if(o.length===0)throw e.patchText.replace(/\r\n/g,`
|
|
2170
|
+
`).replace(/\r/g,`
|
|
2171
|
+
`).trim()===`*** Begin Patch
|
|
2172
|
+
*** End Patch`?new Error("patch rejected: empty patch"):new Error("apply_patch verification failed: no hunks found");let i=[],m="";for(let l of o){let g=io.resolve(he.directory,l.path);switch(await Zn(t,g),l.type){case"add":{let a=l.contents.length===0||l.contents.endsWith(`
|
|
2173
|
+
`)?l.contents:`${l.contents}
|
|
2174
|
+
`,w=er(ql(g,g,"",a)),I=0,r=0;for(let x of um("",a))x.added&&(I+=x.count||0),x.removed&&(r+=x.count||0);i.push({filePath:g,oldContent:"",newContent:a,type:"add",diff:w,additions:I,deletions:r}),m+=w+`
|
|
2175
|
+
`;break}case"update":{let u=await Jn.stat(g).catch(()=>null);if(!u||u.isDirectory())throw new Error(`apply_patch verification failed: Failed to read file to update: ${g}`);let a=await Jn.readFile(g,"utf-8"),w=a;try{w=Wa.deriveNewContentsFromChunks(g,l.chunks).content}catch(v){throw new Error(`apply_patch verification failed: ${v}`)}let I=er(ql(g,g,a,w)),r=0,x=0;for(let v of um(a,w))v.added&&(r+=v.count||0),v.removed&&(x+=v.count||0);let h=l.move_path?io.resolve(he.directory,l.move_path):void 0;await Zn(t,h),i.push({filePath:g,oldContent:a,newContent:w,type:l.move_path?"move":"update",movePath:h,diff:I,additions:r,deletions:x}),m+=I+`
|
|
2176
|
+
`;break}case"delete":{let u=await Jn.readFile(g,"utf-8").catch(I=>{throw new Error(`apply_patch verification failed: ${I}`)}),a=er(ql(g,g,u,"")),w=u.split(`
|
|
2177
|
+
`).length;i.push({filePath:g,oldContent:u,newContent:"",type:"delete",diff:a,additions:0,deletions:w}),m+=a+`
|
|
2178
|
+
`;break}}}let y=i.map(l=>({filePath:l.filePath,relativePath:io.relative(he.worktree,l.movePath??l.filePath).replaceAll("\\","/"),type:l.type,diff:l.diff,before:l.oldContent,after:l.newContent,additions:l.additions,deletions:l.deletions,movePath:l.movePath})),p=i.map(l=>io.relative(he.worktree,l.filePath).replaceAll("\\","/"));await t.ask({permission:"edit",patterns:p,always:["*"],metadata:{filepath:p.join(", "),diff:m,files:y}});for(let l of i)Ir.assert(l.filePath,"apply_patch"),l.movePath&&Ir.assert(l.movePath,"apply_patch");let f=[];for(let l of i){let g=l.type==="delete"?void 0:l.movePath??l.filePath;switch(l.type){case"add":await Jn.mkdir(io.dirname(l.filePath),{recursive:!0}),await Jn.writeFile(l.filePath,l.newContent,"utf-8"),f.push({file:l.filePath,event:"add"});break;case"update":await Jn.writeFile(l.filePath,l.newContent,"utf-8"),f.push({file:l.filePath,event:"change"});break;case"move":l.movePath&&(await Jn.mkdir(io.dirname(l.movePath),{recursive:!0}),await Jn.writeFile(l.movePath,l.newContent,"utf-8"),await Jn.unlink(l.filePath),f.push({file:l.filePath,event:"unlink"}),f.push({file:l.movePath,event:"add"}));break;case"delete":await Jn.unlink(l.filePath),f.push({file:l.filePath,event:"unlink"});break}g&&(await xr.file(g),Ve.publish(br.Event.Edited,{file:g}))}for(let l of f)await Ve.publish(wr.Event.Updated,l);for(let l of i){if(l.type==="delete")continue;let g=l.movePath??l.filePath;await Pt.touchFile(g,!0)}let b=await Pt.diagnostics(),s=`Success. Updated the following files:
|
|
2179
|
+
${i.map(l=>{if(l.type==="add")return`A ${io.relative(he.worktree,l.filePath).replaceAll("\\","/")}`;if(l.type==="delete")return`D ${io.relative(he.worktree,l.filePath).replaceAll("\\","/")}`;let g=l.movePath??l.filePath;return`M ${io.relative(he.worktree,g).replaceAll("\\","/")}`}).join(`
|
|
2180
|
+
`)}`,c=20;for(let l of i){if(l.type==="delete")continue;let g=l.movePath??l.filePath,u=Ee.normalizePath(g),w=(b[u]??[]).filter(I=>I.severity===1);if(w.length>0){let I=w.slice(0,c),r=w.length>c?`
|
|
2181
|
+
... and ${w.length-c} more`:"";s+=`
|
|
2182
|
+
|
|
2183
|
+
LSP errors detected in ${io.relative(he.worktree,g).replaceAll("\\","/")}, please fix:
|
|
2184
|
+
<diagnostics file="${g}">
|
|
2185
|
+
${I.map(Pt.Diagnostic.pretty).join(`
|
|
2186
|
+
`)}${r}
|
|
2187
|
+
</diagnostics>`}}return{title:s,metadata:{diff:m,files:y,diagnostics:b},output:s}}});import{pathToFileURL as dI}from"url";import{Effect as vo,Layer as Uo,ServiceMap as uI}from"effect";var La;(f=>{let e=qe.create({service:"tool.registry"});class t extends uI.Service()("@opencode/ToolRegistry"){static{n(this,"Service")}}f.Service=t,f.layer=Uo.effect(t,vo.gen(function*(){let b=yield*rt.Service,d=yield*ln.Service,s=n(M=>vo.isEffect(M)?M:vo.succeed(M),"build"),c=yield*ge.make(vo.fn("ToolRegistry.state")(function*(M){let C=[];function T(F,V){return{id:F,init:n(async Y=>({parameters:lI.object(V.args),description:V.description,execute:n(async(re,ue)=>{let H={...ue,directory:M.directory,worktree:M.worktree},R=await V.execute(re,H),L=await po.output(R,{},Y?.agent);return{title:"",output:L.truncated?L.content:R,metadata:{truncated:L.truncated,outputPath:L.truncated?L.outputPath:void 0}}},"execute")}),"init")}}n(T,"fromPlugin");let N=(yield*b.directories()).flatMap(F=>co.scanSync("{tool,tools}/*.{js,ts}",{cwd:F,absolute:!0,dot:!0,symlink:!0}));N.length&&(yield*b.waitForDependencies());for(let F of N){let V=fm.basename(F,fm.extname(F)),Y=yield*vo.promise(()=>process.platform==="win32"?import(F):import(dI(F).href));for(let[re,ue]of Object.entries(Y))C.push(T(re==="default"?V:`${V}_${re}`,ue))}let A=yield*d.list();for(let F of A)for(let[V,Y]of Object.entries(F.tool??{}))C.push(T(V,Y));return{custom:C}})),l=yield*s(Wf),g=yield*s(Zp),u=yield*s(Df),a=yield*s(gf),w=yield*s(xf),I=yield*s(ff),r=yield*s(Bf),x=yield*s(_f),h=yield*s(Uf),v=yield*s(Rf),S=yield*s(nm),j=yield*s(sm),O=yield*s(Vf),k=yield*s(pm),E=yield*s(am),D=yield*s(If),z=yield*s(Jp),_=vo.fn("ToolRegistry.all")(function*(M){let C=yield*b.get(),T=!Ce.ALCHEMYLAB&&["app","cli","desktop"].includes(Ce.OPENCODE_CLIENT)||Ce.OPENCODE_ENABLE_QUESTION_TOOL;return[l,...T?[g]:[],u,a,w,I,r,x,h,v,S,j,O,k,...Ce.OPENCODE_EXPERIMENTAL_LSP_TOOL?[E]:[],...C.experimental?.batch_tool===!0?[D]:[],...Ce.OPENCODE_EXPERIMENTAL_PLAN_MODE&&!Ce.ALCHEMYLAB&&Ce.OPENCODE_CLIENT==="cli"?[z]:[],...M]}),B=vo.fn("ToolRegistry.ids")(function*(){let M=yield*ge.get(c);return(yield*_(M.custom)).map(T=>T.id)}),$=vo.fn("ToolRegistry.tools")(function*(M,C){let T=yield*ge.get(c),N=(yield*_(T.custom)).filter(A=>{if(C?.permission){let V=["write","edit","patch","multiedit","apply_patch"].includes(A.id)?"edit":A.id;try{if(lt.evaluate(V,"*",C.permission)?.action==="deny")return!1}catch{}}if(A.id==="codesearch"||A.id==="websearch")return M.providerID===Et.opencode||Ce.OPENCODE_ENABLE_EXA;let F=!!Tt.get("OPENCODE_E2E_LLM_URL")||M.modelID.includes("gpt-")&&!M.modelID.includes("oss")&&!M.modelID.includes("gpt-4");return A.id==="apply_patch"?F:A.id==="edit"||A.id==="write"?!F:!0});return yield*vo.forEach(N,vo.fnUntraced(function*(A){var re=[];try{let F=kn(re,e.time(A.id));let V=yield*vo.promise(()=>A.init({agent:C}));let Y={description:V.description,parameters:V.parameters};yield*d.trigger("tool.definition",{toolID:A.id},Y);return{id:A.id,description:Y.description,parameters:Y.parameters,execute:V.execute,formatValidationError:V.formatValidationError}}catch(ue){var H=ue,R=!0}finally{En(re,H,R)}}),{concurrency:"unbounded"})});return t.of({ids:B,named:{task:x,read:u},tools:$})})),f.defaultLayer=Uo.unwrap(vo.sync(()=>f.layer.pipe(Uo.provide(rt.defaultLayer),Uo.provide(ln.defaultLayer),Uo.provide(Eo.defaultLayer),Uo.provide(js.defaultLayer),Uo.provide(Pt.defaultLayer),Uo.provide(Nn.defaultLayer),Uo.provide(hr.defaultLayer),Uo.provide(ut.defaultLayer))));let{runPromise:m}=Ke(t,f.defaultLayer);async function y(){return m(b=>b.ids())}f.ids=y,n(y,"ids");async function p(b,d){return m(s=>s.tools(b,d))}f.tools=p,n(p,"tools")})(La||={});export{Fn as a,Yf as b,Et as c,Ut as d,jo as e,Ft as f,ir as g,Ve as h,Ni as i,ec as j,Gi as k,Ya as l,on as m,mo as n,Pt as o,$n as p,Qe as q,dr as r,da as s,yn as t,zr as u,lt as v,Bn as w,ro as x,Ko as y,Ur as z,Tr as A,Eo as B,nn as C,_a as D,br as E,wr as F,xr as G,js as H,La as I,fl as J,Br as K,Wr as L,ja as M,Vr as N,No as O,wl as P,yt as Q,rt as R,ln as S};
|