alchemylab-opencode 1.0.20 → 1.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/{chunk-T7EXROHP.js → chunk-2ANK3QEN.js} +1 -1
  2. package/dist/chunk-5FGJUXLI.js +2260 -0
  3. package/dist/{chunk-FT4RVZXD.js → chunk-735MVPNG.js} +1 -1
  4. package/dist/{chunk-A4S3BYGY.js → chunk-CZVKIDQZ.js} +1 -1
  5. package/dist/chunk-TECR6KUK.js +18 -0
  6. package/dist/chunk-WF7L36SZ.js +75 -0
  7. package/dist/{chunk-M4DCWBCO.js → chunk-X7PHY2B3.js} +1 -1
  8. package/dist/{chunk-XREX5MYM.js → chunk-YRY5Y3QL.js} +1 -1
  9. package/dist/{default-u_dwuiYb-5QQ4GXMV.js → default-u_dwuiYb-652AQZKX.js} +1 -1
  10. package/dist/{effect-QlVUlMFu-ORZ7TVO5.js → effect-QlVUlMFu-JVYEXAZL.js} +1 -1
  11. package/dist/{mcp-7UCWZJLJ.js → mcp-JSKIR2KQ.js} +1 -1
  12. package/dist/{registry-HGPZOISH.js → registry-REVWYAGR.js} +1 -1
  13. package/dist/{run-DYJ5YKU4.js → run-CPHBVDZ4.js} +1 -1
  14. package/dist/run.js +1 -1
  15. package/dist/serve.js +1 -1
  16. package/dist/{server-VKRBP2QM.js → server-VHCQ5HOC.js} +1 -1
  17. package/dist/{session-Z4P4Y6MB.js → session-5BXSPMPJ.js} +1 -1
  18. package/dist/{share-next-WZUJANDA.js → share-next-GSWCSZSC.js} +1 -1
  19. package/dist/{sury-CWZTCd75-IXNCX752.js → sury-CWZTCd75-3YHH6KVI.js} +1 -1
  20. package/dist/{valibot--1zFm7rT-SSCP4J5I.js → valibot--1zFm7rT-FSYJNYJ6.js} +1 -1
  21. package/dist/{valibot-D_HTw1Gn-KPCJMJMC.js → valibot-D_HTw1Gn-E5NKVIOV.js} +1 -1
  22. package/dist/{worktree-5JVGPJ42.js → worktree-HPW4CL36.js} +1 -1
  23. package/dist/{zod-Bwrt9trS-BYLM45IZ.js → zod-Bwrt9trS-HVDOFWRP.js} +1 -1
  24. package/dist/{zod-DSgpEGAE-T3VJY2W3.js → zod-DSgpEGAE-DSH6V7MG.js} +1 -1
  25. package/package.json +1 -1
  26. package/dist/chunk-BYJU35KA.js +0 -18
  27. package/dist/chunk-QRUX5DYI.js +0 -75
  28. package/dist/chunk-UO2AIECR.js +0 -2214
  29. /package/dist/{arktype-aI7TBD0R-ETU7X65Q.js → arktype-aI7TBD0R-TFNARRIP.js} +0 -0
  30. /package/dist/{chunk-T6MY2WE4.js → chunk-FXLFZ5DL.js} +0 -0
  31. /package/dist/{chunk-BGADAZN4.js → chunk-PWFRMDDF.js} +0 -0
  32. /package/dist/{typebox-Dei93FPO-K67WT2FO.js → typebox-Dei93FPO-GLI7OCTY.js} +0 -0
