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.
- package/dist/{chunk-T7EXROHP.js → chunk-2ANK3QEN.js} +1 -1
- package/dist/chunk-5FGJUXLI.js +2260 -0
- package/dist/{chunk-FT4RVZXD.js → chunk-735MVPNG.js} +1 -1
- package/dist/{chunk-A4S3BYGY.js → chunk-CZVKIDQZ.js} +1 -1
- package/dist/chunk-TECR6KUK.js +18 -0
- package/dist/chunk-WF7L36SZ.js +75 -0
- package/dist/{chunk-M4DCWBCO.js → chunk-X7PHY2B3.js} +1 -1
- package/dist/{chunk-XREX5MYM.js → chunk-YRY5Y3QL.js} +1 -1
- package/dist/{default-u_dwuiYb-5QQ4GXMV.js → default-u_dwuiYb-652AQZKX.js} +1 -1
- package/dist/{effect-QlVUlMFu-ORZ7TVO5.js → effect-QlVUlMFu-JVYEXAZL.js} +1 -1
- package/dist/{mcp-7UCWZJLJ.js → mcp-JSKIR2KQ.js} +1 -1
- package/dist/{registry-HGPZOISH.js → registry-REVWYAGR.js} +1 -1
- package/dist/{run-DYJ5YKU4.js → run-CPHBVDZ4.js} +1 -1
- package/dist/run.js +1 -1
- package/dist/serve.js +1 -1
- package/dist/{server-VKRBP2QM.js → server-VHCQ5HOC.js} +1 -1
- package/dist/{session-Z4P4Y6MB.js → session-5BXSPMPJ.js} +1 -1
- package/dist/{share-next-WZUJANDA.js → share-next-GSWCSZSC.js} +1 -1
- package/dist/{sury-CWZTCd75-IXNCX752.js → sury-CWZTCd75-3YHH6KVI.js} +1 -1
- package/dist/{valibot--1zFm7rT-SSCP4J5I.js → valibot--1zFm7rT-FSYJNYJ6.js} +1 -1
- package/dist/{valibot-D_HTw1Gn-KPCJMJMC.js → valibot-D_HTw1Gn-E5NKVIOV.js} +1 -1
- package/dist/{worktree-5JVGPJ42.js → worktree-HPW4CL36.js} +1 -1
- package/dist/{zod-Bwrt9trS-BYLM45IZ.js → zod-Bwrt9trS-HVDOFWRP.js} +1 -1
- package/dist/{zod-DSgpEGAE-T3VJY2W3.js → zod-DSgpEGAE-DSH6V7MG.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-BYJU35KA.js +0 -18
- package/dist/chunk-QRUX5DYI.js +0 -75
- package/dist/chunk-UO2AIECR.js +0 -2214
- /package/dist/{arktype-aI7TBD0R-ETU7X65Q.js → arktype-aI7TBD0R-TFNARRIP.js} +0 -0
- /package/dist/{chunk-T6MY2WE4.js → chunk-FXLFZ5DL.js} +0 -0
- /package/dist/{chunk-BGADAZN4.js → chunk-PWFRMDDF.js} +0 -0
- /package/dist/{typebox-Dei93FPO-K67WT2FO.js → typebox-Dei93FPO-GLI7OCTY.js} +0 -0
package/dist/serve.js
CHANGED
|
@@ -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 s}from"./chunk-MBZTOEAD.js";import{Agent as i,setGlobalDispatcher as c}from"undici";import{homedir as p}from"node:os";import{join as l}from"node:path";c(new i({connect:{keepAlive:!0,keepAliveInitialDelay:5e3},headersTimeout:0,bodyTimeout:0}));function o(e,t){let r=process.argv.indexOf(`--${e}`);return r!==-1&&process.argv[r+1]?process.argv[r+1]:t}s(o,"arg");var m=l(p(),".alchemy_lab","opencode"),d=o("data-dir",m);process.env.OPENCODE_DATA_DIR=d;var{Log:a}=await import("./log-MVJ7H4K5.js"),v=o("log-level","INFO").toUpperCase(),n=a.Level.safeParse(v);a.init({print:!0,level:n.success?n.data:"INFO"});var{Server:g}=await import("./server-
|
|
12
|
+
import{a as s}from"./chunk-MBZTOEAD.js";import{Agent as i,setGlobalDispatcher as c}from"undici";import{homedir as p}from"node:os";import{join as l}from"node:path";c(new i({connect:{keepAlive:!0,keepAliveInitialDelay:5e3},headersTimeout:0,bodyTimeout:0}));function o(e,t){let r=process.argv.indexOf(`--${e}`);return r!==-1&&process.argv[r+1]?process.argv[r+1]:t}s(o,"arg");var m=l(p(),".alchemy_lab","opencode"),d=o("data-dir",m);process.env.OPENCODE_DATA_DIR=d;var{Log:a}=await import("./log-MVJ7H4K5.js"),v=o("log-level","INFO").toUpperCase(),n=a.Level.safeParse(v);a.init({print:!0,level:n.success?n.data:"INFO"});var{Server:g}=await import("./server-VHCQ5HOC.js"),u=parseInt(o("port","4096"),10),h=o("hostname","127.0.0.1");try{let e=await g.listen({port:u,hostname:h});console.log(`opencode server listening on http://${e.hostname}:${e.port}`);let t=s(async()=>{await e.stop(!0),process.exit(0)},"shutdown");process.on("SIGINT",t),process.on("SIGTERM",t),await new Promise(()=>{})}catch(e){console.error("Failed to start server:",e),process.exit(1)}
|
|
@@ -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}from"./chunk-
|
|
12
|
+
import{a}from"./chunk-TECR6KUK.js";import"./chunk-735MVPNG.js";import"./chunk-X7PHY2B3.js";import"./chunk-2ANK3QEN.js";import"./chunk-PWFRMDDF.js";import"./chunk-5FGJUXLI.js";import"./chunk-WF7L36SZ.js";import"./chunk-N7PLTD3P.js";import"./chunk-7KKA6WBY.js";import"./chunk-LTCXIXYM.js";import"./chunk-M4CB72HE.js";import"./chunk-CZVKIDQZ.js";import"./chunk-MBZTOEAD.js";export{a as Server};
|
|
@@ -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{
|
|
12
|
+
import{F as a}from"./chunk-5FGJUXLI.js";import"./chunk-WF7L36SZ.js";import"./chunk-N7PLTD3P.js";import"./chunk-7KKA6WBY.js";import"./chunk-LTCXIXYM.js";import"./chunk-M4CB72HE.js";import"./chunk-MBZTOEAD.js";export{a as Session};
|
|
@@ -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}from"./chunk-
|
|
12
|
+
import{a}from"./chunk-X7PHY2B3.js";import"./chunk-5FGJUXLI.js";import"./chunk-WF7L36SZ.js";import"./chunk-N7PLTD3P.js";import"./chunk-7KKA6WBY.js";import"./chunk-LTCXIXYM.js";import"./chunk-M4CB72HE.js";import"./chunk-MBZTOEAD.js";export{a as ShareNext};
|
|
@@ -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 r}from"./chunk-
|
|
12
|
+
import{a as r}from"./chunk-CZVKIDQZ.js";import{a as t}from"./chunk-MBZTOEAD.js";async function e(){try{let{toJSONSchema:o}=await import("sury");return o}catch{throw new r("sury")}}t(e,"getToJsonSchemaFn");export{e as default};
|
|
@@ -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 t}from"./chunk-
|
|
12
|
+
import{a as t}from"./chunk-CZVKIDQZ.js";import{a as o}from"./chunk-MBZTOEAD.js";async function a(){try{let{toJsonSchema:n}=await import("@valibot/to-json-schema");return n}catch{throw new t("@valibot/to-json-schema")}}o(a,"getToJsonSchemaFn");export{a as default};
|
|
@@ -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 t}from"./chunk-
|
|
12
|
+
import{a as t}from"./chunk-FXLFZ5DL.js";import"./chunk-PWFRMDDF.js";import{b as s}from"./chunk-CZVKIDQZ.js";import{a as o}from"./chunk-MBZTOEAD.js";function h(){return async(p,m)=>{let n=await s(p,{errorMode:"ignore",overrideAction:o(({valibotAction:r,jsonSchema:c})=>{let a=t(c,m);if(r.kind==="metadata"&&r.type==="metadata"&&!("$ref"in a)){let e=r.metadata;if(e.example!==void 0&&(a.example=e.example),e.examples&&e.examples.length>0&&(a.examples=e.examples),e.ref)return m.components.schemas={...m.components.schemas,[e.ref]:a},{$ref:`#/components/schemas/${e.ref}`}}return a},"overrideAction"),...m.options});return"$schema"in n&&delete n.$schema,n}}o(h,"getToOpenAPISchemaFn");export{h as default};
|
|
@@ -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{c as n,d as o}from"./chunk-
|
|
12
|
+
import{c as n,d as o}from"./chunk-735MVPNG.js";import"./chunk-X7PHY2B3.js";import"./chunk-5FGJUXLI.js";import"./chunk-WF7L36SZ.js";import"./chunk-N7PLTD3P.js";import"./chunk-7KKA6WBY.js";import"./chunk-LTCXIXYM.js";import"./chunk-M4CB72HE.js";import"./chunk-MBZTOEAD.js";var t=o.extend({name:o.shape.name.unwrap(),branch:o.shape.branch.unwrap(),directory:o.shape.directory.unwrap()}),i={async configure(e){let r=await n.makeWorktreeInfo(e.name??void 0);return{...e,name:r.name,branch:r.branch,directory:r.directory}},async create(e){let r=t.parse(e);await n.createFromInfo({name:r.name,directory:r.directory,branch:r.branch})},async remove(e){let r=t.parse(e);await n.remove({directory:r.directory})},target(e){return{type:"local",directory:t.parse(e).directory}}};export{i as WorktreeAdaptor};
|
|
@@ -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 t}from"./chunk-
|
|
12
|
+
import{a as t}from"./chunk-CZVKIDQZ.js";import{a as n}from"./chunk-MBZTOEAD.js";var c=new t("zod v4");async function d(){return async(r,e)=>{let o;if("_zod"in r)try{o=(await import("zod/v4/core")).toJSONSchema}catch{throw c}else try{o=(await import("zod-to-json-schema")).zodToJsonSchema}catch{throw new t("zod-to-json-schema")}return o(r,e)}}n(d,"getToJsonSchemaFn");export{d as default};
|
|
@@ -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 s}from"./chunk-
|
|
12
|
+
import{a as s}from"./chunk-2ANK3QEN.js";import{a as p}from"./chunk-YRY5Y3QL.js";import"./chunk-FXLFZ5DL.js";import"./chunk-PWFRMDDF.js";import"./chunk-CZVKIDQZ.js";import{a as r}from"./chunk-MBZTOEAD.js";function u(){return async(e,o)=>{if("_zod"in e)return p()(e,{components:o.components,options:{io:"input",...o.options}});try{let{createSchema:t}=await import("zod-openapi"),{schema:i,components:n}=t(e,{schemaType:"input",...o.options});return n&&(o.components.schemas={...o.components.schemas,...n}),i}catch{throw new Error(s('Missing dependencies "zod-openapi v4".'))}}}r(u,"getToOpenAPISchemaFn");export{u as default};
|
package/package.json
CHANGED
package/dist/chunk-BYJU35KA.js
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
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 no}from"./chunk-FT4RVZXD.js";import{b as Ct}from"./chunk-T7EXROHP.js";import{A as Nt,B as Gt,C as fe,D as ze,E as h,F 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 Tt,o as Be,p as zt,q as He,r as _t,s as $e,t as It,u as ro,v as Ut,w as Ae,y as Lt,z as Mt}from"./chunk-UO2AIECR.js";import{B as se,C as $,D as V,b as De,f as We,h as Rt,n as F,o as oo,p as so,q as ot}from"./chunk-QRUX5DYI.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 G,m as eo,n as we,o as Ge,p as Fe,s as le,u as ut,y as ue,z}from"./chunk-N7PLTD3P.js";import{a as Et,b as X,c as st,d as Ot}from"./chunk-7KKA6WBY.js";import{a as to}from"./chunk-LTCXIXYM.js";import{c as Qt,d as lt,e as N}from"./chunk-M4CB72HE.js";import{b as Zt}from"./chunk-A4S3BYGY.js";import{a as c,e as Kt,f as Xt}from"./chunk-MBZTOEAD.js";import{validator as is}from"hono/validator";var io={header:["cookie"]};function as(e,t,o){if(!(o in io))return e;let s=io[o]||[];return t==="arktype"?cs(e,s):t==="valibot"?ps(e,s):e}c(as,"sanitizeIssues");function cs(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(cs,"sanitizeArktypeIssues");function ps(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(ps,"sanitizeValibotIssues");var ao=c((e,t,o)=>is(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=as(n.issues,t["~standard"].vendor,e);return r.json({data:s,error:d,success:!1},400)}return n.value}),"sValidator");var Ft=Symbol("openapi"),ms=["GET","PUT","POST","DELETE","OPTIONS","HEAD","PATCH","TRACE"],ls=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"),co=c(e=>e.charAt(0).toUpperCase()+e.slice(1),"capitalize"),us=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${co(o.slice(1,-1))}`:t+=co(o);return t},"generateOperationId"),fs=c(e=>"$ref"in e?e.$ref:`${e.in} ${e.name}`,"paramKey");function po(...e){let t=e.flatMap(o=>o??[]).reduce((o,s)=>(o.set(fs(s),s),o),new Map);return Array.from(t.values())}c(po,"mergeParameters");var Ye=new Map;function ys(e){let t=[];for(let[o,s]of Ye)s&&e.match(o)&&t.push(s);return t}c(ys,"getPathContext");function hs(){Ye.clear()}c(hs,"clearSpecsContext");function mo(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]=po(d):o[r]=d}else typeof n=="function"?o[r]=n(e):r==="parameters"?o[r]=po(o[r],n):o[r]={...o[r],...n};else o[r]=n;return o},{operationId:us(e)})}c(mo,"mergeSpecs");function lo({route:e,specs:t,paths:o}){let s=ls(e.path),r=e.method.toLowerCase();if(r==="all"){if(!t)return;if(Ye.has(s)){let n=Ye.get(s)??{};Ye.set(s,mo(e,n,t))}else Ye.set(s,t)}else{let n=ys(s);s in o||(o[s]={}),o[s]&&(o[s][r]=mo(e,...n,o[s]?.[r],t))}}c(lo,"registerSchemaPath");function gs(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 L=w.$ref.split("/").pop();if(L){let ee=t.components.parameters?.[L];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(gs,"removeExcludedPaths");var uo={documentation:{},excludeStaticFile:!0,exclude:[],excludeMethods:["OPTIONS"],excludeTags:[]};function yo(e,t){let o;return async s=>(o||(o=await Wt(e,t,s)),s.json(o))}c(yo,"openAPIRouteHandler");async function Wt(e,t=uo,o){let s={components:{},options:{...uo,...t}},r=s.options.documentation??{};hs();let n=await bs(e,s);for(let u in n)for(let f in n[u])Is({valueOrFunc:n[u][f]?.hide,method:f,path:u,c:o})&&(n[u][f]=void 0);let d=Bt(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:{...gs(n,s),...r.paths},components:d}}c(Wt,"generateSpecs");async function bs(e,t){let o={};for(let s of e.routes){let r=s.handler[Ft];if(!r){t.options.includeEmptyPaths&&lo({route:s,paths:o});continue}let n=s.method;if(n!=="ALL"&&(t.options.excludeMethods?.includes(n)||!ms.includes(n)))continue;let d=t.options.defaultOptions?.[n],{schema:u,components:f={}}=await vs(r,d);t.components=Bt(t.components,f),lo({route:s,specs:u,paths:o})}return o}c(bs,"generatePaths");function Is(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(Is,"getHiddenValue");async function vs(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=Bt(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=fo(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=fo(e.target,o.schema);s.parameters=r}return{schema:s,components:o.components}}c(vs,"getSpec");function fo(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(fo,"generateParameters");function Bt(...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(Bt,"mergeComponentsObjects");function i(e,t){return{vendor:e["~standard"].vendor,validate:e["~standard"].validate,toJSONSchema:c(o=>Zt(e,{...t,...o}),"toJSONSchema"),toOpenAPISchema:c(o=>Ct(e,{...t,...o}),"toOpenAPISchema")}}c(i,"resolver");function p(e,t,o,s){let r=ao(e,t,o);return Object.assign(r,{[Ft]:{target:e,...i(t,s),options:s}})}c(p,"validator");function a(e){return Object.assign(c(async(o,s)=>{await s()},"middleware"),{[Ft]:{spec:e}})}c(a,"describeRoute");import{Hono as Zo}from"hono";import{compress as kr}from"hono/compress";import{cors as xr}from"hono/cors";import{basicAuth as qr}from"hono/basic-auth";import ae from"zod";import{createAdaptorServer as Ar}from"@hono/node-server";import{createNodeWebSocket as Cr}from"@hono/node-ws";var js={worktree:A(async()=>(await import("./worktree-5JVGPJ42.js")).WorktreeAdaptor)};function Ke(e){return js[e]()}c(Ke,"getAdaptor");import at from"zod";import{setTimeout as go}from"node:timers/promises";import{sqliteTable as ws,text as _e}from"drizzle-orm/sqlite-core";var je=ws("workspace",{id:_e().$type().primaryKey(),type:_e().notNull(),branch:_e(),name:_e(),directory:_e(),extra:_e({mode:"json"}),project_id:_e().$type().notNull().references(()=>eo.id,{onDelete:"cascade"})});async function ho(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(ho,"parseSSE");var ye;(y=>{y.Event={Ready:le.define("workspace.ready",at.object({name:at.string()})),Failed:le.define("workspace.failed",at.object({message:at.string()}))},y.Info=no.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(L=>{L.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,G.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,G.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,G.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,G.eq)(je.id,v)).run()),m}});let f=N.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(/\/?$/,"/"),L=await fetch(new URL(w+"/event"),{method:"GET",signal:g});if(!L.ok||!L.body){await go(1e3);continue}await ho(L.body,g,ee=>{Te.emit("event",{directory:v.id,payload:ee})}),await go(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 bo}from"hono";import{createNodeWebSocket as Ds}from"@hono/node-ws";var{upgradeWebSocket:Ss}=Ds({app:new bo}),Ps=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","proxy-connection","te","trailer","transfer-encoding","upgrade","host"]);function ks(e,t){let o=new Headers(e.headers);for(let s of Ps)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(ks,"headers");function xs(e){let t=e.headers.get("sec-websocket-protocol");return t?t.split(",").map(o=>o.trim()).filter(Boolean):[]}c(xs,"protocols");function qs(e){let t=new URL(e);return t.protocol==="http:"&&(t.protocol="ws:"),t.protocol==="https:"&&(t.protocol="wss:"),t.toString()}c(qs,"socket");function As(e,t){return t instanceof Blob?t.arrayBuffer().then(o=>e.send(o)):e.send(t)}c(As,"send");var Cs=A(()=>new bo().get("/__workspace_ws",Ss(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,xs(e.req.raw)),s.binaryType="arraybuffer",s.onopen=()=>{for(let d of o)s?.send(d);o.length=0},s.onmessage=d=>{As(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)}}}))),vt;(o=>{function e(s,r){return fetch(new Request(s.url,{method:r.method,headers:ks(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",qs(s.url)),Cs().fetch(new Request(d,{method:r.method,headers:u,signal:r.signal}),n)}o.websocket=t,c(t,"websocket")})(vt||={});import{Hono as lr}from"hono";import{proxy as ur}from"hono/proxy";import Re from"zod";import{createHash as fr}from"node:crypto";import{Hono as Io}from"hono";import W 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 Rs={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,Rs[t]]))}c(l,"errors");var Es=W.object({path:W.string(),body:W.any()}),Os=new Se,Ts=new Se;var zs=new Io().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(Es)}}}}}),async e=>{let t=await Os.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(W.boolean())}}}}}),p("json",W.any()),async e=>{let t=e.req.valid("json");return Ts.push(t),e.json(!0)}),vo=A(()=>new Io().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(W.boolean())}}},...l(400)}}),p("json",se.PromptAppend.properties),async e=>(await F.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(W.boolean())}}}}}),async e=>(await F.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(W.boolean())}}}}}),async e=>(await F.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(W.boolean())}}}}}),async e=>(await F.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(W.boolean())}}}}}),async e=>(await F.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(W.boolean())}}}}}),async e=>(await F.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(W.boolean())}}}}}),async e=>(await F.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(W.boolean())}}},...l(400)}}),p("json",W.object({command:W.string()})),async e=>{let t=e.req.valid("json").command;return await F.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(W.boolean())}}}}}),p("json",se.ToastShow.properties),async e=>(await F.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(W.boolean())}}},...l(400)}}),p("json",W.union(Object.values(se).map(e=>W.object({type:W.literal(e.type),properties:e.properties}).meta({ref:"Event."+e.type})))),async e=>{let t=e.req.valid("json");return await F.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(W.boolean())}}},...l(400,404)}}),p("json",se.SessionSelect.properties),async e=>{let{sessionID:t}=e.req.valid("json");return await h.get(t),await F.publish(se.SessionSelect,{sessionID:t}),e.json(!0)}).route("/control",zs));import{Hono as _s}from"hono";import jt from"zod";var jo=A(()=>new _s().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(jt.boolean())}}},...l(400,404)}}),p("param",jt.object({requestID:_t.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(jt.boolean())}}},...l(400,404)}}),p("param",jt.object({requestID:_t.zod})),async e=>{let t=e.req.valid("param");return await $e.reject(t.requestID),e.json(!0)}));import{Hono as Us}from"hono";import wt from"zod";var wo=A(()=>new Us().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(wt.boolean())}}},...l(400,404)}}),p("param",wt.object({requestID:bt.zod})),p("json",wt.object({reply:qe.Reply,message:wt.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 Ls}from"hono";import Ms from"zod";var Do=A(()=>new Ls().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(ue.Info.array())}}}}}),async e=>{let t=ue.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(ue.Info)}}}}}),async e=>e.json(z.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(ue.Info)}}}}}),async e=>{let t=z.directory,o=z.project,s=await ue.initGit({directory:t,project:o});return s.id===o.id&&s.vcs===o.vcs&&s.worktree===o.worktree||await z.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(ue.Info)}}},...l(400,404)}}),p("param",Ms.object({projectID:ut.zod})),p("json",ue.UpdateInput.omit({projectID:!0})),async e=>{let t=e.req.valid("param").projectID,o=e.req.valid("json"),s=await ue.update({...o,projectID:t});return e.json(s)}));import{Hono as Ns}from"hono";import{stream as So}from"hono/streaming";import b from"zod";var Ht=N.create({service:"server"}),Po=A(()=>new Ns().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;Ht.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(Mt.Info.array())}}},...l(400,404)}}),p("param",b.object({sessionID:X.zod})),async e=>{let t=e.req.valid("param").sessionID,o=await Mt.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 fe.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 ro.create({sessionID:t,agent:n,model:{providerID:o.providerID,modelID:o.modelID},auto:o.auto}),await fe.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 fe.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:Ot.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:Ot.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",fe.PromptInput.omit({sessionID:!0})),async e=>(e.status(200),e.header("Content-Type","application/json"),So(e,async t=>{let o=e.req.valid("param").sessionID,s=e.req.valid("json"),r=await fe.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",fe.PromptInput.omit({sessionID:!0})),async e=>(e.status(202),So(e,async()=>{let t=e.req.valid("param").sessionID,o=e.req.valid("json");fe.prompt({...o,sessionID:t}).catch(s=>{Ht.error("prompt_async failed",{sessionID:t,error:s}),F.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",fe.CommandInput.omit({sessionID:!0})),async e=>{let t=e.req.valid("param").sessionID,o=e.req.valid("json"),s=await fe.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",fe.ShellInput.omit({sessionID:!0})),async e=>{let t=e.req.valid("param").sessionID,o=e.req.valid("json"),s=await fe.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;Ht.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 Bs}from"hono";import Xe from"zod";import O from"zod";function ko(e){let t,o=!1;return()=>(o||(o=!0,t=e()),t)}c(ko,"lazy");import{Schema as xo}from"effect";import Gs from"zod";var Fs=xo.String.pipe(xo.brand("PtyID")),be=Fs.pipe(to(e=>({make:c(t=>e.makeUnsafe(t),"make"),ascending:c(t=>e.makeUnsafe(Et.ascending("pty",t)),"ascending"),zod:Et.schema("pty").pipe(Gs.custom())})));import{Effect as re,Layer as $t,ServiceMap as Ws}from"effect";var ie;(D=>{let e=N.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 R=JSON.stringify({cursor:S}),H=s.encode(R),Z=new Uint8Array(H.length+1);return Z[0]=0,Z.set(H,1),Z},"meta"),d=ko(()=>import("./pty.node-X2EITEZ4.js"));D.Info=O.object({id:be.zod,title:O.string(),command:O.string(),args:O.array(O.string()),cwd:O.string(),status:O.enum(["running","exited"]),pid:O.number()}).meta({ref:"Pty"}),D.CreateInput=O.object({command:O.string().optional(),args:O.array(O.string()).optional(),cwd:O.string().optional(),title:O.string().optional(),env:O.record(O.string(),O.string()).optional()}),D.UpdateInput=O.object({title:O.string().optional(),size:O.object({rows:O.number(),cols:O.number()}).optional()}),D.Event={Created:le.define("pty.created",O.object({info:D.Info})),Updated:le.define("pty.updated",O.object({info:D.Info})),Exited:le.define("pty.exited",O.object({id:be.zod,exitCode:O.number()})),Deleted:le.define("pty.deleted",O.object({id:be.zod}))};class y extends Ws.Service()("@opencode/Pty"){static{c(this,"Service")}}D.Service=y,D.layer=$t.effect(y,re.gen(function*(){let S=yield*F.Service,R=yield*Ve.Service;function H(C){try{C.process.kill()}catch{}for(let[q,T]of C.subscribers.entries())try{r(T)===q&&T.close()}catch{}C.subscribers.clear()}c(H,"teardown");let Z=yield*ne.make(re.fn("Pty.state")(function*(C){let q={dir:C.directory,sessions:new Map};return yield*re.addFinalizer(()=>re.sync(()=>{for(let T of q.sessions.values())H(T);q.sessions.clear()})),q})),dt=re.fn("Pty.remove")(function*(C){let q=yield*ne.get(Z),T=q.sessions.get(C);T&&(q.sessions.delete(C),e.info("removing session",{id:C}),H(T),yield*S.publish(D.Event.Deleted,{id:T.info.id}))}),qt=re.fn("Pty.list")(function*(){let C=yield*ne.get(Z);return Array.from(C.sessions.values()).map(q=>q.info)}),es=re.fn("Pty.get")(function*(C){return(yield*ne.get(Z)).sessions.get(C)?.info}),ts=re.fn("Pty.create")(function*(C){let q=yield*ne.get(Z),T=be.ascending(),oe=C.command||Ut.preferred(),K=C.args||[];Ut.login(oe)&&K.push("-l");let Pe=C.cwd||q.dir,Ze=yield*R.trigger("shell.env",{cwd:Pe},{env:{}}),Me={...process.env,...C.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:T,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:T,title:C.title||`Terminal ${T.slice(-4)}`,command:oe,args:K,cwd:Pe,status:"running",pid:Ee.pid},U={info:Oe,process:Ee,buffer:"",bufferCursor:0,cursor:0,subscribers:new Map};return q.sessions.set(T,U),Ee.onData(z.bind(Ne=>{U.cursor+=Ne.length;for(let[mt,At]of U.subscribers.entries()){if(At.readyState!==1){U.subscribers.delete(mt);continue}if(r(At)!==mt){U.subscribers.delete(mt);continue}try{At.send(Ne)}catch{U.subscribers.delete(mt)}}if(U.buffer+=Ne,U.buffer.length<=t)return;let Yt=U.buffer.length-t;U.buffer=U.buffer.slice(Yt),U.bufferCursor+=Yt})),Ee.onExit(z.bind(({exitCode:Ne})=>{U.info.status!=="exited"&&(e.info("session exited",{id:T,exitCode:Ne}),U.info.status="exited",re.runFork(S.publish(D.Event.Exited,{id:T,exitCode:Ne})),re.runFork(dt(T)))})),yield*S.publish(D.Event.Created,{info:Oe}),Oe}),os=re.fn("Pty.update")(function*(C,q){let oe=(yield*ne.get(Z)).sessions.get(C);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}),ss=re.fn("Pty.resize")(function*(C,q,T){let K=(yield*ne.get(Z)).sessions.get(C);K&&K.info.status==="running"&&K.process.resize(q,T)}),rs=re.fn("Pty.write")(function*(C,q){let oe=(yield*ne.get(Z)).sessions.get(C);oe&&oe.info.status==="running"&&oe.process.write(q)}),ns=re.fn("Pty.connect")(function*(C,q,T){let K=(yield*ne.get(Z)).sessions.get(C);if(!K){q.close();return}e.info("client connected to session",{id:C});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=T===-1?et:typeof T=="number"&&Number.isSafeInteger(T)?Math.max(0,T):0,Oe=(()=>{if(!K.buffer||Ee>=et)return"";let U=Math.max(0,Ee-Me);return U>=K.buffer.length?"":K.buffer.slice(U)})();if(Oe)try{for(let U=0;U<Oe.length;U+=o)q.send(Oe.slice(U,U+o))}catch{Ze(),q.close();return}try{q.send(n(et))}catch{Ze(),q.close();return}return{onMessage:c(U=>{K.process.write(String(U))},"onMessage"),onClose:c(()=>{e.info("client disconnected from session",{id:C}),Ze()},"onClose")}});return y.of({list:qt,get:es,create:ts,update:os,remove:dt,resize:ss,write:rs,connect:ns})}));let g=D.layer.pipe($t.provide(F.layer),$t.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(R=>R.get(S))}D.get=w,c(w,"get");async function L(S,R,H){return m(Z=>Z.resize(S,R,H))}D.resize=L,c(L,"resize");async function ee(S,R){return m(H=>H.write(S,R))}D.write=ee,c(ee,"write");async function he(S,R,H){return m(Z=>Z.connect(S,R,H))}D.connect=he,c(he,"connect");async function _(S){return m(R=>R.create(S))}D.create=_,c(_,"create");async function me(S,R){return m(H=>H.update(S,R))}D.update=me,c(me,"update");async function M(S){return m(R=>R.remove(S))}D.remove=M,c(M,"remove")})(ie||={});function qo(e){return new Bs().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(qo,"PtyRoutes");import{Hono as Hs}from"hono";import B from"zod";var Ao=A(()=>new Hs().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(B.record(B.string(),$.Status))}}}}}),async e=>e.json(await $.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(B.record(B.string(),B.array($.ToolManifestEntry)))}}}}}),async e=>e.json(await $.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(B.record(B.string(),$.Status))}}},...l(400)}}),p("json",B.object({name:B.string(),config:V.Mcp})),async e=>{let{name:t,config:o}=e.req.valid("json"),s=await $.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(B.object({authorizationUrl:B.string().describe("URL to open in browser for authorization")}))}}},...l(400,404)}}),async e=>{let t=e.req.param("name");if(!await $.supportsOAuth(t))return e.json({error:`MCP server ${t} does not support OAuth`},400);let s=await $.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($.Status)}}},...l(400,404)}}),p("json",B.object({code:B.string().describe("Authorization code from OAuth callback")})),async e=>{let t=e.req.param("name"),{code:o}=e.req.valid("json"),s=await $.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($.Status)}}},...l(400,404)}}),async e=>{let t=e.req.param("name");if(!await $.supportsOAuth(t))return e.json({error:`MCP server ${t} does not support OAuth`},400);let s=await $.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(B.object({success:B.literal(!0)}))}}},...l(404)}}),async e=>{let t=e.req.param("name");return await $.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(B.boolean())}}}}}),p("param",B.object({name:B.string()})),async e=>{let{name:t}=e.req.valid("param");return await $.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(B.boolean())}}}}}),p("param",B.object({name:B.string()})),async e=>{let{name:t}=e.req.valid("param");return await $.disconnect(t),e.json(!0)}));import{Hono as $s}from"hono";import de from"zod";var Co=A(()=>new $s().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(zt.Match.shape.data.array())}}}}}),p("query",de.object({pattern:de.string()})),async e=>{let t=e.req.valid("query").pattern,o=await zt.search({cwd:z.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(de.string().array())}}}}}),p("query",de.object({query:de.string(),dirs:de.enum(["true","false"]).optional(),type:de.enum(["file","directory"]).optional(),limit:de.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",de.object({query:de.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",de.object({path:de.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",de.object({path:de.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 Vs}from"hono";import J from"zod";import{mapValues as Ro}from"remeda";var Js=6e4,Qe,Eo=new Map;async function zo(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(zo,"readUsageJson");function Ys(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(Ys,"openaiWindows");async function Ks(e){let t={authorization:`Bearer ${e.access}`};e.accountId&&(t["ChatGPT-Account-Id"]=e.accountId);let o=await zo("https://chatgpt.com/backend-api/wham/usage",t);return{providerID:"openai",plan:typeof o?.plan_type=="string"?o.plan_type:null,windows:Ys(o?.rate_limit)}}c(Ks,"openaiUsage");async function Xs(e){let t=await zo("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(Xs,"anthropicUsage");async function Qs(e=!1){if(!e&&Qe&&Date.now()-Qe.at<Js)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 Ks(n):await Xs(n),readAt:Date.now()};Eo.set(s,d),o.push(d)}catch(d){let u=d instanceof Error?d.message:String(d),f=Eo.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(Qs,"providerUsage");var Dt;async function Oo(){let e=await He.list().catch(()=>new Map);for(let t of e.values())if(t.type!=="idle")return!0;return!1}c(Oo,"anySessionBusy");async function To(){let e=Dt;Dt=void 0,e&&(e.unsubscribe(),clearTimeout(e.timer)),await V.invalidate(!0)}c(To,"fireDeferredReload");var Zs=N.create({service:"server"}),_o=A(()=>new Vs().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(V.Info)}}}}}),async e=>e.json(await V.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(V.Info)}}},...l(400)}}),p("json",V.Info),async e=>{let t=e.req.valid("json");return await V.update(t),e.json(t)}).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(J.object({ok:J.boolean()}))}}}}}),async e=>{if(await Oo()){if(!Dt){let t=F.subscribe(He.Event.Status,async()=>{await Oo()||await To()}),o=setTimeout(()=>{To()},12e4);Dt={unsubscribe:t,timer:o}}return e.json({ok:!0,deferred:!0})}return await V.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(J.object({fetchedAt:J.number(),providers:J.array(J.object({providerID:J.string(),plan:J.string().nullable(),error:J.string().optional(),readAt:J.number().optional(),windows:J.array(J.object({kind:J.string(),label:J.string(),usedPercent:J.number(),resetsAt:J.number().nullable()}))}))}))}}}}}),async e=>e.json(await Qs(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(J.object({providers:ve.Info.array(),default:J.record(J.string(),J.string())}))}}}}}),async e=>{var s=[];try{let t=Kt(s,Zs.time("providers"));let o=await ve.list().then(u=>Ro(u,f=>f));return e.json({providers:Object.values(o),default:Ro(o,u=>ve.sort(Object.values(u.models))[0].id)})}catch(r){var n=r,d=!0}finally{Xt(s,n,d)}}));import{Hono as tr}from"hono";import P from"zod";import ct from"zod";var Uo=ct.object({consoleManagedProviders:ct.array(ct.string()),activeOrgName:ct.string().optional(),switchableOrgCount:ct.number().int().nonnegative()});import{zodToJsonSchema as or}from"zod-to-json-schema";import{Hono as er}from"hono";import Lo from"zod";var Mo=A(()=>new er().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:z.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(Lo.array(ye.Info))}}}}}),async e=>e.json(ye.list(z.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",Lo.object({id:ye.Info.shape.id})),async e=>{let{id:t}=e.req.valid("param");return e.json(await ye.remove(t))}));var sr=P.object({accountID:P.string(),accountEmail:P.string(),accountUrl:P.string(),orgID:P.string(),orgName:P.string(),active:P.boolean()}),rr=P.object({orgs:P.array(sr)}),nr=P.object({accountID:P.string(),orgID:P.string()}),No=A(()=>new tr().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(Uo)}}}}}),async e=>{let[t,o]=await Promise.all([V.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(rr)}}}}}),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",nr),async e=>{let t=e.req.valid("json");return await ot.switchOrg(oo.make(t.accountID),so.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 Nt.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 Nt.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?or(r.parameters):r.parameters})))}).route("/workspace",Mo()).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 ue.sandboxes(z.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 ue.removeSandbox(z.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(),$.Resource))}}}}}),async e=>e.json(await $.resources())));import{Hono as cr}from"hono";import Y from"zod";import{Array as ir,Effect as Ie,Layer as St,Record as Go,Result as Fo,ServiceMap as ar}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 ar.Service()("@opencode/ProviderAuth"){static{c(this,"Service")}}g.Service=d,g.layer=St.effect(d,Ie.gen(function*(){let m=yield*De.Service,I=yield*Ve.Service,w=yield*ne.make(Ie.fn("ProviderAuth.state")(function*(){let _=yield*I.list();return{hooks:Go.fromEntries(ir.filterMap(_,me=>me.auth?.provider!==void 0?Fo.succeed([ce.make(me.auth.provider),me.auth]):Fo.failVoid)),pending:new Map}})),L=Ie.fn("ProviderAuth.methods")(function*(){let _=(yield*ne.get(w)).hooks;return Go.map(_,me=>me.methods.map(M=>({type:M.type,label:M.label,prompts:M.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*(_){let{hooks:me,pending:M}=yield*ne.get(w),D=me[_.providerID].methods[_.method];if(D.type!=="oauth")return;if(D.prompts&&_.inputs){for(let R of D.prompts)if(R.type==="text"&&R.validate&&_.inputs[R.key]!==void 0){let H=R.validate(_.inputs[R.key]);if(H)return yield*Ie.fail(new g.ValidationFailed({field:R.key,message:H}))}}let S=yield*Ie.promise(()=>D.authorize(_.inputs));return M.set(_.providerID,S),{url:S.url,method:S.method,instructions:S.instructions}}),he=Ie.fn("ProviderAuth.callback")(function*(_){let M=(yield*ne.get(w)).pending.get(_.providerID);if(!M)return yield*Ie.fail(new g.OauthMissing({providerID:_.providerID}));if(M.method==="code"&&!_.code)return yield*Ie.fail(new g.OauthCodeMissing({providerID:_.providerID}));let D=yield*Ie.promise(()=>M.method==="code"?M.callback(_.code):M.callback());if(!D||D.type!=="success")return yield*Ie.fail(new g.OauthCallbackFailed({}));if("key"in D&&(yield*m.set(_.providerID,{type:"api",key:D.key})),"refresh"in D){let{type:S,provider:R,refresh:H,access:Z,expires:dt,...qt}=D;yield*m.set(_.providerID,{type:"oauth",access:Z,refresh:H,expires:dt,...qt})}});return d.of({methods:L,authorize:ee,callback:he})})),g.defaultLayer=St.suspend(()=>g.layer.pipe(St.provide(De.defaultLayer),St.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 Wo}from"remeda";var Lc=N.create({service:"server"}),Bo=A(()=>new cr().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:Rt.Provider.array(),default:Y.record(Y.string(),Y.string()),connected:Y.array(Y.string())}))}}}}}),async e=>{let t=await V.get(),o=new Set(t.disabled_providers??[]),s=t.enabled_providers?new Set(t.enabled_providers):void 0,r=await Rt.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(Wo(n,f=>ve.fromModelsDevProvider(f)),d);return e.json({all:Object.values(u),default:Wo(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 pr}from"hono";import{streamSSE as dr}from"hono/streaming";var Ho=N.create({service:"server"}),$o=c(()=>new pr().get("/event",a({summary:"Subscribe to events",description:"Get events",operationId:"event.subscribe",responses:{200:{description:"Event stream",content:{"text/event-stream":{schema:i(le.payloads())}}}}}),async e=>(Ho.info("event connected"),e.header("Cache-Control","no-cache, no-transform"),e.header("X-Accel-Buffering","no"),e.header("X-Content-Type-Options","nosniff"),dr(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),Ho.info("event disconnected"))},"stop"),d=F.subscribeAll(u=>{o.push(JSON.stringify(u)),u.type===F.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 mr}from"hono/http-exception";function Pt(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 mr)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(Pt,"errorHandler");var yr=N.create({service:"server"}),hr=tt.OPENCODE_DISABLE_EMBEDDED_WEB_UI?Promise.resolve(null):import("opencode-web-ui.gen.ts").then(e=>e.default).catch(()=>null),gr="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:",br=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"),kt=c((e,t=new lr)=>t.onError(Pt(yr)).route("/project",Do()).route("/pty",qo(e)).route("/config",_o()).route("/experimental",No()).route("/session",Po()).route("/permission",wo()).route("/question",jo()).route("/provider",Bo()).route("/",Co()).route("/",$o()).route("/mcp",Ao()).route("/tui",vo()).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 z.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:z.worktree,directory:z.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(Gt.Info.array())}}}}}),async o=>{let s=await Gt.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(Tt.Info.array())}}}}}),async o=>{let s=await Tt.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(Lt.Status.array())}}}}}),async o=>o.json(await Lt.status())).all("/*",async o=>{let s=await hr,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",gr),o.body(f)}catch{return o.json({error:"Not Found"},404)}}else{let n=await ur(`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?fr("sha256").update(d[2]).digest("base64"):"";return n.headers.set("Content-Security-Policy",br(u)),n}}),"InstanceRoutes");var Ir=[{path:"/session/status",action:"forward"},{method:"GET",path:"/session",action:"local"}];function vr(e,t){for(let o of Ir){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(vr,"local");function Vo(e){let t=A(()=>kt(e));return async o=>{let s=o.req.query("directory")||o.req.header("x-opencode-directory")||process.cwd(),r=Qt.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 z.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 z.provide({directory:k.directory,init:it,async fn(){return t().fetch(o.req.raw,o.env)}});if(vr(o.req.method,n.pathname))return t().fetch(o.req.raw,o.env);if(o.req.header("upgrade")?.toLowerCase()==="websocket")return vt.websocket(k,o.req.raw,o.env);let y=new Headers(o.req.raw.headers);return y.delete("x-opencode-workspace"),vt.http(k,new Request(o.req.raw,{headers:y}))}}c(Vo,"WorkspaceRouterMiddleware");import{Hono as jr}from"hono";import{streamSSE as wr}from"hono/streaming";import te from"zod";var Vt=N.create({service:"server"}),Dr=le.define("global.disposed",te.object({}));async function Jo(e,t){return wr(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),Vt.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(Jo,"streamEvents");var Yo=A(()=>new jr().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:le.payloads()}).meta({ref:"GlobalEvent"}))}}}}}),async e=>(Vt.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"),Jo(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=>(Vt.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"),Jo(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(V.Info)}}}}}),async e=>e.json(await V.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(V.Info)}}},...l(400)}}),p("json",V.Info),async e=>{let t=e.req.valid("json"),o=await V.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 z.disposeAll(),Te.emit("event",{directory:"global",payload:{type:Dr.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 Sr}from"bonjour-service";var pt=N.create({service:"mdns"}),xt;(r=>{let e,t;function o(n,d){if(t!==n){e&&s();try{let u=d??"opencode.local",f=`opencode-${n}`;e=new Sr;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")})(xt||={});var Ko=N.create({service:"session.projector"});function Xo(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(Xo,"foreign");function E(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(E,"grab");function Pr(e){let t={id:E(e,"id"),project_id:E(e,"projectID"),workspace_id:E(e,"workspaceID"),parent_id:E(e,"parentID"),slug:E(e,"slug"),directory:E(e,"directory"),title:E(e,"title"),version:E(e,"version"),share_url:E(e,"share",o=>E(o,"url")),summary_additions:E(e,"summary",o=>E(o,"additions")),summary_deletions:E(e,"summary",o=>E(o,"deletions")),summary_files:E(e,"summary",o=>E(o,"files")),summary_diffs:E(e,"summary",o=>E(o,"diffs")),revert:E(e,"revert"),permission:E(e,"permission"),time_created:E(e,"time",o=>E(o,"created")),time_updated:E(e,"time",o=>E(o,"updated")),time_compacting:E(e,"time",o=>E(o,"compacting")),time_archived:E(e,"time",o=>E(o,"archived"))};return Object.fromEntries(Object.entries(t).filter(([o,s])=>s!==void 0))}c(Pr,"toPartialRow");var Qo=[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(Pr(o)).where((0,G.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,G.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(!Xo(d))throw d;Ko.warn("ignored late message update",{messageID:s,sessionID:r})}}),pe.project(Q.Event.Removed,(e,t)=>{e.delete(Ge).where((0,G.and)((0,G.eq)(Ge.id,t.messageID),(0,G.eq)(Ge.session_id,t.sessionID))).run()}),pe.project(Q.Event.PartRemoved,(e,t)=>{e.delete(Fe).where((0,G.and)((0,G.eq)(Fe.id,t.partID),(0,G.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(!Xo(d))throw d;Ko.warn("ignored late part update",{partID:o,messageID:s,sessionID:r})}})];function Jt(){pe.init({projectors:Qo,convertEvent:c((e,t)=>{if(e==="session.updated"){let o=t.sessionID,s=xe.use(r=>r.select().from(we).where((0,G.eq)(we.id,o)).get());return s?{sessionID:o,info:h.fromRow(s)}:t}return t},"convertEvent")})}c(Jt,"initProjectors");Jt();globalThis.AI_SDK_LOG_WARNINGS=!1;Jt();var Rr;(k=>{let e=N.create({service:"server"}),t=kr(),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 Zo,g){return v.onError(Pt(e)).use((m,I)=>{if(m.req.method==="OPTIONS")return I();let w=tt.OPENCODE_SERVER_PASSWORD;if(!w)return I();let L=tt.OPENCODE_SERVER_USERNAME??"opencode";return qr({username:L,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 L=e.time("request",{method:m.req.method,path:m.req.path});await I(),w||L.stop()}).use(xr({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",Yo()).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",yo(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:L,extra:ee}=m.req.valid("json"),he=N.create({service:I});switch(w){case"debug":he.debug(L,ee);break;case"info":he.info(L,ee);break;case"error":he.error(L,ee);break;case"warn":he.warn(L,ee);break}return m.json(!0)}).use(Vo(y))}k.ControlPlaneRoutes=r,c(r,"ControlPlaneRoutes");function n(y){let v=new Zo,g=Cr({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 kt(v.upgradeWebSocket,y),await Wt(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((_,me)=>{let M=Ar({fetch:v.app.fetch});v.ws.injectWebSocket(M);let D=c(H=>{R(),me(H)},"fail"),S=c(()=>{R(),_(M)},"ready"),R=c(()=>{M.off("error",D),M.off("listening",S)},"cleanup");M.once("error",D),M.once("listening",S),M.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 L=y.mdns&&I.port&&y.hostname!=="127.0.0.1"&&y.hostname!=="localhost"&&y.hostname!=="::1";L?xt.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((_,me)=>{L&&xt.unpublish(),m.close(M=>{if(M){me(M);return}_()}),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")})(Rr||={});export{Rr as a};
|