@@ -9,7 +9,7 @@ if (typeof globalThis.Bun === 'undefined') {
9
9
  if (typeof globalThis.__name === 'undefined') { globalThis.__name = (t, n) => { Object.defineProperty(t, 'name', { value: n, configurable: true }); return t; }; }
10
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
11
 
12
- import{a as Me}from"./chunk-M4DCWBCO.js";import{B as le,D as Ue,F as ze,c as pe,e as O,f as De,g as Be,w as Ge,x as Z,y as Le}from"./chunk-UO2AIECR.js";import{c as fe,n as V}from"./chunk-QRUX5DYI.js";import{B as Y,a as Q,d as D,h as S,j as Ce,k as ae,m as de,s as q,u as Re,v as A,w as Pe,y as T,z as g}from"./chunk-N7PLTD3P.js";import{d as je,e as z}from"./chunk-M4CB72HE.js";import{a as m}from"./chunk-MBZTOEAD.js";import p from"zod";import{Effect as h,Layer as ee,ServiceMap as Ke,Stream as Ae}from"effect";import Qe from"path";import $ from"zod";var ue;(P=>{let E=z.create({service:"vcs"}),G=m(d=>d?d.endsWith(`
12
+ import{a as Me}from"./chunk-X7PHY2B3.js";import{B as le,E as Ue,G as ze,c as pe,e as O,f as De,g as Be,w as Ge,x as Z,y as Le}from"./chunk-5FGJUXLI.js";import{c as fe,n as V}from"./chunk-WF7L36SZ.js";import{B as Y,a as Q,d as D,h as S,j as Ce,k as ae,m as de,s as q,u as Re,v as A,w as Pe,y as T,z as g}from"./chunk-N7PLTD3P.js";import{d as je,e as z}from"./chunk-M4CB72HE.js";import{a as m}from"./chunk-MBZTOEAD.js";import p from"zod";import{Effect as h,Layer as ee,ServiceMap as Ke,Stream as Ae}from"effect";import Qe from"path";import $ from"zod";var ue;(P=>{let E=z.create({service:"vcs"}),G=m(d=>d?d.endsWith(`
13
13
  `)?d.slice(0,-1).split(`
14
14
  `).length:d.split(`
15
15
  `).length:0,"count"),te=h.fnUntraced(function*(d,s,u){let r=Qe.join(s,u);if(!(yield*d.exists(r).pipe(h.orDie)))return"";let i=yield*d.readFile(r).pipe(h.catch(()=>h.succeed(new Uint8Array)));return Buffer.from(i).includes(0)?"":Buffer.from(i).toString("utf8")}),re=m(d=>new Map(d.map(s=>[s.file,{additions:s.additions,deletions:s.deletions}])),"nums"),me=m((...d)=>{let s=new Map;return d.flat().forEach(u=>{s.has(u.file)||s.set(u.file,u)}),[...s.values()]},"merge"),J=h.fnUntraced(function*(d,s,u,r,i,a){let w=r?yield*s.prefix(u):"";return(yield*h.forEach(i,y=>h.gen(function*(){let x=y.status==="added"||!r?"":yield*s.show(u,r,y.file,w),j=y.status==="deleted"?"":yield*te(d,u,y.file),K=a.get(y.file);return{file:y.file,before:x,after:j,additions:K?.additions??(y.status==="added"?G(j):0),deletions:K?.deletions??(y.status==="deleted"?G(x):0),status:y.status}}),{concurrency:8})).toSorted((y,x)=>y.file.localeCompare(x.file))}),W=h.fnUntraced(function*(d,s,u,r){if(!r)return yield*J(d,s,u,r,yield*s.status(u),new Map);let[i,a]=yield*h.all([s.status(u),s.stats(u,r)],{concurrency:2});return yield*J(d,s,u,r,i,re(a))}),ne=h.fnUntraced(function*(d,s,u,r){let[i,a,w]=yield*h.all([s.diff(u,r),s.stats(u,r),s.status(u)],{concurrency:3});return yield*J(d,s,u,r,me(i,w.filter(F=>F.code==="??")),re(a))});P.Mode=$.enum(["git","branch"]),P.Event={BranchUpdated:q.define("vcs.branch.updated",$.object({branch:$.string().optional()}))},P.Info=$.object({branch:$.string().optional(),default_branch:$.string().optional()}).meta({ref:"VcsInfo"});class I extends Ke.Service()("@opencode/Vcs"){static{m(this,"Service")}}P.Service=I,P.layer=ee.effect(I,h.gen(function*(){let d=yield*A.Service,s=yield*O.Service,u=yield*V.Service,r=yield*S.make(h.fn("Vcs.state")(i=>h.gen(function*(){if(i.project.vcs!=="git")return{current:void 0,root:void 0};let a=h.fnUntraced(function*(){return yield*s.branch(i.directory)}),[w,F]=yield*h.all([s.branch(i.directory),s.defaultBranch(i.directory)],{concurrency:2}),y={current:w,root:F};return E.info("initialized",{branch:y.current,default_branch:y.root?.name}),yield*u.subscribe(Z.Event.Updated).pipe(Ae.filter(x=>x.properties.file.endsWith("HEAD")),Ae.runForEach(x=>h.gen(function*(){let j=yield*a();j!==y.current&&(E.info("branch changed",{from:y.current,to:j}),y.current=j,yield*u.publish(P.Event.BranchUpdated,{branch:j}))})),h.forkScoped),y})));return I.of({init:h.fn("Vcs.init")(function*(){yield*S.get(r)}),branch:h.fn("Vcs.branch")(function*(){return yield*S.use(r,i=>i.current)}),defaultBranch:h.fn("Vcs.defaultBranch")(function*(){return yield*S.use(r,i=>i.root?.name)}),diff:h.fn("Vcs.diff")(function*(i){let a=yield*S.get(r);if(g.project.vcs!=="git")return[];if(i==="git")return yield*W(d,s,g.directory,(yield*s.hasHead(g.directory))?"HEAD":void 0);if(!a.root)return[];if(a.current&&a.current===a.root.name)return[];let w=yield*s.mergeBase(g.directory,a.root.ref);return w?yield*ne(d,s,g.directory,w):[]})})}));let ie=P.layer.pipe(ee.provide(O.defaultLayer),ee.provide(A.defaultLayer),ee.provide(V.layer)),{runPromise:C}=Y(I,ie);async function he(){return C(d=>d.init())}P.init=he,m(he,"init");async function we(){return C(d=>d.branch())}P.branch=we,m(we,"branch");async function U(){return C(d=>d.defaultBranch())}P.defaultBranch=U,m(U,"defaultBranch");async function Ne(d){return C(s=>s.diff(d))}P.diff=Ne,m(Ne,"diff")})(ue||={});async function Te(){z.Default.info("bootstrapping",{directory:g.directory}),await ze.init(),Me.init(),Le.init(),await De.init(),Ge.init(),Z.init(),ue.init(),Be.init(),V.subscribe(le.Event.Executed,async E=>{E.properties.name===le.Default.INIT&&T.setInitialized(g.project.id)})}m(Te,"InstanceBootstrap");import{Effect as o,Layer as X,Path as Ye,Scope as Ze,ServiceMap as et,Stream as B}from"effect";import{ChildProcess as $e,ChildProcessSpawner as tt}from"effect/unstable/process";import{NodePath as rt}from"@effect/platform-node";var nt;(r=>{let E=z.create({service:"worktree"});r.Event={Ready:q.define("worktree.ready",p.object({name:p.string(),branch:p.string()})),Failed:q.define("worktree.failed",p.object({message:p.string()}))},r.Info=p.object({name:p.string(),branch:p.string(),directory:p.string()}).meta({ref:"Worktree"}),r.CreateInput=p.object({name:p.string().optional(),startCommand:p.string().optional().describe("Additional startup script to run after the project's start command")}).meta({ref:"WorktreeCreateInput"}),r.RemoveInput=p.object({directory:p.string()}).meta({ref:"WorktreeRemoveInput"}),r.ResetInput=p.object({directory:p.string()}).meta({ref:"WorktreeResetInput"}),r.NotGitError=D.create("WorktreeNotGitError",p.object({message:p.string()})),r.NameGenerationFailedError=D.create("WorktreeNameGenerationFailedError",p.object({message:p.string()})),r.CreateFailedError=D.create("WorktreeCreateFailedError",p.object({message:p.string()})),r.StartCommandFailedError=D.create("WorktreeStartCommandFailedError",p.object({message:p.string()})),r.RemoveFailedError=D.create("WorktreeRemoveFailedError",p.object({message:p.string()})),r.ResetFailedError=D.create("WorktreeResetFailedError",p.object({message:p.string()}));function oe(i){return i.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+/,"").replace(/-+$/,"")}m(oe,"slugify");function ie(...i){return i.filter(Boolean).flatMap(a=>a.split(`
@@ -9,4 +9,4 @@ if (typeof globalThis.Bun === 'undefined') {
9
9
  if (typeof globalThis.__name === 'undefined') { globalThis.__name = (t, n) => { Object.defineProperty(t, 'name', { value: n, configurable: true }); return t; }; }
10
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
11
 
12
- import{a as e}from"./chunk-MBZTOEAD.js";var u=Symbol.for("quansync.getIsAsync"),f=class extends Error{static{e(this,"QuansyncError")}constructor(n="Unexpected promise in sync context"){super(n),this.name="QuansyncError"}};function y(n){return n&&typeof n=="object"&&typeof n.then=="function"}e(y,"isThenable");function x(n){return n&&typeof n=="object"&&typeof n[Symbol.iterator]=="function"&&"__quansync"in n}e(x,"isQuansyncGenerator");function d(n){let r=e(function*(...a){return(yield u)?yield n.async.apply(this,a):n.sync.apply(this,a)},"generator");function t(...a){let o=r.apply(this,a);return o.then=(...b)=>n.async.apply(this,a).then(...b),o.__quansync=!0,o}return e(t,"fn"),t.sync=n.sync,t.async=n.async,t}e(d,"fromObject");function _(n){return d({async:e(()=>Promise.resolve(n),"async"),sync:e(()=>{if(y(n))throw new f;return n},"sync")})}e(_,"fromPromise");function i(n,r){if(n===u)return r;if(x(n))return r?w(n):h(n);if(!r&&y(n))throw new f;return n}e(i,"unwrapYield");var p=e(n=>n,"DEFAULT_ON_YIELD");function h(n,r=p){let t=n.next();for(;!t.done;)try{t=n.next(i(r(t.value,!1)))}catch(a){t=n.throw(a)}return i(t.value)}e(h,"iterateSync");async function w(n,r=p){let t=n.next();for(;!t.done;)try{t=n.next(await i(r(t.value,!0),!0))}catch(a){t=n.throw(a)}return t.value}e(w,"iterateAsync");function S(n,r){return d({name:n.name,async(...t){return w(n.apply(this,t),r?.onYield)},sync(...t){return h(n.apply(this,t),r?.onYield)}})}e(S,"fromGeneratorFn");function s(n,r){return y(n)?_(n):typeof n=="function"?S(n,r):d(n)}e(s,"quansync");var E=s({async:e(()=>Promise.resolve(!0),"async"),sync:e(()=>!1,"sync")});var l=new Map,c=class extends Error{static{e(this,"UnsupportedVendorError")}constructor(r){super(`standard-json: Unsupported schema vendor "${r}".`)}},m=class extends Error{static{e(this,"MissingDependencyError")}constructor(r){super(`standard-json: Missing dependencies "${r}".`)}},k=e(async n=>{let r=l.get(n);if(r)return r;let t;switch(n){case"arktype":t=(await import("./arktype-aI7TBD0R-ETU7X65Q.js")).default();break;case"effect":t=(await import("./effect-QlVUlMFu-ORZ7TVO5.js")).default();break;case"sury":t=(await import("./sury-CWZTCd75-IXNCX752.js")).default();break;case"typebox":t=(await import("./typebox-Dei93FPO-K67WT2FO.js")).default();break;case"valibot":t=(await import("./valibot--1zFm7rT-SSCP4J5I.js")).default();break;case"zod":t=(await import("./zod-Bwrt9trS-BYLM45IZ.js")).default();break;default:throw new c(n)}let a=await t;return l.set(n,a),a},"getToJsonSchemaFn"),P=s({sync:e((n,r)=>{let t=n["~standard"].vendor,a=l.get(t);if(!a)throw new c(t);return a(n,r)},"sync"),async:e(async(n,r)=>(await k(n["~standard"].vendor))(n,r),"async")});export{m as a,P as b};
12
+ import{a as e}from"./chunk-MBZTOEAD.js";var u=Symbol.for("quansync.getIsAsync"),f=class extends Error{static{e(this,"QuansyncError")}constructor(n="Unexpected promise in sync context"){super(n),this.name="QuansyncError"}};function y(n){return n&&typeof n=="object"&&typeof n.then=="function"}e(y,"isThenable");function x(n){return n&&typeof n=="object"&&typeof n[Symbol.iterator]=="function"&&"__quansync"in n}e(x,"isQuansyncGenerator");function d(n){let r=e(function*(...a){return(yield u)?yield n.async.apply(this,a):n.sync.apply(this,a)},"generator");function t(...a){let o=r.apply(this,a);return o.then=(...b)=>n.async.apply(this,a).then(...b),o.__quansync=!0,o}return e(t,"fn"),t.sync=n.sync,t.async=n.async,t}e(d,"fromObject");function _(n){return d({async:e(()=>Promise.resolve(n),"async"),sync:e(()=>{if(y(n))throw new f;return n},"sync")})}e(_,"fromPromise");function i(n,r){if(n===u)return r;if(x(n))return r?w(n):h(n);if(!r&&y(n))throw new f;return n}e(i,"unwrapYield");var p=e(n=>n,"DEFAULT_ON_YIELD");function h(n,r=p){let t=n.next();for(;!t.done;)try{t=n.next(i(r(t.value,!1)))}catch(a){t=n.throw(a)}return i(t.value)}e(h,"iterateSync");async function w(n,r=p){let t=n.next();for(;!t.done;)try{t=n.next(await i(r(t.value,!0),!0))}catch(a){t=n.throw(a)}return t.value}e(w,"iterateAsync");function S(n,r){return d({name:n.name,async(...t){return w(n.apply(this,t),r?.onYield)},sync(...t){return h(n.apply(this,t),r?.onYield)}})}e(S,"fromGeneratorFn");function s(n,r){return y(n)?_(n):typeof n=="function"?S(n,r):d(n)}e(s,"quansync");var E=s({async:e(()=>Promise.resolve(!0),"async"),sync:e(()=>!1,"sync")});var l=new Map,c=class extends Error{static{e(this,"UnsupportedVendorError")}constructor(r){super(`standard-json: Unsupported schema vendor "${r}".`)}},m=class extends Error{static{e(this,"MissingDependencyError")}constructor(r){super(`standard-json: Missing dependencies "${r}".`)}},k=e(async n=>{let r=l.get(n);if(r)return r;let t;switch(n){case"arktype":t=(await import("./arktype-aI7TBD0R-TFNARRIP.js")).default();break;case"effect":t=(await import("./effect-QlVUlMFu-JVYEXAZL.js")).default();break;case"sury":t=(await import("./sury-CWZTCd75-3YHH6KVI.js")).default();break;case"typebox":t=(await import("./typebox-Dei93FPO-GLI7OCTY.js")).default();break;case"valibot":t=(await import("./valibot--1zFm7rT-FSYJNYJ6.js")).default();break;case"zod":t=(await import("./zod-Bwrt9trS-HVDOFWRP.js")).default();break;default:throw new c(n)}let a=await t;return l.set(n,a),a},"getToJsonSchemaFn"),P=s({sync:e((n,r)=>{let t=n["~standard"].vendor,a=l.get(t);if(!a)throw new c(t);return a(n,r)},"sync"),async:e(async(n,r)=>(await k(n["~standard"].vendor))(n,r),"async")});export{m as a,P as b};
@@ -0,0 +1,18 @@
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 Je,b as it,c as Ce,d as io}from"./chunk-735MVPNG.js";import{b as Rt}from"./chunk-2ANK3QEN.js";import{A as Gt,B as Ft,C as vt,D as de,E as ze,F as h,G as Ve,a as ce,b as yt,d as pe,f as rt,g as ht,h as Q,i as gt,j as nt,k as ve,l as bt,m as qe,n as zt,o as Be,p as _t,q as He,r as Ut,s as $e,t as It,u as no,v as Lt,w as Ae,y as Mt,z as Nt}from"./chunk-5FGJUXLI.js";import{B as se,C as V,D as J,b as De,f as We,h as Et,n as W,o as so,p as ro,q as ot}from"./chunk-WF7L36SZ.js";import{B as ft,a as Te,c as A,d as ge,e as tt,h as ne,i as ke,j as xe,k as F,m as to,n as we,o as Ge,p as Fe,s as ue,u as ut,y as fe,z as _}from"./chunk-N7PLTD3P.js";import{a as Ot,b as X,c as st,d as Tt}from"./chunk-7KKA6WBY.js";import{a as oo}from"./chunk-LTCXIXYM.js";import{c as Zt,d as lt,e as G}from"./chunk-M4CB72HE.js";import{b as eo}from"./chunk-CZVKIDQZ.js";import{a as c,e as Xt,f as Qt}from"./chunk-MBZTOEAD.js";import{validator as as}from"hono/validator";var ao={header:["cookie"]};function cs(e,t,o){if(!(o in ao))return e;let s=ao[o]||[];return t==="arktype"?ps(e,s):t==="valibot"?ds(e,s):e}c(cs,"sanitizeIssues");function ps(e,t){return e.map(o=>{if(o&&typeof o=="object"&&"data"in o&&typeof o.data=="object"&&o.data!==null&&!Array.isArray(o.data)){let s={...o.data};for(let n of t)delete s[n];let r=Object.create(Object.getPrototypeOf(o));return Object.assign(r,o,{data:s}),r}return o})}c(ps,"sanitizeArktypeIssues");function ds(e,t){return e.map(o=>{if(o&&typeof o=="object"&&"path"in o&&Array.isArray(o.path)){for(let s of o.path)if(typeof s=="object"&&"input"in s&&typeof s.input=="object"&&s.input!==null&&!Array.isArray(s.input))for(let r of t)delete s.input[r]}return o})}c(ds,"sanitizeValibotIssues");var co=c((e,t,o)=>as(e,async(s,r)=>{let n=await t["~standard"].validate(s);if(o){let d=await o(n.issues?{data:s,error:n.issues,success:!1,target:e}:{data:s,success:!0,target:e},r);if(d){if(d instanceof Response)return d;if("response"in d)return d.response}}if(n.issues){let d=cs(n.issues,t["~standard"].vendor,e);return r.json({data:s,error:d,success:!1},400)}return n.value}),"sValidator");var Wt=Symbol("openapi"),ls=["GET","PUT","POST","DELETE","OPTIONS","HEAD","PATCH","TRACE"],us=c(e=>e.split("/").map(t=>{let o=t;if(o.startsWith(":")){let s=o.match(/^:([^{?]+)(?:{(.+)})?(\?)?$/);s?o=`{${s[1]}}`:(o=o.slice(1,o.length),o.endsWith("?")&&(o=o.slice(0,-1)),o=`{${o}}`)}return o}).join("/"),"toOpenAPIPath"),po=c(e=>e.charAt(0).toUpperCase()+e.slice(1),"capitalize"),fs=c(e=>{let t=e.method.toLowerCase();if(e.path==="/")return`${t}Index`;for(let o of e.path.split("/"))o.charCodeAt(0)===123?t+=`By${po(o.slice(1,-1))}`:t+=po(o);return t},"generateOperationId"),ys=c(e=>"$ref"in e?e.$ref:`${e.in} ${e.name}`,"paramKey");function mo(...e){let t=e.flatMap(o=>o??[]).reduce((o,s)=>(o.set(ys(s),s),o),new Map);return Array.from(t.values())}c(mo,"mergeParameters");var Ye=new Map;function hs(e){let t=[];for(let[o,s]of Ye)s&&e.match(o)&&t.push(s);return t}c(hs,"getPathContext");function gs(){Ye.clear()}c(gs,"clearSpecsContext");function lo(e,...t){return t.reduce((o,s)=>{if(!s||!o)return o;for(let[r,n]of Object.entries(s))if(n!=null)if(r in o&&(typeof n=="object"||typeof n=="function"&&r==="operationId"))if(Array.isArray(n)){let d=[...o[r]??[],...n];r==="tags"?o[r]=Array.from(new Set(d)):r==="parameters"?o[r]=mo(d):o[r]=d}else typeof n=="function"?o[r]=n(e):r==="parameters"?o[r]=mo(o[r],n):o[r]={...o[r],...n};else o[r]=n;return o},{operationId:fs(e)})}c(lo,"mergeSpecs");function uo({route:e,specs:t,paths:o}){let s=us(e.path),r=e.method.toLowerCase();if(r==="all"){if(!t)return;if(Ye.has(s)){let n=Ye.get(s)??{};Ye.set(s,lo(e,n,t))}else Ye.set(s,t)}else{let n=hs(s);s in o||(o[s]={}),o[s]&&(o[s][r]=lo(e,...n,o[s]?.[r],t))}}c(uo,"registerSchemaPath");function bs(e,t){let{exclude:o,excludeStaticFile:s}=t.options,r={},n=Array.isArray(o)?o:[o];for(let[d,u]of Object.entries(e))if(!(u==null||n.some(k=>typeof k=="string"?d===k:k.test(d))||d.includes("*")&&!d.includes("{"))){if(s){let k=d.includes("{"),v=(d.split("/").pop()||"").includes(".");if(!k&&v)continue}for(let k of Object.keys(u)){let y=u[k];if(y!=null){if(d.includes("{")){y.parameters=y.parameters?[...y.parameters]:[];let v=d.split("/").filter(g=>g.startsWith("{")&&!y.parameters.find(m=>m.in==="path"&&m.name===g.slice(1,g.length-1)));for(let g of v){let m=g.slice(1,g.length-1);y.parameters.findIndex(w=>{if("$ref"in w){let M=w.$ref.split("/").pop();if(M){let ee=t.components.parameters?.[M];if(ee&&!("$ref"in ee))return ee.in==="path"&&ee.name===m}return!1}return w.in==="path"&&w.name===m})===-1&&y.parameters.push({schema:{type:"string"},in:"path",name:m,required:!0})}}y.responses||(y.responses={200:{}})}}r[d]=u}return r}c(bs,"removeExcludedPaths");var fo={documentation:{},excludeStaticFile:!0,exclude:[],excludeMethods:["OPTIONS"],excludeTags:[]};function ho(e,t){let o;return async s=>(o||(o=await Bt(e,t,s)),s.json(o))}c(ho,"openAPIRouteHandler");async function Bt(e,t=fo,o){let s={components:{},options:{...fo,...t}},r=s.options.documentation??{};gs();let n=await Is(e,s);for(let u in n)for(let f in n[u])vs({valueOrFunc:n[u][f]?.hide,method:f,path:u,c:o})&&(n[u][f]=void 0);let d=Ht(r.components,s.components);return{openapi:"3.1.0",...r,tags:r.tags?.filter(u=>!s.options.excludeTags?.includes(u?.name)),info:{title:"Hono Documentation",description:"Development documentation",version:"0.0.0",...r.info},paths:{...bs(n,s),...r.paths},components:d}}c(Bt,"generateSpecs");async function Is(e,t){let o={};for(let s of e.routes){let r=s.handler[Wt];if(!r){t.options.includeEmptyPaths&&uo({route:s,paths:o});continue}let n=s.method;if(n!=="ALL"&&(t.options.excludeMethods?.includes(n)||!ls.includes(n)))continue;let d=t.options.defaultOptions?.[n],{schema:u,components:f={}}=await js(r,d);t.components=Ht(t.components,f),uo({route:s,specs:u,paths:o})}return o}c(Is,"generatePaths");function vs(e){let{valueOrFunc:t,c:o,method:s,path:r}=e;if(t!=null){if(typeof t=="boolean")return t;if(typeof t=="function")return t({c:o,method:s,path:r})}return!1}c(vs,"getHiddenValue");async function js(e,t){if("spec"in e){let r={},n={...t,...e.spec,responses:{...t?.responses,...e.spec.responses}};if(n.responses)for(let d of Object.keys(n.responses)){let u=n.responses[d];if(!(!u||!("content"in u)))for(let f of Object.keys(u.content??{})){let x=u.content?.[f];if(x&&x.schema&&"toOpenAPISchema"in x.schema){let k=await x.schema.toOpenAPISchema();x.schema=k.schema,k.components&&(r=Ht(r,k.components))}}}return{schema:n,components:r}}let o=await e.toOpenAPISchema(),s=t??{};if(e.target==="form"||e.target==="json"){let r=e.options?.media??e.target==="json"?"application/json":"multipart/form-data";!s.requestBody||!("content"in s.requestBody)||!s.requestBody.content?s.requestBody={content:{[r]:{schema:o.schema}}}:s.requestBody.content[r]={schema:o.schema}}else{let r=[];if("$ref"in o.schema){let d=o.schema.$ref.split("/").pop();if(d&&o.components?.schemas?.[d]){let u=o.components.schemas[d],f=yo(e.target,u)[0];o.components.parameters||(o.components.parameters={}),o.components.parameters[d]=f,delete o.components.schemas[d],r.push({$ref:`#/components/parameters/${d}`})}}else r=yo(e.target,o.schema);s.parameters=r}return{schema:s,components:o.components}}c(js,"getSpec");function yo(e,t){let o=[];for(let[s,r]of Object.entries(t.properties??{})){let n={in:e==="param"?"path":e,name:s,schema:r};t.required?.includes(s)&&(n.required=!0),n.schema&&"description"in n.schema&&n.schema.description&&(n.description=n.schema.description,n.schema.description=void 0),o.push(n)}return o}c(yo,"generateParameters");function Ht(...e){return e.reduce((t,o,s)=>(o==null||s===0||((t.schemas&&Object.keys(t.schemas).length>0||o.schemas&&Object.keys(o.schemas).length>0)&&(t.schemas={...t.schemas,...o.schemas}),(t.parameters&&Object.keys(t.parameters).length>0||o.parameters&&Object.keys(o.parameters).length>0)&&(t.parameters={...t.parameters,...o.parameters})),t),e[0]??{})}c(Ht,"mergeComponentsObjects");function i(e,t){return{vendor:e["~standard"].vendor,validate:e["~standard"].validate,toJSONSchema:c(o=>eo(e,{...t,...o}),"toJSONSchema"),toOpenAPISchema:c(o=>Rt(e,{...t,...o}),"toOpenAPISchema")}}c(i,"resolver");function p(e,t,o,s){let r=co(e,t,o);return Object.assign(r,{[Wt]:{target:e,...i(t,s),options:s}})}c(p,"validator");function a(e){return Object.assign(c(async(o,s)=>{await s()},"middleware"),{[Wt]:{spec:e}})}c(a,"describeRoute");import{Hono as es}from"hono";import{compress as xr}from"hono/compress";import{cors as qr}from"hono/cors";import{basicAuth as Ar}from"hono/basic-auth";import ae from"zod";import{createAdaptorServer as Cr}from"@hono/node-server";import{createNodeWebSocket as Rr}from"@hono/node-ws";var ws={worktree:A(async()=>(await import("./worktree-HPW4CL36.js")).WorktreeAdaptor)};function Ke(e){return ws[e]()}c(Ke,"getAdaptor");import at from"zod";import{setTimeout as bo}from"node:timers/promises";import{sqliteTable as Ds,text as _e}from"drizzle-orm/sqlite-core";var je=Ds("workspace",{id:_e().$type().primaryKey(),type:_e().notNull(),branch:_e(),name:_e(),directory:_e(),extra:_e({mode:"json"}),project_id:_e().$type().notNull().references(()=>to.id,{onDelete:"cascade"})});async function go(e,t,o){let s=e.getReader(),r=new TextDecoder,n="",d="",u=1e3,f=c(()=>{s.cancel().catch(()=>{})},"abort");t.addEventListener("abort",f);try{for(;!t.aborted;){let x=await s.read().catch(()=>({done:!0,value:void 0}));if(x.done)break;n+=r.decode(x.value,{stream:!0}),n=n.replace(/\r\n/g,`
13
+ `).replace(/\r/g,`
14
+ `);let k=n.split(`
15
+
16
+ `);n=k.pop()??"",k.forEach(y=>{let v=[];if(y.split(`
17
+ `).forEach(m=>{if(m.startsWith("data:")){v.push(m.replace(/^data:\s*/,""));return}if(m.startsWith("id:")){d=m.replace(/^id:\s*/,"");return}if(m.startsWith("retry:")){let I=Number.parseInt(m.replace(/^retry:\s*/,""),10);Number.isNaN(I)||(u=I)}}),!v.length)return;let g=v.join(`
18
+ `);try{o(JSON.parse(g))}catch{o({type:"sse.message",properties:{data:g,id:d||void 0,retry:u}})}})}}finally{t.removeEventListener("abort",f),s.releaseLock()}}c(go,"parseSSE");var ye;(y=>{y.Event={Ready:ue.define("workspace.ready",at.object({name:at.string()})),Failed:ue.define("workspace.failed",at.object({message:at.string()}))},y.Info=io.meta({ref:"Workspace"});function o(v){return{id:v.id,type:v.type,branch:v.branch,name:v.name,directory:v.directory,extra:v.extra,projectID:v.project_id}}c(o,"fromRow");let s=at.object({id:ze.zod.optional(),type:y.Info.shape.type,branch:y.Info.shape.branch,projectID:ut.zod,extra:y.Info.shape.extra});y.create=It(s,async v=>{let g=ze.ascending(v.id),m=await Ke(v.type),I=await m.configure({...v,id:g,name:null,directory:null}),w={id:g,type:I.type,branch:I.branch??null,name:I.name??null,directory:I.directory??null,extra:I.extra??null,projectID:v.projectID};return xe.use(M=>{M.insert(je).values({id:w.id,type:w.type,branch:w.branch,name:w.name,directory:w.directory,extra:w.extra,project_id:w.projectID}).run()}),await m.create(I),w});function n(v){return xe.use(m=>m.select().from(je).where((0,F.eq)(je.project_id,v.id)).all()).map(o).sort((m,I)=>m.id.localeCompare(I.id))}y.list=n,c(n,"list"),y.get=It(ze.zod,async v=>{let g=xe.use(m=>m.select().from(je).where((0,F.eq)(je.id,v)).get());if(g)return o(g)}),y.remove=It(ze.zod,async v=>{let g=xe.use(m=>m.select().from(je).where((0,F.eq)(je.id,v)).get());if(g){let m=o(g);return(await Ke(g.type)).remove(m),xe.use(w=>w.delete(je).where((0,F.eq)(je.id,v)).run()),m}});let f=G.create({service:"workspace-sync"});async function x(v,g){for(;!g.aborted;){let m=await Ke(v.type),I=await Promise.resolve(m.target(v));if(I.type==="local")return;let w=String(I.url).replace(/\/?$/,"/"),M=await fetch(new URL(w+"/event"),{method:"GET",signal:g});if(!M.ok||!M.body){await bo(1e3);continue}await go(M.body,g,ee=>{Te.emit("event",{directory:v.id,payload:ee})}),await bo(250)}}c(x,"workspaceEventLoop");function k(v){let g=new AbortController;return n(v).filter(I=>I.type!=="worktree").forEach(I=>{x(I,g.signal).catch(w=>{f.warn("workspace sync listener failed",{workspaceID:I.id,error:w})})}),{async stop(){g.abort()}}}y.startSyncing=k,c(k,"startSyncing")})(ye||={});import{Hono as Io}from"hono";import{createNodeWebSocket as Ss}from"@hono/node-ws";var{upgradeWebSocket:Ps}=Ss({app:new Io}),ks=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","proxy-connection","te","trailer","transfer-encoding","upgrade","host"]);function xs(e,t){let o=new Headers(e.headers);for(let s of ks)o.delete(s);if(o.delete("x-opencode-directory"),o.delete("x-opencode-workspace"),!t)return o;for(let[s,r]of new Headers(t).entries())o.set(s,r);return o}c(xs,"headers");function qs(e){let t=e.headers.get("sec-websocket-protocol");return t?t.split(",").map(o=>o.trim()).filter(Boolean):[]}c(qs,"protocols");function As(e){let t=new URL(e);return t.protocol==="http:"&&(t.protocol="ws:"),t.protocol==="https:"&&(t.protocol="wss:"),t.toString()}c(As,"socket");function Cs(e,t){return t instanceof Blob?t.arrayBuffer().then(o=>e.send(o)):e.send(t)}c(Cs,"send");var Rs=A(()=>new Io().get("/__workspace_ws",Ps(e=>{let t=e.req.header("x-opencode-proxy-url"),o=[],s;return{onOpen(r,n){if(!t){n.close(1011,"missing proxy target");return}s=new WebSocket(t,qs(e.req.raw)),s.binaryType="arraybuffer",s.onopen=()=>{for(let d of o)s?.send(d);o.length=0},s.onmessage=d=>{Cs(n,d.data)},s.onerror=()=>{n.close(1011,"proxy error")},s.onclose=d=>{n.close(d.code,d.reason)}},onMessage(r){let n=r.data;if(!(typeof n!="string"&&!(n instanceof Uint8Array)&&!(n instanceof ArrayBuffer))){if(s?.readyState===WebSocket.OPEN){s.send(n);return}o.push(n)}},onClose(r){s?.close(r.code,r.reason)}}}))),jt;(o=>{function e(s,r){return fetch(new Request(s.url,{method:r.method,headers:xs(r,s.headers),body:r.method==="GET"||r.method==="HEAD"?void 0:r.body,redirect:"manual",signal:r.signal}))}o.http=e,c(e,"http");function t(s,r,n){let d=new URL(r.url);d.pathname="/__workspace_ws",d.search="";let u=new Headers(r.headers);return u.set("x-opencode-proxy-url",As(s.url)),Rs().fetch(new Request(d,{method:r.method,headers:u,signal:r.signal}),n)}o.websocket=t,c(t,"websocket")})(jt||={});import{Hono as ur}from"hono";import{proxy as fr}from"hono/proxy";import Re from"zod";import{createHash as yr}from"node:crypto";import{Hono as vo}from"hono";import B from"zod";var Se=class{static{c(this,"AsyncQueue")}queue=[];resolvers=[];push(t){let o=this.resolvers.shift();o?o(t):this.queue.push(t)}async next(){return this.queue.length>0?this.queue.shift():new Promise(t=>this.resolvers.push(t))}async*[Symbol.asyncIterator](){for(;;)yield await this.next()}};import Ue from"zod";var Es={400:{description:"Bad request",content:{"application/json":{schema:i(Ue.object({data:Ue.any(),errors:Ue.array(Ue.record(Ue.string(),Ue.any())),success:Ue.literal(!1)}).meta({ref:"BadRequestError"}))}}},404:{description:"Not found",content:{"application/json":{schema:i(ke.Schema)}}}};function l(...e){return Object.fromEntries(e.map(t=>[t,Es[t]]))}c(l,"errors");var Os=B.object({path:B.string(),body:B.any()}),Ts=new Se,zs=new Se;var _s=new vo().get("/next",a({summary:"Get next TUI request",description:"Retrieve the next TUI (Terminal User Interface) request from the queue for processing.",operationId:"tui.control.next",responses:{200:{description:"Next TUI request",content:{"application/json":{schema:i(Os)}}}}}),async e=>{let t=await Ts.next();return e.json(t)}).post("/response",a({summary:"Submit TUI response",description:"Submit a response to the TUI request queue to complete a pending request.",operationId:"tui.control.response",responses:{200:{description:"Response submitted successfully",content:{"application/json":{schema:i(B.boolean())}}}}}),p("json",B.any()),async e=>{let t=e.req.valid("json");return zs.push(t),e.json(!0)}),jo=A(()=>new vo().post("/append-prompt",a({summary:"Append TUI prompt",description:"Append prompt to the TUI",operationId:"tui.appendPrompt",responses:{200:{description:"Prompt processed successfully",content:{"application/json":{schema:i(B.boolean())}}},...l(400)}}),p("json",se.PromptAppend.properties),async e=>(await W.publish(se.PromptAppend,e.req.valid("json")),e.json(!0))).post("/open-help",a({summary:"Open help dialog",description:"Open the help dialog in the TUI to display user assistance information.",operationId:"tui.openHelp",responses:{200:{description:"Help dialog opened successfully",content:{"application/json":{schema:i(B.boolean())}}}}}),async e=>(await W.publish(se.CommandExecute,{command:"help.show"}),e.json(!0))).post("/open-sessions",a({summary:"Open sessions dialog",description:"Open the session dialog",operationId:"tui.openSessions",responses:{200:{description:"Session dialog opened successfully",content:{"application/json":{schema:i(B.boolean())}}}}}),async e=>(await W.publish(se.CommandExecute,{command:"session.list"}),e.json(!0))).post("/open-themes",a({summary:"Open themes dialog",description:"Open the theme dialog",operationId:"tui.openThemes",responses:{200:{description:"Theme dialog opened successfully",content:{"application/json":{schema:i(B.boolean())}}}}}),async e=>(await W.publish(se.CommandExecute,{command:"session.list"}),e.json(!0))).post("/open-models",a({summary:"Open models dialog",description:"Open the model dialog",operationId:"tui.openModels",responses:{200:{description:"Model dialog opened successfully",content:{"application/json":{schema:i(B.boolean())}}}}}),async e=>(await W.publish(se.CommandExecute,{command:"model.list"}),e.json(!0))).post("/submit-prompt",a({summary:"Submit TUI prompt",description:"Submit the prompt",operationId:"tui.submitPrompt",responses:{200:{description:"Prompt submitted successfully",content:{"application/json":{schema:i(B.boolean())}}}}}),async e=>(await W.publish(se.CommandExecute,{command:"prompt.submit"}),e.json(!0))).post("/clear-prompt",a({summary:"Clear TUI prompt",description:"Clear the prompt",operationId:"tui.clearPrompt",responses:{200:{description:"Prompt cleared successfully",content:{"application/json":{schema:i(B.boolean())}}}}}),async e=>(await W.publish(se.CommandExecute,{command:"prompt.clear"}),e.json(!0))).post("/execute-command",a({summary:"Execute TUI command",description:"Execute a TUI command (e.g. agent_cycle)",operationId:"tui.executeCommand",responses:{200:{description:"Command executed successfully",content:{"application/json":{schema:i(B.boolean())}}},...l(400)}}),p("json",B.object({command:B.string()})),async e=>{let t=e.req.valid("json").command;return await W.publish(se.CommandExecute,{command:{session_new:"session.new",session_share:"session.share",session_interrupt:"session.interrupt",session_compact:"session.compact",messages_page_up:"session.page.up",messages_page_down:"session.page.down",messages_line_up:"session.line.up",messages_line_down:"session.line.down",messages_half_page_up:"session.half.page.up",messages_half_page_down:"session.half.page.down",messages_first:"session.first",messages_last:"session.last",agent_cycle:"agent.cycle"}[t]}),e.json(!0)}).post("/show-toast",a({summary:"Show TUI toast",description:"Show a toast notification in the TUI",operationId:"tui.showToast",responses:{200:{description:"Toast notification shown successfully",content:{"application/json":{schema:i(B.boolean())}}}}}),p("json",se.ToastShow.properties),async e=>(await W.publish(se.ToastShow,e.req.valid("json")),e.json(!0))).post("/publish",a({summary:"Publish TUI event",description:"Publish a TUI event",operationId:"tui.publish",responses:{200:{description:"Event published successfully",content:{"application/json":{schema:i(B.boolean())}}},...l(400)}}),p("json",B.union(Object.values(se).map(e=>B.object({type:B.literal(e.type),properties:e.properties}).meta({ref:"Event."+e.type})))),async e=>{let t=e.req.valid("json");return await W.publish(Object.values(se).find(o=>o.type===t.type),t.properties),e.json(!0)}).post("/select-session",a({summary:"Select session",description:"Navigate the TUI to display the specified session.",operationId:"tui.selectSession",responses:{200:{description:"Session selected successfully",content:{"application/json":{schema:i(B.boolean())}}},...l(400,404)}}),p("json",se.SessionSelect.properties),async e=>{let{sessionID:t}=e.req.valid("json");return await h.get(t),await W.publish(se.SessionSelect,{sessionID:t}),e.json(!0)}).route("/control",_s));import{Hono as Us}from"hono";import wt from"zod";var wo=A(()=>new Us().get("/",a({summary:"List pending questions",description:"Get all pending question requests across all sessions.",operationId:"question.list",responses:{200:{description:"List of pending questions",content:{"application/json":{schema:i($e.Request.array())}}}}}),async e=>{let t=await $e.list();return e.json(t)}).post("/:requestID/reply",a({summary:"Reply to question request",description:"Provide answers to a question request from the AI assistant.",operationId:"question.reply",responses:{200:{description:"Question answered successfully",content:{"application/json":{schema:i(wt.boolean())}}},...l(400,404)}}),p("param",wt.object({requestID:Ut.zod})),p("json",$e.Reply),async e=>{let t=e.req.valid("param"),o=e.req.valid("json");return await $e.reply({requestID:t.requestID,answers:o.answers}),e.json(!0)}).post("/:requestID/reject",a({summary:"Reject question request",description:"Reject a question request from the AI assistant.",operationId:"question.reject",responses:{200:{description:"Question rejected successfully",content:{"application/json":{schema:i(wt.boolean())}}},...l(400,404)}}),p("param",wt.object({requestID:Ut.zod})),async e=>{let t=e.req.valid("param");return await $e.reject(t.requestID),e.json(!0)}));import{Hono as Ls}from"hono";import Dt from"zod";var Do=A(()=>new Ls().post("/:requestID/reply",a({summary:"Respond to permission request",description:"Approve or deny a permission request from the AI assistant.",operationId:"permission.reply",responses:{200:{description:"Permission processed successfully",content:{"application/json":{schema:i(Dt.boolean())}}},...l(400,404)}}),p("param",Dt.object({requestID:bt.zod})),p("json",Dt.object({reply:qe.Reply,message:Dt.string().optional()})),async e=>{let t=e.req.valid("param"),o=e.req.valid("json");return await qe.reply({requestID:t.requestID,reply:o.reply,message:o.message}),e.json(!0)}).get("/",a({summary:"List pending permissions",description:"Get all pending permission requests across all sessions.",operationId:"permission.list",responses:{200:{description:"List of pending permissions",content:{"application/json":{schema:i(qe.Request.array())}}}}}),async e=>{let t=await qe.list();return e.json(t)}));import{Hono as Ms}from"hono";import Ns from"zod";var So=A(()=>new Ms().get("/",a({summary:"List all projects",description:"Get a list of projects that have been opened with OpenCode.",operationId:"project.list",responses:{200:{description:"List of projects",content:{"application/json":{schema:i(fe.Info.array())}}}}}),async e=>{let t=fe.list();return e.json(t)}).get("/current",a({summary:"Get current project",description:"Retrieve the currently active project that OpenCode is working with.",operationId:"project.current",responses:{200:{description:"Current project information",content:{"application/json":{schema:i(fe.Info)}}}}}),async e=>e.json(_.project)).post("/git/init",a({summary:"Initialize git repository",description:"Create a git repository for the current project and return the refreshed project info.",operationId:"project.initGit",responses:{200:{description:"Project information after git initialization",content:{"application/json":{schema:i(fe.Info)}}}}}),async e=>{let t=_.directory,o=_.project,s=await fe.initGit({directory:t,project:o});return s.id===o.id&&s.vcs===o.vcs&&s.worktree===o.worktree||await _.reload({directory:t,worktree:t,project:s,init:it}),e.json(s)}).patch("/:projectID",a({summary:"Update project",description:"Update project properties such as name, icon, and commands.",operationId:"project.update",responses:{200:{description:"Updated project information",content:{"application/json":{schema:i(fe.Info)}}},...l(400,404)}}),p("param",Ns.object({projectID:ut.zod})),p("json",fe.UpdateInput.omit({projectID:!0})),async e=>{let t=e.req.valid("param").projectID,o=e.req.valid("json"),s=await fe.update({...o,projectID:t});return e.json(s)}));import{Hono as Gs}from"hono";import{stream as Po}from"hono/streaming";import b from"zod";var $t=G.create({service:"server"}),ko=A(()=>new Gs().get("/",a({summary:"List sessions",description:"Get a list of all OpenCode sessions, sorted by most recently updated.",operationId:"session.list",responses:{200:{description:"List of sessions",content:{"application/json":{schema:i(h.Info.array())}}}}}),p("query",b.object({directory:b.string().optional().meta({description:"Filter sessions by project directory"}),roots:b.coerce.boolean().optional().meta({description:"Only return root sessions (no parentID)"}),start:b.coerce.number().optional().meta({description:"Filter sessions updated on or after this timestamp (milliseconds since epoch)"}),search:b.string().optional().meta({description:"Filter sessions by title (case-insensitive)"}),limit:b.coerce.number().optional().meta({description:"Maximum number of sessions to return"})})),async e=>{let t=e.req.valid("query"),o=[];for await(let s of h.list({directory:t.directory,roots:t.roots,start:t.start,search:t.search,limit:t.limit}))o.push(s);return e.json(o)}).get("/status",a({summary:"Get session status",description:"Retrieve the current status of all sessions, including active, idle, and completed states.",operationId:"session.status",responses:{200:{description:"Get session status",content:{"application/json":{schema:i(b.record(b.string(),He.Info))}}},...l(400)}}),async e=>{let t=await He.list();return e.json(Object.fromEntries(t))}).get("/:sessionID",a({summary:"Get session",description:"Retrieve detailed information about a specific OpenCode session.",tags:["Session"],operationId:"session.get",responses:{200:{description:"Get session",content:{"application/json":{schema:i(h.Info)}}},...l(400,404)}}),p("param",b.object({sessionID:h.get.schema})),async e=>{let t=e.req.valid("param").sessionID;$t.info("SEARCH",{url:e.req.url});let o=await h.get(t);return e.json(o)}).get("/:sessionID/children",a({summary:"Get session children",tags:["Session"],description:"Retrieve all child sessions that were forked from the specified parent session.",operationId:"session.children",responses:{200:{description:"List of children",content:{"application/json":{schema:i(h.Info.array())}}},...l(400,404)}}),p("param",b.object({sessionID:h.children.schema})),async e=>{let t=e.req.valid("param").sessionID,o=await h.children(t);return e.json(o)}).get("/:sessionID/todo",a({summary:"Get session todos",description:"Retrieve the todo list associated with a specific session, showing tasks and action items.",operationId:"session.todo",responses:{200:{description:"Todo list",content:{"application/json":{schema:i(Nt.Info.array())}}},...l(400,404)}}),p("param",b.object({sessionID:X.zod})),async e=>{let t=e.req.valid("param").sessionID,o=await Nt.get(t);return e.json(o)}).post("/",a({summary:"Create session",description:"Create a new OpenCode session for interacting with AI assistants and managing conversations.",operationId:"session.create",responses:{...l(400),200:{description:"Successfully created session",content:{"application/json":{schema:i(h.Info)}}}}}),p("json",h.create.schema.optional()),async e=>{let t=e.req.valid("json")??{},o=await h.create(t);return e.json(o)}).delete("/:sessionID",a({summary:"Delete session",description:"Delete a session and permanently remove all associated data, including messages and history.",operationId:"session.delete",responses:{200:{description:"Successfully deleted session",content:{"application/json":{schema:i(b.boolean())}}},...l(400,404)}}),p("param",b.object({sessionID:h.remove.schema})),async e=>{let t=e.req.valid("param").sessionID;return await h.remove(t),e.json(!0)}).patch("/:sessionID",a({summary:"Update session",description:"Update properties of an existing session, such as title or other metadata.",operationId:"session.update",responses:{200:{description:"Successfully updated session",content:{"application/json":{schema:i(h.Info)}}},...l(400,404)}}),p("param",b.object({sessionID:X.zod})),p("json",b.object({title:b.string().optional(),time:b.object({archived:b.number().optional()}).optional()})),async e=>{let t=e.req.valid("param").sessionID,o=e.req.valid("json");o.title!==void 0&&await h.setTitle({sessionID:t,title:o.title}),o.time?.archived!==void 0&&await h.setArchived({sessionID:t,time:o.time.archived});let s=await h.get(t);return e.json(s)}).post("/:sessionID/init",a({summary:"Initialize session",description:"Analyze the current application and create an AGENTS.md file with project-specific agent configurations.",operationId:"session.init",responses:{200:{description:"200",content:{"application/json":{schema:i(b.boolean())}}},...l(400,404)}}),p("param",b.object({sessionID:X.zod})),p("json",h.initialize.schema.omit({sessionID:!0})),async e=>{let t=e.req.valid("param").sessionID,o=e.req.valid("json");return await h.initialize({...o,sessionID:t}),e.json(!0)}).post("/:sessionID/fork",a({summary:"Fork session",description:"Create a new session by forking an existing session at a specific message point.",operationId:"session.fork",responses:{200:{description:"200",content:{"application/json":{schema:i(h.Info)}}}}}),p("param",b.object({sessionID:h.fork.schema.shape.sessionID})),p("json",h.fork.schema.omit({sessionID:!0})),async e=>{let t=e.req.valid("param").sessionID,o=e.req.valid("json"),s=await h.fork({...o,sessionID:t});return e.json(s)}).post("/:sessionID/abort",a({summary:"Abort session",description:"Abort an active session and stop any ongoing AI processing or command execution.",operationId:"session.abort",responses:{200:{description:"Aborted session",content:{"application/json":{schema:i(b.boolean())}}},...l(400,404)}}),p("param",b.object({sessionID:X.zod})),async e=>(await de.cancel(e.req.valid("param").sessionID),e.json(!0))).post("/:sessionID/share",a({summary:"Share session",description:"Create a shareable link for a session, allowing others to view the conversation.",operationId:"session.share",responses:{200:{description:"Successfully shared session",content:{"application/json":{schema:i(h.Info)}}},...l(400,404)}}),p("param",b.object({sessionID:X.zod})),async e=>{let t=e.req.valid("param").sessionID;await h.share(t);let o=await h.get(t);return e.json(o)}).get("/:sessionID/diff",a({summary:"Get message diff",description:"Get the file changes (diff) that resulted from a specific user message in the session.",operationId:"session.diff",responses:{200:{description:"Successfully retrieved diff",content:{"application/json":{schema:i(ht.FileDiff.array())}}}}}),p("param",b.object({sessionID:gt.DiffInput.shape.sessionID})),p("query",b.object({messageID:gt.DiffInput.shape.messageID})),async e=>{let t=e.req.valid("query"),o=e.req.valid("param"),s=await gt.diff({sessionID:o.sessionID,messageID:t.messageID});return e.json(s)}).delete("/:sessionID/share",a({summary:"Unshare session",description:"Remove the shareable link for a session, making it private again.",operationId:"session.unshare",responses:{200:{description:"Successfully unshared session",content:{"application/json":{schema:i(h.Info)}}},...l(400,404)}}),p("param",b.object({sessionID:h.unshare.schema})),async e=>{let t=e.req.valid("param").sessionID;await h.unshare(t);let o=await h.get(t);return e.json(o)}).post("/:sessionID/summarize",a({summary:"Summarize session",description:"Generate a concise summary of the session using AI compaction to preserve key information.",operationId:"session.summarize",responses:{200:{description:"Summarized session",content:{"application/json":{schema:i(b.boolean())}}},...l(400,404)}}),p("param",b.object({sessionID:X.zod})),p("json",b.object({providerID:ce.zod,modelID:yt.zod,auto:b.boolean().optional().default(!1)})),async e=>{let t=e.req.valid("param").sessionID,o=e.req.valid("json"),s=await h.get(t);await nt.cleanup(s);let r=await h.messages({sessionID:t}),n=await Be.defaultAgent();for(let d=r.length-1;d>=0;d--){let u=r[d].info;if(u.role==="user"){n=u.agent||await Be.defaultAgent();break}}return await no.create({sessionID:t,agent:n,model:{providerID:o.providerID,modelID:o.modelID},auto:o.auto}),await de.loop({sessionID:t}),e.json(!0)}).get("/:sessionID/message",a({summary:"Get session messages",description:"Retrieve all messages in a session, including user prompts and AI responses.",operationId:"session.messages",responses:{200:{description:"List of messages",content:{"application/json":{schema:i(Q.WithParts.array())}}},...l(400,404)}}),p("param",b.object({sessionID:X.zod})),p("query",b.object({limit:b.coerce.number().int().min(0).optional().meta({description:"Maximum number of messages to return"}),before:b.string().optional().meta({description:"Opaque cursor for loading older messages"}).refine(e=>{if(!e)return!0;try{return Q.cursor.decode(e),!0}catch{return!1}},{message:"Invalid cursor"})}).refine(e=>!e.before||e.limit!==void 0,{message:"before requires limit",path:["before"]})),async e=>{let t=e.req.valid("query"),o=e.req.valid("param").sessionID;if(t.limit===void 0){await h.get(o);let r=await h.messages({sessionID:o});return e.json(r)}if(t.limit===0){await h.get(o);let r=await h.messages({sessionID:o});return e.json(r)}let s=await Q.page({sessionID:o,limit:t.limit,before:t.before});if(s.cursor){let r=new URL(e.req.url);r.searchParams.set("limit",t.limit.toString()),r.searchParams.set("before",s.cursor),e.header("Access-Control-Expose-Headers","Link, X-Next-Cursor"),e.header("Link",`<${r.toString()}>; rel="next"`),e.header("X-Next-Cursor",s.cursor)}return e.json(s.items)}).get("/:sessionID/message/:messageID",a({summary:"Get message",description:"Retrieve a specific message from a session by its message ID.",operationId:"session.message",responses:{200:{description:"Message",content:{"application/json":{schema:i(b.object({info:Q.Info,parts:Q.Part.array()}))}}},...l(400,404)}}),p("param",b.object({sessionID:X.zod,messageID:st.zod})),async e=>{let t=e.req.valid("param"),o=await Q.get({sessionID:t.sessionID,messageID:t.messageID});return e.json(o)}).delete("/:sessionID/message/:messageID",a({summary:"Delete message",description:"Permanently delete a specific message (and all of its parts) from a session. This does not revert any file changes that may have been made while processing the message.",operationId:"session.deleteMessage",responses:{200:{description:"Successfully deleted message",content:{"application/json":{schema:i(b.boolean())}}},...l(400,404)}}),p("param",b.object({sessionID:X.zod,messageID:st.zod})),async e=>{let t=e.req.valid("param");return await de.assertNotBusy(t.sessionID),await h.removeMessage({sessionID:t.sessionID,messageID:t.messageID}),e.json(!0)}).delete("/:sessionID/message/:messageID/part/:partID",a({description:"Delete a part from a message",operationId:"part.delete",responses:{200:{description:"Successfully deleted part",content:{"application/json":{schema:i(b.boolean())}}},...l(400,404)}}),p("param",b.object({sessionID:X.zod,messageID:st.zod,partID:Tt.zod})),async e=>{let t=e.req.valid("param");return await h.removePart({sessionID:t.sessionID,messageID:t.messageID,partID:t.partID}),e.json(!0)}).patch("/:sessionID/message/:messageID/part/:partID",a({description:"Update a part in a message",operationId:"part.update",responses:{200:{description:"Successfully updated part",content:{"application/json":{schema:i(Q.Part)}}},...l(400,404)}}),p("param",b.object({sessionID:X.zod,messageID:st.zod,partID:Tt.zod})),p("json",Q.Part),async e=>{let t=e.req.valid("param"),o=e.req.valid("json");if(o.id!==t.partID||o.messageID!==t.messageID||o.sessionID!==t.sessionID)throw new Error(`Part mismatch: body.id='${o.id}' vs partID='${t.partID}', body.messageID='${o.messageID}' vs messageID='${t.messageID}', body.sessionID='${o.sessionID}' vs sessionID='${t.sessionID}'`);let s=await h.updatePart(o);return e.json(s)}).post("/:sessionID/message",a({summary:"Send message",description:"Create and send a new message to a session, streaming the AI response.",operationId:"session.prompt",responses:{200:{description:"Created message",content:{"application/json":{schema:i(b.object({info:Q.Assistant,parts:Q.Part.array()}))}}},...l(400,404)}}),p("param",b.object({sessionID:X.zod})),p("json",de.PromptInput.omit({sessionID:!0})),async e=>(e.status(200),e.header("Content-Type","application/json"),Po(e,async t=>{let o=e.req.valid("param").sessionID,s=e.req.valid("json"),r=await de.prompt({...s,sessionID:o});t.write(JSON.stringify(r))}))).post("/:sessionID/prompt_async",a({summary:"Send async message",description:"Create and send a new message to a session asynchronously, starting the session if needed and returning immediately.",operationId:"session.prompt_async",responses:{202:{description:"Prompt accepted"},...l(400,404)}}),p("param",b.object({sessionID:X.zod})),p("json",de.PromptInput.omit({sessionID:!0})),async e=>(e.status(202),Po(e,async()=>{let t=e.req.valid("param").sessionID,o=e.req.valid("json");de.prompt({...o,sessionID:t}).catch(s=>{$t.error("prompt_async failed",{sessionID:t,error:s}),W.publish(h.Event.Error,{sessionID:t,error:new ge.Unknown({message:s instanceof Error?s.message:String(s)}).toObject()})})}))).post("/:sessionID/command",a({summary:"Send command",description:"Send a new command to a session for execution by the AI assistant.",operationId:"session.command",responses:{200:{description:"Created message",content:{"application/json":{schema:i(b.object({info:Q.Assistant,parts:Q.Part.array()}))}}},...l(400,404)}}),p("param",b.object({sessionID:X.zod})),p("json",de.CommandInput.omit({sessionID:!0})),async e=>{let t=e.req.valid("param").sessionID,o=e.req.valid("json"),s=await de.command({...o,sessionID:t});return e.json(s)}).post("/:sessionID/shell",a({summary:"Run shell command",description:"Execute a shell command within the session context and return the AI's response.",operationId:"session.shell",responses:{200:{description:"Created message",content:{"application/json":{schema:i(Q.Assistant)}}},...l(400,404)}}),p("param",b.object({sessionID:X.zod})),p("json",de.ShellInput.omit({sessionID:!0})),async e=>{let t=e.req.valid("param").sessionID,o=e.req.valid("json"),s=await de.shell({...o,sessionID:t});return e.json(s)}).post("/:sessionID/revert",a({summary:"Revert message",description:"Revert a specific message in a session, undoing its effects and restoring the previous state.",operationId:"session.revert",responses:{200:{description:"Updated session",content:{"application/json":{schema:i(h.Info)}}},...l(400,404)}}),p("param",b.object({sessionID:X.zod})),p("json",nt.RevertInput.omit({sessionID:!0})),async e=>{let t=e.req.valid("param").sessionID;$t.info("revert",e.req.valid("json"));let o=await nt.revert({sessionID:t,...e.req.valid("json")});return e.json(o)}).post("/:sessionID/unrevert",a({summary:"Restore reverted messages",description:"Restore all previously reverted messages in a session.",operationId:"session.unrevert",responses:{200:{description:"Updated session",content:{"application/json":{schema:i(h.Info)}}},...l(400,404)}}),p("param",b.object({sessionID:X.zod})),async e=>{let t=e.req.valid("param").sessionID,o=await nt.unrevert({sessionID:t});return e.json(o)}).post("/:sessionID/permissions/:permissionID",a({summary:"Respond to permission",deprecated:!0,description:"Approve or deny a permission request from the AI assistant.",operationId:"permission.respond",responses:{200:{description:"Permission processed successfully",content:{"application/json":{schema:i(b.boolean())}}},...l(400,404)}}),p("param",b.object({sessionID:X.zod,permissionID:bt.zod})),p("json",b.object({response:qe.Reply})),async e=>{let t=e.req.valid("param");return qe.reply({requestID:t.permissionID,reply:e.req.valid("json").response}),e.json(!0)}));import{Hono as Hs}from"hono";import Xe from"zod";import T from"zod";function xo(e){let t,o=!1;return()=>(o||(o=!0,t=e()),t)}c(xo,"lazy");import{Schema as qo}from"effect";import Fs from"zod";var Ws=qo.String.pipe(qo.brand("PtyID")),be=Ws.pipe(oo(e=>({make:c(t=>e.makeUnsafe(t),"make"),ascending:c(t=>e.makeUnsafe(Ot.ascending("pty",t)),"ascending"),zod:Ot.schema("pty").pipe(Fs.custom())})));import{Effect as re,Layer as Vt,ServiceMap as Bs}from"effect";var ie;(D=>{let e=G.create({service:"pty"}),t=1024*1024*2,o=64*1024,s=new TextEncoder,r=c(S=>S.data&&typeof S.data=="object"?S.data:S,"sock"),n=c(S=>{let E=JSON.stringify({cursor:S}),$=s.encode(E),Z=new Uint8Array($.length+1);return Z[0]=0,Z.set($,1),Z},"meta"),d=xo(()=>import("./pty.node-X2EITEZ4.js"));D.Info=T.object({id:be.zod,title:T.string(),command:T.string(),args:T.array(T.string()),cwd:T.string(),status:T.enum(["running","exited"]),pid:T.number()}).meta({ref:"Pty"}),D.CreateInput=T.object({command:T.string().optional(),args:T.array(T.string()).optional(),cwd:T.string().optional(),title:T.string().optional(),env:T.record(T.string(),T.string()).optional()}),D.UpdateInput=T.object({title:T.string().optional(),size:T.object({rows:T.number(),cols:T.number()}).optional()}),D.Event={Created:ue.define("pty.created",T.object({info:D.Info})),Updated:ue.define("pty.updated",T.object({info:D.Info})),Exited:ue.define("pty.exited",T.object({id:be.zod,exitCode:T.number()})),Deleted:ue.define("pty.deleted",T.object({id:be.zod}))};class y extends Bs.Service()("@opencode/Pty"){static{c(this,"Service")}}D.Service=y,D.layer=Vt.effect(y,re.gen(function*(){let S=yield*W.Service,E=yield*Ve.Service;function $(R){try{R.process.kill()}catch{}for(let[q,z]of R.subscribers.entries())try{r(z)===q&&z.close()}catch{}R.subscribers.clear()}c($,"teardown");let Z=yield*ne.make(re.fn("Pty.state")(function*(R){let q={dir:R.directory,sessions:new Map};return yield*re.addFinalizer(()=>re.sync(()=>{for(let z of q.sessions.values())$(z);q.sessions.clear()})),q})),dt=re.fn("Pty.remove")(function*(R){let q=yield*ne.get(Z),z=q.sessions.get(R);z&&(q.sessions.delete(R),e.info("removing session",{id:R}),$(z),yield*S.publish(D.Event.Deleted,{id:z.info.id}))}),At=re.fn("Pty.list")(function*(){let R=yield*ne.get(Z);return Array.from(R.sessions.values()).map(q=>q.info)}),ts=re.fn("Pty.get")(function*(R){return(yield*ne.get(Z)).sessions.get(R)?.info}),os=re.fn("Pty.create")(function*(R){let q=yield*ne.get(Z),z=be.ascending(),oe=R.command||Lt.preferred(),K=R.args||[];Lt.login(oe)&&K.push("-l");let Pe=R.cwd||q.dir,Ze=yield*E.trigger("shell.env",{cwd:Pe},{env:{}}),Me={...process.env,...R.env,...Ze.env,TERM:"xterm-256color",OPENCODE_TERMINAL:"1"};process.platform==="win32"&&(Me.LC_ALL="C.UTF-8",Me.LC_CTYPE="C.UTF-8",Me.LANG="C.UTF-8"),e.info("creating session",{id:z,cmd:oe,args:K,cwd:Pe});let{spawn:et}=yield*re.promise(()=>d()),Ee=yield*re.sync(()=>et(oe,K,{name:"xterm-256color",cwd:Pe,env:Me})),Oe={id:z,title:R.title||`Terminal ${z.slice(-4)}`,command:oe,args:K,cwd:Pe,status:"running",pid:Ee.pid},L={info:Oe,process:Ee,buffer:"",bufferCursor:0,cursor:0,subscribers:new Map};return q.sessions.set(z,L),Ee.onData(_.bind(Ne=>{L.cursor+=Ne.length;for(let[mt,Ct]of L.subscribers.entries()){if(Ct.readyState!==1){L.subscribers.delete(mt);continue}if(r(Ct)!==mt){L.subscribers.delete(mt);continue}try{Ct.send(Ne)}catch{L.subscribers.delete(mt)}}if(L.buffer+=Ne,L.buffer.length<=t)return;let Kt=L.buffer.length-t;L.buffer=L.buffer.slice(Kt),L.bufferCursor+=Kt})),Ee.onExit(_.bind(({exitCode:Ne})=>{L.info.status!=="exited"&&(e.info("session exited",{id:z,exitCode:Ne}),L.info.status="exited",re.runFork(S.publish(D.Event.Exited,{id:z,exitCode:Ne})),re.runFork(dt(z)))})),yield*S.publish(D.Event.Created,{info:Oe}),Oe}),ss=re.fn("Pty.update")(function*(R,q){let oe=(yield*ne.get(Z)).sessions.get(R);if(oe)return q.title&&(oe.info.title=q.title),q.size&&oe.process.resize(q.size.cols,q.size.rows),yield*S.publish(D.Event.Updated,{info:oe.info}),oe.info}),rs=re.fn("Pty.resize")(function*(R,q,z){let K=(yield*ne.get(Z)).sessions.get(R);K&&K.info.status==="running"&&K.process.resize(q,z)}),ns=re.fn("Pty.write")(function*(R,q){let oe=(yield*ne.get(Z)).sessions.get(R);oe&&oe.info.status==="running"&&oe.process.write(q)}),is=re.fn("Pty.connect")(function*(R,q,z){let K=(yield*ne.get(Z)).sessions.get(R);if(!K){q.close();return}e.info("client connected to session",{id:R});let Pe=r(q);K.subscribers.delete(Pe),K.subscribers.set(Pe,q);let Ze=c(()=>{K.subscribers.delete(Pe)},"cleanup"),Me=K.bufferCursor,et=K.cursor,Ee=z===-1?et:typeof z=="number"&&Number.isSafeInteger(z)?Math.max(0,z):0,Oe=(()=>{if(!K.buffer||Ee>=et)return"";let L=Math.max(0,Ee-Me);return L>=K.buffer.length?"":K.buffer.slice(L)})();if(Oe)try{for(let L=0;L<Oe.length;L+=o)q.send(Oe.slice(L,L+o))}catch{Ze(),q.close();return}try{q.send(n(et))}catch{Ze(),q.close();return}return{onMessage:c(L=>{K.process.write(String(L))},"onMessage"),onClose:c(()=>{e.info("client disconnected from session",{id:R}),Ze()},"onClose")}});return y.of({list:At,get:ts,create:os,update:ss,remove:dt,resize:rs,write:ns,connect:is})}));let g=D.layer.pipe(Vt.provide(W.layer),Vt.provide(Ve.defaultLayer)),{runPromise:m}=ft(y,g);async function I(){return m(S=>S.list())}D.list=I,c(I,"list");async function w(S){return m(E=>E.get(S))}D.get=w,c(w,"get");async function M(S,E,$){return m(Z=>Z.resize(S,E,$))}D.resize=M,c(M,"resize");async function ee(S,E){return m($=>$.write(S,E))}D.write=ee,c(ee,"write");async function he(S,E,$){return m(Z=>Z.connect(S,E,$))}D.connect=he,c(he,"connect");async function U(S){return m(E=>E.create(S))}D.create=U,c(U,"create");async function le(S,E){return m($=>$.update(S,E))}D.update=le,c(le,"update");async function N(S){return m(E=>E.remove(S))}D.remove=N,c(N,"remove")})(ie||={});function Ao(e){return new Hs().get("/",a({summary:"List PTY sessions",description:"Get a list of all active pseudo-terminal (PTY) sessions managed by OpenCode.",operationId:"pty.list",responses:{200:{description:"List of sessions",content:{"application/json":{schema:i(ie.Info.array())}}}}}),async t=>t.json(await ie.list())).post("/",a({summary:"Create PTY session",description:"Create a new pseudo-terminal (PTY) session for running shell commands and processes.",operationId:"pty.create",responses:{200:{description:"Created session",content:{"application/json":{schema:i(ie.Info)}}},...l(400)}}),p("json",ie.CreateInput),async t=>{let o=await ie.create(t.req.valid("json"));return t.json(o)}).get("/:ptyID",a({summary:"Get PTY session",description:"Retrieve detailed information about a specific pseudo-terminal (PTY) session.",operationId:"pty.get",responses:{200:{description:"Session info",content:{"application/json":{schema:i(ie.Info)}}},...l(404)}}),p("param",Xe.object({ptyID:be.zod})),async t=>{let o=await ie.get(t.req.valid("param").ptyID);if(!o)throw new ke({message:"Session not found"});return t.json(o)}).put("/:ptyID",a({summary:"Update PTY session",description:"Update properties of an existing pseudo-terminal (PTY) session.",operationId:"pty.update",responses:{200:{description:"Updated session",content:{"application/json":{schema:i(ie.Info)}}},...l(400)}}),p("param",Xe.object({ptyID:be.zod})),p("json",ie.UpdateInput),async t=>{let o=await ie.update(t.req.valid("param").ptyID,t.req.valid("json"));return t.json(o)}).delete("/:ptyID",a({summary:"Remove PTY session",description:"Remove and terminate a specific pseudo-terminal (PTY) session.",operationId:"pty.remove",responses:{200:{description:"Session removed",content:{"application/json":{schema:i(Xe.boolean())}}},...l(404)}}),p("param",Xe.object({ptyID:be.zod})),async t=>(await ie.remove(t.req.valid("param").ptyID),t.json(!0))).get("/:ptyID/connect",a({summary:"Connect to PTY session",description:"Establish a WebSocket connection to interact with a pseudo-terminal (PTY) session in real-time.",operationId:"pty.connect",responses:{200:{description:"Connected session",content:{"application/json":{schema:i(Xe.boolean())}}},...l(404)}}),p("param",Xe.object({ptyID:be.zod})),e(async t=>{let o=be.zod.parse(t.req.param("ptyID")),s=(()=>{let f=t.req.query("cursor");if(!f)return;let x=Number(f);if(!(!Number.isSafeInteger(x)||x<-1))return x})(),r;if(!await ie.get(o))throw new Error("Session not found");let n=c(f=>!f||typeof f!="object"||!("readyState"in f)||!("send"in f)||typeof f.send!="function"||!("close"in f)||typeof f.close!="function"?!1:typeof f.readyState=="number","isSocket"),d=[],u=!1;return{async onOpen(f,x){let k=x.raw;if(!n(k)){x.close();return}r=await ie.connect(o,k,s),u=!0;for(let y of d)r?.onMessage(y);d.length=0},onMessage(f){if(typeof f.data=="string"){if(!u){d.push(f.data);return}r?.onMessage(f.data)}},onClose(){r?.onClose()},onError(){r?.onClose()}}}))}c(Ao,"PtyRoutes");import{Hono as $s}from"hono";import H from"zod";var Co=A(()=>new $s().get("/",a({summary:"Get MCP status",description:"Get the status of all Model Context Protocol (MCP) servers.",operationId:"mcp.status",responses:{200:{description:"MCP server status",content:{"application/json":{schema:i(H.record(H.string(),V.Status))}}}}}),async e=>e.json(await V.status())).get("/tools",a({summary:"List MCP tools",description:"The tool catalogue each connected MCP server advertises, with read-only annotations intact. This is the catalogue, not the callable tool set: use it to show or govern what a server offers.",operationId:"mcp.tools",responses:{200:{description:"Tools per connected server",content:{"application/json":{schema:i(H.record(H.string(),H.array(V.ToolManifestEntry)))}}}}}),async e=>e.json(await V.toolManifest())).post("/",a({summary:"Add MCP server",description:"Dynamically add a new Model Context Protocol (MCP) server to the system.",operationId:"mcp.add",responses:{200:{description:"MCP server added successfully",content:{"application/json":{schema:i(H.record(H.string(),V.Status))}}},...l(400)}}),p("json",H.object({name:H.string(),config:J.Mcp})),async e=>{let{name:t,config:o}=e.req.valid("json"),s=await V.add(t,o);return e.json(s.status)}).post("/:name/auth",a({summary:"Start MCP OAuth",description:"Start OAuth authentication flow for a Model Context Protocol (MCP) server.",operationId:"mcp.auth.start",responses:{200:{description:"OAuth flow started",content:{"application/json":{schema:i(H.object({authorizationUrl:H.string().describe("URL to open in browser for authorization")}))}}},...l(400,404)}}),async e=>{let t=e.req.param("name");if(!await V.supportsOAuth(t))return e.json({error:`MCP server ${t} does not support OAuth`},400);let s=await V.startAuth(t);return e.json(s)}).post("/:name/auth/callback",a({summary:"Complete MCP OAuth",description:"Complete OAuth authentication for a Model Context Protocol (MCP) server using the authorization code.",operationId:"mcp.auth.callback",responses:{200:{description:"OAuth authentication completed",content:{"application/json":{schema:i(V.Status)}}},...l(400,404)}}),p("json",H.object({code:H.string().describe("Authorization code from OAuth callback")})),async e=>{let t=e.req.param("name"),{code:o}=e.req.valid("json"),s=await V.finishAuth(t,o);return e.json(s)}).post("/:name/auth/authenticate",a({summary:"Authenticate MCP OAuth",description:"Start OAuth flow and wait for callback (opens browser)",operationId:"mcp.auth.authenticate",responses:{200:{description:"OAuth authentication completed",content:{"application/json":{schema:i(V.Status)}}},...l(400,404)}}),async e=>{let t=e.req.param("name");if(!await V.supportsOAuth(t))return e.json({error:`MCP server ${t} does not support OAuth`},400);let s=await V.authenticate(t);return e.json(s)}).delete("/:name/auth",a({summary:"Remove MCP OAuth",description:"Remove OAuth credentials for an MCP server",operationId:"mcp.auth.remove",responses:{200:{description:"OAuth credentials removed",content:{"application/json":{schema:i(H.object({success:H.literal(!0)}))}}},...l(404)}}),async e=>{let t=e.req.param("name");return await V.removeAuth(t),e.json({success:!0})}).post("/:name/connect",a({description:"Connect an MCP server",operationId:"mcp.connect",responses:{200:{description:"MCP server connected successfully",content:{"application/json":{schema:i(H.boolean())}}}}}),p("param",H.object({name:H.string()})),async e=>{let{name:t}=e.req.valid("param");return await V.connect(t),e.json(!0)}).post("/:name/disconnect",a({description:"Disconnect an MCP server",operationId:"mcp.disconnect",responses:{200:{description:"MCP server disconnected successfully",content:{"application/json":{schema:i(H.boolean())}}}}}),p("param",H.object({name:H.string()})),async e=>{let{name:t}=e.req.valid("param");return await V.disconnect(t),e.json(!0)}));import{Hono as Vs}from"hono";import me from"zod";var Ro=A(()=>new Vs().get("/find",a({summary:"Find text",description:"Search for text patterns across files in the project using ripgrep.",operationId:"find.text",responses:{200:{description:"Matches",content:{"application/json":{schema:i(_t.Match.shape.data.array())}}}}}),p("query",me.object({pattern:me.string()})),async e=>{let t=e.req.valid("query").pattern,o=await _t.search({cwd:_.directory,pattern:t,limit:10});return e.json(o)}).get("/find/file",a({summary:"Find files",description:"Search for files or directories by name or pattern in the project directory.",operationId:"find.files",responses:{200:{description:"File paths",content:{"application/json":{schema:i(me.string().array())}}}}}),p("query",me.object({query:me.string(),dirs:me.enum(["true","false"]).optional(),type:me.enum(["file","directory"]).optional(),limit:me.coerce.number().int().min(1).max(200).optional()})),async e=>{let t=e.req.valid("query").query,o=e.req.valid("query").dirs,s=e.req.valid("query").type,r=e.req.valid("query").limit,n=await Ae.search({query:t,limit:r??10,dirs:o!=="false",type:s});return e.json(n)}).get("/find/symbol",a({summary:"Find symbols",description:"Search for workspace symbols like functions, classes, and variables using LSP.",operationId:"find.symbols",responses:{200:{description:"Symbols",content:{"application/json":{schema:i(rt.Symbol.array())}}}}}),p("query",me.object({query:me.string()})),async e=>e.json([])).get("/file",a({summary:"List files",description:"List files and directories in a specified path.",operationId:"file.list",responses:{200:{description:"Files and directories",content:{"application/json":{schema:i(Ae.Node.array())}}}}}),p("query",me.object({path:me.string()})),async e=>{let t=e.req.valid("query").path,o=await Ae.list(t);return e.json(o)}).get("/file/content",a({summary:"Read file",description:"Read the content of a specified file.",operationId:"file.read",responses:{200:{description:"File content",content:{"application/json":{schema:i(Ae.Content)}}}}}),p("query",me.object({path:me.string()})),async e=>{let t=e.req.valid("query").path,o=await Ae.read(t);return e.json(o)}).get("/file/status",a({summary:"Get file status",description:"Get the git status of all files in the project.",operationId:"file.status",responses:{200:{description:"File status",content:{"application/json":{schema:i(Ae.Info.array())}}}}}),async e=>{let t=await Ae.status();return e.json(t)}));import{Hono as Js}from"hono";import C from"zod";import{mapValues as Eo}from"remeda";var Ys=6e4,Qe,Oo=new Map;async function _o(e,t){let o=await fetch(e,{headers:t,signal:AbortSignal.timeout(1e4)});if(!o.ok)throw new Error(`HTTP ${o.status}`);return o.json()}c(_o,"readUsageJson");function Ks(e){let t=[];for(let o of["primary_window","secondary_window"]){let s=e?.[o];if(!s||typeof s!="object")continue;let r=Number(s.limit_window_seconds??0),n=r>=5e5?"7d":r>0&&r<=21600?"5h":"other";t.push({kind:n,label:n==="7d"?"weekly":n==="5h"?"5-hour window":`${Math.round(r/3600)}h window`,usedPercent:Number(s.used_percent??0),resetsAt:typeof s.reset_at=="number"?s.reset_at:null})}return t}c(Ks,"openaiWindows");async function Xs(e){let t={authorization:`Bearer ${e.access}`};e.accountId&&(t["ChatGPT-Account-Id"]=e.accountId);let o=await _o("https://chatgpt.com/backend-api/wham/usage",t);return{providerID:"openai",plan:typeof o?.plan_type=="string"?o.plan_type:null,windows:Ks(o?.rate_limit)}}c(Xs,"openaiUsage");async function Qs(e){let t=await _o("https://api.anthropic.com/api/oauth/usage",{authorization:`Bearer ${e.access}`,"anthropic-beta":"oauth-2025-04-20"}),o=c(r=>typeof r=="string"&&!Number.isNaN(Date.parse(r))?Math.floor(Date.parse(r)/1e3):null,"toTs"),s=[];t?.five_hour&&typeof t.five_hour=="object"&&s.push({kind:"5h",label:"5-hour window",usedPercent:Number(t.five_hour.utilization??0),resetsAt:o(t.five_hour.resets_at)}),t?.seven_day&&typeof t.seven_day=="object"&&s.push({kind:"7d",label:"weekly",usedPercent:Number(t.seven_day.utilization??0),resetsAt:o(t.seven_day.resets_at)});for(let r of Array.isArray(t?.limits)?t.limits:[]){let n=r?.scope?.model?.display_name;r?.kind==="weekly_scoped"&&typeof n=="string"&&n&&s.push({kind:"other",label:`weekly, ${n}`,usedPercent:Number(r.percent??0),resetsAt:o(r.resets_at)})}return{providerID:"anthropic",plan:null,windows:s}}c(Qs,"anthropicUsage");async function Zs(e=!1){if(!e&&Qe&&Date.now()-Qe.at<Ys)return{providers:Qe.data,fetchedAt:Qe.at};let t=await De.all().catch(()=>({})),o=[];for(let[s,r]of Object.entries(t)){if(r.type!=="oauth"||s!=="openai"&&s!=="anthropic")continue;let n=r;if(n.expires<Date.now()){o.push({providerID:s,plan:null,windows:[],error:"token expired; it refreshes on the next model call"});continue}try{let d={...s==="openai"?await Xs(n):await Qs(n),readAt:Date.now()};Oo.set(s,d),o.push(d)}catch(d){let u=d instanceof Error?d.message:String(d),f=Oo.get(s);o.push(f?{...f,error:u}:{providerID:s,plan:null,windows:[],error:u})}}return Qe={at:Date.now(),data:o},{providers:o,fetchedAt:Qe.at}}c(Zs,"providerUsage");var St;async function To(){let e=await He.list().catch(()=>new Map);for(let t of e.values())if(t.type!=="idle")return!0;return!1}c(To,"anySessionBusy");async function zo(){let e=St;St=void 0,e&&(e.unsubscribe(),clearTimeout(e.timer)),await J.invalidate(!0)}c(zo,"fireDeferredReload");var er=G.create({service:"server"}),Uo=A(()=>new Js().get("/",a({summary:"Get configuration",description:"Retrieve the current OpenCode configuration settings and preferences.",operationId:"config.get",responses:{200:{description:"Get config info",content:{"application/json":{schema:i(J.Info)}}}}}),async e=>e.json(await J.get())).patch("/",a({summary:"Update configuration",description:"Update OpenCode configuration settings and preferences.",operationId:"config.update",responses:{200:{description:"Successfully updated config",content:{"application/json":{schema:i(J.Info)}}},...l(400)}}),p("json",J.Info),async e=>{let t=e.req.valid("json");return await J.update(t),e.json(t)}).get("/pause",a({summary:"Pause state",description:"Whether this project's turns are paused, and the sessions whose turns wait for Resume (alchemy fork).",operationId:"config.pauseState",responses:{200:{description:"Pause state",content:{"application/json":{schema:i(C.object({paused:C.boolean(),waiting:C.array(C.string())}))}}}}}),async e=>e.json(vt.state())).post("/pause",a({summary:"Pause or resume the project",description:"Paused, no turn runs: running turns stop and their sessions wait, and anything sent meanwhile lands and waits. Resume returns the sessions that wait, for the caller to wake (alchemy fork, session/pause.ts).",operationId:"config.pause",responses:{200:{description:"The new state; `stopped` on pause, `waiting` on resume",content:{"application/json":{schema:i(C.object({paused:C.boolean(),stopped:C.array(C.string()).optional(),waiting:C.array(C.string()).optional()}))}}}}}),p("json",C.object({paused:C.boolean()})),async e=>{if(e.req.valid("json").paused){vt.pause();let t=await de.stopForPause();return e.json({paused:!0,stopped:t})}return e.json({paused:!1,waiting:vt.resume()})}).post("/reload",a({summary:"Reload configuration",description:"Invalidate all cached config and agent state, forcing a re-read from disk on next access.",operationId:"config.reload",responses:{200:{description:"Config cache invalidated",content:{"application/json":{schema:i(C.object({ok:C.boolean()}))}}}}}),async e=>{if(await To()){if(!St){let t=W.subscribe(He.Event.Status,async()=>{await To()||await zo()}),o=setTimeout(()=>{zo()},12e4);St={unsubscribe:t,timer:o}}return e.json({ok:!0,deferred:!0})}return await J.invalidate(!0),e.json({ok:!0})}).get("/usage",a({summary:"Plan usage",description:"Percent used and reset times of the usage windows on the OAuth providers this instance is signed into.",operationId:"config.usage",responses:{200:{description:"Per-provider usage windows",content:{"application/json":{schema:i(C.object({fetchedAt:C.number(),providers:C.array(C.object({providerID:C.string(),plan:C.string().nullable(),error:C.string().optional(),readAt:C.number().optional(),windows:C.array(C.object({kind:C.string(),label:C.string(),usedPercent:C.number(),resetsAt:C.number().nullable()}))}))}))}}}}}),async e=>e.json(await Zs(e.req.query("force")==="1"))).get("/providers",a({summary:"List config providers",description:"Get a list of all configured AI providers and their default models.",operationId:"config.providers",responses:{200:{description:"List of providers",content:{"application/json":{schema:i(C.object({providers:ve.Info.array(),default:C.record(C.string(),C.string())}))}}}}}),async e=>{var s=[];try{let t=Xt(s,er.time("providers"));let o=await ve.list().then(u=>Eo(u,f=>f));return e.json({providers:Object.values(o),default:Eo(o,u=>ve.sort(Object.values(u.models))[0].id)})}catch(r){var n=r,d=!0}finally{Qt(s,n,d)}}));import{Hono as or}from"hono";import P from"zod";import ct from"zod";var Lo=ct.object({consoleManagedProviders:ct.array(ct.string()),activeOrgName:ct.string().optional(),switchableOrgCount:ct.number().int().nonnegative()});import{zodToJsonSchema as sr}from"zod-to-json-schema";import{Hono as tr}from"hono";import Mo from"zod";var No=A(()=>new tr().post("/",a({summary:"Create workspace",description:"Create a workspace for the current project.",operationId:"experimental.workspace.create",responses:{200:{description:"Workspace created",content:{"application/json":{schema:i(ye.Info)}}},...l(400)}}),p("json",ye.create.schema.omit({projectID:!0})),async e=>{let t=e.req.valid("json"),o=await ye.create({projectID:_.project.id,...t});return e.json(o)}).get("/",a({summary:"List workspaces",description:"List all workspaces.",operationId:"experimental.workspace.list",responses:{200:{description:"Workspaces",content:{"application/json":{schema:i(Mo.array(ye.Info))}}}}}),async e=>e.json(ye.list(_.project))).delete("/:id",a({summary:"Remove workspace",description:"Remove an existing workspace.",operationId:"experimental.workspace.remove",responses:{200:{description:"Workspace removed",content:{"application/json":{schema:i(ye.Info.optional())}}},...l(400)}}),p("param",Mo.object({id:ye.Info.shape.id})),async e=>{let{id:t}=e.req.valid("param");return e.json(await ye.remove(t))}));var rr=P.object({accountID:P.string(),accountEmail:P.string(),accountUrl:P.string(),orgID:P.string(),orgName:P.string(),active:P.boolean()}),nr=P.object({orgs:P.array(rr)}),ir=P.object({accountID:P.string(),orgID:P.string()}),Go=A(()=>new or().get("/console",a({summary:"Get active Console provider metadata",description:"Get the active Console org name and the set of provider IDs managed by that Console org.",operationId:"experimental.console.get",responses:{200:{description:"Active Console provider metadata",content:{"application/json":{schema:i(Lo)}}}}}),async e=>{let[t,o]=await Promise.all([J.getConsoleState(),ot.orgsByAccount()]);return e.json({...t,switchableOrgCount:o.reduce((s,r)=>s+r.orgs.length,0)})}).get("/console/orgs",a({summary:"List switchable Console orgs",description:"Get the available Console orgs across logged-in accounts, including the current active org.",operationId:"experimental.console.listOrgs",responses:{200:{description:"Switchable Console orgs",content:{"application/json":{schema:i(nr)}}}}}),async e=>{let[t,o]=await Promise.all([ot.orgsByAccount(),ot.active()]),s=t.flatMap(r=>r.orgs.map(n=>({accountID:r.account.id,accountEmail:r.account.email,accountUrl:r.account.url,orgID:n.id,orgName:n.name,active:!!o&&o.id===r.account.id&&o.active_org_id===n.id})));return e.json({orgs:s})}).post("/console/switch",a({summary:"Switch active Console org",description:"Persist a new active Console account/org selection for the current local OpenCode state.",operationId:"experimental.console.switchOrg",responses:{200:{description:"Switch success",content:{"application/json":{schema:i(P.boolean())}}}}}),p("json",ir),async e=>{let t=e.req.valid("json");return await ot.switchOrg(so.make(t.accountID),ro.make(t.orgID)),e.json(!0)}).get("/tool/ids",a({summary:"List tool IDs",description:"Get a list of all available tool IDs, including both built-in tools and dynamically registered tools.",operationId:"tool.ids",responses:{200:{description:"Tool IDs",content:{"application/json":{schema:i(P.array(P.string()).meta({ref:"ToolIDs"}))}}},...l(400)}}),async e=>e.json(await Gt.ids())).get("/tool",a({summary:"List tools",description:"Get a list of available tools with their JSON schema parameters for a specific provider and model combination.",operationId:"tool.list",responses:{200:{description:"Tools",content:{"application/json":{schema:i(P.array(P.object({id:P.string(),description:P.string(),parameters:P.any()}).meta({ref:"ToolListItem"})).meta({ref:"ToolList"}))}}},...l(400)}}),p("query",P.object({provider:P.string(),model:P.string()})),async e=>{let{provider:t,model:o}=e.req.valid("query"),s=await Gt.tools({providerID:ce.make(t),modelID:yt.make(o)});return e.json(s.map(r=>({id:r.id,description:r.description,parameters:r.parameters?._def?sr(r.parameters):r.parameters})))}).route("/workspace",No()).post("/worktree",a({summary:"Create worktree",description:"Create a new git worktree for the current project and run any configured startup scripts.",operationId:"worktree.create",responses:{200:{description:"Worktree created",content:{"application/json":{schema:i(Ce.Info)}}},...l(400)}}),p("json",Ce.CreateInput.optional()),async e=>{let t=e.req.valid("json"),o=await Ce.create(t);return e.json(o)}).get("/worktree",a({summary:"List worktrees",description:"List all sandbox worktrees for the current project.",operationId:"worktree.list",responses:{200:{description:"List of worktree directories",content:{"application/json":{schema:i(P.array(P.string()))}}}}}),async e=>{let t=await fe.sandboxes(_.project.id);return e.json(t)}).delete("/worktree",a({summary:"Remove worktree",description:"Remove a git worktree and delete its branch.",operationId:"worktree.remove",responses:{200:{description:"Worktree removed",content:{"application/json":{schema:i(P.boolean())}}},...l(400)}}),p("json",Ce.RemoveInput),async e=>{let t=e.req.valid("json");return await Ce.remove(t),await fe.removeSandbox(_.project.id,t.directory),e.json(!0)}).post("/worktree/reset",a({summary:"Reset worktree",description:"Reset a worktree branch to the primary default branch.",operationId:"worktree.reset",responses:{200:{description:"Worktree reset",content:{"application/json":{schema:i(P.boolean())}}},...l(400)}}),p("json",Ce.ResetInput),async e=>{let t=e.req.valid("json");return await Ce.reset(t),e.json(!0)}).get("/session",a({summary:"List sessions",description:"Get a list of all OpenCode sessions across projects, sorted by most recently updated. Archived sessions are excluded by default.",operationId:"experimental.session.list",responses:{200:{description:"List of sessions",content:{"application/json":{schema:i(h.GlobalInfo.array())}}}}}),p("query",P.object({directory:P.string().optional().meta({description:"Filter sessions by project directory"}),roots:P.coerce.boolean().optional().meta({description:"Only return root sessions (no parentID)"}),start:P.coerce.number().optional().meta({description:"Filter sessions updated on or after this timestamp (milliseconds since epoch)"}),cursor:P.coerce.number().optional().meta({description:"Return sessions updated before this timestamp (milliseconds since epoch)"}),search:P.string().optional().meta({description:"Filter sessions by title (case-insensitive)"}),limit:P.coerce.number().optional().meta({description:"Maximum number of sessions to return"}),archived:P.coerce.boolean().optional().meta({description:"Include archived sessions (default false)"})})),async e=>{let t=e.req.valid("query"),o=t.limit??100,s=[];for await(let d of h.listGlobal({directory:t.directory,roots:t.roots,start:t.start,cursor:t.cursor,search:t.search,limit:o+1,archived:t.archived}))s.push(d);let r=s.length>o,n=r?s.slice(0,o):s;return r&&n.length>0&&e.header("x-next-cursor",String(n[n.length-1].time.updated)),e.json(n)}).get("/resource",a({summary:"Get MCP resources",description:"Get all available MCP resources from connected servers. Optionally filter by name.",operationId:"experimental.resource.list",responses:{200:{description:"MCP resources",content:{"application/json":{schema:i(P.record(P.string(),V.Resource))}}}}}),async e=>e.json(await V.resources())));import{Hono as pr}from"hono";import Y from"zod";import{Array as ar,Effect as Ie,Layer as Pt,Record as Fo,Result as Wo,ServiceMap as cr}from"effect";import j from"zod";var Le;(g=>{g.Method=j.object({type:j.union([j.literal("oauth"),j.literal("api")]),label:j.string(),prompts:j.array(j.union([j.object({type:j.literal("text"),key:j.string(),message:j.string(),placeholder:j.string().optional(),when:j.object({key:j.string(),op:j.union([j.literal("eq"),j.literal("neq")]),value:j.string()}).optional()}),j.object({type:j.literal("select"),key:j.string(),message:j.string(),options:j.array(j.object({label:j.string(),value:j.string(),hint:j.string().optional()})),when:j.object({key:j.string(),op:j.union([j.literal("eq"),j.literal("neq")]),value:j.string()}).optional()})])).optional()}).meta({ref:"ProviderAuthMethod"}),g.Authorization=j.object({url:j.string(),method:j.union([j.literal("auto"),j.literal("code")]),instructions:j.string()}).meta({ref:"ProviderAuthAuthorization"}),g.OauthMissing=ge.create("ProviderAuthOauthMissing",j.object({providerID:ce.zod})),g.OauthCodeMissing=ge.create("ProviderAuthOauthCodeMissing",j.object({providerID:ce.zod})),g.OauthCallbackFailed=ge.create("ProviderAuthOauthCallbackFailed",j.object({})),g.ValidationFailed=ge.create("ProviderAuthValidationFailed",j.object({field:j.string(),message:j.string()}));class d extends cr.Service()("@opencode/ProviderAuth"){static{c(this,"Service")}}g.Service=d,g.layer=Pt.effect(d,Ie.gen(function*(){let m=yield*De.Service,I=yield*Ve.Service,w=yield*ne.make(Ie.fn("ProviderAuth.state")(function*(){let U=yield*I.list();return{hooks:Fo.fromEntries(ar.filterMap(U,le=>le.auth?.provider!==void 0?Wo.succeed([ce.make(le.auth.provider),le.auth]):Wo.failVoid)),pending:new Map}})),M=Ie.fn("ProviderAuth.methods")(function*(){let U=(yield*ne.get(w)).hooks;return Fo.map(U,le=>le.methods.map(N=>({type:N.type,label:N.label,prompts:N.prompts?.map(D=>D.type==="select"?{type:"select",key:D.key,message:D.message,options:D.options,when:D.when}:{type:"text",key:D.key,message:D.message,placeholder:D.placeholder,when:D.when})})))}),ee=Ie.fn("ProviderAuth.authorize")(function*(U){let{hooks:le,pending:N}=yield*ne.get(w),D=le[U.providerID].methods[U.method];if(D.type!=="oauth")return;if(D.prompts&&U.inputs){for(let E of D.prompts)if(E.type==="text"&&E.validate&&U.inputs[E.key]!==void 0){let $=E.validate(U.inputs[E.key]);if($)return yield*Ie.fail(new g.ValidationFailed({field:E.key,message:$}))}}let S=yield*Ie.promise(()=>D.authorize(U.inputs));return N.set(U.providerID,S),{url:S.url,method:S.method,instructions:S.instructions}}),he=Ie.fn("ProviderAuth.callback")(function*(U){let N=(yield*ne.get(w)).pending.get(U.providerID);if(!N)return yield*Ie.fail(new g.OauthMissing({providerID:U.providerID}));if(N.method==="code"&&!U.code)return yield*Ie.fail(new g.OauthCodeMissing({providerID:U.providerID}));let D=yield*Ie.promise(()=>N.method==="code"?N.callback(U.code):N.callback());if(!D||D.type!=="success")return yield*Ie.fail(new g.OauthCallbackFailed({}));if("key"in D&&(yield*m.set(U.providerID,{type:"api",key:D.key})),"refresh"in D){let{type:S,provider:E,refresh:$,access:Z,expires:dt,...At}=D;yield*m.set(U.providerID,{type:"oauth",access:Z,refresh:$,expires:dt,...At})}});return d.of({methods:M,authorize:ee,callback:he})})),g.defaultLayer=Pt.suspend(()=>g.layer.pipe(Pt.provide(De.defaultLayer),Pt.provide(Ve.defaultLayer)));let{runPromise:x}=ft(d,g.defaultLayer);async function k(){return x(m=>m.methods())}g.methods=k,c(k,"methods");async function y(m){return x(I=>I.authorize(m))}g.authorize=y,c(y,"authorize");async function v(m){return x(I=>I.callback(m))}g.callback=v,c(v,"callback")})(Le||={});import{mapValues as Bo}from"remeda";var Gc=G.create({service:"server"}),Ho=A(()=>new pr().get("/",a({summary:"List providers",description:"Get a list of all available AI providers, including both available and connected ones.",operationId:"provider.list",responses:{200:{description:"List of providers",content:{"application/json":{schema:i(Y.object({all:Et.Provider.array(),default:Y.record(Y.string(),Y.string()),connected:Y.array(Y.string())}))}}}}}),async e=>{let t=await J.get(),o=new Set(t.disabled_providers??[]),s=t.enabled_providers?new Set(t.enabled_providers):void 0,r=await Et.get(),n={};for(let[f,x]of Object.entries(r))(!s||s.has(f))&&!o.has(f)&&(n[f]=x);let d=await ve.list(),u=Object.assign(Bo(n,f=>ve.fromModelsDevProvider(f)),d);return e.json({all:Object.values(u),default:Bo(u,f=>ve.sort(Object.values(f.models))[0].id),connected:Object.keys(d)})}).get("/auth",a({summary:"Get provider auth methods",description:"Retrieve available authentication methods for all AI providers.",operationId:"provider.auth",responses:{200:{description:"Provider auth methods",content:{"application/json":{schema:i(Y.record(Y.string(),Y.array(Le.Method)))}}}}}),async e=>e.json(await Le.methods())).post("/:providerID/oauth/authorize",a({summary:"OAuth authorize",description:"Initiate OAuth authorization for a specific AI provider to get an authorization URL.",operationId:"provider.oauth.authorize",responses:{200:{description:"Authorization URL and method",content:{"application/json":{schema:i(Le.Authorization.optional())}}},...l(400)}}),p("param",Y.object({providerID:ce.zod.meta({description:"Provider ID"})})),p("json",Y.object({method:Y.number().meta({description:"Auth method index"}),inputs:Y.record(Y.string(),Y.string()).optional().meta({description:"Prompt inputs"})})),async e=>{let t=e.req.valid("param").providerID,{method:o,inputs:s}=e.req.valid("json"),r=await Le.authorize({providerID:t,method:o,inputs:s});return e.json(r)}).post("/:providerID/oauth/callback",a({summary:"OAuth callback",description:"Handle the OAuth callback from a provider after user authorization.",operationId:"provider.oauth.callback",responses:{200:{description:"OAuth callback processed successfully",content:{"application/json":{schema:i(Y.boolean())}}},...l(400)}}),p("param",Y.object({providerID:ce.zod.meta({description:"Provider ID"})})),p("json",Y.object({method:Y.number().meta({description:"Auth method index"}),code:Y.string().optional().meta({description:"OAuth authorization code"})})),async e=>{let t=e.req.valid("param").providerID,{method:o,code:s}=e.req.valid("json");return await Le.callback({providerID:t,method:o,code:s}),e.json(!0)}));import{Hono as dr}from"hono";import{streamSSE as mr}from"hono/streaming";var $o=G.create({service:"server"}),Vo=c(()=>new dr().get("/event",a({summary:"Subscribe to events",description:"Get events",operationId:"event.subscribe",responses:{200:{description:"Event stream",content:{"text/event-stream":{schema:i(ue.payloads())}}}}}),async e=>($o.info("event connected"),e.header("Cache-Control","no-cache, no-transform"),e.header("X-Accel-Buffering","no"),e.header("X-Content-Type-Options","nosniff"),mr(e,async t=>{let o=new Se,s=!1;o.push(JSON.stringify({type:"server.connected",properties:{}}));let r=setInterval(()=>{o.push(JSON.stringify({type:"server.heartbeat",properties:{}}))},1e4),n=c(()=>{s||(s=!0,clearInterval(r),d(),o.push(null),$o.info("event disconnected"))},"stop"),d=W.subscribeAll(u=>{o.push(JSON.stringify(u)),u.type===W.InstanceDisposed.type&&n()});t.onAbort(n);try{for await(let u of o){if(u===null)return;await t.writeSSE({data:u})}}finally{n()}}))),"EventRoutes");import{HTTPException as lr}from"hono/http-exception";function kt(e){return(t,o)=>{if(e.error("failed",{error:t}),t instanceof ge){let r;return t instanceof ke?r=404:t instanceof ve.ModelNotFoundError||t.name==="ProviderAuthValidationFailed"||t.name.startsWith("Worktree")?r=400:r=500,o.json(t.toObject(),{status:r})}if(t instanceof h.BusyError)return o.json(new ge.Unknown({message:t.message}).toObject(),{status:400});if(t instanceof lr)return t.getResponse();let s=t instanceof Error&&t.stack?t.stack:t.toString();return o.json(new ge.Unknown({message:s}).toObject(),{status:500})}}c(kt,"errorHandler");var hr=G.create({service:"server"}),gr=tt.OPENCODE_DISABLE_EMBEDDED_WEB_UI?Promise.resolve(null):import("opencode-web-ui.gen.ts").then(e=>e.default).catch(()=>null),br="default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; media-src 'self' data:; connect-src 'self' data:",Ir=c((e="")=>`default-src 'self'; script-src 'self' 'wasm-unsafe-eval'${e?` 'sha256-${e}'`:""}; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; media-src 'self' data:; connect-src 'self' data:`,"csp"),xt=c((e,t=new ur)=>t.onError(kt(hr)).route("/project",So()).route("/pty",Ao(e)).route("/config",Uo()).route("/experimental",Go()).route("/session",ko()).route("/permission",Do()).route("/question",wo()).route("/provider",Ho()).route("/",Ro()).route("/",Vo()).route("/mcp",Co()).route("/tui",jo()).post("/instance/dispose",a({summary:"Dispose instance",description:"Clean up and dispose the current OpenCode instance, releasing all resources.",operationId:"instance.dispose",responses:{200:{description:"Instance disposed",content:{"application/json":{schema:i(Re.boolean())}}}}}),async o=>(await _.dispose(),o.json(!0))).get("/path",a({summary:"Get paths",description:"Retrieve the current working directory and related path information for the OpenCode instance.",operationId:"path.get",responses:{200:{description:"Path",content:{"application/json":{schema:i(Re.object({home:Re.string(),state:Re.string(),config:Re.string(),worktree:Re.string(),directory:Re.string()}).meta({ref:"Path"}))}}}}}),async o=>o.json({home:lt.Path.home,state:lt.Path.state,config:lt.Path.config,worktree:_.worktree,directory:_.directory})).get("/vcs",a({summary:"Get VCS info",description:"Retrieve version control system (VCS) information for the current project, such as git branch.",operationId:"vcs.get",responses:{200:{description:"VCS info",content:{"application/json":{schema:i(Je.Info)}}}}}),async o=>{let[s,r]=await Promise.all([Je.branch(),Je.defaultBranch()]);return o.json({branch:s,default_branch:r})}).get("/vcs/diff",a({summary:"Get VCS diff",description:"Retrieve the current git diff for the working tree or against the default branch.",operationId:"vcs.diff",responses:{200:{description:"VCS diff",content:{"application/json":{schema:i(ht.FileDiff.array())}}}}}),p("query",Re.object({mode:Je.Mode})),async o=>o.json(await Je.diff(o.req.valid("query").mode))).get("/command",a({summary:"List commands",description:"Get a list of all available commands in the OpenCode system.",operationId:"command.list",responses:{200:{description:"List of commands",content:{"application/json":{schema:i(Ft.Info.array())}}}}}),async o=>{let s=await Ft.list();return o.json(s)}).get("/agent",a({summary:"List agents",description:"Get a list of all available AI agents in the OpenCode system.",operationId:"app.agents",responses:{200:{description:"List of agents",content:{"application/json":{schema:i(Be.Info.array())}}}}}),async o=>{let s=await Be.list();return o.json(s)}).get("/skill",a({summary:"List skills",description:"Get a list of all available skills in the OpenCode system.",operationId:"app.skills",responses:{200:{description:"List of skills",content:{"application/json":{schema:i(zt.Info.array())}}}}}),async o=>{let s=await zt.all();return o.json(s)}).get("/lsp",a({summary:"Get LSP status",description:"Get LSP server status",operationId:"lsp.status",responses:{200:{description:"LSP server status",content:{"application/json":{schema:i(rt.Status.array())}}}}}),async o=>o.json(await rt.status())).get("/formatter",a({summary:"Get formatter status",description:"Get formatter status",operationId:"formatter.status",responses:{200:{description:"Formatter status",content:{"application/json":{schema:i(Mt.Status.array())}}}}}),async o=>o.json(await Mt.status())).all("/*",async o=>{let s=await gr,r=o.req.path;if(s){let n=s[r.replace(/^\//,"")]??s["index.html"]??null;if(!n)return o.json({error:"Not Found"},404);let d=await import("fs"),u=await import("path");try{let f=d.readFileSync(n),x=u.extname(n).toLowerCase(),y={".html":"text/html",".js":"application/javascript",".css":"text/css",".json":"application/json",".png":"image/png",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2"}[x]||"application/octet-stream";return o.header("Content-Type",y),y.startsWith("text/html")&&o.header("Content-Security-Policy",br),o.body(f)}catch{return o.json({error:"Not Found"},404)}}else{let n=await fr(`https://app.opencode.ai${r}`,{...o.req,headers:{...o.req.raw.headers,host:"app.opencode.ai"}}),d=n.headers.get("content-type")?.includes("text/html")?(await n.clone().text()).match(/<script\b(?![^>]*\bsrc\s*=)[^>]*\bid=(['"])oc-theme-preload-script\1[^>]*>([\s\S]*?)<\/script>/i):void 0,u=d?yr("sha256").update(d[2]).digest("base64"):"";return n.headers.set("Content-Security-Policy",Ir(u)),n}}),"InstanceRoutes");var vr=[{path:"/session/status",action:"forward"},{method:"GET",path:"/session",action:"local"}];function jr(e,t){for(let o of vr){if(o.method&&o.method!==e)continue;if(o.exact?t===o.path:t===o.path||t.startsWith(o.path+"/"))return o.action==="local"}return!1}c(jr,"local");function Jo(e){let t=A(()=>xt(e));return async o=>{let s=o.req.query("directory")||o.req.header("x-opencode-directory")||process.cwd(),r=Zt.resolve((()=>{try{return decodeURIComponent(s)}catch{return s}})()),n=new URL(o.req.url),d=n.searchParams.get("workspace")||o.req.header("x-opencode-workspace");if(!d)return _.provide({directory:r,init:it,async fn(){return t().fetch(o.req.raw,o.env)}});let u=ze.make(d),f=await ye.get(u);if(!f)return new Response(`Workspace not found: ${u}`,{status:500,headers:{"content-type":"text/plain; charset=utf-8"}});let k=await(await Ke(f.type)).target(f);if(k.type==="local")return _.provide({directory:k.directory,init:it,async fn(){return t().fetch(o.req.raw,o.env)}});if(jr(o.req.method,n.pathname))return t().fetch(o.req.raw,o.env);if(o.req.header("upgrade")?.toLowerCase()==="websocket")return jt.websocket(k,o.req.raw,o.env);let y=new Headers(o.req.raw.headers);return y.delete("x-opencode-workspace"),jt.http(k,new Request(o.req.raw,{headers:y}))}}c(Jo,"WorkspaceRouterMiddleware");import{Hono as wr}from"hono";import{streamSSE as Dr}from"hono/streaming";import te from"zod";var Jt=G.create({service:"server"}),Sr=ue.define("global.disposed",te.object({}));async function Yo(e,t){return Dr(e,async o=>{let s=new Se,r=!1;s.push(JSON.stringify({payload:{type:"server.connected",properties:{}}}));let n=setInterval(()=>{s.push(JSON.stringify({payload:{type:"server.heartbeat",properties:{}}}))},1e4),d=c(()=>{r||(r=!0,clearInterval(n),u(),s.push(null),Jt.info("global event disconnected"))},"stop"),u=t(s);o.onAbort(d);try{for await(let f of s){if(f===null)return;await o.writeSSE({data:f})}}finally{d()}})}c(Yo,"streamEvents");var Ko=A(()=>new wr().get("/health",a({summary:"Get health",description:"Get health information about the OpenCode server.",operationId:"global.health",responses:{200:{description:"Health information",content:{"application/json":{schema:i(te.object({healthy:te.literal(!0),version:te.string()}))}}}}}),async e=>e.json({healthy:!0,version:We.VERSION})).get("/event",a({summary:"Get global events",description:"Subscribe to global events from the OpenCode system using server-sent events.",operationId:"global.event",responses:{200:{description:"Event stream",content:{"text/event-stream":{schema:i(te.object({directory:te.string(),payload:ue.payloads()}).meta({ref:"GlobalEvent"}))}}}}}),async e=>(Jt.info("global event connected"),e.header("Cache-Control","no-cache, no-transform"),e.header("X-Accel-Buffering","no"),e.header("X-Content-Type-Options","nosniff"),Yo(e,t=>{async function o(s){t.push(JSON.stringify(s))}return c(o,"handler"),Te.on("event",o),()=>Te.off("event",o)}))).get("/sync-event",a({summary:"Subscribe to global sync events",description:"Get global sync events",operationId:"global.sync-event.subscribe",responses:{200:{description:"Event stream",content:{"text/event-stream":{schema:i(te.object({payload:pe.payloads()}).meta({ref:"SyncEvent"}))}}}}}),async e=>(Jt.info("global sync event connected"),e.header("Cache-Control","no-cache, no-transform"),e.header("X-Accel-Buffering","no"),e.header("X-Content-Type-Options","nosniff"),Yo(e,t=>pe.subscribeAll(({def:o,event:s})=>{t.push(JSON.stringify({payload:{...s,type:pe.versionedType(o.type,o.version)}}))})))).get("/config",a({summary:"Get global configuration",description:"Retrieve the current global OpenCode configuration settings and preferences.",operationId:"global.config.get",responses:{200:{description:"Get global config info",content:{"application/json":{schema:i(J.Info)}}}}}),async e=>e.json(await J.getGlobal())).patch("/config",a({summary:"Update global configuration",description:"Update global OpenCode configuration settings and preferences.",operationId:"global.config.update",responses:{200:{description:"Successfully updated global config",content:{"application/json":{schema:i(J.Info)}}},...l(400)}}),p("json",J.Info),async e=>{let t=e.req.valid("json"),o=await J.updateGlobal(t);return e.json(o)}).post("/dispose",a({summary:"Dispose instance",description:"Clean up and dispose all OpenCode instances, releasing all resources.",operationId:"global.dispose",responses:{200:{description:"Global disposed",content:{"application/json":{schema:i(te.boolean())}}}}}),async e=>(await _.disposeAll(),Te.emit("event",{directory:"global",payload:{type:Sr.type,properties:{}}}),e.json(!0))).post("/upgrade",a({summary:"Upgrade opencode",description:"Upgrade opencode to the specified version or latest if not specified.",operationId:"global.upgrade",responses:{200:{description:"Upgrade result",content:{"application/json":{schema:i(te.union([te.object({success:te.literal(!0),version:te.string()}),te.object({success:te.literal(!1),error:te.string()})]))}}},...l(400)}}),p("json",te.object({target:te.string().optional()})),async e=>{let t=await We.method();if(t==="unknown")return e.json({success:!1,error:"Unknown installation method"},400);let o=e.req.valid("json").target||await We.latest(t),s=await We.upgrade(t,o).then(()=>({success:!0,version:o})).catch(r=>({success:!1,error:r instanceof Error?r.message:String(r)}));return s.success?(Te.emit("event",{directory:"global",payload:{type:We.Event.Updated.type,properties:{version:o}}}),e.json(s)):e.json(s,500)}));import{Bonjour as Pr}from"bonjour-service";var pt=G.create({service:"mdns"}),qt;(r=>{let e,t;function o(n,d){if(t!==n){e&&s();try{let u=d??"opencode.local",f=`opencode-${n}`;e=new Pr;let x=e.publish({name:f,type:"http",host:u,port:n,txt:{path:"/"}});x.on("up",()=>{pt.info("mDNS service published",{name:f,port:n})}),x.on("error",k=>{pt.error("mDNS service error",{error:k})}),t=n}catch(u){if(pt.error("mDNS publish failed",{error:u}),e)try{e.destroy()}catch{}e=void 0,t=void 0}}}r.publish=o,c(o,"publish");function s(){if(e){try{e.unpublishAll(),e.destroy()}catch(n){pt.error("mDNS unpublish failed",{error:n})}e=void 0,t=void 0,pt.info("mDNS service unpublished")}}r.unpublish=s,c(s,"unpublish")})(qt||={});var Xo=G.create({service:"session.projector"});function Qo(e){return typeof e!="object"||e===null?!1:"code"in e&&e.code==="SQLITE_CONSTRAINT_FOREIGNKEY"?!0:"message"in e&&typeof e.message=="string"&&e.message.includes("FOREIGN KEY constraint failed")}c(Qo,"foreign");function O(e,t,o){if(e==null||!(t in e))return;let s=e[t];if(s&&typeof s=="object"&&o)return o(s);if(s===void 0)throw new Error("Session update failure: pass `null` to clear a field instead of `undefined`: "+JSON.stringify(e));return s}c(O,"grab");function kr(e){let t={id:O(e,"id"),project_id:O(e,"projectID"),workspace_id:O(e,"workspaceID"),parent_id:O(e,"parentID"),slug:O(e,"slug"),directory:O(e,"directory"),title:O(e,"title"),version:O(e,"version"),share_url:O(e,"share",o=>O(o,"url")),summary_additions:O(e,"summary",o=>O(o,"additions")),summary_deletions:O(e,"summary",o=>O(o,"deletions")),summary_files:O(e,"summary",o=>O(o,"files")),summary_diffs:O(e,"summary",o=>O(o,"diffs")),revert:O(e,"revert"),permission:O(e,"permission"),time_created:O(e,"time",o=>O(o,"created")),time_updated:O(e,"time",o=>O(o,"updated")),time_compacting:O(e,"time",o=>O(o,"compacting")),time_archived:O(e,"time",o=>O(o,"archived"))};return Object.fromEntries(Object.entries(t).filter(([o,s])=>s!==void 0))}c(kr,"toPartialRow");var Zo=[pe.project(h.Event.Created,(e,t)=>{e.insert(we).values(h.toRow(t.info)).run()}),pe.project(h.Event.Updated,(e,t)=>{let o=t.info;if(!e.update(we).set(kr(o)).where((0,F.eq)(we.id,t.sessionID)).returning().get())throw new ke({message:`Session not found: ${t.sessionID}`})}),pe.project(h.Event.Deleted,(e,t)=>{e.delete(we).where((0,F.eq)(we.id,t.sessionID)).run()}),pe.project(Q.Event.Updated,(e,t)=>{let o=t.info.time.created,{id:s,sessionID:r,...n}=t.info;try{e.insert(Ge).values({id:s,session_id:r,time_created:o,data:n}).onConflictDoUpdate({target:Ge.id,set:{data:n}}).run()}catch(d){if(!Qo(d))throw d;Xo.warn("ignored late message update",{messageID:s,sessionID:r})}}),pe.project(Q.Event.Removed,(e,t)=>{e.delete(Ge).where((0,F.and)((0,F.eq)(Ge.id,t.messageID),(0,F.eq)(Ge.session_id,t.sessionID))).run()}),pe.project(Q.Event.PartRemoved,(e,t)=>{e.delete(Fe).where((0,F.and)((0,F.eq)(Fe.id,t.partID),(0,F.eq)(Fe.session_id,t.sessionID))).run()}),pe.project(Q.Event.PartUpdated,(e,t)=>{let{id:o,messageID:s,sessionID:r,...n}=t.part;try{e.insert(Fe).values({id:o,message_id:s,session_id:r,time_created:t.time,data:n}).onConflictDoUpdate({target:Fe.id,set:{data:n}}).run()}catch(d){if(!Qo(d))throw d;Xo.warn("ignored late part update",{partID:o,messageID:s,sessionID:r})}})];function Yt(){pe.init({projectors:Zo,convertEvent:c((e,t)=>{if(e==="session.updated"){let o=t.sessionID,s=xe.use(r=>r.select().from(we).where((0,F.eq)(we.id,o)).get());return s?{sessionID:o,info:h.fromRow(s)}:t}return t},"convertEvent")})}c(Yt,"initProjectors");Yt();globalThis.AI_SDK_LOG_WARNINGS=!1;Yt();var Er;(k=>{let e=G.create({service:"server"}),t=xr(),o=c((y,v)=>!!(y==="/event"||y==="/global/event"||y==="/global/sync-event"||v==="POST"&&/\/session\/[^/]+\/(message|prompt_async)$/.test(y)),"skipCompress");k.Default=A(()=>n({}).app);function r(y,v=new es,g){return v.onError(kt(e)).use((m,I)=>{if(m.req.method==="OPTIONS")return I();let w=tt.OPENCODE_SERVER_PASSWORD;if(!w)return I();let M=tt.OPENCODE_SERVER_USERNAME??"opencode";return Ar({username:M,password:w})(m,I)}).use(async(m,I)=>{let w=m.req.path==="/log";w||e.info("request",{method:m.req.method,path:m.req.path});let M=e.time("request",{method:m.req.method,path:m.req.path});await I(),w||M.stop()}).use(qr({maxAge:86400,origin(m){if(m&&(m.startsWith("http://localhost:")||m.startsWith("http://127.0.0.1:")||m==="tauri://localhost"||m==="http://tauri.localhost"||m==="https://tauri.localhost"||/^https:\/\/([a-z0-9-]+\.)*opencode\.ai$/.test(m)||g?.cors?.includes(m)))return m}})).use((m,I)=>o(m.req.path,m.req.method)?I():t(m,I)).route("/global",Ko()).put("/auth/:providerID",a({summary:"Set auth credentials",description:"Set authentication credentials",operationId:"auth.set",responses:{200:{description:"Successfully set authentication credentials",content:{"application/json":{schema:i(ae.boolean())}}},...l(400)}}),p("param",ae.object({providerID:ce.zod})),p("json",De.Info.zod),async m=>{let I=m.req.valid("param").providerID,w=m.req.valid("json");return await De.set(I,w),m.json(!0)}).delete("/auth/:providerID",a({summary:"Remove auth credentials",description:"Remove authentication credentials",operationId:"auth.remove",responses:{200:{description:"Successfully removed authentication credentials",content:{"application/json":{schema:i(ae.boolean())}}},...l(400)}}),p("param",ae.object({providerID:ce.zod})),async m=>{let I=m.req.valid("param").providerID;return await De.remove(I),m.json(!0)}).get("/doc",ho(v,{documentation:{info:{title:"opencode",version:"0.0.3",description:"opencode api"},openapi:"3.1.1"}})).use(p("query",ae.object({directory:ae.string().optional(),workspace:ae.string().optional()}))).post("/log",a({summary:"Write log",description:"Write a log entry to the server logs with specified level and metadata.",operationId:"app.log",responses:{200:{description:"Log entry written successfully",content:{"application/json":{schema:i(ae.boolean())}}},...l(400)}}),p("json",ae.object({service:ae.string().meta({description:"Service name for the log entry"}),level:ae.enum(["debug","info","error","warn"]).meta({description:"Log level"}),message:ae.string().meta({description:"Log message"}),extra:ae.record(ae.string(),ae.any()).optional().meta({description:"Additional metadata for the log entry"})})),async m=>{let{service:I,level:w,message:M,extra:ee}=m.req.valid("json"),he=G.create({service:I});switch(w){case"debug":he.debug(M,ee);break;case"info":he.info(M,ee);break;case"error":he.error(M,ee);break;case"warn":he.warn(M,ee);break}return m.json(!0)}).use(Jo(y))}k.ControlPlaneRoutes=r,c(r,"ControlPlaneRoutes");function n(y){let v=new es,g=Rr({app:v});return{app:r(g.upgradeWebSocket,v,y),ws:g}}c(n,"create");function d(y){return n(y).app}k.createApp=d,c(d,"createApp");async function u(){let{app:y,ws:v}=n({});return xt(v.upgradeWebSocket,y),await Bt(y,{documentation:{info:{title:"opencode",version:"1.0.0",description:"opencode api"},openapi:"3.1.1"}})}k.openapi=u,c(u,"openapi");async function x(y){let v=n(y),g=c(he=>new Promise((U,le)=>{let N=Cr({fetch:v.app.fetch});v.ws.injectWebSocket(N);let D=c($=>{E(),le($)},"fail"),S=c(()=>{E(),U(N)},"ready"),E=c(()=>{N.off("error",D),N.off("listening",S)},"cleanup");N.once("error",D),N.once("listening",S),N.listen(he,y.hostname)}),"start"),m=y.port===0?await g(4096).catch(()=>g(0)):await g(y.port),I=m.address();if(!I||typeof I=="string")throw new Error(`Failed to resolve server address for port ${y.port}`);let w=new URL("http://localhost");w.hostname=y.hostname,w.port=String(I.port),k.url=w;let M=y.mdns&&I.port&&y.hostname!=="127.0.0.1"&&y.hostname!=="localhost"&&y.hostname!=="::1";M?qt.publish(I.port,y.mdnsDomain):y.mdns&&e.warn("mDNS enabled but hostname is loopback; skipping mDNS publish");let ee;return{hostname:y.hostname,port:I.port,url:w,stop(he){return ee??=new Promise((U,le)=>{M&&qt.unpublish(),m.close(N=>{if(N){le(N);return}U()}),he&&("closeAllConnections"in m&&typeof m.closeAllConnections=="function"&&m.closeAllConnections(),"closeIdleConnections"in m&&typeof m.closeIdleConnections=="function"&&m.closeIdleConnections())}),ee}}}k.listen=x,c(x,"listen")})(Er||={});export{Er as a};